rssutils.php 46 KB

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