rssutils.php 46 KB

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