rssfuncs.php 40 KB

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