PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/include/rssfuncs.php

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