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