rssutils.php 50 KB

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