PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/include/rssfuncs.php

https://github.com/kpadilha/Tiny-Tiny-RSS
PHP | 1370 lines | 933 code | 324 blank | 113 comment | 246 complexity | 7340ac412a386d5984664076200a3579 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.0, LGPL-3.0, GPL-3.0
  1. <?php
  2. define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
  3. define('DAEMON_FEED_LIMIT', 100);
  4. define('DAEMON_SLEEP_INTERVAL', 60);
  5. function update_feedbrowser_cache($link) {
  6. $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
  7. FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
  8. WHERE tf.feed_url = ttrss_feeds.feed_url
  9. AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
  10. GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
  11. db_query($link, "BEGIN");
  12. db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
  13. $count = 0;
  14. while ($line = db_fetch_assoc($result)) {
  15. $subscribers = db_escape_string($link, $line["subscribers"]);
  16. $feed_url = db_escape_string($link, $line["feed_url"]);
  17. $title = db_escape_string($link, $line["title"]);
  18. $site_url = db_escape_string($link, $line["site_url"]);
  19. $tmp_result = db_query($link, "SELECT subscribers FROM
  20. ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
  21. if (db_num_rows($tmp_result) == 0) {
  22. db_query($link, "INSERT INTO ttrss_feedbrowser_cache
  23. (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
  24. '$site_url', '$title', '$subscribers')");
  25. ++$count;
  26. }
  27. }
  28. db_query($link, "COMMIT");
  29. return $count;
  30. }
  31. /**
  32. * Update a feed batch.
  33. * Used by daemons to update n feeds by run.
  34. * Only update feed needing a update, and not being processed
  35. * by another process.
  36. *
  37. * @param mixed $link Database link
  38. * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
  39. * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
  40. * @param boolean $debug Set to false to disable debug output. Default to true.
  41. * @return void
  42. */
  43. function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
  44. // Process all other feeds using last_updated and interval parameters
  45. define('PREFS_NO_CACHE', true);
  46. // Test if the user has loggued in recently. If not, it does not update its feeds.
  47. if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
  48. if (DB_TYPE == "pgsql") {
  49. $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
  50. } else {
  51. $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
  52. }
  53. } else {
  54. $login_thresh_qpart = "";
  55. }
  56. // Test if the feed need a update (update interval exceded).
  57. if (DB_TYPE == "pgsql") {
  58. $update_limit_qpart = "AND ((
  59. ttrss_feeds.update_interval = 0
  60. AND ttrss_user_prefs.value != '-1'
  61. AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
  62. ) OR (
  63. ttrss_feeds.update_interval > 0
  64. AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
  65. ) OR ttrss_feeds.last_updated IS NULL
  66. OR last_updated = '1970-01-01 00:00:00')";
  67. } else {
  68. $update_limit_qpart = "AND ((
  69. ttrss_feeds.update_interval = 0
  70. AND ttrss_user_prefs.value != '-1'
  71. AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
  72. ) OR (
  73. ttrss_feeds.update_interval > 0
  74. AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
  75. ) OR ttrss_feeds.last_updated IS NULL
  76. OR last_updated = '1970-01-01 00:00:00')";
  77. }
  78. // Test if feed is currently being updated by another process.
  79. if (DB_TYPE == "pgsql") {
  80. $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
  81. } else {
  82. $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
  83. }
  84. // Test if there is a limit to number of updated feeds
  85. $query_limit = "";
  86. if($limit) $query_limit = sprintf("LIMIT %d", $limit);
  87. $random_qpart = sql_random_function();
  88. // We search for feed needing update.
  89. $result = db_query($link, "SELECT DISTINCT ttrss_feeds.feed_url,$random_qpart
  90. FROM
  91. ttrss_feeds, ttrss_users, ttrss_user_prefs
  92. WHERE
  93. ttrss_feeds.owner_uid = ttrss_users.id
  94. AND ttrss_users.id = ttrss_user_prefs.owner_uid
  95. AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
  96. $login_thresh_qpart $update_limit_qpart
  97. $updstart_thresh_qpart
  98. ORDER BY $random_qpart $query_limit");
  99. $user_prefs_cache = array();
  100. if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
  101. // Here is a little cache magic in order to minimize risk of double feed updates.
  102. $feeds_to_update = array();
  103. while ($line = db_fetch_assoc($result)) {
  104. array_push($feeds_to_update, db_escape_string($link, $line['feed_url']));
  105. }
  106. // We update the feed last update started date before anything else.
  107. // There is no lag due to feed contents downloads
  108. // It prevent an other process to update the same feed.
  109. if(count($feeds_to_update) > 0) {
  110. $feeds_quoted = array();
  111. foreach ($feeds_to_update as $feed) {
  112. array_push($feeds_quoted, "'" . db_escape_string($link, $feed) . "'");
  113. }
  114. db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
  115. WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
  116. }
  117. expire_cached_files($debug);
  118. expire_lock_files($debug);
  119. $nf = 0;
  120. // For each feed, we call the feed update function.
  121. foreach ($feeds_to_update as $feed) {
  122. if($debug) _debug("Base feed: $feed");
  123. //update_rss_feed($link, $line["id"], true);
  124. // since we have the data cached, we can deal with other feeds with the same url
  125. $tmp_result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id,last_updated
  126. FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
  127. ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
  128. ttrss_users.id = ttrss_user_prefs.owner_uid AND
  129. ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
  130. feed_url = '".db_escape_string($link, $feed)."' AND
  131. (ttrss_feeds.update_interval > 0 OR
  132. ttrss_user_prefs.value != '-1')
  133. $login_thresh_qpart
  134. ORDER BY feed_url $query_limit");
  135. if (db_num_rows($tmp_result) > 0) {
  136. while ($tline = db_fetch_assoc($tmp_result)) {
  137. if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"]);
  138. update_rss_feed($link, $tline["id"], true);
  139. ++$nf;
  140. }
  141. }
  142. }
  143. require_once "digest.php";
  144. // Send feed digests by email if needed.
  145. send_headlines_digests($link, $debug);
  146. return $nf;
  147. } // function update_daemon_common
  148. // ignore_daemon is not used
  149. function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
  150. $override_url = false) {
  151. require_once "lib/simplepie/simplepie.inc";
  152. $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
  153. if ($debug_enabled) {
  154. _debug("update_rss_feed: start");
  155. }
  156. $result = db_query($link, "SELECT id,update_interval,auth_login,
  157. feed_url,auth_pass,cache_images,last_updated,
  158. mark_unread_on_update, owner_uid,
  159. pubsub_state
  160. FROM ttrss_feeds WHERE id = '$feed'");
  161. if (db_num_rows($result) == 0) {
  162. if ($debug_enabled) {
  163. _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
  164. }
  165. return false;
  166. }
  167. $last_updated = db_fetch_result($result, 0, "last_updated");
  168. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  169. $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
  170. 0, "mark_unread_on_update"));
  171. $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
  172. db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
  173. WHERE id = '$feed'");
  174. $auth_login = db_fetch_result($result, 0, "auth_login");
  175. $auth_pass = db_fetch_result($result, 0, "auth_pass");
  176. $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
  177. $fetch_url = db_fetch_result($result, 0, "feed_url");
  178. $feed = db_escape_string($link, $feed);
  179. if ($override_url) $fetch_url = $override_url;
  180. $date_feed_processed = date('Y-m-d H:i');
  181. $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".feed";
  182. // Ignore cache if new feed or manual update.
  183. $cache_age = ($no_cache || is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
  184. 30 : get_feed_update_interval($link, $feed) * 60;
  185. if ($debug_enabled) {
  186. _debug("update_rss_feed: cache filename: $cache_filename exists: " . file_exists($cache_filename));
  187. _debug("update_rss_feed: cache age: $cache_age; no cache: $no_cache");
  188. }
  189. $cached_feed_data_hash = false;
  190. $rss = false;
  191. $rss_hash = false;
  192. $cache_timestamp = file_exists($cache_filename) ? filemtime($cache_filename) : 0;
  193. $last_updated_timestamp = strtotime($last_updated);
  194. if (file_exists($cache_filename) &&
  195. is_readable($cache_filename) &&
  196. !$auth_login && !$auth_pass &&
  197. filemtime($cache_filename) > time() - $cache_age) {
  198. if ($debug_enabled) {
  199. _debug("update_rss_feed: using local cache.");
  200. }
  201. if ($cache_timestamp > $last_updated_timestamp) {
  202. @$rss_data = file_get_contents($cache_filename);
  203. if ($rss_data) {
  204. $rss_hash = sha1($rss_data);
  205. @$rss = unserialize($rss_data);
  206. }
  207. } else {
  208. if ($debug_enabled) {
  209. _debug("update_rss_feed: local cache valid and older than last_updated, nothing to do.");
  210. }
  211. return;
  212. }
  213. }
  214. if (!$rss) {
  215. if (!$feed_data) {
  216. if ($debug_enabled) {
  217. _debug("update_rss_feed: fetching [$fetch_url] (ts: $cache_timestamp/$last_updated_timestamp)");
  218. }
  219. $force_refetch = isset($_REQUEST["force_refetch"]);
  220. $feed_data = fetch_file_contents($fetch_url, false,
  221. $auth_login, $auth_pass, false,
  222. $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
  223. $force_refetch ? 0 : max($last_updated_timestamp, $cache_timestamp));
  224. if ($debug_enabled) {
  225. _debug("update_rss_feed: fetch done.");
  226. }
  227. }
  228. if (!$feed_data) {
  229. global $fetch_last_error;
  230. global $fetch_last_error_code;
  231. if ($debug_enabled) {
  232. _debug("update_rss_feed: unable to fetch: $fetch_last_error [$fetch_last_error_code]");
  233. }
  234. $error_escaped = '';
  235. // If-Modified-Since
  236. if ($fetch_last_error_code != 304) {
  237. $error_escaped = db_escape_string($link, $fetch_last_error);
  238. } else {
  239. if ($debug_enabled) {
  240. _debug("update_rss_feed: source claims data not modified, nothing to do.");
  241. }
  242. }
  243. db_query($link,
  244. "UPDATE ttrss_feeds SET last_error = '$error_escaped',
  245. last_updated = NOW() WHERE id = '$feed'");
  246. return;
  247. }
  248. }
  249. $pluginhost = new PluginHost($link);
  250. $pluginhost->set_debug($debug_enabled);
  251. $user_plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
  252. $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
  253. $pluginhost->load($user_plugins, $pluginhost::KIND_USER, $owner_uid);
  254. $pluginhost->load_data();
  255. foreach ($pluginhost->get_hooks($pluginhost::HOOK_FEED_FETCHED) as $plugin) {
  256. $feed_data = $plugin->hook_feed_fetched($feed_data);
  257. }
  258. if (!$rss) {
  259. $rss = new SimplePie();
  260. $rss->set_sanitize_class("SanitizeDummy");
  261. // simplepie ignores the above and creates default sanitizer anyway,
  262. // so let's override it...
  263. $rss->sanitize = new SanitizeDummy();
  264. $rss->set_output_encoding('UTF-8');
  265. $rss->set_raw_data($feed_data);
  266. $rss->enable_cache(false);
  267. @$rss->init();
  268. }
  269. // print_r($rss);
  270. $feed = db_escape_string($link, $feed);
  271. if (!$rss->error()) {
  272. // cache data for later
  273. if (!$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
  274. $rss_data = serialize($rss);
  275. $new_rss_hash = sha1($rss_data);
  276. if ($new_rss_hash != $rss_hash) {
  277. if ($debug_enabled) {
  278. _debug("update_rss_feed: saving $cache_filename");
  279. }
  280. @file_put_contents($cache_filename, serialize($rss));
  281. }
  282. }
  283. // We use local pluginhost here because we need to load different per-user feed plugins
  284. $pluginhost->run_hooks($pluginhost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
  285. if ($debug_enabled) {
  286. _debug("update_rss_feed: processing feed data...");
  287. }
  288. // db_query($link, "BEGIN");
  289. if (DB_TYPE == "pgsql") {
  290. $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
  291. } else {
  292. $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
  293. }
  294. $result = db_query($link, "SELECT title,site_url,owner_uid,
  295. (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
  296. favicon_needs_check
  297. FROM ttrss_feeds WHERE id = '$feed'");
  298. $registered_title = db_fetch_result($result, 0, "title");
  299. $orig_site_url = db_fetch_result($result, 0, "site_url");
  300. $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
  301. "favicon_needs_check"));
  302. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  303. $site_url = db_escape_string($link, mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
  304. if ($debug_enabled) {
  305. _debug("update_rss_feed: checking favicon...");
  306. }
  307. if ($favicon_needs_check) {
  308. check_feed_favicon($site_url, $feed, $link);
  309. db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
  310. WHERE id = '$feed'");
  311. }
  312. if (!$registered_title || $registered_title == "[Unknown]") {
  313. $feed_title = db_escape_string($link, $rss->get_title());
  314. if ($debug_enabled) {
  315. _debug("update_rss_feed: registering title: $feed_title");
  316. }
  317. db_query($link, "UPDATE ttrss_feeds SET
  318. title = '$feed_title' WHERE id = '$feed'");
  319. }
  320. if ($site_url && $orig_site_url != $site_url) {
  321. db_query($link, "UPDATE ttrss_feeds SET
  322. site_url = '$site_url' WHERE id = '$feed'");
  323. }
  324. if ($debug_enabled) {
  325. _debug("update_rss_feed: loading filters & labels...");
  326. }
  327. $filters = load_filters($link, $feed, $owner_uid);
  328. $labels = get_all_labels($link, $owner_uid);
  329. if ($debug_enabled) {
  330. //print_r($filters);
  331. _debug("update_rss_feed: " . count($filters) . " filters loaded.");
  332. }
  333. $items = $rss->get_items();
  334. if (!is_array($items)) {
  335. if ($debug_enabled) {
  336. _debug("update_rss_feed: no articles found.");
  337. }
  338. db_query($link, "UPDATE ttrss_feeds
  339. SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
  340. return; // no articles
  341. }
  342. if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
  343. if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
  344. $feed_hub_url = false;
  345. $links = $rss->get_links('hub');
  346. if ($links && is_array($links)) {
  347. foreach ($links as $l) {
  348. $feed_hub_url = $l;
  349. break;
  350. }
  351. }
  352. if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
  353. if ($feed_hub_url && function_exists('curl_init') &&
  354. !ini_get("open_basedir")) {
  355. require_once 'lib/pubsubhubbub/subscriber.php';
  356. $callback_url = get_self_url_prefix() .
  357. "/public.php?op=pubsub&id=$feed";
  358. $s = new Subscriber($feed_hub_url, $callback_url);
  359. $rc = $s->subscribe($fetch_url);
  360. if ($debug_enabled)
  361. _debug("update_rss_feed: feed hub url found, subscribe request sent.");
  362. db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
  363. WHERE id = '$feed'");
  364. }
  365. }
  366. if ($debug_enabled) {
  367. _debug("update_rss_feed: processing articles...");
  368. }
  369. foreach ($items as $item) {
  370. if ($_REQUEST['xdebug'] == 3) {
  371. print_r($item);
  372. }
  373. $entry_guid = $item->get_id();
  374. if (!$entry_guid) $entry_guid = $item->get_link();
  375. if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
  376. if ($debug_enabled) {
  377. _debug("update_rss_feed: guid $entry_guid");
  378. }
  379. if (!$entry_guid) continue;
  380. $entry_guid = "$owner_uid,$entry_guid";
  381. $entry_timestamp = "";
  382. $entry_timestamp = strtotime($item->get_date());
  383. if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
  384. $entry_timestamp = time();
  385. $no_orig_date = 'true';
  386. } else {
  387. $no_orig_date = 'false';
  388. }
  389. $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
  390. if ($debug_enabled) {
  391. _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
  392. }
  393. $entry_title = $item->get_title();
  394. $entry_link = rewrite_relative_url($site_url, $item->get_link());
  395. if ($debug_enabled) {
  396. _debug("update_rss_feed: title $entry_title");
  397. _debug("update_rss_feed: link $entry_link");
  398. }
  399. if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
  400. $entry_content = $item->get_content();
  401. if (!$entry_content) $entry_content = $item->get_description();
  402. if ($_REQUEST["xdebug"] == 2) {
  403. print "update_rss_feed: content: ";
  404. print $entry_content;
  405. print "\n";
  406. }
  407. $entry_comments = $item->data["comments"];
  408. if ($item->get_author()) {
  409. $entry_author_item = $item->get_author();
  410. $entry_author = $entry_author_item->get_name();
  411. if (!$entry_author) $entry_author = $entry_author_item->get_email();
  412. $entry_author = db_escape_string($link, $entry_author);
  413. }
  414. $entry_guid = db_escape_string($link, mb_substr($entry_guid, 0, 245));
  415. $entry_comments = db_escape_string($link, mb_substr($entry_comments, 0, 245));
  416. $entry_author = db_escape_string($link, mb_substr($entry_author, 0, 245));
  417. $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
  418. if (is_array($num_comments) && is_array($num_comments[0])) {
  419. $num_comments = (int) $num_comments[0]["data"];
  420. } else {
  421. $num_comments = 0;
  422. }
  423. if ($debug_enabled) {
  424. _debug("update_rss_feed: num_comments: $num_comments");
  425. _debug("update_rss_feed: looking for tags [1]...");
  426. }
  427. // parse <category> entries into tags
  428. $additional_tags = array();
  429. $additional_tags_src = $item->get_categories();
  430. if (is_array($additional_tags_src)) {
  431. foreach ($additional_tags_src as $tobj) {
  432. array_push($additional_tags, $tobj->get_term());
  433. }
  434. }
  435. if ($debug_enabled) {
  436. _debug("update_rss_feed: category tags:");
  437. print_r($additional_tags);
  438. }
  439. if ($debug_enabled) {
  440. _debug("update_rss_feed: looking for tags [2]...");
  441. }
  442. $entry_tags = array_unique($additional_tags);
  443. for ($i = 0; $i < count($entry_tags); $i++)
  444. $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
  445. if ($debug_enabled) {
  446. //_debug("update_rss_feed: unfiltered tags found:");
  447. //print_r($entry_tags);
  448. }
  449. if ($debug_enabled) {
  450. _debug("update_rss_feed: done collecting data.");
  451. }
  452. // TODO: less memory-hungry implementation
  453. if ($debug_enabled) {
  454. _debug("update_rss_feed: applying plugin filters..");
  455. }
  456. // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
  457. $result = db_query($link, "SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries
  458. WHERE ref_id = id AND guid = '".db_escape_string($link, $entry_guid)."' AND owner_uid = $owner_uid");
  459. if (db_num_rows($result) != 0) {
  460. $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
  461. $stored_article = array("title" => db_fetch_result($result, 0, "title"),
  462. "content" => db_fetch_result($result, 0, "content"),
  463. "link" => db_fetch_result($result, 0, "link"),
  464. "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")),
  465. "author" => db_fetch_result($result, 0, "author"));
  466. } else {
  467. $entry_plugin_data = "";
  468. $stored_article = array();
  469. }
  470. $article = array("owner_uid" => $owner_uid, // read only
  471. "guid" => $entry_guid, // read only
  472. "title" => $entry_title,
  473. "content" => $entry_content,
  474. "link" => $entry_link,
  475. "tags" => $entry_tags,
  476. "plugin_data" => $entry_plugin_data,
  477. "author" => $entry_author,
  478. "stored" => $stored_article);
  479. foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER) as $plugin) {
  480. $article = $plugin->hook_article_filter($article);
  481. }
  482. $entry_tags = $article["tags"];
  483. $entry_guid = db_escape_string($link, $entry_guid);
  484. $entry_title = db_escape_string($link, $article["title"]);
  485. $entry_author = db_escape_string($link, $article["author"]);
  486. $entry_link = db_escape_string($link, $article["link"]);
  487. $entry_plugin_data = db_escape_string($link, $article["plugin_data"]);
  488. $entry_content = $article["content"]; // escaped below
  489. if ($debug_enabled) {
  490. _debug("update_rss_feed: plugin data: $entry_plugin_data");
  491. }
  492. if ($cache_images && is_writable(CACHE_DIR . '/images'))
  493. cache_images($entry_content, $site_url, $debug_enabled);
  494. $entry_content = db_escape_string($link, $entry_content, false);
  495. $content_hash = "SHA1:" . sha1($entry_content);
  496. db_query($link, "BEGIN");
  497. $result = db_query($link, "SELECT id FROM ttrss_entries
  498. WHERE guid = '$entry_guid'");
  499. if (db_num_rows($result) == 0) {
  500. if ($debug_enabled) {
  501. _debug("update_rss_feed: base guid [$entry_guid] not found");
  502. }
  503. // base post entry does not exist, create it
  504. $result = db_query($link,
  505. "INSERT INTO ttrss_entries
  506. (title,
  507. guid,
  508. link,
  509. updated,
  510. content,
  511. content_hash,
  512. cached_content,
  513. no_orig_date,
  514. date_updated,
  515. date_entered,
  516. comments,
  517. num_comments,
  518. plugin_data,
  519. author)
  520. VALUES
  521. ('$entry_title',
  522. '$entry_guid',
  523. '$entry_link',
  524. '$entry_timestamp_fmt',
  525. '$entry_content',
  526. '$content_hash',
  527. '',
  528. $no_orig_date,
  529. NOW(),
  530. '$date_feed_processed',
  531. '$entry_comments',
  532. '$num_comments',
  533. '$entry_plugin_data',
  534. '$entry_author')");
  535. $article_labels = array();
  536. } else {
  537. // we keep encountering the entry in feeds, so we need to
  538. // update date_updated column so that we don't get horrible
  539. // dupes when the entry gets purged and reinserted again e.g.
  540. // in the case of SLOW SLOW OMG SLOW updating feeds
  541. $base_entry_id = db_fetch_result($result, 0, "id");
  542. db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
  543. WHERE id = '$base_entry_id'");
  544. $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
  545. }
  546. // now it should exist, if not - bad luck then
  547. $result = db_query($link, "SELECT
  548. id,content_hash,no_orig_date,title,plugin_data,
  549. ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
  550. ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
  551. num_comments
  552. FROM
  553. ttrss_entries
  554. WHERE guid = '$entry_guid'");
  555. $entry_ref_id = 0;
  556. $entry_int_id = 0;
  557. if (db_num_rows($result) == 1) {
  558. if ($debug_enabled) {
  559. _debug("update_rss_feed: base guid [$entry_guid] found, checking for user record");
  560. }
  561. // this will be used below in update handler
  562. $orig_content_hash = db_fetch_result($result, 0, "content_hash");
  563. $orig_title = db_fetch_result($result, 0, "title");
  564. $orig_num_comments = db_fetch_result($result, 0, "num_comments");
  565. $orig_date_updated = strtotime(db_fetch_result($result,
  566. 0, "date_updated"));
  567. $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
  568. $ref_id = db_fetch_result($result, 0, "id");
  569. $entry_ref_id = $ref_id;
  570. // check for user post link to main table
  571. // do we allow duplicate posts with same GUID in different feeds?
  572. if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
  573. $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
  574. } else {
  575. $dupcheck_qpart = "";
  576. }
  577. /* Collect article tags here so we could filter by them: */
  578. $article_filters = get_article_filters($filters, $entry_title,
  579. $entry_content, $entry_link, $entry_timestamp, $entry_author,
  580. $entry_tags);
  581. if ($debug_enabled) {
  582. _debug("update_rss_feed: article filters: ");
  583. if (count($article_filters) != 0) {
  584. print_r($article_filters);
  585. }
  586. }
  587. if (find_article_filter($article_filters, "filter")) {
  588. db_query($link, "COMMIT"); // close transaction in progress
  589. continue;
  590. }
  591. $score = calculate_article_score($article_filters);
  592. if ($debug_enabled) {
  593. _debug("update_rss_feed: initial score: $score");
  594. }
  595. $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
  596. ref_id = '$ref_id' AND owner_uid = '$owner_uid'
  597. $dupcheck_qpart";
  598. // if ($_REQUEST["xdebug"]) print "$query\n";
  599. $result = db_query($link, $query);
  600. // okay it doesn't exist - create user entry
  601. if (db_num_rows($result) == 0) {
  602. if ($debug_enabled) {
  603. _debug("update_rss_feed: user record not found, creating...");
  604. }
  605. if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
  606. $unread = 'true';
  607. $last_read_qpart = 'NULL';
  608. } else {
  609. $unread = 'false';
  610. $last_read_qpart = 'NOW()';
  611. }
  612. if (find_article_filter($article_filters, 'mark') || $score > 1000) {
  613. $marked = 'true';
  614. } else {
  615. $marked = 'false';
  616. }
  617. if (find_article_filter($article_filters, 'publish')) {
  618. $published = 'true';
  619. } else {
  620. $published = 'false';
  621. }
  622. // N-grams
  623. if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
  624. $result = db_query($link, "SELECT COUNT(*) AS similar FROM
  625. ttrss_entries,ttrss_user_entries
  626. WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
  627. AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
  628. AND owner_uid = $owner_uid");
  629. $ngram_similar = db_fetch_result($result, 0, "similar");
  630. if ($debug_enabled) {
  631. _debug("update_rss_feed: N-gram similar results: $ngram_similar");
  632. }
  633. if ($ngram_similar > 0) {
  634. $unread = 'false';
  635. }
  636. }
  637. $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
  638. $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
  639. $result = db_query($link,
  640. "INSERT INTO ttrss_user_entries
  641. (ref_id, owner_uid, feed_id, unread, last_read, marked,
  642. published, score, tag_cache, label_cache, uuid,
  643. last_marked, last_published)
  644. VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
  645. $last_read_qpart, $marked, $published, '$score', '', '',
  646. '', $last_marked, $last_published)");
  647. if (PUBSUBHUBBUB_HUB && $published == 'true') {
  648. $rss_link = get_self_url_prefix() .
  649. "/public.php?op=rss&id=-2&key=" .
  650. get_feed_access_key($link, -2, false, $owner_uid);
  651. $p = new Publisher(PUBSUBHUBBUB_HUB);
  652. $pubsub_result = $p->publish_update($rss_link);
  653. }
  654. $result = db_query($link,
  655. "SELECT int_id FROM ttrss_user_entries WHERE
  656. ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
  657. feed_id = '$feed' LIMIT 1");
  658. if (db_num_rows($result) == 1) {
  659. $entry_int_id = db_fetch_result($result, 0, "int_id");
  660. }
  661. } else {
  662. if ($debug_enabled) {
  663. _debug("update_rss_feed: user record FOUND");
  664. }
  665. $entry_ref_id = db_fetch_result($result, 0, "ref_id");
  666. $entry_int_id = db_fetch_result($result, 0, "int_id");
  667. }
  668. if ($debug_enabled) {
  669. _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
  670. }
  671. $post_needs_update = false;
  672. $update_insignificant = false;
  673. if ($orig_num_comments != $num_comments) {
  674. $post_needs_update = true;
  675. $update_insignificant = true;
  676. }
  677. if ($entry_plugin_data != $orig_plugin_data) {
  678. $post_needs_update = true;
  679. $update_insignificant = true;
  680. }
  681. if ($content_hash != $orig_content_hash) {
  682. $post_needs_update = true;
  683. $update_insignificant = false;
  684. }
  685. if (db_escape_string($link, $orig_title) != $entry_title) {
  686. $post_needs_update = true;
  687. $update_insignificant = false;
  688. }
  689. // if post needs update, update it and mark all user entries
  690. // linking to this post as updated
  691. if ($post_needs_update) {
  692. if (defined('DAEMON_EXTENDED_DEBUG')) {
  693. _debug("update_rss_feed: post $entry_guid needs update...");
  694. }
  695. // print "<!-- post $orig_title needs update : $post_needs_update -->";
  696. db_query($link, "UPDATE ttrss_entries
  697. SET title = '$entry_title', content = '$entry_content',
  698. content_hash = '$content_hash',
  699. updated = '$entry_timestamp_fmt',
  700. num_comments = '$num_comments',
  701. plugin_data = '$entry_plugin_data'
  702. WHERE id = '$ref_id'");
  703. if (!$update_insignificant) {
  704. if ($mark_unread_on_update) {
  705. db_query($link, "UPDATE ttrss_user_entries
  706. SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
  707. }
  708. }
  709. }
  710. }
  711. db_query($link, "COMMIT");
  712. if ($debug_enabled) {
  713. _debug("update_rss_feed: assigning labels...");
  714. }
  715. assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
  716. $owner_uid, $article_labels);
  717. if ($debug_enabled) {
  718. _debug("update_rss_feed: looking for enclosures...");
  719. }
  720. // enclosures
  721. $enclosures = array();
  722. $encs = $item->get_enclosures();
  723. if (is_array($encs)) {
  724. foreach ($encs as $e) {
  725. $e_item = array(
  726. $e->link, $e->type, $e->length);
  727. array_push($enclosures, $e_item);
  728. }
  729. }
  730. if ($debug_enabled) {
  731. _debug("update_rss_feed: article enclosures:");
  732. print_r($enclosures);
  733. }
  734. db_query($link, "BEGIN");
  735. foreach ($enclosures as $enc) {
  736. $enc_url = db_escape_string($link, $enc[0]);
  737. $enc_type = db_escape_string($link, $enc[1]);
  738. $enc_dur = db_escape_string($link, $enc[2]);
  739. $result = db_query($link, "SELECT id FROM ttrss_enclosures
  740. WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
  741. if (db_num_rows($result) == 0) {
  742. db_query($link, "INSERT INTO ttrss_enclosures
  743. (content_url, content_type, title, duration, post_id) VALUES
  744. ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
  745. }
  746. }
  747. db_query($link, "COMMIT");
  748. // check for manual tags (we have to do it here since they're loaded from filters)
  749. foreach ($article_filters as $f) {
  750. if ($f["type"] == "tag") {
  751. $manual_tags = trim_array(explode(",", $f["param"]));
  752. foreach ($manual_tags as $tag) {
  753. if (tag_is_valid($tag)) {
  754. array_push($entry_tags, $tag);
  755. }
  756. }
  757. }
  758. }
  759. // Skip boring tags
  760. $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
  761. 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
  762. $filtered_tags = array();
  763. $tags_to_cache = array();
  764. if ($entry_tags && is_array($entry_tags)) {
  765. foreach ($entry_tags as $tag) {
  766. if (array_search($tag, $boring_tags) === false) {
  767. array_push($filtered_tags, $tag);
  768. }
  769. }
  770. }
  771. $filtered_tags = array_unique($filtered_tags);
  772. if ($debug_enabled) {
  773. _debug("update_rss_feed: filtered article tags:");
  774. print_r($filtered_tags);
  775. }
  776. // Save article tags in the database
  777. if (count($filtered_tags) > 0) {
  778. db_query($link, "BEGIN");
  779. foreach ($filtered_tags as $tag) {
  780. $tag = sanitize_tag($tag);
  781. $tag = db_escape_string($link, $tag);
  782. if (!tag_is_valid($tag)) continue;
  783. $result = db_query($link, "SELECT id FROM ttrss_tags
  784. WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
  785. owner_uid = '$owner_uid' LIMIT 1");
  786. if ($result && db_num_rows($result) == 0) {
  787. db_query($link, "INSERT INTO ttrss_tags
  788. (owner_uid,tag_name,post_int_id)
  789. VALUES ('$owner_uid','$tag', '$entry_int_id')");
  790. }
  791. array_push($tags_to_cache, $tag);
  792. }
  793. /* update the cache */
  794. $tags_to_cache = array_unique($tags_to_cache);
  795. $tags_str = db_escape_string($link, join(",", $tags_to_cache));
  796. db_query($link, "UPDATE ttrss_user_entries
  797. SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
  798. AND owner_uid = $owner_uid");
  799. db_query($link, "COMMIT");
  800. }
  801. if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
  802. if ($debug_enabled) {
  803. _debug("update_rss_feed: auto-assigning labels...");
  804. }
  805. foreach ($labels as $label) {
  806. $caption = preg_quote($label["caption"]);
  807. if ($caption && preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
  808. if (!labels_contains_caption($article_labels, $caption)) {
  809. label_add_article($link, $entry_ref_id, $caption, $owner_uid);
  810. }
  811. }
  812. }
  813. }
  814. if ($debug_enabled) {
  815. _debug("update_rss_feed: article processed");
  816. }
  817. }
  818. if (!$last_updated) {
  819. if ($debug_enabled) {
  820. _debug("update_rss_feed: new feed, catching it up...");
  821. }
  822. catchup_feed($link, $feed, false, $owner_uid);
  823. }
  824. if ($debug_enabled) {
  825. _debug("purging feed...");
  826. }
  827. purge_feed($link, $feed, 0, $debug_enabled);
  828. db_query($link, "UPDATE ttrss_feeds
  829. SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
  830. // db_query($link, "COMMIT");
  831. } else {
  832. $error_msg = db_escape_string($link, mb_substr($rss->error(), 0, 245));
  833. if ($debug_enabled) {
  834. _debug("update_rss_feed: error fetching feed: $error_msg");
  835. }
  836. db_query($link,
  837. "UPDATE ttrss_feeds SET last_error = '$error_msg',
  838. last_updated = NOW() WHERE id = '$feed'");
  839. }
  840. unset($rss);
  841. if ($debug_enabled) {
  842. _debug("update_rss_feed: done");
  843. }
  844. }
  845. function cache_images($html, $site_url, $debug) {
  846. $cache_dir = CACHE_DIR . "/images";
  847. libxml_use_internal_errors(true);
  848. $charset_hack = '<head>
  849. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  850. </head>';
  851. $doc = new DOMDocument();
  852. $doc->loadHTML($charset_hack . $html);
  853. $xpath = new DOMXPath($doc);
  854. $entries = $xpath->query('(//img[@src])');
  855. foreach ($entries as $entry) {
  856. if ($entry->hasAttribute('src')) {
  857. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  858. $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
  859. if ($debug) _debug("cache_images: downloading: $src to $local_filename");
  860. if (!file_exists($local_filename)) {
  861. $file_content = fetch_file_contents($src);
  862. if ($file_content && strlen($file_content) > 1024) {
  863. file_put_contents($local_filename, $file_content);
  864. }
  865. }
  866. if (file_exists($local_filename)) {
  867. $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
  868. base64_encode($src));
  869. }
  870. }
  871. }
  872. $node = $doc->getElementsByTagName('body')->item(0);
  873. return $doc->saveXML($node);
  874. }
  875. function expire_lock_files($debug) {
  876. if ($debug) _debug("Removing old lock files...");
  877. $num_deleted = 0;
  878. if (is_writable(LOCK_DIRECTORY)) {
  879. $files = glob(LOCK_DIRECTORY . "/*.lock");
  880. if ($files) {
  881. foreach ($files as $file) {
  882. if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
  883. unlink($file);
  884. ++$num_deleted;
  885. }
  886. }
  887. }
  888. }
  889. if ($debug) _debug("Removed $num_deleted files.");
  890. }
  891. function expire_cached_files($debug) {
  892. foreach (array("simplepie", "images", "export") as $dir) {
  893. $cache_dir = CACHE_DIR . "/$dir";
  894. if ($debug) _debug("Expiring $cache_dir");
  895. $num_deleted = 0;
  896. if (is_writable($cache_dir)) {
  897. $files = glob("$cache_dir/*");
  898. if ($files) {
  899. foreach ($files as $file) {
  900. if (time() - filemtime($file) > 86400*7) {
  901. unlink($file);
  902. ++$num_deleted;
  903. }
  904. }
  905. }
  906. }
  907. if ($debug) _debug("Removed $num_deleted files.");
  908. }
  909. }
  910. /**
  911. * Source: http://www.php.net/manual/en/function.parse-url.php#104527
  912. * Returns the url query as associative array
  913. *
  914. * @param string query
  915. * @return array params
  916. */
  917. function convertUrlQuery($query) {
  918. $queryParts = explode('&', $query);
  919. $params = array();
  920. foreach ($queryParts as $param) {
  921. $item = explode('=', $param);
  922. $params[$item[0]] = $item[1];
  923. }
  924. return $params;
  925. }
  926. function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
  927. $matches = array();
  928. foreach ($filters as $filter) {
  929. $match_any_rule = $filter["match_any_rule"];
  930. $inverse = $filter["inverse"];
  931. $filter_match = false;
  932. foreach ($filter["rules"] as $rule) {
  933. $match = false;
  934. $reg_exp = $rule["reg_exp"];
  935. $rule_inverse = $rule["inverse"];
  936. if (!$reg_exp)
  937. continue;
  938. switch ($rule["type"]) {
  939. case "title":
  940. $match = @preg_match("/$reg_exp/i", $title);
  941. break;
  942. case "content":
  943. // we don't need to deal with multiline regexps
  944. $content = preg_replace("/[\r\n\t]/", "", $content);
  945. $match = @preg_match("/$reg_exp/i", $content);
  946. break;
  947. case "both":
  948. // we don't need to deal with multiline regexps
  949. $content = preg_replace("/[\r\n\t]/", "", $content);
  950. $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
  951. break;
  952. case "link":
  953. $match = @preg_match("/$reg_exp/i", $link);
  954. break;
  955. case "author":
  956. $match = @preg_match("/$reg_exp/i", $author);
  957. break;
  958. case "tag":
  959. $tag_string = join(",", $tags);
  960. $match = @preg_match("/$reg_exp/i", $tag_string);
  961. break;
  962. }
  963. if ($rule_inverse) $match = !$match;
  964. if ($match_any_rule) {
  965. if ($match) {
  966. $filter_match = true;
  967. break;
  968. }
  969. } else {
  970. $filter_match = $match;
  971. if (!$match) {
  972. break;
  973. }
  974. }
  975. }
  976. if ($inverse) $filter_match = !$filter_match;
  977. if ($filter_match) {
  978. foreach ($filter["actions"] AS $action) {
  979. array_push($matches, $action);
  980. // if Stop action encountered, perform no further processing
  981. if ($action["type"] == "stop") return $matches;
  982. }
  983. }
  984. }
  985. return $matches;
  986. }
  987. function find_article_filter($filters, $filter_name) {
  988. foreach ($filters as $f) {
  989. if ($f["type"] == $filter_name) {
  990. return $f;
  991. };
  992. }
  993. return false;
  994. }
  995. function find_article_filters($filters, $filter_name) {
  996. $results = array();
  997. foreach ($filters as $f) {
  998. if ($f["type"] == $filter_name) {
  999. array_push($results, $f);
  1000. };
  1001. }
  1002. return $results;
  1003. }
  1004. function calculate_article_score($filters) {
  1005. $score = 0;
  1006. foreach ($filters as $f) {
  1007. if ($f["type"] == "score") {
  1008. $score += $f["param"];
  1009. };
  1010. }
  1011. return $score;
  1012. }
  1013. function labels_contains_caption($labels, $caption) {
  1014. foreach ($labels as $label) {
  1015. if ($label[1] == $caption) {
  1016. return true;
  1017. }
  1018. }
  1019. return false;
  1020. }
  1021. function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
  1022. foreach ($filters as $f) {
  1023. if ($f["type"] == "label") {
  1024. if (!labels_contains_caption($article_labels, $f["param"])) {
  1025. label_add_article($link, $id, $f["param"], $owner_uid);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. function make_guid_from_title($title) {
  1031. return preg_replace("/[ \"\',.:;]/", "-",
  1032. mb_strtolower(strip_tags($title), 'utf-8'));
  1033. }
  1034. ?>