init.php 13 KB

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