rssutils.php 45 KB

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