rssutils.php 47 KB

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