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