]> git.wh0rd.org - tt-rss.git/blob - js/functions.js
25dc587dc51a3847ef634dcb711c5368ac251809
[tt-rss.git] / js / functions.js
1 /* global dijit, __ */
2
3 var loading_progress = 0;
4 var sanity_check_done = false;
5 var init_params = {};
6 var _label_base_index = -1024;
7 var notify_hide_timerid = false;
8
9 Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
10 function (callOriginal, options) {
11
12 if (getInitParam("csrf_token") != undefined) {
13 Object.extend(options, options || { });
14
15 if (Object.isString(options.parameters))
16 options.parameters = options.parameters.toQueryParams();
17 else if (Object.isHash(options.parameters))
18 options.parameters = options.parameters.toObject();
19
20 options.parameters["csrf_token"] = getInitParam("csrf_token");
21 }
22
23 return callOriginal(options);
24 }
25 );
26
27 /* add method to remove element from array */
28
29 Array.prototype.remove = function(s) {
30 for (let i=0; i < this.length; i++) {
31 if (s == this[i]) this.splice(i, 1);
32 }
33 };
34
35 function report_error(message, filename, lineno, colno, error) {
36 exception_error(error, null, filename, lineno);
37 }
38
39 function exception_error(e, e_compat, filename, lineno, colno) {
40 if (typeof e == "string") e = e_compat;
41
42 if (!e) return; // no exception object, nothing to report.
43
44 try {
45 console.error(e);
46 const msg = e.toString();
47
48 try {
49 new Ajax.Request("backend.php", {
50 parameters: {op: "rpc", method: "log",
51 file: e.fileName ? e.fileName : filename,
52 line: e.lineNumber ? e.lineNumber : lineno,
53 msg: msg, context: e.stack},
54 onComplete: function (transport) {
55 console.warn(transport.responseText);
56 } });
57
58 } catch (e) {
59 console.error("Exception while trying to log the error.", e);
60 }
61
62 let content = "<div class='fatalError'><p>" + msg + "</p>";
63
64 if (e.stack) {
65 content += "<div><b>Stack trace:</b></div>" +
66 "<textarea name=\"stack\" readonly=\"1\">" + e.stack + "</textarea>";
67 }
68
69 content += "</div>";
70
71 content += "<div class='dlgButtons'>";
72
73 content += "<button dojoType=\"dijit.form.Button\" "+
74 "onclick=\"dijit.byId('exceptionDlg').hide()\">" +
75 __('Close') + "</button>";
76 content += "</div>";
77
78 if (dijit.byId("exceptionDlg"))
79 dijit.byId("exceptionDlg").destroyRecursive();
80
81 const dialog = new dijit.Dialog({
82 id: "exceptionDlg",
83 title: "Unhandled exception",
84 style: "width: 600px",
85 content: content});
86
87 dialog.show();
88
89 } catch (ei) {
90 console.error("Exception while trying to report an exception:", ei);
91 console.error("Original exception:", e);
92
93 alert("Exception occured while trying to report an exception.\n" +
94 ei.stack + "\n\nOriginal exception:\n" + e.stack);
95 }
96
97 }
98
99 function param_escape(arg) {
100 return encodeURIComponent(arg);
101 }
102
103 function notify_real(msg, no_hide, n_type) {
104
105 const n = $("notify");
106
107 if (!n) return;
108
109 if (notify_hide_timerid) {
110 window.clearTimeout(notify_hide_timerid);
111 }
112
113 if (msg == "") {
114 if (n.hasClassName("visible")) {
115 notify_hide_timerid = window.setTimeout(function() {
116 n.removeClassName("visible") }, 0);
117 }
118 return;
119 }
120
121 /* types:
122
123 1 - generic
124 2 - progress
125 3 - error
126 4 - info
127
128 */
129
130 msg = "<span class=\"msg\"> " + __(msg) + "</span>";
131
132 if (n_type == 2) {
133 msg = "<span><img src=\""+getInitParam("icon_indicator_white")+"\"></span>" + msg;
134 no_hide = true;
135 } else if (n_type == 3) {
136 msg = "<span><img src=\""+getInitParam("icon_alert")+"\"></span>" + msg;
137 } else if (n_type == 4) {
138 msg = "<span><img src=\""+getInitParam("icon_information")+"\"></span>" + msg;
139 }
140
141 msg += " <span><img src=\""+getInitParam("icon_cross")+"\" class=\"close\" title=\"" +
142 __("Click to close") + "\" onclick=\"notify('')\"></span>";
143
144 n.innerHTML = msg;
145
146 window.setTimeout(function() {
147 // goddamnit firefox
148 if (n_type == 2) {
149 n.className = "notify notify_progress visible";
150 } else if (n_type == 3) {
151 n.className = "notify notify_error visible";
152 msg = "<span><img src='images/alert.png'></span>" + msg;
153 } else if (n_type == 4) {
154 n.className = "notify notify_info visible";
155 } else {
156 n.className = "notify visible";
157 }
158
159 if (!no_hide) {
160 notify_hide_timerid = window.setTimeout(function() {
161 n.removeClassName("visible") }, 5*1000);
162 }
163
164 }, 10);
165
166 }
167
168 function notify(msg, no_hide) {
169 notify_real(msg, no_hide, 1);
170 }
171
172 function notify_progress(msg, no_hide) {
173 notify_real(msg, no_hide, 2);
174 }
175
176 function notify_error(msg, no_hide) {
177 notify_real(msg, no_hide, 3);
178
179 }
180
181 function notify_info(msg, no_hide) {
182 notify_real(msg, no_hide, 4);
183 }
184
185 function setCookie(name, value, lifetime, path, domain, secure) {
186
187 let d = false;
188
189 if (lifetime) {
190 d = new Date();
191 d.setTime(d.getTime() + (lifetime * 1000));
192 }
193
194 console.log("setCookie: " + name + " => " + value + ": " + d);
195
196 int_setCookie(name, value, d, path, domain, secure);
197
198 }
199
200 function int_setCookie(name, value, expires, path, domain, secure) {
201 document.cookie= name + "=" + escape(value) +
202 ((expires) ? "; expires=" + expires.toGMTString() : "") +
203 ((path) ? "; path=" + path : "") +
204 ((domain) ? "; domain=" + domain : "") +
205 ((secure) ? "; secure" : "");
206 }
207
208 function delCookie(name, path, domain) {
209 if (getCookie(name)) {
210 document.cookie = name + "=" +
211 ((path) ? ";path=" + path : "") +
212 ((domain) ? ";domain=" + domain : "" ) +
213 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
214 }
215 }
216
217
218 function getCookie(name) {
219
220 const dc = document.cookie;
221 const prefix = name + "=";
222 let begin = dc.indexOf("; " + prefix);
223 if (begin == -1) {
224 begin = dc.indexOf(prefix);
225 if (begin != 0) return null;
226 }
227 else {
228 begin += 2;
229 }
230 let end = document.cookie.indexOf(";", begin);
231 if (end == -1) {
232 end = dc.length;
233 }
234 return unescape(dc.substring(begin + prefix.length, end));
235 }
236
237 function gotoPreferences() {
238 document.location.href = "prefs.php";
239 }
240
241 function gotoLogout() {
242 document.location.href = "backend.php?op=logout";
243 }
244
245 function gotoMain() {
246 document.location.href = "index.php";
247 }
248
249 function toggleSelectRowById(sender, id) {
250 const row = $(id);
251 return toggleSelectRow(sender, row);
252 }
253
254 /* this is for dijit Checkbox */
255 function toggleSelectListRow2(sender) {
256 const row = sender.domNode.parentNode;
257 return toggleSelectRow(sender, row);
258 }
259
260 /* this is for dijit Checkbox */
261 function toggleSelectRow2(sender, row, is_cdm) {
262
263 if (!row)
264 if (!is_cdm)
265 row = sender.domNode.parentNode.parentNode;
266 else
267 row = sender.domNode.parentNode.parentNode.parentNode; // oh ffs
268
269 if (sender.checked && !row.hasClassName('Selected'))
270 row.addClassName('Selected');
271 else
272 row.removeClassName('Selected');
273
274 if (typeof updateSelectedPrompt != undefined)
275 updateSelectedPrompt();
276 }
277
278
279 function toggleSelectRow(sender, row) {
280
281 if (!row) row = sender.parentNode.parentNode;
282
283 if (sender.checked && !row.hasClassName('Selected'))
284 row.addClassName('Selected');
285 else
286 row.removeClassName('Selected');
287
288 if (typeof updateSelectedPrompt != undefined)
289 updateSelectedPrompt();
290 }
291
292 function checkboxToggleElement(elem, id) {
293 if (elem.checked) {
294 Effect.Appear(id, {duration : 0.5});
295 } else {
296 Effect.Fade(id, {duration : 0.5});
297 }
298 }
299
300 function getURLParam(param){
301 return String(window.location.href).parseQuery()[param];
302 }
303
304 function closeInfoBox() {
305 const dialog = dijit.byId("infoBox");
306
307 if (dialog) dialog.hide();
308
309 return false;
310 }
311
312
313 function displayDlg(title, id, param, callback) {
314
315 notify_progress("Loading, please wait...", true);
316
317 const query = "?op=dlg&method=" +
318 param_escape(id) + "&param=" + param_escape(param);
319
320 new Ajax.Request("backend.php", {
321 parameters: query,
322 onComplete: function (transport) {
323 infobox_callback2(transport, title);
324 if (callback) callback(transport);
325 } });
326
327 return false;
328 }
329
330 function infobox_callback2(transport, title) {
331 let dialog = false;
332
333 if (dijit.byId("infoBox")) {
334 dialog = dijit.byId("infoBox");
335 }
336
337 //console.log("infobox_callback2");
338 notify('');
339
340 const content = transport.responseText;
341
342 if (!dialog) {
343 dialog = new dijit.Dialog({
344 title: title,
345 id: 'infoBox',
346 style: "width: 600px",
347 onCancel: function() {
348 return true;
349 },
350 onExecute: function() {
351 return true;
352 },
353 onClose: function() {
354 return true;
355 },
356 content: content});
357 } else {
358 dialog.attr('title', title);
359 dialog.attr('content', content);
360 }
361
362 dialog.show();
363
364 notify("");
365 }
366
367 function getInitParam(key) {
368 return init_params[key];
369 }
370
371 function setInitParam(key, value) {
372 init_params[key] = value;
373 }
374
375 function fatalError(code, msg, ext_info) {
376 if (code == 6) {
377 window.location.href = "index.php";
378 } else if (code == 5) {
379 window.location.href = "public.php?op=dbupdate";
380 } else {
381
382 if (msg == "") msg = "Unknown error";
383
384 if (ext_info) {
385 if (ext_info.responseText) {
386 ext_info = ext_info.responseText;
387 }
388 }
389
390 if (ERRORS && ERRORS[code] && !msg) {
391 msg = ERRORS[code];
392 }
393
394 let content = "<div><b>Error code:</b> " + code + "</div>" +
395 "<p>" + msg + "</p>";
396
397 if (ext_info) {
398 content = content + "<div><b>Additional information:</b></div>" +
399 "<textarea style='width: 100%' readonly=\"1\">" +
400 ext_info + "</textarea>";
401 }
402
403 const dialog = new dijit.Dialog({
404 title: "Fatal error",
405 style: "width: 600px",
406 content: content});
407
408 dialog.show();
409
410 }
411
412 return false;
413
414 }
415
416 function filterDlgCheckAction(sender) {
417 const action = sender.value;
418
419 const action_param = $("filterDlg_paramBox");
420
421 if (!action_param) {
422 console.log("filterDlgCheckAction: can't find action param box!");
423 return;
424 }
425
426 // if selected action supports parameters, enable params field
427 if (action == 4 || action == 6 || action == 7 || action == 9) {
428 new Effect.Appear(action_param, {duration : 0.5});
429
430 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
431 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
432 Element.hide(dijit.byId("filterDlg_actionParamPlugin").domNode);
433
434 if (action == 7) {
435 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
436 } else if (action == 9) {
437 Element.show(dijit.byId("filterDlg_actionParamPlugin").domNode);
438 } else {
439 Element.show(dijit.byId("filterDlg_actionParam").domNode);
440 }
441
442 } else {
443 Element.hide(action_param);
444 }
445 }
446
447
448 function explainError(code) {
449 return displayDlg(__("Error explained"), "explainError", code);
450 }
451
452 function loading_set_progress(p) {
453 loading_progress += p;
454
455 if (dijit.byId("loading_bar"))
456 dijit.byId("loading_bar").update({progress: loading_progress});
457
458 if (loading_progress >= 90)
459 remove_splash();
460
461 }
462
463 function remove_splash() {
464 Element.hide("overlay");
465 }
466
467 function strip_tags(s) {
468 return s.replace(/<\/?[^>]+(>|$)/g, "");
469 }
470
471 function hotkey_prefix_timeout() {
472
473 const date = new Date();
474 const ts = Math.round(date.getTime() / 1000);
475
476 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
477 console.log("hotkey_prefix seems to be stuck, aborting");
478 hotkey_prefix_pressed = false;
479 hotkey_prefix = false;
480 Element.hide('cmdline');
481 }
482
483 setTimeout(hotkey_prefix_timeout, 1000);
484
485 }
486
487 function uploadIconHandler(rc) {
488 switch (rc) {
489 case 0:
490 notify_info("Upload complete.");
491 if (inPreferences()) {
492 updateFeedList();
493 } else {
494 setTimeout('updateFeedList(false, false)', 50);
495 }
496 break;
497 case 1:
498 notify_error("Upload failed: icon is too big.");
499 break;
500 case 2:
501 notify_error("Upload failed.");
502 break;
503 }
504 }
505
506 function removeFeedIcon(id) {
507 if (confirm(__("Remove stored feed icon?"))) {
508 const query = "backend.php?op=pref-feeds&method=removeicon&feed_id=" + param_escape(id);
509
510 console.log(query);
511
512 notify_progress("Removing feed icon...", true);
513
514 new Ajax.Request("backend.php", {
515 parameters: query,
516 onComplete: function(transport) {
517 notify_info("Feed icon removed.");
518 if (inPreferences()) {
519 updateFeedList();
520 } else {
521 setTimeout('updateFeedList(false, false)', 50);
522 }
523 } });
524 }
525
526 return false;
527 }
528
529 function uploadFeedIcon() {
530 const file = $("icon_file");
531
532 if (file.value.length == 0) {
533 alert(__("Please select an image file to upload."));
534 } else if (confirm(__("Upload new icon for this feed?"))) {
535 notify_progress("Uploading, please wait...", true);
536 return true;
537 }
538
539 return false;
540 }
541
542 function addLabel(select, callback) {
543
544 const caption = prompt(__("Please enter label caption:"), "");
545
546 if (caption != undefined) {
547
548 if (caption == "") {
549 alert(__("Can't create label: missing caption."));
550 return false;
551 }
552
553 let query = "?op=pref-labels&method=add&caption=" +
554 param_escape(caption);
555
556 if (select)
557 query += "&output=select";
558
559 notify_progress("Loading, please wait...", true);
560
561 new Ajax.Request("backend.php", {
562 parameters: query,
563 onComplete: function(transport) {
564 if (callback) {
565 callback(transport);
566 } else if (inPreferences()) {
567 updateLabelList();
568 } else {
569 updateFeedList();
570 }
571 } });
572
573 }
574
575 }
576
577 function quickAddFeed() {
578 const query = "backend.php?op=feeds&method=quickAddFeed";
579
580 // overlapping widgets
581 if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive();
582 if (dijit.byId("feedAddDlg")) dijit.byId("feedAddDlg").destroyRecursive();
583
584 const dialog = new dijit.Dialog({
585 id: "feedAddDlg",
586 title: __("Subscribe to Feed"),
587 style: "width: 600px",
588 show_error: function(msg) {
589 const elem = $("fadd_error_message");
590
591 elem.innerHTML = msg;
592
593 if (!Element.visible(elem))
594 new Effect.Appear(elem);
595
596 },
597 execute: function() {
598 if (this.validate()) {
599 console.log(dojo.objectToQuery(this.attr('value')));
600
601 const feed_url = this.attr('value').feed;
602
603 Element.show("feed_add_spinner");
604 Element.hide("fadd_error_message");
605
606 new Ajax.Request("backend.php", {
607 parameters: dojo.objectToQuery(this.attr('value')),
608 onComplete: function(transport) {
609 try {
610
611 try {
612 var reply = JSON.parse(transport.responseText);
613 } catch (e) {
614 Element.hide("feed_add_spinner");
615 alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console."));
616 console.log('quickAddFeed, backend returned:' + transport.responseText);
617 return;
618 }
619
620 const rc = reply['result'];
621
622 notify('');
623 Element.hide("feed_add_spinner");
624
625 console.log(rc);
626
627 switch (parseInt(rc['code'])) {
628 case 1:
629 dialog.hide();
630 notify_info(__("Subscribed to %s").replace("%s", feed_url));
631
632 updateFeedList();
633 break;
634 case 2:
635 dialog.show_error(__("Specified URL seems to be invalid."));
636 break;
637 case 3:
638 dialog.show_error(__("Specified URL doesn't seem to contain any feeds."));
639 break;
640 case 4:
641 var feeds = rc['feeds'];
642
643 Element.show("fadd_multiple_notify");
644
645 var select = dijit.byId("feedDlg_feedContainerSelect");
646
647 while (select.getOptions().length > 0)
648 select.removeOption(0);
649
650 select.addOption({value: '', label: __("Expand to select feed")});
651
652 var count = 0;
653 for (const feedUrl in feeds) {
654 select.addOption({value: feedUrl, label: feeds[feedUrl]});
655 count++;
656 }
657
658 Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
659
660 break;
661 case 5:
662 dialog.show_error(__("Couldn't download the specified URL: %s").
663 replace("%s", rc['message']));
664 break;
665 case 6:
666 dialog.show_error(__("XML validation failed: %s").
667 replace("%s", rc['message']));
668 break;
669 case 0:
670 dialog.show_error(__("You are already subscribed to this feed."));
671 break;
672 }
673
674 } catch (e) {
675 console.error(transport.responseText);
676 exception_error(e);
677 }
678
679 } });
680
681 }
682 },
683 href: query});
684
685 dialog.show();
686 }
687
688 function createNewRuleElement(parentNode, replaceNode) {
689 const form = document.forms["filter_new_rule_form"];
690
691 //form.reg_exp.value = form.reg_exp.value.replace(/(<([^>]+)>)/ig,"");
692
693 const query = "backend.php?op=pref-filters&method=printrulename&rule="+
694 param_escape(dojo.formToJson(form));
695
696 console.log(query);
697
698 new Ajax.Request("backend.php", {
699 parameters: query,
700 onComplete: function (transport) {
701 try {
702 const li = dojo.create("li");
703
704 const cb = dojo.create("input", { type: "checkbox" }, li);
705
706 new dijit.form.CheckBox({
707 onChange: function() {
708 toggleSelectListRow2(this) },
709 }, cb);
710
711 dojo.create("input", { type: "hidden",
712 name: "rule[]",
713 value: dojo.formToJson(form) }, li);
714
715 dojo.create("span", {
716 onclick: function() {
717 dijit.byId('filterEditDlg').editRule(this);
718 },
719 innerHTML: transport.responseText }, li);
720
721 if (replaceNode) {
722 parentNode.replaceChild(li, replaceNode);
723 } else {
724 parentNode.appendChild(li);
725 }
726 } catch (e) {
727 exception_error(e);
728 }
729 } });
730 }
731
732 function createNewActionElement(parentNode, replaceNode) {
733 const form = document.forms["filter_new_action_form"];
734
735 if (form.action_id.value == 7) {
736 form.action_param.value = form.action_param_label.value;
737 } else if (form.action_id.value == 9) {
738 form.action_param.value = form.action_param_plugin.value;
739 }
740
741 const query = "backend.php?op=pref-filters&method=printactionname&action="+
742 param_escape(dojo.formToJson(form));
743
744 console.log(query);
745
746 new Ajax.Request("backend.php", {
747 parameters: query,
748 onComplete: function (transport) {
749 try {
750 const li = dojo.create("li");
751
752 const cb = dojo.create("input", { type: "checkbox" }, li);
753
754 new dijit.form.CheckBox({
755 onChange: function() {
756 toggleSelectListRow2(this) },
757 }, cb);
758
759 dojo.create("input", { type: "hidden",
760 name: "action[]",
761 value: dojo.formToJson(form) }, li);
762
763 dojo.create("span", {
764 onclick: function() {
765 dijit.byId('filterEditDlg').editAction(this);
766 },
767 innerHTML: transport.responseText }, li);
768
769 if (replaceNode) {
770 parentNode.replaceChild(li, replaceNode);
771 } else {
772 parentNode.appendChild(li);
773 }
774
775 } catch (e) {
776 exception_error(e);
777 }
778 } });
779 }
780
781
782 function addFilterRule(replaceNode, ruleStr) {
783 if (dijit.byId("filterNewRuleDlg"))
784 dijit.byId("filterNewRuleDlg").destroyRecursive();
785
786 const query = "backend.php?op=pref-filters&method=newrule&rule=" +
787 param_escape(ruleStr);
788
789 const rule_dlg = new dijit.Dialog({
790 id: "filterNewRuleDlg",
791 title: ruleStr ? __("Edit rule") : __("Add rule"),
792 style: "width: 600px",
793 execute: function() {
794 if (this.validate()) {
795 createNewRuleElement($("filterDlg_Matches"), replaceNode);
796 this.hide();
797 }
798 },
799 href: query});
800
801 rule_dlg.show();
802 }
803
804 function addFilterAction(replaceNode, actionStr) {
805 if (dijit.byId("filterNewActionDlg"))
806 dijit.byId("filterNewActionDlg").destroyRecursive();
807
808 const query = "backend.php?op=pref-filters&method=newaction&action=" +
809 param_escape(actionStr);
810
811 const rule_dlg = new dijit.Dialog({
812 id: "filterNewActionDlg",
813 title: actionStr ? __("Edit action") : __("Add action"),
814 style: "width: 600px",
815 execute: function() {
816 if (this.validate()) {
817 createNewActionElement($("filterDlg_Actions"), replaceNode);
818 this.hide();
819 }
820 },
821 href: query});
822
823 rule_dlg.show();
824 }
825
826 function editFilterTest(query) {
827
828 if (dijit.byId("filterTestDlg"))
829 dijit.byId("filterTestDlg").destroyRecursive();
830
831 var test_dlg = new dijit.Dialog({
832 id: "filterTestDlg",
833 title: "Test Filter",
834 style: "width: 600px",
835 results: 0,
836 limit: 100,
837 max_offset: 10000,
838 getTestResults: function(query, offset) {
839 const updquery = query + "&offset=" + offset + "&limit=" + test_dlg.limit;
840
841 console.log("getTestResults:" + offset);
842
843 new Ajax.Request("backend.php", {
844 parameters: updquery,
845 onComplete: function (transport) {
846 try {
847 const result = JSON.parse(transport.responseText);
848
849 if (result && dijit.byId("filterTestDlg") && dijit.byId("filterTestDlg").open) {
850 test_dlg.results += result.length;
851
852 console.log("got results:" + result.length);
853
854 $("prefFilterProgressMsg").innerHTML = __("Looking for articles (%d processed, %f found)...")
855 .replace("%f", test_dlg.results)
856 .replace("%d", offset);
857
858 console.log(offset + " " + test_dlg.max_offset);
859
860 for (let i = 0; i < result.length; i++) {
861 const tmp = new Element("table");
862 tmp.innerHTML = result[i];
863 dojo.parser.parse(tmp);
864
865 $("prefFilterTestResultList").innerHTML += tmp.innerHTML;
866 }
867
868 if (test_dlg.results < 30 && offset < test_dlg.max_offset) {
869
870 // get the next batch
871 window.setTimeout(function () {
872 test_dlg.getTestResults(query, offset + test_dlg.limit);
873 }, 0);
874
875 } else {
876 // all done
877
878 Element.hide("prefFilterLoadingIndicator");
879
880 if (test_dlg.results == 0) {
881 $("prefFilterTestResultList").innerHTML = "<tr><td align='center'>No recent articles matching this filter have been found.</td></tr>";
882 $("prefFilterProgressMsg").innerHTML = "Articles matching this filter:";
883 } else {
884 $("prefFilterProgressMsg").innerHTML = __("Found %d articles matching this filter:")
885 .replace("%d", test_dlg.results);
886 }
887
888 }
889
890 } else if (!result) {
891 console.log("getTestResults: can't parse results object");
892
893 Element.hide("prefFilterLoadingIndicator");
894
895 notify_error("Error while trying to get filter test results.");
896
897 } else {
898 console.log("getTestResults: dialog closed, bailing out.");
899 }
900 } catch (e) {
901 exception_error(e);
902 }
903
904 } });
905 },
906 href: query});
907
908 dojo.connect(test_dlg, "onLoad", null, function(e) {
909 test_dlg.getTestResults(query, 0);
910 });
911
912 test_dlg.show();
913
914 }
915
916 function quickAddFilter() {
917 let query = "";
918 if (!inPreferences()) {
919 query = "backend.php?op=pref-filters&method=newfilter&feed=" +
920 param_escape(getActiveFeedId()) + "&is_cat=" +
921 param_escape(activeFeedIsCat());
922 } else {
923 query = "backend.php?op=pref-filters&method=newfilter";
924 }
925
926 console.log(query);
927
928 if (dijit.byId("feedEditDlg"))
929 dijit.byId("feedEditDlg").destroyRecursive();
930
931 if (dijit.byId("filterEditDlg"))
932 dijit.byId("filterEditDlg").destroyRecursive();
933
934 const dialog = new dijit.Dialog({
935 id: "filterEditDlg",
936 title: __("Create Filter"),
937 style: "width: 600px",
938 test: function() {
939 const query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test";
940
941 editFilterTest(query);
942 },
943 selectRules: function(select) {
944 $$("#filterDlg_Matches input[type=checkbox]").each(function(e) {
945 e.checked = select;
946 if (select)
947 e.parentNode.addClassName("Selected");
948 else
949 e.parentNode.removeClassName("Selected");
950 });
951 },
952 selectActions: function(select) {
953 $$("#filterDlg_Actions input[type=checkbox]").each(function(e) {
954 e.checked = select;
955
956 if (select)
957 e.parentNode.addClassName("Selected");
958 else
959 e.parentNode.removeClassName("Selected");
960
961 });
962 },
963 editRule: function(e) {
964 const li = e.parentNode;
965 const rule = li.getElementsByTagName("INPUT")[1].value;
966 addFilterRule(li, rule);
967 },
968 editAction: function(e) {
969 const li = e.parentNode;
970 const action = li.getElementsByTagName("INPUT")[1].value;
971 addFilterAction(li, action);
972 },
973 addAction: function() { addFilterAction(); },
974 addRule: function() { addFilterRule(); },
975 deleteAction: function() {
976 $$("#filterDlg_Actions li[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
977 },
978 deleteRule: function() {
979 $$("#filterDlg_Matches li[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
980 },
981 execute: function() {
982 if (this.validate()) {
983
984 const query = dojo.formToQuery("filter_new_form");
985
986 console.log(query);
987
988 new Ajax.Request("backend.php", {
989 parameters: query,
990 onComplete: function (transport) {
991 if (inPreferences()) {
992 updateFilterList();
993 }
994
995 dialog.hide();
996 } });
997 }
998 },
999 href: query});
1000
1001 if (!inPreferences()) {
1002 const selectedText = getSelectionText();
1003
1004 var lh = dojo.connect(dialog, "onLoad", function(){
1005 dojo.disconnect(lh);
1006
1007 if (selectedText != "") {
1008
1009 const feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1010 getActiveFeedId();
1011
1012 const rule = { reg_exp: selectedText, feed_id: [feed_id], filter_type: 1 };
1013
1014 addFilterRule(null, dojo.toJson(rule));
1015
1016 } else {
1017
1018 const query = "op=rpc&method=getlinktitlebyid&id=" + getActiveArticleId();
1019
1020 new Ajax.Request("backend.php", {
1021 parameters: query,
1022 onComplete: function(transport) {
1023 const reply = JSON.parse(transport.responseText);
1024
1025 let title = false;
1026
1027 if (reply && reply.title) title = reply.title;
1028
1029 if (title || getActiveFeedId() || activeFeedIsCat()) {
1030
1031 console.log(title + " " + getActiveFeedId());
1032
1033 const feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1034 getActiveFeedId();
1035
1036 const rule = { reg_exp: title, feed_id: [feed_id], filter_type: 1 };
1037
1038 addFilterRule(null, dojo.toJson(rule));
1039 }
1040
1041 } });
1042
1043 }
1044
1045 });
1046 }
1047
1048 dialog.show();
1049
1050 }
1051
1052 function unsubscribeFeed(feed_id, title) {
1053
1054 const msg = __("Unsubscribe from %s?").replace("%s", title);
1055
1056 if (title == undefined || confirm(msg)) {
1057 notify_progress("Removing feed...");
1058
1059 const query = "?op=pref-feeds&quiet=1&method=remove&ids=" + feed_id;
1060
1061 new Ajax.Request("backend.php", {
1062 parameters: query,
1063 onComplete: function(transport) {
1064
1065 if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1066
1067 if (inPreferences()) {
1068 updateFeedList();
1069 } else {
1070 if (feed_id == getActiveFeedId())
1071 setTimeout(function() { viewfeed({feed:-5}) }, 100);
1072
1073 if (feed_id < 0) updateFeedList();
1074 }
1075
1076 } });
1077 }
1078
1079 return false;
1080 }
1081
1082
1083 function backend_sanity_check_callback(transport) {
1084
1085 if (sanity_check_done) {
1086 fatalError(11, "Sanity check request received twice. This can indicate "+
1087 "presence of Firebug or some other disrupting extension. "+
1088 "Please disable it and try again.");
1089 return;
1090 }
1091
1092 const reply = JSON.parse(transport.responseText);
1093
1094 if (!reply) {
1095 fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1096 return;
1097 }
1098
1099 const error_code = reply['error']['code'];
1100
1101 if (error_code && error_code != 0) {
1102 return fatalError(error_code, reply['error']['message']);
1103 }
1104
1105 console.log("sanity check ok");
1106
1107 const params = reply['init-params'];
1108
1109 if (params) {
1110 console.log('reading init-params...');
1111
1112 for (const k in params) {
1113 console.log("IP: " + k + " => " + JSON.stringify(params[k]));
1114 if (k == "label_base_index") _label_base_index = parseInt(params[k]);
1115 }
1116
1117 init_params = params;
1118
1119 // PluginHost might not be available on non-index pages
1120 window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params);
1121 }
1122
1123 sanity_check_done = true;
1124
1125 init_second_stage();
1126
1127 }
1128
1129 function genUrlChangeKey(feed, is_cat) {
1130 const ok = confirm(__("Generate new syndication address for this feed?"));
1131
1132 if (ok) {
1133
1134 notify_progress("Trying to change address...", true);
1135
1136 const query = "?op=pref-feeds&method=regenFeedKey&id=" + param_escape(feed) +
1137 "&is_cat=" + param_escape(is_cat);
1138
1139 new Ajax.Request("backend.php", {
1140 parameters: query,
1141 onComplete: function(transport) {
1142 const reply = JSON.parse(transport.responseText);
1143 const new_link = reply.link;
1144
1145 const e = $('gen_feed_url');
1146
1147 if (new_link) {
1148
1149 e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/,
1150 "&amp;key=" + new_link);
1151
1152 e.href = e.href.replace(/\&key=.*$/,
1153 "&key=" + new_link);
1154
1155 new Effect.Highlight(e);
1156
1157 notify('');
1158
1159 } else {
1160 notify_error("Could not change feed URL.");
1161 }
1162 } });
1163 }
1164 return false;
1165 }
1166
1167 // mode = all, none, invert
1168 function selectTableRows(id, mode) {
1169 const rows = $(id).rows;
1170
1171 for (let i = 0; i < rows.length; i++) {
1172 const row = rows[i];
1173 let cb = false;
1174 let dcb = false;
1175
1176 if (row.id && row.className) {
1177 const bare_id = row.id.replace(/^[A-Z]*?-/, "");
1178 const inputs = rows[i].getElementsByTagName("input");
1179
1180 for (let j = 0; j < inputs.length; j++) {
1181 const input = inputs[j];
1182
1183 if (input.getAttribute("type") == "checkbox" &&
1184 input.id.match(bare_id)) {
1185
1186 cb = input;
1187 dcb = dijit.getEnclosingWidget(cb);
1188 break;
1189 }
1190 }
1191
1192 if (cb || dcb) {
1193 const issel = row.hasClassName("Selected");
1194
1195 if (mode == "all" && !issel) {
1196 row.addClassName("Selected");
1197 cb.checked = true;
1198 if (dcb) dcb.set("checked", true);
1199 } else if (mode == "none" && issel) {
1200 row.removeClassName("Selected");
1201 cb.checked = false;
1202 if (dcb) dcb.set("checked", false);
1203
1204 } else if (mode == "invert") {
1205
1206 if (issel) {
1207 row.removeClassName("Selected");
1208 cb.checked = false;
1209 if (dcb) dcb.set("checked", false);
1210 } else {
1211 row.addClassName("Selected");
1212 cb.checked = true;
1213 if (dcb) dcb.set("checked", true);
1214 }
1215 }
1216 }
1217 }
1218 }
1219
1220 }
1221
1222 function getSelectedTableRowIds(id) {
1223 const rows = [];
1224
1225 const elem_rows = $(id).rows;
1226
1227 for (let i = 0; i < elem_rows.length; i++) {
1228 if (elem_rows[i].hasClassName("Selected")) {
1229 const bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1230 rows.push(bare_id);
1231 }
1232 }
1233
1234 return rows;
1235 }
1236
1237 function editFeed(feed) {
1238 if (feed <= 0)
1239 return alert(__("You can't edit this kind of feed."));
1240
1241 const query = "backend.php?op=pref-feeds&method=editfeed&id=" +
1242 param_escape(feed);
1243
1244 console.log(query);
1245
1246 if (dijit.byId("filterEditDlg"))
1247 dijit.byId("filterEditDlg").destroyRecursive();
1248
1249 if (dijit.byId("feedEditDlg"))
1250 dijit.byId("feedEditDlg").destroyRecursive();
1251
1252 const dialog = new dijit.Dialog({
1253 id: "feedEditDlg",
1254 title: __("Edit Feed"),
1255 style: "width: 600px",
1256 execute: function() {
1257 if (this.validate()) {
1258 // console.log(dojo.objectToQuery(this.attr('value')));
1259
1260 notify_progress("Saving data...", true);
1261
1262 new Ajax.Request("backend.php", {
1263 parameters: dojo.objectToQuery(dialog.attr('value')),
1264 onComplete: function(transport) {
1265 dialog.hide();
1266 notify('');
1267 updateFeedList();
1268 }});
1269 }
1270 },
1271 href: query});
1272
1273 dialog.show();
1274 }
1275
1276 function feedBrowser() {
1277 const query = "backend.php?op=feeds&method=feedBrowser";
1278
1279 if (dijit.byId("feedAddDlg"))
1280 dijit.byId("feedAddDlg").hide();
1281
1282 if (dijit.byId("feedBrowserDlg"))
1283 dijit.byId("feedBrowserDlg").destroyRecursive();
1284
1285 const dialog = new dijit.Dialog({
1286 id: "feedBrowserDlg",
1287 title: __("More Feeds"),
1288 style: "width: 600px",
1289 getSelectedFeedIds: function () {
1290 const list = $$("#browseFeedList li[id*=FBROW]");
1291 const selected = [];
1292
1293 list.each(function (child) {
1294 const id = child.id.replace("FBROW-", "");
1295
1296 if (child.hasClassName('Selected')) {
1297 selected.push(id);
1298 }
1299 });
1300
1301 return selected;
1302 },
1303 getSelectedFeeds: function () {
1304 const list = $$("#browseFeedList li.Selected");
1305 const selected = [];
1306
1307 list.each(function (child) {
1308 const title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1309 const url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1310
1311 selected.push([title, url]);
1312
1313 });
1314
1315 return selected;
1316 },
1317
1318 subscribe: function () {
1319 const mode = this.attr('value').mode;
1320 let selected = [];
1321
1322 if (mode == "1")
1323 selected = this.getSelectedFeeds();
1324 else
1325 selected = this.getSelectedFeedIds();
1326
1327 if (selected.length > 0) {
1328 dijit.byId("feedBrowserDlg").hide();
1329
1330 notify_progress("Loading, please wait...", true);
1331
1332 // we use dojo.toJson instead of JSON.stringify because
1333 // it somehow escapes everything TWICE, at least in Chrome 9
1334
1335 const query = "?op=rpc&method=massSubscribe&payload=" +
1336 param_escape(dojo.toJson(selected)) + "&mode=" + param_escape(mode);
1337
1338 console.log(query);
1339
1340 new Ajax.Request("backend.php", {
1341 parameters: query,
1342 onComplete: function (transport) {
1343 notify('');
1344 updateFeedList();
1345 }
1346 });
1347
1348 } else {
1349 alert(__("No feeds are selected."));
1350 }
1351
1352 },
1353 update: function () {
1354 const query = dojo.objectToQuery(dialog.attr('value'));
1355
1356 Element.show('feed_browser_spinner');
1357
1358 new Ajax.Request("backend.php", {
1359 parameters: query,
1360 onComplete: function (transport) {
1361 notify('');
1362
1363 Element.hide('feed_browser_spinner');
1364
1365 const reply = JSON.parse(transport.responseText);
1366 const mode = reply['mode'];
1367
1368 if ($("browseFeedList") && reply['content']) {
1369 $("browseFeedList").innerHTML = reply['content'];
1370 }
1371
1372 dojo.parser.parse("browseFeedList");
1373
1374 if (mode == 2) {
1375 Element.show(dijit.byId('feed_archive_remove').domNode);
1376 } else {
1377 Element.hide(dijit.byId('feed_archive_remove').domNode);
1378 }
1379
1380 }
1381 });
1382 },
1383 removeFromArchive: function () {
1384 const selected = this.getSelectedFeedIds();
1385
1386 if (selected.length > 0) {
1387
1388 const pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1389
1390 if (confirm(pr)) {
1391 Element.show('feed_browser_spinner');
1392
1393 const query = "?op=rpc&method=remarchive&ids=" +
1394 param_escape(selected.toString());
1395
1396
1397 new Ajax.Request("backend.php", {
1398 parameters: query,
1399 onComplete: function (transport) {
1400 dialog.update();
1401 }
1402 });
1403 }
1404 }
1405 },
1406 execute: function () {
1407 if (this.validate()) {
1408 this.subscribe();
1409 }
1410 },
1411 href: query
1412 });
1413
1414 dialog.show();
1415 }
1416
1417 function showFeedsWithErrors() {
1418 const query = "backend.php?op=pref-feeds&method=feedsWithErrors";
1419
1420 if (dijit.byId("errorFeedsDlg"))
1421 dijit.byId("errorFeedsDlg").destroyRecursive();
1422
1423 const dialog = new dijit.Dialog({
1424 id: "errorFeedsDlg",
1425 title: __("Feeds with update errors"),
1426 style: "width: 600px",
1427 getSelectedFeeds: function() {
1428 return getSelectedTableRowIds("prefErrorFeedList");
1429 },
1430 removeSelected: function() {
1431 const sel_rows = this.getSelectedFeeds();
1432
1433 console.log(sel_rows);
1434
1435 if (sel_rows.length > 0) {
1436 const ok = confirm(__("Remove selected feeds?"));
1437
1438 if (ok) {
1439 notify_progress("Removing selected feeds...", true);
1440
1441 const query = "?op=pref-feeds&method=remove&ids="+
1442 param_escape(sel_rows.toString());
1443
1444 new Ajax.Request("backend.php", {
1445 parameters: query,
1446 onComplete: function(transport) {
1447 notify('');
1448 dialog.hide();
1449 updateFeedList();
1450 } });
1451 }
1452
1453 } else {
1454 alert(__("No feeds are selected."));
1455 }
1456 },
1457 execute: function() {
1458 if (this.validate()) {
1459 }
1460 },
1461 href: query});
1462
1463 dialog.show();
1464 }
1465
1466 function get_timestamp() {
1467 const date = new Date();
1468 return Math.round(date.getTime() / 1000);
1469 }
1470
1471 function helpDialog(topic) {
1472 const query = "backend.php?op=backend&method=help&topic=" + param_escape(topic);
1473
1474 if (dijit.byId("helpDlg"))
1475 dijit.byId("helpDlg").destroyRecursive();
1476
1477 const dialog = new dijit.Dialog({
1478 id: "helpDlg",
1479 title: __("Help"),
1480 style: "width: 600px",
1481 href: query,
1482 });
1483
1484 dialog.show();
1485 }
1486
1487 function htmlspecialchars_decode (string, quote_style) {
1488 // http://kevin.vanzonneveld.net
1489 // + original by: Mirek Slugen
1490 // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1491 // + bugfixed by: Mateusz "loonquawl" Zalega
1492 // + input by: ReverseSyntax
1493 // + input by: Slawomir Kaniecki
1494 // + input by: Scott Cariss
1495 // + input by: Francois
1496 // + bugfixed by: Onno Marsman
1497 // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1498 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1499 // + input by: Ratheous
1500 // + input by: Mailfaker (http://www.weedem.fr/)
1501 // + reimplemented by: Brett Zamir (http://brett-zamir.me)
1502 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1503 // * example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
1504 // * returns 1: '<p>this -> &quot;</p>'
1505 // * example 2: htmlspecialchars_decode("&amp;quot;");
1506 // * returns 2: '&quot;'
1507 let optTemp = 0,
1508 i = 0,
1509 noquotes = false;
1510 if (typeof quote_style === 'undefined') {
1511 quote_style = 2;
1512 }
1513 string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
1514 const OPTS = {
1515 'ENT_NOQUOTES': 0,
1516 'ENT_HTML_QUOTE_SINGLE': 1,
1517 'ENT_HTML_QUOTE_DOUBLE': 2,
1518 'ENT_COMPAT': 2,
1519 'ENT_QUOTES': 3,
1520 'ENT_IGNORE': 4
1521 };
1522 if (quote_style === 0) {
1523 noquotes = true;
1524 }
1525 if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
1526 quote_style = [].concat(quote_style);
1527 for (i = 0; i < quote_style.length; i++) {
1528 // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1529 if (OPTS[quote_style[i]] === 0) {
1530 noquotes = true;
1531 } else if (OPTS[quote_style[i]]) {
1532 optTemp = optTemp | OPTS[quote_style[i]];
1533 }
1534 }
1535 quote_style = optTemp;
1536 }
1537 if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
1538 string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
1539 // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
1540 }
1541 if (!noquotes) {
1542 string = string.replace(/&quot;/g, '"');
1543 }
1544 // Put this in last place to avoid escape being double-decoded
1545 string = string.replace(/&amp;/g, '&');
1546
1547 return string;
1548 }
1549
1550
1551 function label_to_feed_id(label) {
1552 return _label_base_index - 1 - Math.abs(label);
1553 }
1554
1555 function feed_to_label_id(feed) {
1556 return _label_base_index - 1 + Math.abs(feed);
1557 }
1558
1559 // http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac
1560
1561 function getSelectionText() {
1562 let text = "";
1563
1564 if (typeof window.getSelection != "undefined") {
1565 const sel = window.getSelection();
1566 if (sel.rangeCount) {
1567 const container = document.createElement("div");
1568 for (let i = 0, len = sel.rangeCount; i < len; ++i) {
1569 container.appendChild(sel.getRangeAt(i).cloneContents());
1570 }
1571 text = container.innerHTML;
1572 }
1573 } else if (typeof document.selection != "undefined") {
1574 if (document.selection.type == "Text") {
1575 text = document.selection.createRange().textText;
1576 }
1577 }
1578
1579 return text.stripTags();
1580 }
1581
1582 function openUrlPopup(url) {
1583 const w = window.open("");
1584
1585 w.opener = null;
1586 w.location = url;
1587 }
1588 function openArticlePopup(id) {
1589 const w = window.open("",
1590 "ttrss_article_popup",
1591 "height=900,width=900,resizable=yes,status=no,location=no,menubar=no,directories=no,scrollbars=yes,toolbar=no");
1592
1593 w.opener = null;
1594 w.location = "backend.php?op=article&method=view&mode=raw&html=1&zoom=1&id=" + id + "&csrf_token=" + getInitParam("csrf_token");
1595 }