rssutils.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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. _debug("title $entry_title", $debug_enabled);
  467. _debug("link $entry_link", $debug_enabled);
  468. if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
  469. $entry_content = $item->get_content();
  470. if (!$entry_content) $entry_content = $item->get_description();
  471. if (clean($_REQUEST["xdebug"]) == 2) {
  472. print "content: ";
  473. print htmlspecialchars($entry_content);
  474. print "\n";
  475. }
  476. $entry_comments = mb_substr(strip_tags($item->get_comments_url()), 0, 245);
  477. $num_comments = (int) $item->get_comments_count();
  478. $entry_author = strip_tags($item->get_author());
  479. $entry_guid = mb_substr($entry_guid, 0, 245);
  480. _debug("author $entry_author", $debug_enabled);
  481. _debug("num_comments: $num_comments", $debug_enabled);
  482. _debug("looking for tags...", $debug_enabled);
  483. // parse <category> entries into tags
  484. $additional_tags = array();
  485. $additional_tags_src = $item->get_categories();
  486. if (is_array($additional_tags_src)) {
  487. foreach ($additional_tags_src as $tobj) {
  488. array_push($additional_tags, $tobj);
  489. }
  490. }
  491. $entry_tags = array_unique($additional_tags);
  492. for ($i = 0; $i < count($entry_tags); $i++) {
  493. $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
  494. // we don't support numeric tags, let's prefix them
  495. if (is_numeric($entry_tags[$i])) $entry_tags[$i] = 't:' . $entry_tags[$i];
  496. }
  497. _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
  498. _debug("done collecting data.", $debug_enabled);
  499. $sth = $pdo->prepare("SELECT id, content_hash, lang FROM ttrss_entries
  500. WHERE guid = ? OR guid = ?");
  501. $sth->execute([$entry_guid, $entry_guid_hashed]);
  502. if ($row = $sth->fetch()) {
  503. $base_entry_id = $row["id"];
  504. $entry_stored_hash = $row["content_hash"];
  505. $article_labels = Article::get_article_labels($base_entry_id, $owner_uid);
  506. $entry_language = $row["lang"];
  507. $existing_tags = Article::get_article_tags($base_entry_id, $owner_uid);
  508. $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
  509. } else {
  510. $base_entry_id = false;
  511. $entry_stored_hash = "";
  512. $article_labels = array();
  513. $entry_language = "";
  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") {
  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. num_comments = :num_comments,
  735. plugin_data = :plugin_data,
  736. author = :author,
  737. lang = :lang
  738. WHERE id = :id");
  739. $params = [":title" => $entry_title,
  740. ":content" => "$entry_content",
  741. ":content_hash" => $entry_current_hash,
  742. ":updated" => $entry_timestamp_fmt,
  743. ":num_comments" => (int)$num_comments,
  744. ":plugin_data" => $entry_plugin_data,
  745. ":author" => "$entry_author",
  746. ":lang" => $entry_language,
  747. ":id" => $ref_id];
  748. if (DB_TYPE == "pgsql") {
  749. $params[":ts_lang"] = $feed_language;
  750. $params[":ts_content"] = mb_substr(strip_tags($entry_title . " " . $entry_content), 0, 1000000);
  751. }
  752. $sth->execute($params);
  753. // update aux data
  754. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  755. SET score = ? WHERE ref_id = ?");
  756. $sth->execute([$score, $ref_id]);
  757. if ($mark_unread_on_update) {
  758. _debug("article updated, marking unread as requested.", $debug_enabled);
  759. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  760. SET last_read = null, unread = true WHERE ref_id = ?");
  761. $sth->execute([$ref_id]);
  762. }
  763. }
  764. _debug("assigning labels [other]...", $debug_enabled);
  765. foreach ($article_labels as $label) {
  766. Labels::add_article($entry_ref_id, $label[1], $owner_uid);
  767. }
  768. _debug("assigning labels [filters]...", $debug_enabled);
  769. RSSUtils::assign_article_to_label_filters($entry_ref_id, $article_filters,
  770. $owner_uid, $article_labels);
  771. _debug("looking for enclosures...", $debug_enabled);
  772. // enclosures
  773. $enclosures = array();
  774. $encs = $item->get_enclosures();
  775. if (is_array($encs)) {
  776. foreach ($encs as $e) {
  777. $e_item = array(
  778. rewrite_relative_url($site_url, $e->link),
  779. $e->type, $e->length, $e->title, $e->width, $e->height);
  780. // Yet another episode of "mysql utf8_general_ci is gimped"
  781. if (DB_TYPE == "mysql") {
  782. for ($i = 0; $i < count($e_item); $i++) {
  783. if (is_string($e_item[$i])) {
  784. $e_item[$i] = RSSUtils::strip_utf8mb4($e_item[$i]);
  785. }
  786. }
  787. }
  788. array_push($enclosures, $e_item);
  789. }
  790. }
  791. if ($cache_images && is_writable(CACHE_DIR . '/images'))
  792. RSSUtils::cache_enclosures($enclosures, $site_url, $debug_enabled);
  793. if ($debug_enabled) {
  794. _debug("article enclosures:", $debug_enabled);
  795. print_r($enclosures);
  796. }
  797. $esth = $pdo->prepare("SELECT id FROM ttrss_enclosures
  798. WHERE content_url = ? AND post_id = ?");
  799. $usth = $pdo->prepare("INSERT INTO ttrss_enclosures
  800. (content_url, content_type, title, duration, post_id, width, height) VALUES
  801. (?, ?, ?, ?, ?, ?, ?)");
  802. foreach ($enclosures as $enc) {
  803. $enc_url = $enc[0];
  804. $enc_type = $enc[1];
  805. $enc_dur = (int)$enc[2];
  806. $enc_title = $enc[3];
  807. $enc_width = intval($enc[4]);
  808. $enc_height = intval($enc[5]);
  809. $esth->execute([$enc_url, $entry_ref_id]);
  810. if (!$esth->fetch()) {
  811. $usth->execute([$enc_url, $enc_type, (string)$enc_title, $enc_dur, $entry_ref_id, $enc_width, $enc_height]);
  812. }
  813. }
  814. // check for manual tags (we have to do it here since they're loaded from filters)
  815. foreach ($article_filters as $f) {
  816. if ($f["type"] == "tag") {
  817. $manual_tags = trim_array(explode(",", $f["param"]));
  818. foreach ($manual_tags as $tag) {
  819. if (tag_is_valid($tag)) {
  820. array_push($entry_tags, $tag);
  821. }
  822. }
  823. }
  824. }
  825. // Skip boring tags
  826. $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
  827. 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
  828. $filtered_tags = array();
  829. $tags_to_cache = array();
  830. if ($entry_tags && is_array($entry_tags)) {
  831. foreach ($entry_tags as $tag) {
  832. if (array_search($tag, $boring_tags) === false) {
  833. array_push($filtered_tags, $tag);
  834. }
  835. }
  836. }
  837. $filtered_tags = array_unique($filtered_tags);
  838. if ($debug_enabled) {
  839. _debug("filtered article tags:", $debug_enabled);
  840. print_r($filtered_tags);
  841. }
  842. // Save article tags in the database
  843. if (count($filtered_tags) > 0) {
  844. $tsth = $pdo->prepare("SELECT id FROM ttrss_tags
  845. WHERE tag_name = ? AND post_int_id = ? AND
  846. owner_uid = ? LIMIT 1");
  847. $usth = $pdo->prepare("INSERT INTO ttrss_tags
  848. (owner_uid,tag_name,post_int_id)
  849. VALUES (?, ?, ?)");
  850. foreach ($filtered_tags as $tag) {
  851. $tag = sanitize_tag($tag);
  852. if (!tag_is_valid($tag)) continue;
  853. $tsth->execute([$tag, $entry_int_id, $owner_uid]);
  854. if (!$tsth->fetch()) {
  855. $usth->execute([$owner_uid, $tag, $entry_int_id]);
  856. }
  857. array_push($tags_to_cache, $tag);
  858. }
  859. /* update the cache */
  860. $tags_to_cache = array_unique($tags_to_cache);
  861. $tags_str = join(",", $tags_to_cache);
  862. $tsth = $pdo->prepare("UPDATE ttrss_user_entries
  863. SET tag_cache = ? WHERE ref_id = ?
  864. AND owner_uid = ?");
  865. $tsth->execute([$tags_str, $entry_ref_id, $owner_uid]);
  866. }
  867. _debug("article processed", $debug_enabled);
  868. $pdo->commit();
  869. }
  870. _debug("purging feed...", $debug_enabled);
  871. purge_feed($feed, 0, $debug_enabled);
  872. $sth = $pdo->prepare("UPDATE ttrss_feeds
  873. SET last_updated = NOW(), last_unconditional = NOW(), last_error = '' WHERE id = ?");
  874. $sth->execute([$feed]);
  875. } else {
  876. $error_msg = mb_substr($rss->error(), 0, 245);
  877. _debug("fetch error: $error_msg", $debug_enabled);
  878. if (count($rss->errors()) > 1) {
  879. foreach ($rss->errors() as $error) {
  880. _debug("+ $error");
  881. }
  882. }
  883. $sth = $pdo->prepare("UPDATE ttrss_feeds SET last_error = ?,
  884. last_updated = NOW(), last_unconditional = NOW() WHERE id = ?");
  885. $sth->execute([$error_msg, $feed]);
  886. unset($rss);
  887. return false;
  888. }
  889. _debug("done", $debug_enabled);
  890. return true;
  891. }
  892. static function cache_enclosures($enclosures, $site_url, $debug) {
  893. foreach ($enclosures as $enc) {
  894. if (preg_match("/(image|audio|video)/", $enc[1])) {
  895. $src = rewrite_relative_url($site_url, $enc[0]);
  896. $local_filename = CACHE_DIR . "/images/" . sha1($src);
  897. if ($debug) _debug("cache_enclosures: downloading: $src to $local_filename");
  898. if (!file_exists($local_filename)) {
  899. $file_content = fetch_file_contents($src);
  900. if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
  901. file_put_contents($local_filename, $file_content);
  902. }
  903. } else {
  904. touch($local_filename);
  905. }
  906. }
  907. }
  908. }
  909. static function cache_media($html, $site_url, $debug) {
  910. libxml_use_internal_errors(true);
  911. $charset_hack = '<head>
  912. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  913. </head>';
  914. $doc = new DOMDocument();
  915. $doc->loadHTML($charset_hack . $html);
  916. $xpath = new DOMXPath($doc);
  917. $entries = $xpath->query('(//img[@src])|(//video/source[@src])|(//audio/source[@src])');
  918. foreach ($entries as $entry) {
  919. if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
  920. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  921. $local_filename = CACHE_DIR . "/images/" . sha1($src);
  922. if ($debug) _debug("cache_media: downloading: $src to $local_filename");
  923. if (!file_exists($local_filename)) {
  924. $file_content = fetch_file_contents($src);
  925. if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
  926. file_put_contents($local_filename, $file_content);
  927. }
  928. } else {
  929. touch($local_filename);
  930. }
  931. }
  932. }
  933. }
  934. static function expire_error_log($debug) {
  935. if ($debug) _debug("Removing old error log entries...");
  936. $pdo = Db::pdo();
  937. if (DB_TYPE == "pgsql") {
  938. $pdo->query("DELETE FROM ttrss_error_log
  939. WHERE created_at < NOW() - INTERVAL '7 days'");
  940. } else {
  941. $pdo->query("DELETE FROM ttrss_error_log
  942. WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
  943. }
  944. }
  945. static function expire_lock_files($debug) {
  946. //if ($debug) _debug("Removing old lock files...");
  947. $num_deleted = 0;
  948. if (is_writable(LOCK_DIRECTORY)) {
  949. $files = glob(LOCK_DIRECTORY . "/*.lock");
  950. if ($files) {
  951. foreach ($files as $file) {
  952. if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
  953. unlink($file);
  954. ++$num_deleted;
  955. }
  956. }
  957. }
  958. }
  959. if ($debug) _debug("Removed $num_deleted old lock files.");
  960. }
  961. static function expire_cached_files($debug) {
  962. foreach (array("simplepie", "feeds", "images", "export", "upload") as $dir) {
  963. $cache_dir = CACHE_DIR . "/$dir";
  964. // if ($debug) _debug("Expiring $cache_dir");
  965. $num_deleted = 0;
  966. if (is_writable($cache_dir)) {
  967. $files = glob("$cache_dir/*");
  968. if ($files) {
  969. foreach ($files as $file) {
  970. if (time() - filemtime($file) > 86400*CACHE_MAX_DAYS) {
  971. unlink($file);
  972. ++$num_deleted;
  973. }
  974. }
  975. }
  976. }
  977. if ($debug) _debug("$cache_dir: removed $num_deleted files.");
  978. }
  979. }
  980. /**
  981. * Source: http://www.php.net/manual/en/function.parse-url.php#104527
  982. * Returns the url query as associative array
  983. *
  984. * @param string query
  985. * @return array params
  986. */
  987. static function convertUrlQuery($query) {
  988. $queryParts = explode('&', $query);
  989. $params = array();
  990. foreach ($queryParts as $param) {
  991. $item = explode('=', $param);
  992. $params[$item[0]] = $item[1];
  993. }
  994. return $params;
  995. }
  996. static function get_article_filters($filters, $title, $content, $link, $author, $tags, &$matched_rules = false) {
  997. $matches = array();
  998. foreach ($filters as $filter) {
  999. $match_any_rule = $filter["match_any_rule"];
  1000. $inverse = $filter["inverse"];
  1001. $filter_match = false;
  1002. foreach ($filter["rules"] as $rule) {
  1003. $match = false;
  1004. $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
  1005. $rule_inverse = $rule["inverse"];
  1006. if (!$reg_exp)
  1007. continue;
  1008. switch ($rule["type"]) {
  1009. case "title":
  1010. $match = @preg_match("/$reg_exp/iu", $title);
  1011. break;
  1012. case "content":
  1013. // we don't need to deal with multiline regexps
  1014. $content = preg_replace("/[\r\n\t]/", "", $content);
  1015. $match = @preg_match("/$reg_exp/iu", $content);
  1016. break;
  1017. case "both":
  1018. // we don't need to deal with multiline regexps
  1019. $content = preg_replace("/[\r\n\t]/", "", $content);
  1020. $match = (@preg_match("/$reg_exp/iu", $title) || @preg_match("/$reg_exp/iu", $content));
  1021. break;
  1022. case "link":
  1023. $match = @preg_match("/$reg_exp/iu", $link);
  1024. break;
  1025. case "author":
  1026. $match = @preg_match("/$reg_exp/iu", $author);
  1027. break;
  1028. case "tag":
  1029. foreach ($tags as $tag) {
  1030. if (@preg_match("/$reg_exp/iu", $tag)) {
  1031. $match = true;
  1032. break;
  1033. }
  1034. }
  1035. break;
  1036. }
  1037. if ($rule_inverse) $match = !$match;
  1038. if ($match_any_rule) {
  1039. if ($match) {
  1040. $filter_match = true;
  1041. break;
  1042. }
  1043. } else {
  1044. $filter_match = $match;
  1045. if (!$match) {
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. if ($inverse) $filter_match = !$filter_match;
  1051. if ($filter_match) {
  1052. if (is_array($matched_rules)) array_push($matched_rules, $rule);
  1053. foreach ($filter["actions"] AS $action) {
  1054. array_push($matches, $action);
  1055. // if Stop action encountered, perform no further processing
  1056. if (isset($action["type"]) && $action["type"] == "stop") return $matches;
  1057. }
  1058. }
  1059. }
  1060. return $matches;
  1061. }
  1062. static function find_article_filter($filters, $filter_name) {
  1063. foreach ($filters as $f) {
  1064. if ($f["type"] == $filter_name) {
  1065. return $f;
  1066. };
  1067. }
  1068. return false;
  1069. }
  1070. static function find_article_filters($filters, $filter_name) {
  1071. $results = array();
  1072. foreach ($filters as $f) {
  1073. if ($f["type"] == $filter_name) {
  1074. array_push($results, $f);
  1075. };
  1076. }
  1077. return $results;
  1078. }
  1079. static function calculate_article_score($filters) {
  1080. $score = 0;
  1081. foreach ($filters as $f) {
  1082. if ($f["type"] == "score") {
  1083. $score += $f["param"];
  1084. };
  1085. }
  1086. return $score;
  1087. }
  1088. static function labels_contains_caption($labels, $caption) {
  1089. foreach ($labels as $label) {
  1090. if ($label[1] == $caption) {
  1091. return true;
  1092. }
  1093. }
  1094. return false;
  1095. }
  1096. static function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
  1097. foreach ($filters as $f) {
  1098. if ($f["type"] == "label") {
  1099. if (!RSSUtils::labels_contains_caption($article_labels, $f["param"])) {
  1100. Labels::add_article($id, $f["param"], $owner_uid);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. static function make_guid_from_title($title) {
  1106. return preg_replace("/[ \"\',.:;]/", "-",
  1107. mb_strtolower(strip_tags($title), 'utf-8'));
  1108. }
  1109. static function cleanup_counters_cache($debug) {
  1110. $pdo = Db::pdo();
  1111. $res = $pdo->query("DELETE FROM ttrss_counters_cache
  1112. WHERE feed_id > 0 AND
  1113. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  1114. id = feed_id AND
  1115. ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
  1116. $frows = $res->rowCount();
  1117. $res = $pdo->query("DELETE FROM ttrss_cat_counters_cache
  1118. WHERE feed_id > 0 AND
  1119. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  1120. id = feed_id AND
  1121. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
  1122. $crows = $res->rowCount();
  1123. if ($debug) _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
  1124. }
  1125. static function housekeeping_user($owner_uid) {
  1126. $tmph = new PluginHost();
  1127. load_user_plugins($owner_uid, $tmph);
  1128. $tmph->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
  1129. }
  1130. static function housekeeping_common($debug) {
  1131. RSSUtils::expire_cached_files($debug);
  1132. RSSUtils::expire_lock_files($debug);
  1133. RSSUtils::expire_error_log($debug);
  1134. $count = RSSUtils::update_feedbrowser_cache();
  1135. _debug("Feedbrowser updated, $count feeds processed.");
  1136. Article::purge_orphans( true);
  1137. RSSUtils::cleanup_counters_cache($debug);
  1138. //$rc = cleanup_tags( 14, 50000);
  1139. //_debug("Cleaned $rc cached tags.");
  1140. PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
  1141. }
  1142. static function check_feed_favicon($site_url, $feed) {
  1143. # print "FAVICON [$site_url]: $favicon_url\n";
  1144. $icon_file = ICONS_DIR . "/$feed.ico";
  1145. if (!file_exists($icon_file)) {
  1146. $favicon_url = get_favicon_url($site_url);
  1147. if ($favicon_url) {
  1148. // Limiting to "image" type misses those served with text/plain
  1149. $contents = fetch_file_contents($favicon_url); // , "image");
  1150. if ($contents) {
  1151. // Crude image type matching.
  1152. // Patterns gleaned from the file(1) source code.
  1153. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  1154. // 0 string \000\000\001\000 MS Windows icon resource
  1155. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  1156. }
  1157. elseif (preg_match('/^GIF8/', $contents)) {
  1158. // 0 string GIF8 GIF image data
  1159. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  1160. }
  1161. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  1162. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  1163. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  1164. }
  1165. elseif (preg_match('/^\xff\xd8/', $contents)) {
  1166. // 0 beshort 0xffd8 JPEG image data
  1167. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  1168. }
  1169. elseif (preg_match('/^BM/', $contents)) {
  1170. // 0 string BM PC bitmap (OS2, Windows BMP files)
  1171. //error_log("check_feed_favicon, favicon_url=$favicon_url isa BMP image");
  1172. }
  1173. else {
  1174. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  1175. $contents = "";
  1176. }
  1177. }
  1178. if ($contents) {
  1179. $fp = @fopen($icon_file, "w");
  1180. if ($fp) {
  1181. fwrite($fp, $contents);
  1182. fclose($fp);
  1183. chmod($icon_file, 0644);
  1184. }
  1185. }
  1186. }
  1187. return $icon_file;
  1188. }
  1189. }
  1190. }