rssutils.php 46 KB

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