rssutils.php 44 KB

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