]> git.wh0rd.org - tt-rss.git/blob - js/functions.js
remove duplicated code from hotkey actions handler
[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 remove_splash();
482
483 }
484
485 function remove_splash() {
486 Element.hide("overlay");
487 }
488
489 function strip_tags(s) {
490 return s.replace(/<\/?[^>]+(>|$)/g, "");
491 }
492
493 function hotkey_prefix_timeout() {
494
495 const date = new Date();
496 const ts = Math.round(date.getTime() / 1000);
497
498 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
499 console.log("hotkey_prefix seems to be stuck, aborting");
500 hotkey_prefix_pressed = false;
501 hotkey_prefix = false;
502 Element.hide('cmdline');
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 switch (k) {
1091 case "label_base_index":
1092 _label_base_index = parseInt(params[k])
1093 break;
1094 case "hotkeys":
1095 // filter mnemonic definitions (used for help panel) from hotkeys map
1096 // i.e. *(191)|Ctrl-/ -> *(191)
1097
1098 const tmp = [];
1099 for (const sequence in params[k][1]) {
1100 const filtered = sequence.replace(/\|.*$/, "");
1101 tmp[filtered] = params[k][1][sequence];
1102 }
1103
1104 params[k][1] = tmp;
1105 break;
1106 }
1107
1108 console.log("IP:", k, "=>", params[k]);
1109 }
1110
1111 init_params = params;
1112
1113 // PluginHost might not be available on non-index pages
1114 window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params);
1115 }
1116
1117 init_second_stage();
1118 }
1119
1120 function genUrlChangeKey(feed, is_cat) {
1121 const ok = confirm(__("Generate new syndication address for this feed?"));
1122
1123 if (ok) {
1124
1125 notify_progress("Trying to change address...", true);
1126
1127 const query = { op: "pref-feeds", method: "regenFeedKey", id: feed, is_cat: is_cat };
1128
1129 xhrJson("backend.php", query, (reply) => {
1130 const new_link = reply.link;
1131 const e = $('gen_feed_url');
1132
1133 if (new_link) {
1134 e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/,
1135 "&amp;key=" + new_link);
1136
1137 e.href = e.href.replace(/\&key=.*$/,
1138 "&key=" + new_link);
1139
1140 new Effect.Highlight(e);
1141
1142 notify('');
1143
1144 } else {
1145 notify_error("Could not change feed URL.");
1146 }
1147 });
1148 }
1149 return false;
1150 }
1151
1152 // mode = all, none, invert
1153 function selectTableRows(id, mode) {
1154 const rows = $(id).rows;
1155
1156 for (let i = 0; i < rows.length; i++) {
1157 const row = rows[i];
1158 let cb = false;
1159 let dcb = false;
1160
1161 if (row.id && row.className) {
1162 const bare_id = row.id.replace(/^[A-Z]*?-/, "");
1163 const inputs = rows[i].getElementsByTagName("input");
1164
1165 for (let j = 0; j < inputs.length; j++) {
1166 const input = inputs[j];
1167
1168 if (input.getAttribute("type") == "checkbox" &&
1169 input.id.match(bare_id)) {
1170
1171 cb = input;
1172 dcb = dijit.getEnclosingWidget(cb);
1173 break;
1174 }
1175 }
1176
1177 if (cb || dcb) {
1178 const issel = row.hasClassName("Selected");
1179
1180 if (mode == "all" && !issel) {
1181 row.addClassName("Selected");
1182 cb.checked = true;
1183 if (dcb) dcb.set("checked", true);
1184 } else if (mode == "none" && issel) {
1185 row.removeClassName("Selected");
1186 cb.checked = false;
1187 if (dcb) dcb.set("checked", false);
1188
1189 } else if (mode == "invert") {
1190
1191 if (issel) {
1192 row.removeClassName("Selected");
1193 cb.checked = false;
1194 if (dcb) dcb.set("checked", false);
1195 } else {
1196 row.addClassName("Selected");
1197 cb.checked = true;
1198 if (dcb) dcb.set("checked", true);
1199 }
1200 }
1201 }
1202 }
1203 }
1204
1205 }
1206
1207 function getSelectedTableRowIds(id) {
1208 const rows = [];
1209
1210 const elem_rows = $(id).rows;
1211
1212 for (let i = 0; i < elem_rows.length; i++) {
1213 if (elem_rows[i].hasClassName("Selected")) {
1214 const bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1215 rows.push(bare_id);
1216 }
1217 }
1218
1219 return rows;
1220 }
1221
1222 function editFeed(feed) {
1223 if (feed <= 0)
1224 return alert(__("You can't edit this kind of feed."));
1225
1226 const query = "backend.php?op=pref-feeds&method=editfeed&id=" +
1227 param_escape(feed);
1228
1229 console.log(query);
1230
1231 if (dijit.byId("filterEditDlg"))
1232 dijit.byId("filterEditDlg").destroyRecursive();
1233
1234 if (dijit.byId("feedEditDlg"))
1235 dijit.byId("feedEditDlg").destroyRecursive();
1236
1237 const dialog = new dijit.Dialog({
1238 id: "feedEditDlg",
1239 title: __("Edit Feed"),
1240 style: "width: 600px",
1241 execute: function() {
1242 if (this.validate()) {
1243 notify_progress("Saving data...", true);
1244
1245 xhrPost("backend.php", dialog.attr('value'), (transport) => {
1246 dialog.hide();
1247 notify('');
1248 updateFeedList();
1249 });
1250 }
1251 },
1252 href: query});
1253
1254 dialog.show();
1255 }
1256
1257 function feedBrowser() {
1258 const query = "backend.php?op=feeds&method=feedBrowser";
1259
1260 if (dijit.byId("feedAddDlg"))
1261 dijit.byId("feedAddDlg").hide();
1262
1263 if (dijit.byId("feedBrowserDlg"))
1264 dijit.byId("feedBrowserDlg").destroyRecursive();
1265
1266 const dialog = new dijit.Dialog({
1267 id: "feedBrowserDlg",
1268 title: __("More Feeds"),
1269 style: "width: 600px",
1270 getSelectedFeedIds: function () {
1271 const list = $$("#browseFeedList li[id*=FBROW]");
1272 const selected = [];
1273
1274 list.each(function (child) {
1275 const id = child.id.replace("FBROW-", "");
1276
1277 if (child.hasClassName('Selected')) {
1278 selected.push(id);
1279 }
1280 });
1281
1282 return selected;
1283 },
1284 getSelectedFeeds: function () {
1285 const list = $$("#browseFeedList li.Selected");
1286 const selected = [];
1287
1288 list.each(function (child) {
1289 const title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1290 const url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1291
1292 selected.push([title, url]);
1293
1294 });
1295
1296 return selected;
1297 },
1298
1299 subscribe: function () {
1300 const mode = this.attr('value').mode;
1301 let selected = [];
1302
1303 if (mode == "1")
1304 selected = this.getSelectedFeeds();
1305 else
1306 selected = this.getSelectedFeedIds();
1307
1308 if (selected.length > 0) {
1309 dijit.byId("feedBrowserDlg").hide();
1310
1311 notify_progress("Loading, please wait...", true);
1312
1313 const query = { op: "rpc", method: "massSubscribe",
1314 payload: JSON.stringify(selected), mode: mode };
1315
1316 xhrPost("backend.php", query, () => {
1317 notify('');
1318 updateFeedList();
1319 });
1320
1321 } else {
1322 alert(__("No feeds are selected."));
1323 }
1324
1325 },
1326 update: function () {
1327 Element.show('feed_browser_spinner');
1328
1329 xhrPost("backend.php", dialog.attr("value"), (transport) => {
1330 notify('');
1331
1332 Element.hide('feed_browser_spinner');
1333
1334 const reply = JSON.parse(transport.responseText);
1335 const mode = reply['mode'];
1336
1337 if ($("browseFeedList") && reply['content']) {
1338 $("browseFeedList").innerHTML = reply['content'];
1339 }
1340
1341 dojo.parser.parse("browseFeedList");
1342
1343 if (mode == 2) {
1344 Element.show(dijit.byId('feed_archive_remove').domNode);
1345 } else {
1346 Element.hide(dijit.byId('feed_archive_remove').domNode);
1347 }
1348 });
1349 },
1350 removeFromArchive: function () {
1351 const selected = this.getSelectedFeedIds();
1352
1353 if (selected.length > 0) {
1354
1355 const pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1356
1357 if (confirm(pr)) {
1358 Element.show('feed_browser_spinner');
1359
1360 const query = { op: "rpc", method: "remarchive", ids: selected.toString() };
1361
1362 xhrPost("backend.php", query, () => {
1363 dialog.update();
1364 });
1365 }
1366 }
1367 },
1368 execute: function () {
1369 if (this.validate()) {
1370 this.subscribe();
1371 }
1372 },
1373 href: query
1374 });
1375
1376 dialog.show();
1377 }
1378
1379 function showFeedsWithErrors() {
1380 const query = "backend.php?op=pref-feeds&method=feedsWithErrors";
1381
1382 if (dijit.byId("errorFeedsDlg"))
1383 dijit.byId("errorFeedsDlg").destroyRecursive();
1384
1385 const dialog = new dijit.Dialog({
1386 id: "errorFeedsDlg",
1387 title: __("Feeds with update errors"),
1388 style: "width: 600px",
1389 getSelectedFeeds: function() {
1390 return getSelectedTableRowIds("prefErrorFeedList");
1391 },
1392 removeSelected: function() {
1393 const sel_rows = this.getSelectedFeeds();
1394
1395 console.log(sel_rows);
1396
1397 if (sel_rows.length > 0) {
1398 const ok = confirm(__("Remove selected feeds?"));
1399
1400 if (ok) {
1401 notify_progress("Removing selected feeds...", true);
1402
1403 const query = { op: "pref-feeds", method: "remove",
1404 ids: sel_rows.toString() };
1405
1406 xhrPost("backend.php", query, () => {
1407 notify('');
1408 dialog.hide();
1409 updateFeedList();
1410 });
1411 }
1412
1413 } else {
1414 alert(__("No feeds are selected."));
1415 }
1416 },
1417 execute: function() {
1418 if (this.validate()) {
1419 //
1420 }
1421 },
1422 href: query});
1423
1424 dialog.show();
1425 }
1426
1427 function get_timestamp() {
1428 const date = new Date();
1429 return Math.round(date.getTime() / 1000);
1430 }
1431
1432 function helpDialog(topic) {
1433 const query = "backend.php?op=backend&method=help&topic=" + param_escape(topic);
1434
1435 if (dijit.byId("helpDlg"))
1436 dijit.byId("helpDlg").destroyRecursive();
1437
1438 const dialog = new dijit.Dialog({
1439 id: "helpDlg",
1440 title: __("Help"),
1441 style: "width: 600px",
1442 href: query,
1443 });
1444
1445 dialog.show();
1446 }
1447
1448 function htmlspecialchars_decode (string, quote_style) {
1449 // http://kevin.vanzonneveld.net
1450 // + original by: Mirek Slugen
1451 // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1452 // + bugfixed by: Mateusz "loonquawl" Zalega
1453 // + input by: ReverseSyntax
1454 // + input by: Slawomir Kaniecki
1455 // + input by: Scott Cariss
1456 // + input by: Francois
1457 // + bugfixed by: Onno Marsman
1458 // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1459 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1460 // + input by: Ratheous
1461 // + input by: Mailfaker (http://www.weedem.fr/)
1462 // + reimplemented by: Brett Zamir (http://brett-zamir.me)
1463 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1464 // * example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
1465 // * returns 1: '<p>this -> &quot;</p>'
1466 // * example 2: htmlspecialchars_decode("&amp;quot;");
1467 // * returns 2: '&quot;'
1468 let optTemp = 0,
1469 i = 0,
1470 noquotes = false;
1471 if (typeof quote_style === 'undefined') {
1472 quote_style = 2;
1473 }
1474 string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
1475 const OPTS = {
1476 'ENT_NOQUOTES': 0,
1477 'ENT_HTML_QUOTE_SINGLE': 1,
1478 'ENT_HTML_QUOTE_DOUBLE': 2,
1479 'ENT_COMPAT': 2,
1480 'ENT_QUOTES': 3,
1481 'ENT_IGNORE': 4
1482 };
1483 if (quote_style === 0) {
1484 noquotes = true;
1485 }
1486 if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
1487 quote_style = [].concat(quote_style);
1488 for (i = 0; i < quote_style.length; i++) {
1489 // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1490 if (OPTS[quote_style[i]] === 0) {
1491 noquotes = true;
1492 } else if (OPTS[quote_style[i]]) {
1493 optTemp = optTemp | OPTS[quote_style[i]];
1494 }
1495 }
1496 quote_style = optTemp;
1497 }
1498 if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
1499 string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
1500 // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
1501 }
1502 if (!noquotes) {
1503 string = string.replace(/&quot;/g, '"');
1504 }
1505 // Put this in last place to avoid escape being double-decoded
1506 string = string.replace(/&amp;/g, '&');
1507
1508 return string;
1509 }
1510
1511
1512 function label_to_feed_id(label) {
1513 return _label_base_index - 1 - Math.abs(label);
1514 }
1515
1516 function feed_to_label_id(feed) {
1517 return _label_base_index - 1 + Math.abs(feed);
1518 }
1519
1520 // http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac
1521
1522 function getSelectionText() {
1523 let text = "";
1524
1525 if (typeof window.getSelection != "undefined") {
1526 const sel = window.getSelection();
1527 if (sel.rangeCount) {
1528 const container = document.createElement("div");
1529 for (let i = 0, len = sel.rangeCount; i < len; ++i) {
1530 container.appendChild(sel.getRangeAt(i).cloneContents());
1531 }
1532 text = container.innerHTML;
1533 }
1534 } else if (typeof document.selection != "undefined") {
1535 if (document.selection.type == "Text") {
1536 text = document.selection.createRange().textText;
1537 }
1538 }
1539
1540 return text.stripTags();
1541 }
1542
1543 function openUrlPopup(url) {
1544 const w = window.open("");
1545
1546 w.opener = null;
1547 w.location = url;
1548 }
1549 function openArticlePopup(id) {
1550 const w = window.open("",
1551 "ttrss_article_popup",
1552 "height=900,width=900,resizable=yes,status=no,location=no,menubar=no,directories=no,scrollbars=yes,toolbar=no");
1553
1554 w.opener = null;
1555 w.location = "backend.php?op=article&method=view&mode=raw&html=1&zoom=1&id=" + id + "&csrf_token=" + getInitParam("csrf_token");
1556 }
1557
1558 function keyevent_to_action(e) {
1559
1560 const hotkeys_map = getInitParam("hotkeys");
1561 const keycode = e.which;
1562 const keychar = String.fromCharCode(keycode).toLowerCase();
1563
1564 if (keycode == 27) { // escape and drop prefix
1565 hotkey_prefix = false;
1566 }
1567
1568 if (keycode == 16 || keycode == 17) return; // ignore lone shift / ctrl
1569
1570 if (!hotkey_prefix && hotkeys_map[0].indexOf(keychar) != -1) {
1571
1572 const date = new Date();
1573 const ts = Math.round(date.getTime() / 1000);
1574
1575 hotkey_prefix = keychar;
1576 hotkey_prefix_pressed = ts;
1577
1578 $("cmdline").innerHTML = keychar;
1579 Element.show("cmdline");
1580
1581 e.stopPropagation();
1582
1583 return false;
1584 }
1585
1586 Element.hide("cmdline");
1587
1588 let hotkey_name = keychar.search(/[a-zA-Z0-9]/) != -1 ? keychar : "(" + keycode + ")";
1589
1590 // ensure ^*char notation
1591 if (e.shiftKey) hotkey_name = "*" + hotkey_name;
1592 if (e.ctrlKey) hotkey_name = "^" + hotkey_name;
1593 if (e.altKey) hotkey_name = "+" + hotkey_name;
1594 if (e.metaKey) hotkey_name = "%" + hotkey_name;
1595
1596 const hotkey_full = hotkey_prefix ? hotkey_prefix + " " + hotkey_name : hotkey_name;
1597 hotkey_prefix = false;
1598
1599 let action_name = false;
1600
1601 for (const sequence in hotkeys_map[1]) {
1602 if (sequence == hotkey_full) {
1603 action_name = hotkeys_map[1][sequence];
1604 break;
1605 }
1606 }
1607
1608 console.log('keyevent_to_action', hotkey_full, '=>', action_name);
1609
1610 return action_name;
1611 }