rssutils.php 45 KB

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