rssutils.php 46 KB

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