rssfuncs.php 41 KB

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