rssfuncs.php 43 KB

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