rssutils.php 47 KB

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