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