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