rssfuncs.php 40 KB

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