rssfuncs.php 44 KB

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