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