rssfuncs.php 39 KB

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