1 var loading_progress = 0;
2 var sanity_check_done = false;
4 var _label_base_index = -1024;
5 var notify_hide_timerid = false;
7 Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
8 function (callOriginal, options) {
10 if (getInitParam("csrf_token") != undefined) {
11 Object.extend(options, options || { });
13 if (Object.isString(options.parameters))
14 options.parameters = options.parameters.toQueryParams();
15 else if (Object.isHash(options.parameters))
16 options.parameters = options.parameters.toObject();
18 options.parameters["csrf_token"] = getInitParam("csrf_token");
21 return callOriginal(options);
25 /* add method to remove element from array */
27 Array.prototype.remove = function(s) {
28 for (var i=0; i < this.length; i++) {
29 if (s == this[i]) this.splice(i, 1);
33 /* create console.log if it doesn't exist */
35 if (!window.console) console = {};
36 console.log = console.log || function(msg) { };
37 console.warn = console.warn || function(msg) { };
38 console.error = console.error || function(msg) { };
40 function exception_error(location, e, ext_info) {
41 var msg = format_exception_error(location, e);
43 if (!ext_info) ext_info = false;
48 ext_info = JSON.stringify(ext_info);
51 new Ajax.Request("backend.php", {
52 parameters: {op: "rpc", method: "log", logmsg: msg},
53 onComplete: function (transport) {
54 console.log(transport.responseText);
58 console.log("Exception while trying to log the error.");
62 msg += "<p>"+ __("The error will be reported to the configured log destination.") +
65 var content = "<div class=\"fatalError\">" +
66 "<pre>" + msg + "</pre>";
68 content += "<form name=\"exceptionForm\" id=\"exceptionForm\" target=\"_blank\" "+
69 "action=\"http://tt-rss.org/report.php\" method=\"POST\">";
71 content += "<textarea style=\"display : none\" name=\"message\">" + msg + "</textarea>";
72 content += "<textarea style=\"display : none\" name=\"params\">N/A</textarea>";
75 content += "<div><b>Additional information:</b></div>" +
76 "<textarea name=\"xinfo\" readonly=\"1\">" + ext_info + "</textarea>";
79 content += "<div><b>Stack trace:</b></div>" +
80 "<textarea name=\"stack\" readonly=\"1\">" + e.stack + "</textarea>";
86 content += "<div class='dlgButtons'>";
88 content += "<button dojoType=\"dijit.form.Button\""+
89 "onclick=\"dijit.byId('exceptionDlg').report()\">" +
90 __('Report to tt-rss.org') + "</button> ";
91 content += "<button dojoType=\"dijit.form.Button\" "+
92 "onclick=\"dijit.byId('exceptionDlg').hide()\">" +
93 __('Close') + "</button>";
96 if (dijit.byId("exceptionDlg"))
97 dijit.byId("exceptionDlg").destroyRecursive();
99 var dialog = new dijit.Dialog({
101 title: "Unhandled exception",
102 style: "width: 600px",
104 if (confirm(__("Are you sure to report this exception to tt-rss.org? The report will include information about your web browser and tt-rss configuration. Your IP will be saved in the database."))) {
106 document.forms['exceptionForm'].params.value = $H({
107 browserName: navigator.appName,
108 browserVersion: navigator.appVersion,
109 browserPlatform: navigator.platform,
110 browserCookies: navigator.cookieEnabled,
111 ttrssVersion: __ttrss_version,
112 initParams: JSON.stringify(init_params),
115 document.forms['exceptionForm'].submit();
124 console.log("Exception while trying to report an exception. Oh boy.");
126 console.log("Original exception:");
129 msg += "\n\nAdditional exception caught while trying to show the error dialog.\n\n" + format_exception_error('exception_error', ei);
132 new Ajax.Request("backend.php", {
133 parameters: {op: "rpc", method: "log", logmsg: msg},
134 onComplete: function (transport) {
135 console.log(transport.responseText);
139 console.log("Third exception while trying to log the error! Seriously?");
143 msg += "\n\nThe error will be reported to the configured log destination.";
150 function format_exception_error(location, e) {
154 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
156 msg = "Exception: " + e.name + ", " + e.message +
157 "\nFunction: " + location + "()" +
158 "\nLocation: " + base_fname + ":" + e.lineNumber;
160 } else if (e.description) {
161 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
163 msg = "Exception: " + e + "\nFunction: " + location + "()";
166 console.error("EXCEPTION: " + msg);
171 function param_escape(arg) {
172 if (typeof encodeURIComponent != 'undefined')
173 return encodeURIComponent(arg);
178 function param_unescape(arg) {
179 if (typeof decodeURIComponent != 'undefined')
180 return decodeURIComponent(arg);
182 return unescape(arg);
185 function notify_real(msg, no_hide, n_type) {
191 if (notify_hide_timerid) {
192 window.clearTimeout(notify_hide_timerid);
196 if (n.hasClassName("visible")) {
197 notify_hide_timerid = window.setTimeout(function() {
198 n.removeClassName("visible") }, 0);
212 msg = "<span class=\"msg\"> " + __(msg) + "</span>";
215 msg = "<span><img src='images/indicator_white.gif'></span>" + msg;
217 } else if (n_type == 3) {
218 msg = "<span><img src='images/alert.png'></span>" + msg;
219 } else if (n_type == 4) {
220 msg = "<span><img src='images/information.png'></span>" + msg;
223 msg += " <span><img src=\"images/cross.png\" class=\"close\" title=\"" +
224 __("Click to close") + "\" onclick=\"notify('')\"></span>";
228 window.setTimeout(function() {
231 n.className = "notify notify_progress visible";
232 } else if (n_type == 3) {
233 n.className = "notify notify_error visible";
234 msg = "<span><img src='images/alert.png'></span>" + msg;
235 } else if (n_type == 4) {
236 n.className = "notify notify_info visible";
238 n.className = "notify visible";
242 notify_hide_timerid = window.setTimeout(function() {
243 n.removeClassName("visible") }, 5*1000);
250 function notify(msg, no_hide) {
251 notify_real(msg, no_hide, 1);
254 function notify_progress(msg, no_hide) {
255 notify_real(msg, no_hide, 2);
258 function notify_error(msg, no_hide) {
259 notify_real(msg, no_hide, 3);
263 function notify_info(msg, no_hide) {
264 notify_real(msg, no_hide, 4);
267 function setCookie(name, value, lifetime, path, domain, secure) {
273 d.setTime(d.getTime() + (lifetime * 1000));
276 console.log("setCookie: " + name + " => " + value + ": " + d);
278 int_setCookie(name, value, d, path, domain, secure);
282 function int_setCookie(name, value, expires, path, domain, secure) {
283 document.cookie= name + "=" + escape(value) +
284 ((expires) ? "; expires=" + expires.toGMTString() : "") +
285 ((path) ? "; path=" + path : "") +
286 ((domain) ? "; domain=" + domain : "") +
287 ((secure) ? "; secure" : "");
290 function delCookie(name, path, domain) {
291 if (getCookie(name)) {
292 document.cookie = name + "=" +
293 ((path) ? ";path=" + path : "") +
294 ((domain) ? ";domain=" + domain : "" ) +
295 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
300 function getCookie(name) {
302 var dc = document.cookie;
303 var prefix = name + "=";
304 var begin = dc.indexOf("; " + prefix);
306 begin = dc.indexOf(prefix);
307 if (begin != 0) return null;
312 var end = document.cookie.indexOf(";", begin);
316 return unescape(dc.substring(begin + prefix.length, end));
319 function gotoPreferences() {
320 document.location.href = "prefs.php";
323 function gotoLogout() {
324 document.location.href = "backend.php?op=logout";
327 function gotoMain() {
328 document.location.href = "index.php";
331 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
332 * * @author Sundar Dorai-Raj
333 * * Email: sdoraira@vt.edu
334 * * This program is free software; you can redistribute it and/or
335 * * modify it under the terms of the GNU General Public License
336 * * as published by the Free Software Foundation; either version 2
337 * * of the License, or (at your option) any later version,
338 * * provided that any use properly credits the author.
339 * * This program is distributed in the hope that it will be useful,
340 * * but WITHOUT ANY WARRANTY; without even the implied warranty of
341 * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
342 * * GNU General Public License for more details at http://www.gnu.org * * */
344 var numbers=".0123456789";
345 function isNumeric(x) {
346 // is x a String or a character?
348 // remove negative sign
350 for(var j=0;j<x.length;j++) {
351 // call isNumeric recursively for each character
352 number=isNumeric(x.substring(j,j+1));
353 if(!number) return number;
358 // if x is number return true
359 if(numbers.indexOf(x)>=0) return true;
365 function toggleSelectRowById(sender, id) {
367 return toggleSelectRow(sender, row);
370 function toggleSelectListRow(sender) {
371 var row = sender.parentNode;
372 return toggleSelectRow(sender, row);
375 /* this is for dijit Checkbox */
376 function toggleSelectListRow2(sender) {
377 var row = sender.domNode.parentNode;
378 return toggleSelectRow(sender, row);
381 /* this is for dijit Checkbox */
382 function toggleSelectRow2(sender, row, is_cdm) {
386 row = sender.domNode.parentNode.parentNode;
388 row = sender.domNode.parentNode.parentNode.parentNode; // oh ffs
390 if (sender.checked && !row.hasClassName('Selected'))
391 row.addClassName('Selected');
393 row.removeClassName('Selected');
395 if (typeof updateSelectedPrompt != undefined)
396 updateSelectedPrompt();
400 function toggleSelectRow(sender, row) {
402 if (!row) row = sender.parentNode.parentNode;
404 if (sender.checked && !row.hasClassName('Selected'))
405 row.addClassName('Selected');
407 row.removeClassName('Selected');
409 if (typeof updateSelectedPrompt != undefined)
410 updateSelectedPrompt();
413 function checkboxToggleElement(elem, id) {
415 Effect.Appear(id, {duration : 0.5});
417 Effect.Fade(id, {duration : 0.5});
421 function dropboxSelect(e, v) {
422 for (var i = 0; i < e.length; i++) {
423 if (e[i].value == v) {
430 function getURLParam(param){
431 return String(window.location.href).parseQuery()[param];
434 function closeInfoBox(cleanup) {
436 dialog = dijit.byId("infoBox");
438 if (dialog) dialog.hide();
441 //exception_error("closeInfoBox", e);
447 function displayDlg(title, id, param, callback) {
449 notify_progress("Loading, please wait...", true);
451 var query = "?op=dlg&method=" +
452 param_escape(id) + "¶m=" + param_escape(param);
454 new Ajax.Request("backend.php", {
456 onComplete: function (transport) {
457 infobox_callback2(transport, title);
458 if (callback) callback(transport);
464 function infobox_callback2(transport, title) {
468 if (dijit.byId("infoBox")) {
469 dialog = dijit.byId("infoBox");
472 //console.log("infobox_callback2");
475 var content = transport.responseText;
478 dialog = new dijit.Dialog({
481 style: "width: 600px",
482 onCancel: function() {
485 onExecute: function() {
488 onClose: function() {
493 dialog.attr('title', title);
494 dialog.attr('content', content);
501 exception_error("infobox_callback2", e);
505 function getInitParam(key) {
506 return init_params[key];
509 function setInitParam(key, value) {
510 init_params[key] = value;
513 function fatalError(code, msg, ext_info) {
517 window.location.href = "index.php";
518 } else if (code == 5) {
519 window.location.href = "public.php?op=dbupdate";
522 if (msg == "") msg = "Unknown error";
525 if (ext_info.responseText) {
526 ext_info = ext_info.responseText;
530 if (ERRORS && ERRORS[code] && !msg) {
534 var content = "<div><b>Error code:</b> " + code + "</div>" +
535 "<p>" + msg + "</p>";
538 content = content + "<div><b>Additional information:</b></div>" +
539 "<textarea style='width: 100%' readonly=\"1\">" +
540 ext_info + "</textarea>";
543 var dialog = new dijit.Dialog({
544 title: "Fatal error",
545 style: "width: 600px",
555 exception_error("fatalError", e);
559 function filterDlgCheckAction(sender) {
563 var action = sender.value;
565 var action_param = $("filterDlg_paramBox");
568 console.log("filterDlgCheckAction: can't find action param box!");
572 // if selected action supports parameters, enable params field
573 if (action == 4 || action == 6 || action == 7 || action == 9) {
574 new Effect.Appear(action_param, {duration : 0.5});
576 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
577 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
578 Element.hide(dijit.byId("filterDlg_actionParamPlugin").domNode);
581 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
582 } else if (action == 9) {
583 Element.show(dijit.byId("filterDlg_actionParamPlugin").domNode);
585 Element.show(dijit.byId("filterDlg_actionParam").domNode);
589 Element.hide(action_param);
593 exception_error("filterDlgCheckAction", e);
599 function explainError(code) {
600 return displayDlg(__("Error explained"), "explainError", code);
603 function loading_set_progress(p) {
605 loading_progress += p;
607 if (dijit.byId("loading_bar"))
608 dijit.byId("loading_bar").update({progress: loading_progress});
610 if (loading_progress >= 90)
614 exception_error("loading_set_progress", e);
618 function remove_splash() {
620 if (Element.visible("overlay")) {
621 console.log("about to remove splash, OMG!");
622 Element.hide("overlay");
623 console.log("removed splash!");
627 function transport_error_check(transport) {
629 if (transport.responseXML) {
630 var error = transport.responseXML.getElementsByTagName("error")[0];
633 var code = error.getAttribute("error-code");
634 var msg = error.getAttribute("error-msg");
636 fatalError(code, msg);
642 exception_error("check_for_error_xml", e);
647 function strip_tags(s) {
648 return s.replace(/<\/?[^>]+(>|$)/g, "");
651 function truncate_string(s, length) {
652 if (!length) length = 30;
653 var tmp = s.substring(0, length);
654 if (s.length > length) tmp += "…";
658 function hotkey_prefix_timeout() {
661 var date = new Date();
662 var ts = Math.round(date.getTime() / 1000);
664 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
665 console.log("hotkey_prefix seems to be stuck, aborting");
666 hotkey_prefix_pressed = false;
667 hotkey_prefix = false;
668 Element.hide('cmdline');
671 setTimeout("hotkey_prefix_timeout()", 1000);
674 exception_error("hotkey_prefix_timeout", e);
678 function uploadIconHandler(rc) {
682 notify_info("Upload complete.");
683 if (inPreferences()) {
686 setTimeout('updateFeedList(false, false)', 50);
690 notify_error("Upload failed: icon is too big.");
693 notify_error("Upload failed.");
698 exception_error("uploadIconHandler", e);
702 function removeFeedIcon(id) {
706 if (confirm(__("Remove stored feed icon?"))) {
707 var query = "backend.php?op=pref-feeds&method=removeicon&feed_id=" + param_escape(id);
711 notify_progress("Removing feed icon...", true);
713 new Ajax.Request("backend.php", {
715 onComplete: function(transport) {
716 notify_info("Feed icon removed.");
717 if (inPreferences()) {
720 setTimeout('updateFeedList(false, false)', 50);
727 exception_error("removeFeedIcon", e);
731 function uploadFeedIcon() {
735 var file = $("icon_file");
737 if (file.value.length == 0) {
738 alert(__("Please select an image file to upload."));
740 if (confirm(__("Upload new icon for this feed?"))) {
741 notify_progress("Uploading, please wait...", true);
749 exception_error("uploadFeedIcon", e);
753 function addLabel(select, callback) {
757 var caption = prompt(__("Please enter label caption:"), "");
759 if (caption != undefined) {
762 alert(__("Can't create label: missing caption."));
766 var query = "?op=pref-labels&method=add&caption=" +
767 param_escape(caption);
770 query += "&output=select";
772 notify_progress("Loading, please wait...", true);
774 if (inPreferences() && !select) active_tab = "labelConfig";
776 new Ajax.Request("backend.php", {
778 onComplete: function(transport) {
781 } else if (inPreferences()) {
791 exception_error("addLabel", e);
795 function quickAddFeed() {
797 var query = "backend.php?op=feeds&method=quickAddFeed";
799 // overlapping widgets
800 if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive();
801 if (dijit.byId("feedAddDlg")) dijit.byId("feedAddDlg").destroyRecursive();
803 var dialog = new dijit.Dialog({
805 title: __("Subscribe to Feed"),
806 style: "width: 600px",
807 execute: function() {
808 if (this.validate()) {
809 console.log(dojo.objectToQuery(this.attr('value')));
811 var feed_url = this.attr('value').feed;
813 Element.show("feed_add_spinner");
815 new Ajax.Request("backend.php", {
816 parameters: dojo.objectToQuery(this.attr('value')),
817 onComplete: function(transport) {
821 var reply = JSON.parse(transport.responseText);
823 Element.hide("feed_add_spinner");
824 alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console."));
825 console.log('quickAddFeed, backend returned:' + transport.responseText);
829 var rc = reply['result'];
832 Element.hide("feed_add_spinner");
836 switch (parseInt(rc['code'])) {
839 notify_info(__("Subscribed to %s").replace("%s", feed_url));
844 alert(__("Specified URL seems to be invalid."));
847 alert(__("Specified URL doesn't seem to contain any feeds."));
852 Element.show("fadd_multiple_notify");
854 var select = dijit.byId("feedDlg_feedContainerSelect");
856 while (select.getOptions().length > 0)
857 select.removeOption(0);
859 select.addOption({value: '', label: __("Expand to select feed")});
862 for (var feedUrl in feeds) {
863 select.addOption({value: feedUrl, label: feeds[feedUrl]});
867 Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
871 alert(__("Couldn't download the specified URL: %s").
872 replace("%s", rc['message']));
875 alert(__("XML validation failed: %s").
876 replace("%s", rc['message']));
880 alert(__("You are already subscribed to this feed."));
885 exception_error("subscribeToFeed", e, transport);
896 exception_error("quickAddFeed", e);
900 function createNewRuleElement(parentNode, replaceNode) {
902 var form = document.forms["filter_new_rule_form"];
904 form.reg_exp.value = form.reg_exp.value.replace(/(<([^>]+)>)/ig,"");
906 var query = "backend.php?op=pref-filters&method=printrulename&rule="+
907 param_escape(dojo.formToJson(form));
911 new Ajax.Request("backend.php", {
913 onComplete: function (transport) {
915 var li = dojo.create("li");
917 var cb = dojo.create("input", { type: "checkbox" }, li);
919 new dijit.form.CheckBox({
920 onChange: function() {
921 toggleSelectListRow2(this) },
924 dojo.create("input", { type: "hidden",
926 value: dojo.formToJson(form) }, li);
928 dojo.create("span", {
929 onclick: function() {
930 dijit.byId('filterEditDlg').editRule(this);
932 innerHTML: transport.responseText }, li);
935 parentNode.replaceChild(li, replaceNode);
937 parentNode.appendChild(li);
940 exception_error("createNewRuleElement", e);
944 exception_error("createNewRuleElement", e);
948 function createNewActionElement(parentNode, replaceNode) {
950 var form = document.forms["filter_new_action_form"];
952 if (form.action_id.value == 7) {
953 form.action_param.value = form.action_param_label.value;
954 } else if (form.action_id.value == 9) {
955 form.action_param.value = form.action_param_plugin.value;
958 var query = "backend.php?op=pref-filters&method=printactionname&action="+
959 param_escape(dojo.formToJson(form));
963 new Ajax.Request("backend.php", {
965 onComplete: function (transport) {
967 var li = dojo.create("li");
969 var cb = dojo.create("input", { type: "checkbox" }, li);
971 new dijit.form.CheckBox({
972 onChange: function() {
973 toggleSelectListRow2(this) },
976 dojo.create("input", { type: "hidden",
978 value: dojo.formToJson(form) }, li);
980 dojo.create("span", {
981 onclick: function() {
982 dijit.byId('filterEditDlg').editAction(this);
984 innerHTML: transport.responseText }, li);
987 parentNode.replaceChild(li, replaceNode);
989 parentNode.appendChild(li);
993 exception_error("createNewActionElement", e);
997 exception_error("createNewActionElement", e);
1002 function addFilterRule(replaceNode, ruleStr) {
1004 if (dijit.byId("filterNewRuleDlg"))
1005 dijit.byId("filterNewRuleDlg").destroyRecursive();
1007 var query = "backend.php?op=pref-filters&method=newrule&rule=" +
1008 param_escape(ruleStr);
1010 var rule_dlg = new dijit.Dialog({
1011 id: "filterNewRuleDlg",
1012 title: ruleStr ? __("Edit rule") : __("Add rule"),
1013 style: "width: 600px",
1014 execute: function() {
1015 if (this.validate()) {
1016 createNewRuleElement($("filterDlg_Matches"), replaceNode);
1024 exception_error("addFilterRule", e);
1028 function addFilterAction(replaceNode, actionStr) {
1030 if (dijit.byId("filterNewActionDlg"))
1031 dijit.byId("filterNewActionDlg").destroyRecursive();
1033 var query = "backend.php?op=pref-filters&method=newaction&action=" +
1034 param_escape(actionStr);
1036 var rule_dlg = new dijit.Dialog({
1037 id: "filterNewActionDlg",
1038 title: actionStr ? __("Edit action") : __("Add action"),
1039 style: "width: 600px",
1040 execute: function() {
1041 if (this.validate()) {
1042 createNewActionElement($("filterDlg_Actions"), replaceNode);
1050 exception_error("addFilterAction", e);
1054 function quickAddFilter() {
1057 if (!inPreferences()) {
1058 query = "backend.php?op=pref-filters&method=newfilter&feed=" +
1059 param_escape(getActiveFeedId()) + "&is_cat=" +
1060 param_escape(activeFeedIsCat());
1062 query = "backend.php?op=pref-filters&method=newfilter";
1067 if (dijit.byId("feedEditDlg"))
1068 dijit.byId("feedEditDlg").destroyRecursive();
1070 if (dijit.byId("filterEditDlg"))
1071 dijit.byId("filterEditDlg").destroyRecursive();
1073 dialog = new dijit.Dialog({
1074 id: "filterEditDlg",
1075 title: __("Create Filter"),
1076 style: "width: 600px",
1078 var query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test";
1080 if (dijit.byId("filterTestDlg"))
1081 dijit.byId("filterTestDlg").destroyRecursive();
1083 var test_dlg = new dijit.Dialog({
1084 id: "filterTestDlg",
1085 title: "Test Filter",
1086 style: "width: 600px",
1091 selectRules: function(select) {
1092 $$("#filterDlg_Matches input[type=checkbox]").each(function(e) {
1095 e.parentNode.addClassName("Selected");
1097 e.parentNode.removeClassName("Selected");
1100 selectActions: function(select) {
1101 $$("#filterDlg_Actions input[type=checkbox]").each(function(e) {
1105 e.parentNode.addClassName("Selected");
1107 e.parentNode.removeClassName("Selected");
1111 editRule: function(e) {
1112 var li = e.parentNode;
1113 var rule = li.getElementsByTagName("INPUT")[1].value;
1114 addFilterRule(li, rule);
1116 editAction: function(e) {
1117 var li = e.parentNode;
1118 var action = li.getElementsByTagName("INPUT")[1].value;
1119 addFilterAction(li, action);
1121 addAction: function() { addFilterAction(); },
1122 addRule: function() { addFilterRule(); },
1123 deleteAction: function() {
1124 $$("#filterDlg_Actions li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1126 deleteRule: function() {
1127 $$("#filterDlg_Matches li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1129 execute: function() {
1130 if (this.validate()) {
1132 var query = dojo.formToQuery("filter_new_form");
1136 new Ajax.Request("backend.php", {
1138 onComplete: function (transport) {
1139 if (inPreferences()) {
1149 if (!inPreferences()) {
1150 var selectedText = getSelectionText();
1152 var lh = dojo.connect(dialog, "onLoad", function(){
1153 dojo.disconnect(lh);
1155 if (selectedText != "") {
1157 var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1160 var rule = { reg_exp: selectedText, feed_id: feed_id, filter_type: 1 };
1162 addFilterRule(null, dojo.toJson(rule));
1166 var query = "op=rpc&method=getlinktitlebyid&id=" + getActiveArticleId();
1168 new Ajax.Request("backend.php", {
1170 onComplete: function(transport) {
1171 var reply = JSON.parse(transport.responseText);
1175 if (reply && reply) title = reply.title;
1177 if (title || getActiveFeedId() || activeFeedIsCat()) {
1179 console.log(title + " " + getActiveFeedId());
1181 var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1184 var rule = { reg_exp: title, feed_id: feed_id, filter_type: 1 };
1186 addFilterRule(null, dojo.toJson(rule));
1199 exception_error("quickAddFilter", e);
1203 function resetPubSub(feed_id, title) {
1205 var msg = __("Reset subscription? Tiny Tiny RSS will try to subscribe to the notification hub again on next feed update.").replace("%s", title);
1207 if (title == undefined || confirm(msg)) {
1208 notify_progress("Loading, please wait...");
1210 var query = "?op=pref-feeds&quiet=1&method=resetPubSub&ids=" + feed_id;
1212 new Ajax.Request("backend.php", {
1214 onComplete: function(transport) {
1215 dijit.byId("pubsubReset_Btn").attr('disabled', true);
1216 notify_info("Subscription reset.");
1224 function unsubscribeFeed(feed_id, title) {
1226 var msg = __("Unsubscribe from %s?").replace("%s", title);
1228 if (title == undefined || confirm(msg)) {
1229 notify_progress("Removing feed...");
1231 var query = "?op=pref-feeds&quiet=1&method=remove&ids=" + feed_id;
1233 new Ajax.Request("backend.php", {
1235 onComplete: function(transport) {
1237 if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1239 if (inPreferences()) {
1242 if (feed_id == getActiveFeedId())
1243 setTimeout("viewfeed({feed:-5})", 100);
1245 if (feed_id < 0) updateFeedList();
1255 function backend_sanity_check_callback(transport) {
1259 if (sanity_check_done) {
1260 fatalError(11, "Sanity check request received twice. This can indicate "+
1261 "presence of Firebug or some other disrupting extension. "+
1262 "Please disable it and try again.");
1266 var reply = JSON.parse(transport.responseText);
1269 fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1273 var error_code = reply['error']['code'];
1275 if (error_code && error_code != 0) {
1276 return fatalError(error_code, reply['error']['message']);
1279 console.log("sanity check ok");
1281 var params = reply['init-params'];
1284 console.log('reading init-params...');
1287 console.log("IP: " + k + " => " + JSON.stringify(params[k]));
1288 if (k == "label_base_index") _label_base_index = parseInt(params[k]);
1291 init_params = params;
1293 // PluginHost might not be available on non-index pages
1294 window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params);
1297 sanity_check_done = true;
1299 init_second_stage();
1302 exception_error("backend_sanity_check_callback", e, transport);
1306 /*function has_local_storage() {
1308 return 'sessionStorage' in window && window['sessionStorage'] != null;
1314 function catSelectOnChange(elem) {
1316 /* var value = elem[elem.selectedIndex].value;
1317 var def = elem.getAttribute('default');
1319 if (value == "ADD_CAT") {
1322 dropboxSelect(elem, def);
1324 elem.selectedIndex = 0;
1330 exception_error("catSelectOnChange", e);
1334 function quickAddCat(elem) {
1336 var cat = prompt(__("Please enter category title:"));
1340 var query = "?op=rpc&method=quickAddCat&cat=" + param_escape(cat);
1342 notify_progress("Loading, please wait...", true);
1344 new Ajax.Request("backend.php", {
1346 onComplete: function (transport) {
1347 var response = transport.responseXML;
1348 var select = response.getElementsByTagName("select")[0];
1349 var options = select.getElementsByTagName("option");
1351 dropbox_replace_options(elem, options);
1360 exception_error("quickAddCat", e);
1364 function genUrlChangeKey(feed, is_cat) {
1367 var ok = confirm(__("Generate new syndication address for this feed?"));
1371 notify_progress("Trying to change address...", true);
1373 var query = "?op=pref-feeds&method=regenFeedKey&id=" + param_escape(feed) +
1374 "&is_cat=" + param_escape(is_cat);
1376 new Ajax.Request("backend.php", {
1378 onComplete: function(transport) {
1379 var reply = JSON.parse(transport.responseText);
1380 var new_link = reply.link;
1382 var e = $('gen_feed_url');
1386 e.innerHTML = e.innerHTML.replace(/\&key=.*$/,
1387 "&key=" + new_link);
1389 e.href = e.href.replace(/\&key=.*$/,
1390 "&key=" + new_link);
1392 new Effect.Highlight(e);
1397 notify_error("Could not change feed URL.");
1402 exception_error("genUrlChangeKey", e);
1407 function labelSelectOnChange(elem) {
1409 /* var value = elem[elem.selectedIndex].value;
1410 var def = elem.getAttribute('default');
1412 if (value == "ADD_LABEL") {
1415 dropboxSelect(elem, def);
1417 elem.selectedIndex = 0;
1419 addLabel(elem, function(transport) {
1423 var response = transport.responseXML;
1424 var select = response.getElementsByTagName("select")[0];
1425 var options = select.getElementsByTagName("option");
1427 dropbox_replace_options(elem, options);
1431 exception_error("addLabel", e);
1437 exception_error("labelSelectOnChange", e);
1441 function dropbox_replace_options(elem, options) {
1444 while (elem.hasChildNodes())
1445 elem.removeChild(elem.firstChild);
1449 for (var i = 0; i < options.length; i++) {
1450 var text = options[i].firstChild.nodeValue;
1451 var value = options[i].getAttribute("value");
1453 if (value == undefined) value = text;
1455 var issel = options[i].getAttribute("selected") == "1";
1457 var option = new Option(text, value, issel);
1459 if (options[i].getAttribute("disabled"))
1460 option.setAttribute("disabled", true);
1462 elem.insert(option);
1464 if (issel) sel_idx = i;
1467 // Chrome doesn't seem to just select stuff when you pass new Option(x, y, true)
1468 if (sel_idx >= 0) elem.selectedIndex = sel_idx;
1471 exception_error("dropbox_replace_options", e);
1475 // mode = all, none, invert
1476 function selectTableRows(id, mode) {
1478 var rows = $(id).rows;
1480 for (var i = 0; i < rows.length; i++) {
1485 if (row.id && row.className) {
1486 var bare_id = row.id.replace(/^[A-Z]*?-/, "");
1487 var inputs = rows[i].getElementsByTagName("input");
1489 for (var j = 0; j < inputs.length; j++) {
1490 var input = inputs[j];
1492 if (input.getAttribute("type") == "checkbox" &&
1493 input.id.match(bare_id)) {
1496 dcb = dijit.getEnclosingWidget(cb);
1502 var issel = row.hasClassName("Selected");
1504 if (mode == "all" && !issel) {
1505 row.addClassName("Selected");
1507 if (dcb) dcb.set("checked", true);
1508 } else if (mode == "none" && issel) {
1509 row.removeClassName("Selected");
1511 if (dcb) dcb.set("checked", false);
1513 } else if (mode == "invert") {
1516 row.removeClassName("Selected");
1518 if (dcb) dcb.set("checked", false);
1520 row.addClassName("Selected");
1522 if (dcb) dcb.set("checked", true);
1530 exception_error("selectTableRows", e);
1535 function getSelectedTableRowIds(id) {
1539 var elem_rows = $(id).rows;
1541 for (var i = 0; i < elem_rows.length; i++) {
1542 if (elem_rows[i].hasClassName("Selected")) {
1543 var bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1549 exception_error("getSelectedTableRowIds", e);
1555 function editFeed(feed, event) {
1558 return alert(__("You can't edit this kind of feed."));
1560 var query = "backend.php?op=pref-feeds&method=editfeed&id=" +
1565 if (dijit.byId("filterEditDlg"))
1566 dijit.byId("filterEditDlg").destroyRecursive();
1568 if (dijit.byId("feedEditDlg"))
1569 dijit.byId("feedEditDlg").destroyRecursive();
1571 dialog = new dijit.Dialog({
1573 title: __("Edit Feed"),
1574 style: "width: 600px",
1575 execute: function() {
1576 if (this.validate()) {
1577 // console.log(dojo.objectToQuery(this.attr('value')));
1579 notify_progress("Saving data...", true);
1581 new Ajax.Request("backend.php", {
1582 parameters: dojo.objectToQuery(dialog.attr('value')),
1583 onComplete: function(transport) {
1595 exception_error("editFeed", e);
1599 function feedBrowser() {
1601 var query = "backend.php?op=feeds&method=feedBrowser";
1603 if (dijit.byId("feedAddDlg"))
1604 dijit.byId("feedAddDlg").hide();
1606 if (dijit.byId("feedBrowserDlg"))
1607 dijit.byId("feedBrowserDlg").destroyRecursive();
1609 var dialog = new dijit.Dialog({
1610 id: "feedBrowserDlg",
1611 title: __("More Feeds"),
1612 style: "width: 600px",
1613 getSelectedFeedIds: function() {
1614 var list = $$("#browseFeedList li[id*=FBROW]");
1615 var selected = new Array();
1617 list.each(function(child) {
1618 var id = child.id.replace("FBROW-", "");
1620 if (child.hasClassName('Selected')) {
1627 getSelectedFeeds: function() {
1628 var list = $$("#browseFeedList li.Selected");
1629 var selected = new Array();
1631 list.each(function(child) {
1632 var title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1633 var url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1635 selected.push([title,url]);
1642 subscribe: function() {
1643 var mode = this.attr('value').mode;
1647 selected = this.getSelectedFeeds();
1649 selected = this.getSelectedFeedIds();
1651 if (selected.length > 0) {
1652 dijit.byId("feedBrowserDlg").hide();
1654 notify_progress("Loading, please wait...", true);
1656 // we use dojo.toJson instead of JSON.stringify because
1657 // it somehow escapes everything TWICE, at least in Chrome 9
1659 var query = "?op=rpc&method=massSubscribe&payload="+
1660 param_escape(dojo.toJson(selected)) + "&mode=" + param_escape(mode);
1664 new Ajax.Request("backend.php", {
1666 onComplete: function(transport) {
1672 alert(__("No feeds are selected."));
1676 update: function() {
1677 var query = dojo.objectToQuery(dialog.attr('value'));
1679 Element.show('feed_browser_spinner');
1681 new Ajax.Request("backend.php", {
1683 onComplete: function(transport) {
1686 Element.hide('feed_browser_spinner');
1688 var c = $("browseFeedList");
1690 var reply = JSON.parse(transport.responseText);
1692 var r = reply['content'];
1693 var mode = reply['mode'];
1699 dojo.parser.parse("browseFeedList");
1702 Element.show(dijit.byId('feed_archive_remove').domNode);
1704 Element.hide(dijit.byId('feed_archive_remove').domNode);
1709 removeFromArchive: function() {
1710 var selected = this.getSelectedFeedIds();
1712 if (selected.length > 0) {
1714 var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1717 Element.show('feed_browser_spinner');
1719 var query = "?op=rpc&method=remarchive&ids=" +
1720 param_escape(selected.toString());;
1722 new Ajax.Request("backend.php", {
1724 onComplete: function(transport) {
1730 execute: function() {
1731 if (this.validate()) {
1740 exception_error("editFeed", e);
1744 function showFeedsWithErrors() {
1746 var query = "backend.php?op=pref-feeds&method=feedsWithErrors";
1748 if (dijit.byId("errorFeedsDlg"))
1749 dijit.byId("errorFeedsDlg").destroyRecursive();
1751 dialog = new dijit.Dialog({
1752 id: "errorFeedsDlg",
1753 title: __("Feeds with update errors"),
1754 style: "width: 600px",
1755 getSelectedFeeds: function() {
1756 return getSelectedTableRowIds("prefErrorFeedList");
1758 removeSelected: function() {
1759 var sel_rows = this.getSelectedFeeds();
1761 console.log(sel_rows);
1763 if (sel_rows.length > 0) {
1764 var ok = confirm(__("Remove selected feeds?"));
1767 notify_progress("Removing selected feeds...", true);
1769 var query = "?op=pref-feeds&method=remove&ids="+
1770 param_escape(sel_rows.toString());
1772 new Ajax.Request("backend.php", {
1774 onComplete: function(transport) {
1782 alert(__("No feeds are selected."));
1785 execute: function() {
1786 if (this.validate()) {
1794 exception_error("showFeedsWithErrors", e);
1799 /* new support functions for SelectByTag */
1801 function get_all_tags(selObj){
1803 if( !selObj ) return "";
1806 var len = selObj.options.length;
1808 for (var i=0; i < len; i++){
1809 if (selObj.options[i].selected) {
1810 result += selObj[i].value + "%2C"; // is really a comma
1814 if (result.length > 0){
1815 result = result.substr(0, result.length-3); // remove trailing %2C
1821 exception_error("get_all_tags", e);
1825 function get_radio_checked(radioObj) {
1827 if (!radioObj) return "";
1829 var len = radioObj.length;
1831 if (len == undefined){
1832 if(radioObj.checked){
1833 return(radioObj.value);
1839 for( var i=0; i < len; i++ ){
1840 if( radioObj[i].checked ){
1841 return( radioObj[i].value);
1846 exception_error("get_radio_checked", e);
1851 function get_timestamp() {
1852 var date = new Date();
1853 return Math.round(date.getTime() / 1000);
1856 function helpDialog(topic) {
1858 var query = "backend.php?op=backend&method=help&topic=" + param_escape(topic);
1860 if (dijit.byId("helpDlg"))
1861 dijit.byId("helpDlg").destroyRecursive();
1863 dialog = new dijit.Dialog({
1866 style: "width: 600px",
1873 exception_error("helpDialog", e);
1877 function htmlspecialchars_decode (string, quote_style) {
1878 // http://kevin.vanzonneveld.net
1879 // + original by: Mirek Slugen
1880 // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1881 // + bugfixed by: Mateusz "loonquawl" Zalega
1882 // + input by: ReverseSyntax
1883 // + input by: Slawomir Kaniecki
1884 // + input by: Scott Cariss
1885 // + input by: Francois
1886 // + bugfixed by: Onno Marsman
1887 // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1888 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1889 // + input by: Ratheous
1890 // + input by: Mailfaker (http://www.weedem.fr/)
1891 // + reimplemented by: Brett Zamir (http://brett-zamir.me)
1892 // + bugfixed by: Brett Zamir (http://brett-zamir.me)
1893 // * example 1: htmlspecialchars_decode("<p>this -> "</p>", 'ENT_NOQUOTES');
1894 // * returns 1: '<p>this -> "</p>'
1895 // * example 2: htmlspecialchars_decode("&quot;");
1896 // * returns 2: '"'
1900 if (typeof quote_style === 'undefined') {
1903 string = string.toString().replace(/</g, '<').replace(/>/g, '>');
1906 'ENT_HTML_QUOTE_SINGLE': 1,
1907 'ENT_HTML_QUOTE_DOUBLE': 2,
1912 if (quote_style === 0) {
1915 if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
1916 quote_style = [].concat(quote_style);
1917 for (i = 0; i < quote_style.length; i++) {
1918 // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1919 if (OPTS[quote_style[i]] === 0) {
1921 } else if (OPTS[quote_style[i]]) {
1922 optTemp = optTemp | OPTS[quote_style[i]];
1925 quote_style = optTemp;
1927 if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
1928 string = string.replace(/�*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
1929 // string = string.replace(/'|�*27;/g, "'"); // This would also be useful here, but not a part of PHP
1932 string = string.replace(/"/g, '"');
1934 // Put this in last place to avoid escape being double-decoded
1935 string = string.replace(/&/g, '&');
1941 function label_to_feed_id(label) {
1942 return _label_base_index - 1 - Math.abs(label);
1945 function feed_to_label_id(feed) {
1946 return _label_base_index - 1 + Math.abs(feed);
1949 // http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac
1951 function getSelectionText() {
1954 if (typeof window.getSelection != "undefined") {
1955 var sel = window.getSelection();
1956 if (sel.rangeCount) {
1957 var container = document.createElement("div");
1958 for (var i = 0, len = sel.rangeCount; i < len; ++i) {
1959 container.appendChild(sel.getRangeAt(i).cloneContents());
1961 text = container.innerHTML;
1963 } else if (typeof document.selection != "undefined") {
1964 if (document.selection.type == "Text") {
1965 text = document.selection.createRange().textText;
1969 return text.stripTags();