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