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