init.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. class Instances extends Plugin implements IHandler {
  3. private $host;
  4. private $status_codes = array(
  5. 0 => "Connection failed",
  6. 1 => "Success",
  7. 2 => "Invalid object received",
  8. 16 => "Access denied" );
  9. function about() {
  10. return array(1.0,
  11. "Support for linking tt-rss instances together and sharing popular feeds.",
  12. "fox",
  13. true);
  14. }
  15. function init($host) {
  16. $this->host = $host;
  17. $host->add_hook($host::HOOK_PREFS_TABS, $this);
  18. $host->add_handler("pref-instances", "*", $this);
  19. $host->add_handler("public", "fbexport", $this);
  20. $host->add_command("get-feeds", "receive popular feeds from linked instances", $this);
  21. $host->add_hook($host::HOOK_UPDATE_TASK, $this);
  22. }
  23. function hook_update_task($args) {
  24. _debug("Get linked feeds...");
  25. $this->get_linked_feeds();
  26. }
  27. // Status codes:
  28. // -1 - never connected
  29. // 0 - no data received
  30. // 1 - data received successfully
  31. // 2 - did not receive valid data
  32. // >10 - server error, code + 10 (e.g. 16 means server error 6)
  33. function get_linked_feeds($instance_id = false) {
  34. if ($instance_id)
  35. $instance_qpart = "id = '$instance_id' AND ";
  36. else
  37. $instance_qpart = "";
  38. if (DB_TYPE == "pgsql") {
  39. $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
  40. } else {
  41. $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
  42. }
  43. $result = db_query("SELECT id, access_key, access_url FROM ttrss_linked_instances
  44. WHERE $instance_qpart $date_qpart ORDER BY last_connected");
  45. while ($line = db_fetch_assoc($result)) {
  46. $id = $line['id'];
  47. _debug("Updating: " . $line['access_url'] . " ($id)");
  48. $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
  49. $post_query = 'key=' . $line['access_key'];
  50. $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
  51. // try doing it the old way
  52. if (!$feeds) {
  53. $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
  54. $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
  55. }
  56. if ($feeds) {
  57. $feeds = json_decode($feeds, true);
  58. if ($feeds) {
  59. if ($feeds['error']) {
  60. $status = $feeds['error']['code'] + 10;
  61. // access denied
  62. if ($status == 16) {
  63. db_query("DELETE FROM ttrss_linked_feeds
  64. WHERE instance_id = '$id'");
  65. }
  66. } else {
  67. $status = 1;
  68. if (count($feeds['feeds']) > 0) {
  69. db_query("DELETE FROM ttrss_linked_feeds
  70. WHERE instance_id = '$id'");
  71. foreach ($feeds['feeds'] as $feed) {
  72. $feed_url = db_escape_string($feed['feed_url']);
  73. $title = db_escape_string($feed['title']);
  74. $subscribers = db_escape_string($feed['subscribers']);
  75. $site_url = db_escape_string($feed['site_url']);
  76. db_query("INSERT INTO ttrss_linked_feeds
  77. (feed_url, site_url, title, subscribers, instance_id, created, updated)
  78. VALUES
  79. ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
  80. }
  81. } else {
  82. // received 0 feeds, this might indicate that
  83. // the instance on the other hand is rebuilding feedbrowser cache
  84. // we will try again later
  85. // TODO: maybe perform expiration based on updated here?
  86. }
  87. _debug("Processed " . count($feeds['feeds']) . " feeds.");
  88. }
  89. } else {
  90. $status = 2;
  91. }
  92. } else {
  93. $status = 0;
  94. }
  95. _debug("Status: $status");
  96. db_query("UPDATE ttrss_linked_instances SET
  97. last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
  98. }
  99. }
  100. function get_feeds() {
  101. $this->get_linked_feeds(false);
  102. }
  103. function get_prefs_js() {
  104. return file_get_contents(dirname(__FILE__) . "/instances.js");
  105. }
  106. function hook_prefs_tabs($args) {
  107. if ($_SESSION["access_level"] >= 10 || SINGLE_USER_MODE) {
  108. ?><div id="instanceConfigTab" dojoType="dijit.layout.ContentPane"
  109. href="backend.php?op=pref-instances"
  110. title="<?php echo __('Linked') ?>"></div><?php
  111. }
  112. }
  113. function csrf_ignore($method) {
  114. $csrf_ignored = array("index", "edit");
  115. return array_search($method, $csrf_ignored) !== false;
  116. }
  117. function before($method) {
  118. if ($_SESSION["uid"]) {
  119. if ($_SESSION["access_level"] < 10) {
  120. print __("Your access level is insufficient to open this tab.");
  121. return false;
  122. }
  123. return true;
  124. }
  125. return false;
  126. }
  127. function after() {
  128. return true;
  129. }
  130. function remove() {
  131. $ids = db_escape_string($_REQUEST['ids']);
  132. db_query("DELETE FROM ttrss_linked_instances WHERE
  133. id IN ($ids)");
  134. }
  135. function add() {
  136. $id = db_escape_string($_REQUEST["id"]);
  137. $access_url = db_escape_string($_REQUEST["access_url"]);
  138. $access_key = db_escape_string($_REQUEST["access_key"]);
  139. db_query("BEGIN");
  140. $result = db_query("SELECT id FROM ttrss_linked_instances
  141. WHERE access_url = '$access_url'");
  142. if (db_num_rows($result) == 0) {
  143. db_query("INSERT INTO ttrss_linked_instances
  144. (access_url, access_key, last_connected, last_status_in, last_status_out)
  145. VALUES
  146. ('$access_url', '$access_key', '1970-01-01', -1, -1)");
  147. }
  148. db_query("COMMIT");
  149. }
  150. function edit() {
  151. $id = db_escape_string($_REQUEST["id"]);
  152. $result = db_query("SELECT * FROM ttrss_linked_instances WHERE
  153. id = '$id'");
  154. print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"id\" value=\"$id\">";
  155. print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-instances\">";
  156. print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"editSave\">";
  157. print "<div class=\"dlgSec\">".__("Instance")."</div>";
  158. print "<div class=\"dlgSecCont\">";
  159. /* URL */
  160. $access_url = htmlspecialchars(db_fetch_result($result, 0, "access_url"));
  161. print __("URL:") . " ";
  162. print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\"
  163. placeHolder=\"".__("Instance URL")."\"
  164. regExp='^(http|https)://.*'
  165. style=\"font-size : 16px; width: 20em\" name=\"access_url\"
  166. value=\"$access_url\">";
  167. print "<hr/>";
  168. $access_key = htmlspecialchars(db_fetch_result($result, 0, "access_key"));
  169. /* Access key */
  170. print __("Access key:") . " ";
  171. print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\"
  172. placeHolder=\"".__("Access key")."\"
  173. style=\"width: 20em\" name=\"access_key\" id=\"instance_edit_key\"
  174. value=\"$access_key\">";
  175. print "<p class='insensitive'>" . __("Use one access key for both linked instances.");
  176. print "</div>";
  177. print "<div class=\"dlgButtons\">
  178. <div style='float : left'>
  179. <button dojoType=\"dijit.form.Button\"
  180. onclick=\"return dijit.byId('instanceEditDlg').regenKey()\">".
  181. __('Generate new key')."</button>
  182. </div>
  183. <button dojoType=\"dijit.form.Button\"
  184. onclick=\"return dijit.byId('instanceEditDlg').execute()\">".
  185. __('Save')."</button>
  186. <button dojoType=\"dijit.form.Button\"
  187. onclick=\"return dijit.byId('instanceEditDlg').hide()\"\">".
  188. __('Cancel')."</button></div>";
  189. }
  190. function editSave() {
  191. $id = db_escape_string($_REQUEST["id"]);
  192. $access_url = db_escape_string($_REQUEST["access_url"]);
  193. $access_key = db_escape_string($_REQUEST["access_key"]);
  194. db_query("UPDATE ttrss_linked_instances SET
  195. access_key = '$access_key', access_url = '$access_url',
  196. last_connected = '1970-01-01'
  197. WHERE id = '$id'");
  198. }
  199. function index() {
  200. if (!function_exists('curl_init')) {
  201. print "<div style='padding : 1em'>";
  202. print_error("This functionality requires CURL functions. Please enable CURL in your PHP configuration (you might also want to disable open_basedir in php.ini) and reload this page.");
  203. print "</div>";
  204. }
  205. print "<div id=\"pref-instance-wrap\" dojoType=\"dijit.layout.BorderContainer\" gutters=\"false\">";
  206. print "<div id=\"pref-instance-header\" dojoType=\"dijit.layout.ContentPane\" region=\"top\">";
  207. print "<div id=\"pref-instance-toolbar\" dojoType=\"dijit.Toolbar\">";
  208. $sort = db_escape_string($_REQUEST["sort"]);
  209. if (!$sort || $sort == "undefined") {
  210. $sort = "access_url";
  211. }
  212. print "<div dojoType=\"dijit.form.DropDownButton\">".
  213. "<span>" . __('Select')."</span>";
  214. print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  215. print "<div onclick=\"selectTableRows('prefInstanceList', 'all')\"
  216. dojoType=\"dijit.MenuItem\">".__('All')."</div>";
  217. print "<div onclick=\"selectTableRows('prefInstanceList', 'none')\"
  218. dojoType=\"dijit.MenuItem\">".__('None')."</div>";
  219. print "</div></div>";
  220. print "<button dojoType=\"dijit.form.Button\" onclick=\"addInstance()\">".__('Link instance')."</button>";
  221. print "<button dojoType=\"dijit.form.Button\" onclick=\"editSelectedInstance()\">".__('Edit')."</button>";
  222. print "<button dojoType=\"dijit.form.Button\" onclick=\"removeSelectedInstances()\">".__('Remove')."</button>";
  223. print "</div>"; #toolbar
  224. $result = db_query("SELECT *,
  225. (SELECT COUNT(*) FROM ttrss_linked_feeds
  226. WHERE instance_id = ttrss_linked_instances.id) AS num_feeds
  227. FROM ttrss_linked_instances
  228. ORDER BY $sort");
  229. print "<p class=\"insensitive\" style='margin-left : 1em;'>" . __("You can connect other instances of Tiny Tiny RSS to this one to share Popular feeds. Link to this instance of Tiny Tiny RSS by using this URL:");
  230. print " <a href=\"#\" onclick=\"alert('".htmlspecialchars(get_self_url_prefix())."')\">(display url)</a>";
  231. print "<p><table width='100%' id='prefInstanceList' class='prefInstanceList' cellspacing='0'>";
  232. print "<tr class=\"title\">
  233. <td align='center' width=\"5%\">&nbsp;</td>
  234. <td width=''><a href=\"#\" onclick=\"updateInstanceList('access_url')\">".__('Instance URL')."</a></td>
  235. <td width='20%'><a href=\"#\" onclick=\"updateInstanceList('access_key')\">".__('Access key')."</a></td>
  236. <td width='10%'><a href=\"#\" onclick=\"updateUsersList('last_connected')\">".__('Last connected')."</a></td>
  237. <td width='10%'><a href=\"#\" onclick=\"updateUsersList('last_status_out')\">".__('Status')."</a></td>
  238. <td width='10%'><a href=\"#\" onclick=\"updateUsersList('num_feeds')\">".__('Stored feeds')."</a></td>
  239. </tr>";
  240. $lnum = 0;
  241. while ($line = db_fetch_assoc($result)) {
  242. $class = ($lnum % 2) ? "even" : "odd";
  243. $id = $line['id'];
  244. $this_row_id = "id=\"LIRR-$id\"";
  245. $line["last_connected"] = make_local_datetime($line["last_connected"], false);
  246. print "<tr class=\"$class\" $this_row_id>";
  247. print "<td align='center'><input onclick='toggleSelectRow(this);'
  248. type=\"checkbox\" id=\"LICHK-$id\"></td>";
  249. $onclick = "onclick='editInstance($id, event)' title='".__('Click to edit')."'";
  250. $access_key = mb_substr($line['access_key'], 0, 4) . '...' .
  251. mb_substr($line['access_key'], -4);
  252. print "<td $onclick>" . htmlspecialchars($line['access_url']) . "</td>";
  253. print "<td $onclick>" . htmlspecialchars($access_key) . "</td>";
  254. print "<td $onclick>" . htmlspecialchars($line['last_connected']) . "</td>";
  255. print "<td $onclick>" . $this->status_codes[$line['last_status_out']] . "</td>";
  256. print "<td $onclick>" . htmlspecialchars($line['num_feeds']) . "</td>";
  257. print "</tr>";
  258. ++$lnum;
  259. }
  260. print "</table>";
  261. print "</div>"; #pane
  262. PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB,
  263. "hook_prefs_tab", "prefInstances");
  264. print "</div>"; #container
  265. }
  266. function fbexport() {
  267. $access_key = db_escape_string($_POST["key"]);
  268. // TODO: rate limit checking using last_connected
  269. $result = db_query("SELECT id FROM ttrss_linked_instances
  270. WHERE access_key = '$access_key'");
  271. if (db_num_rows($result) == 1) {
  272. $instance_id = db_fetch_result($result, 0, "id");
  273. $result = db_query("SELECT feed_url, site_url, title, subscribers
  274. FROM ttrss_feedbrowser_cache ORDER BY subscribers DESC LIMIT 100");
  275. $feeds = array();
  276. while ($line = db_fetch_assoc($result)) {
  277. array_push($feeds, $line);
  278. }
  279. db_query("UPDATE ttrss_linked_instances SET
  280. last_status_in = 1 WHERE id = '$instance_id'");
  281. print json_encode(array("feeds" => $feeds));
  282. } else {
  283. print error_json(6);
  284. }
  285. }
  286. function addInstance() {
  287. print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-instances\">";
  288. print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"add\">";
  289. print "<div class=\"dlgSec\">".__("Instance")."</div>";
  290. print "<div class=\"dlgSecCont\">";
  291. /* URL */
  292. print __("URL:") . " ";
  293. print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\"
  294. placeHolder=\"".__("Instance URL")."\"
  295. regExp='^(http|https)://.*'
  296. style=\"font-size : 16px; width: 20em\" name=\"access_url\">";
  297. print "<hr/>";
  298. $access_key = uniqid_short();
  299. /* Access key */
  300. print __("Access key:") . " ";
  301. print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\"
  302. placeHolder=\"".__("Access key")."\"
  303. style=\"width: 20em\" name=\"access_key\" id=\"instance_add_key\"
  304. value=\"$access_key\">";
  305. print "<p class='insensitive'>" . __("Use one access key for both linked instances.");
  306. print "</div>";
  307. print "<div class=\"dlgButtons\">
  308. <div style='float : left'>
  309. <button dojoType=\"dijit.form.Button\"
  310. onclick=\"return dijit.byId('instanceAddDlg').regenKey()\">".
  311. __('Generate new key')."</button>
  312. </div>
  313. <button dojoType=\"dijit.form.Button\"
  314. onclick=\"return dijit.byId('instanceAddDlg').execute()\">".
  315. __('Create link')."</button>
  316. <button dojoType=\"dijit.form.Button\"
  317. onclick=\"return dijit.byId('instanceAddDlg').hide()\"\">".
  318. __('Cancel')."</button></div>";
  319. return;
  320. }
  321. function genHash() {
  322. $hash = uniqid_short();
  323. print json_encode(array("hash" => $hash));
  324. }
  325. function api_version() {
  326. return 2;
  327. }
  328. }
  329. ?>