rssutils.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  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 = sql_bool_to_bool($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') || $_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 = sql_bool_to_bool($row["mark_unread_on_update"]);
  257. $auth_pass_encrypted = sql_bool_to_bool($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 = sql_bool_to_bool($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 . "/simplepie/" . 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 . "/simplepie")) {
  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. $feed = $feed;
  368. if (!$rss->error()) {
  369. // We use local pluginhost here because we need to load different per-user feed plugins
  370. $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
  371. _debug("language: $feed_language", $debug_enabled);
  372. _debug("processing feed data...", $debug_enabled);
  373. if (DB_TYPE == "pgsql") {
  374. $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
  375. } else {
  376. $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
  377. }
  378. $sth = $pdo->prepare("SELECT owner_uid,favicon_avg_color,
  379. (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
  380. favicon_needs_check
  381. FROM ttrss_feeds WHERE id = ?");
  382. $sth->execute([$feed]);
  383. if ($row = $sth->fetch()) {
  384. $favicon_needs_check = sql_bool_to_bool($row["favicon_needs_check"]);
  385. $favicon_avg_color = $row["favicon_avg_color"];
  386. $owner_uid = $row["owner_uid"];
  387. } else {
  388. return false;
  389. }
  390. $site_url = mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245);
  391. _debug("site_url: $site_url", $debug_enabled);
  392. _debug("feed_title: " . $rss->get_title(), $debug_enabled);
  393. if ($favicon_needs_check || $force_refetch) {
  394. /* terrible hack: if we crash on floicon shit here, we won't check
  395. * the icon avgcolor again (unless the icon got updated) */
  396. $favicon_file = ICONS_DIR . "/$feed.ico";
  397. $favicon_modified = @filemtime($favicon_file);
  398. _debug("checking favicon...", $debug_enabled);
  399. RSSUtils::check_feed_favicon($site_url, $feed);
  400. $favicon_modified_new = @filemtime($favicon_file);
  401. if ($favicon_modified_new > $favicon_modified)
  402. $favicon_avg_color = '';
  403. $favicon_colorstring = "";
  404. if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
  405. require_once "colors.php";
  406. $sth = $pdo->prepare("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
  407. id = ?");
  408. $sth->execute([$feed]);
  409. $favicon_color = calculate_avg_color($favicon_file);
  410. $favicon_colorstring = ",favicon_avg_color = " . $pdo->quote($favicon_color);
  411. } else if ($favicon_avg_color == 'fail') {
  412. _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
  413. }
  414. $sth = $pdo->prepare("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
  415. $favicon_colorstring WHERE id = ?");
  416. $sth->execute([$feed]);
  417. }
  418. _debug("loading filters & labels...", $debug_enabled);
  419. $filters = load_filters($feed, $owner_uid);
  420. if ($debug_enabled) {
  421. print_r($filters);
  422. }
  423. _debug("" . count($filters) . " filters loaded.", $debug_enabled);
  424. $items = $rss->get_items();
  425. if (!is_array($items)) {
  426. _debug("no articles found.", $debug_enabled);
  427. $sth = $pdo->prepare("UPDATE ttrss_feeds
  428. SET last_updated = NOW(), last_unconditional = NOW(), last_error = '' WHERE id = ?");
  429. $sth->execute([$feed]);
  430. return true; // no articles
  431. }
  432. _debug("processing articles...", $debug_enabled);
  433. $tstart = time();
  434. foreach ($items as $item) {
  435. $pdo->beginTransaction();
  436. if ($_REQUEST['xdebug'] == 3) {
  437. print_r($item);
  438. }
  439. if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
  440. _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
  441. $pdo->commit();
  442. break;
  443. }
  444. $entry_guid = strip_tags($item->get_id());
  445. if (!$entry_guid) $entry_guid = strip_tags($item->get_link());
  446. if (!$entry_guid) $entry_guid = RSSUtils::make_guid_from_title($item->get_title());
  447. if (!$entry_guid) {
  448. $pdo->commit();
  449. continue;
  450. }
  451. $entry_guid = "$owner_uid,$entry_guid";
  452. $entry_guid_hashed = 'SHA1:' . sha1($entry_guid);
  453. _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
  454. $entry_timestamp = strip_tags($item->get_date());
  455. _debug("orig date: " . $item->get_date(), $debug_enabled);
  456. if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
  457. $entry_timestamp = time();
  458. }
  459. $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
  460. _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
  461. $entry_title = strip_tags($item->get_title());
  462. $entry_link = rewrite_relative_url($site_url, $item->get_link());
  463. _debug("title $entry_title", $debug_enabled);
  464. _debug("link $entry_link", $debug_enabled);
  465. if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
  466. $entry_content = $item->get_content();
  467. if (!$entry_content) $entry_content = $item->get_description();
  468. if ($_REQUEST["xdebug"] == 2) {
  469. print "content: ";
  470. print htmlspecialchars($entry_content);
  471. print "\n";
  472. }
  473. $entry_comments = mb_substr(strip_tags($item->get_comments_url()), 0, 245);
  474. $num_comments = (int) $item->get_comments_count();
  475. $entry_author = strip_tags($item->get_author());
  476. $entry_guid = mb_substr($entry_guid, 0, 245);
  477. _debug("author $entry_author", $debug_enabled);
  478. _debug("num_comments: $num_comments", $debug_enabled);
  479. _debug("looking for tags...", $debug_enabled);
  480. // parse <category> entries into tags
  481. $additional_tags = array();
  482. $additional_tags_src = $item->get_categories();
  483. if (is_array($additional_tags_src)) {
  484. foreach ($additional_tags_src as $tobj) {
  485. array_push($additional_tags, $tobj);
  486. }
  487. }
  488. $entry_tags = array_unique($additional_tags);
  489. for ($i = 0; $i < count($entry_tags); $i++)
  490. $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
  491. _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
  492. _debug("done collecting data.", $debug_enabled);
  493. $sth = $pdo->prepare("SELECT id, content_hash, lang FROM ttrss_entries
  494. WHERE guid = ? OR guid = ?");
  495. $sth->execute([$entry_guid, $entry_guid_hashed]);
  496. if ($row = $sth->fetch()) {
  497. $base_entry_id = $row["id"];
  498. $entry_stored_hash = $row["content_hash"];
  499. $article_labels = Article::get_article_labels($base_entry_id, $owner_uid);
  500. $entry_language = $row["lang"];
  501. $existing_tags = Article::get_article_tags($base_entry_id, $owner_uid);
  502. $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
  503. } else {
  504. $base_entry_id = false;
  505. $entry_stored_hash = "";
  506. $article_labels = array();
  507. $entry_language = "";
  508. }
  509. $article = array("owner_uid" => $owner_uid, // read only
  510. "guid" => $entry_guid, // read only
  511. "guid_hashed" => $entry_guid_hashed, // read only
  512. "title" => $entry_title,
  513. "content" => $entry_content,
  514. "link" => $entry_link,
  515. "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
  516. "tags" => $entry_tags,
  517. "author" => $entry_author,
  518. "force_catchup" => false, // ugly hack for the time being
  519. "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
  520. "language" => $entry_language,
  521. "num_comments" => $num_comments, // read only
  522. "feed" => array("id" => $feed,
  523. "fetch_url" => $fetch_url,
  524. "site_url" => $site_url,
  525. "cache_images" => $cache_images)
  526. );
  527. $entry_plugin_data = "";
  528. $entry_current_hash = RSSUtils::calculate_article_hash($article, $pluginhost);
  529. _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
  530. if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
  531. _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
  532. // we keep encountering the entry in feeds, so we need to
  533. // update date_updated column so that we don't get horrible
  534. // dupes when the entry gets purged and reinserted again e.g.
  535. // in the case of SLOW SLOW OMG SLOW updating feeds
  536. $sth = $pdo->prepare("UPDATE ttrss_entries SET date_updated = NOW()
  537. WHERE id = ?");
  538. $sth->execute([$base_entry_id]);
  539. $pdo->commit();
  540. continue;
  541. }
  542. _debug("hash differs, applying plugin filters:", $debug_enabled);
  543. foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
  544. _debug("... " . get_class($plugin), $debug_enabled);
  545. $start = microtime(true);
  546. $article = $plugin->hook_article_filter($article);
  547. _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
  548. $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
  549. }
  550. if ($_REQUEST["xdebug"] == 2) {
  551. print "processed content: ";
  552. print htmlspecialchars($article["content"]);
  553. print "\n";
  554. }
  555. _debug("plugin data: $entry_plugin_data", $debug_enabled);
  556. // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
  557. if (DB_TYPE == "mysql") {
  558. foreach ($article as $k => $v) {
  559. // i guess we'll have to take the risk of 4byte unicode labels & tags here
  560. if (is_string($article[$k])) {
  561. $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
  562. }
  563. }
  564. }
  565. /* Collect article tags here so we could filter by them: */
  566. $matched_rules = array();
  567. $article_filters = RSSUtils::get_article_filters($filters, $article["title"],
  568. $article["content"], $article["link"], $article["author"],
  569. $article["tags"], $matched_rules);
  570. if ($debug_enabled) {
  571. _debug("matched filter rules: ", $debug_enabled);
  572. if (count($matched_rules) != 0) {
  573. print_r($matched_rules);
  574. }
  575. _debug("filter actions: ", $debug_enabled);
  576. if (count($article_filters) != 0) {
  577. print_r($article_filters);
  578. }
  579. }
  580. $plugin_filter_names = RSSUtils::find_article_filters($article_filters, "plugin");
  581. $plugin_filter_actions = $pluginhost->get_filter_actions();
  582. if (count($plugin_filter_names) > 0) {
  583. _debug("applying plugin filter actions...", $debug_enabled);
  584. foreach ($plugin_filter_names as $pfn) {
  585. list($pfclass,$pfaction) = explode(":", $pfn["param"]);
  586. if (isset($plugin_filter_actions[$pfclass])) {
  587. $plugin = $pluginhost->get_plugin($pfclass);
  588. _debug("... $pfclass: $pfaction", $debug_enabled);
  589. if ($plugin) {
  590. $start = microtime(true);
  591. $article = $plugin->hook_article_filter_action($article, $pfaction);
  592. _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
  593. } else {
  594. _debug("??? $pfclass: plugin object not found.");
  595. }
  596. } else {
  597. _debug("??? $pfclass: filter plugin not registered.");
  598. }
  599. }
  600. }
  601. $entry_tags = $article["tags"];
  602. $entry_title = strip_tags($article["title"]);
  603. $entry_author = mb_substr(strip_tags($article["author"]), 0, 245);
  604. $entry_link = strip_tags($article["link"]);
  605. $entry_content = $article["content"]; // escaped below
  606. $entry_force_catchup = $article["force_catchup"];
  607. $article_labels = $article["labels"];
  608. $entry_score_modifier = (int) $article["score_modifier"];
  609. $entry_language = $article["language"];
  610. if ($debug_enabled) {
  611. _debug("article labels:", $debug_enabled);
  612. if (count($article_labels) != 0) {
  613. print_r($article_labels);
  614. }
  615. }
  616. _debug("force catchup: $entry_force_catchup");
  617. if ($cache_images && is_writable(CACHE_DIR . '/images'))
  618. RSSUtils::cache_media($entry_content, $site_url, $debug_enabled);
  619. $csth = $pdo->prepare("SELECT id FROM ttrss_entries
  620. WHERE guid = ? OR guid = ?");
  621. $csth->execute([$entry_guid, $entry_guid_hashed]);
  622. if (!$row = $csth->fetch()) {
  623. _debug("base guid [$entry_guid or $entry_guid_hashed] not found, creating...", $debug_enabled);
  624. // base post entry does not exist, create it
  625. $usth = $pdo->prepare(
  626. "INSERT INTO ttrss_entries
  627. (title,
  628. guid,
  629. link,
  630. updated,
  631. content,
  632. content_hash,
  633. no_orig_date,
  634. date_updated,
  635. date_entered,
  636. comments,
  637. num_comments,
  638. plugin_data,
  639. lang,
  640. author)
  641. VALUES
  642. (?, ?, ?, ?, ?, ?,
  643. false,
  644. NOW(),
  645. ?, ?, ?, ?, ?, ?)");
  646. $usth->execute([$entry_title,
  647. $entry_guid_hashed,
  648. $entry_link,
  649. $entry_timestamp_fmt,
  650. $entry_content,
  651. $entry_current_hash,
  652. $date_feed_processed,
  653. $entry_comments,
  654. $num_comments,
  655. $entry_plugin_data,
  656. $entry_language,
  657. $entry_author]);
  658. }
  659. $csth->execute([$entry_guid, $entry_guid_hashed]);
  660. $entry_ref_id = 0;
  661. $entry_int_id = 0;
  662. if ($row = $csth->fetch()) {
  663. _debug("base guid found, checking for user record", $debug_enabled);
  664. $ref_id = $row['id'];
  665. $entry_ref_id = $ref_id;
  666. if (RSSUtils::find_article_filter($article_filters, "filter")) {
  667. $pdo->commit();
  668. continue;
  669. }
  670. $score = RSSUtils::calculate_article_score($article_filters) + $entry_score_modifier;
  671. _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
  672. // check for user post link to main table
  673. $sth = $pdo->prepare("SELECT ref_id, int_id FROM ttrss_user_entries WHERE
  674. ref_id = ? AND owner_uid = ?");
  675. $sth->execute([$ref_id, $owner_uid]);
  676. // okay it doesn't exist - create user entry
  677. if ($row = $sth->fetch()) {
  678. $entry_ref_id = $row["ref_id"];
  679. $entry_int_id = $row["int_id"];
  680. _debug("user record FOUND: RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
  681. } else {
  682. _debug("user record not found, creating...", $debug_enabled);
  683. if ($score >= -500 && !RSSUtils::find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
  684. $unread = 1;
  685. $last_read_qpart = null;
  686. } else {
  687. $unread = 0;
  688. $last_read_qpart = 'NOW()';
  689. }
  690. if (RSSUtils::find_article_filter($article_filters, 'mark') || $score > 1000) {
  691. $marked = 1;
  692. } else {
  693. $marked = 0;
  694. }
  695. if (RSSUtils::find_article_filter($article_filters, 'publish')) {
  696. $published = 1;
  697. } else {
  698. $published = 0;
  699. }
  700. $last_marked = ($marked == 'true') ? 'NOW()' : null;
  701. $last_published = ($published == 'true') ? 'NOW()' : null;
  702. $sth = $pdo->prepare(
  703. "INSERT INTO ttrss_user_entries
  704. (ref_id, owner_uid, feed_id, unread, last_read, marked,
  705. published, score, tag_cache, label_cache, uuid,
  706. last_marked, last_published)
  707. VALUES (?, ?, ?, ?, ?, ?, ?, ?, '', '', '', ?, ?)");
  708. $sth->execute([$ref_id, $owner_uid, $feed, $unread, $last_read_qpart, $marked,
  709. $published, $score, $last_marked, $last_published]);
  710. $sth = $pdo->prepare("SELECT int_id FROM ttrss_user_entries WHERE
  711. ref_id = ? AND owner_uid = ? AND
  712. feed_id = ? LIMIT 1");
  713. $sth->execute([$ref_id, $owner_uid, $feed]);
  714. if ($row = $sth->fetch())
  715. $entry_int_id = $row['int_id'];
  716. }
  717. _debug("resulting RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
  718. if (DB_TYPE == "pgsql") {
  719. $tsvector_combined = mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
  720. 0, 1000000);
  721. $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', ".$pdo->quote($tsvector_combined)."),";
  722. } else {
  723. $tsvector_qpart = "";
  724. }
  725. $sth = $pdo->prepare("UPDATE ttrss_entries
  726. SET title = ?,
  727. content = ?,
  728. content_hash = ?,
  729. updated = ?,
  730. $tsvector_qpart
  731. num_comments = ?,
  732. plugin_data = ?,
  733. author = ?,
  734. lang = ?
  735. WHERE id = ?");
  736. $sth->execute([$entry_title, $entry_content, $entry_current_hash, $entry_timestamp_fmt,
  737. $num_comments, $entry_plugin_data, $entry_author, $entry_language, $ref_id]);
  738. // update aux data
  739. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  740. SET score = ? WHERE ref_id = ?");
  741. $sth->execute([$score, $ref_id]);
  742. if ($mark_unread_on_update) {
  743. _debug("article updated, marking unread as requested.", $debug_enabled);
  744. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  745. SET last_read = null, unread = true WHERE ref_id = ?");
  746. $sth->execute([$ref_id]);
  747. }
  748. }
  749. _debug("assigning labels [other]...", $debug_enabled);
  750. foreach ($article_labels as $label) {
  751. Labels::add_article($entry_ref_id, $label[1], $owner_uid);
  752. }
  753. _debug("assigning labels [filters]...", $debug_enabled);
  754. RSSUtils::assign_article_to_label_filters($entry_ref_id, $article_filters,
  755. $owner_uid, $article_labels);
  756. _debug("looking for enclosures...", $debug_enabled);
  757. // enclosures
  758. $enclosures = array();
  759. $encs = $item->get_enclosures();
  760. if (is_array($encs)) {
  761. foreach ($encs as $e) {
  762. $e_item = array(
  763. rewrite_relative_url($site_url, $e->link),
  764. $e->type, $e->length, $e->title, $e->width, $e->height);
  765. array_push($enclosures, $e_item);
  766. }
  767. }
  768. if ($cache_images && is_writable(CACHE_DIR . '/images'))
  769. RSSUtils::cache_enclosures($enclosures, $site_url, $debug_enabled);
  770. if ($debug_enabled) {
  771. _debug("article enclosures:", $debug_enabled);
  772. print_r($enclosures);
  773. }
  774. $esth = $pdo->prepare("SELECT id FROM ttrss_enclosures
  775. WHERE content_url = ? AND post_id = ?");
  776. $usth = $pdo->prepare("INSERT INTO ttrss_enclosures
  777. (content_url, content_type, title, duration, post_id, width, height) VALUES
  778. (?, ?, ?, ?, ?, ?, ?)");
  779. foreach ($enclosures as $enc) {
  780. $enc_url = $enc[0];
  781. $enc_type = $enc[1];
  782. $enc_dur = (int)$enc[2];
  783. $enc_title = $enc[3];
  784. $enc_width = intval($enc[4]);
  785. $enc_height = intval($enc[5]);
  786. $esth->execute([$enc_url, $entry_ref_id]);
  787. if (!$esth->fetch()) {
  788. $usth->execute([$enc_url, $enc_type, (string)$enc_title, $enc_dur, $entry_ref_id, $enc_width, $enc_height]);
  789. }
  790. }
  791. // check for manual tags (we have to do it here since they're loaded from filters)
  792. foreach ($article_filters as $f) {
  793. if ($f["type"] == "tag") {
  794. $manual_tags = trim_array(explode(",", $f["param"]));
  795. foreach ($manual_tags as $tag) {
  796. if (tag_is_valid($tag)) {
  797. array_push($entry_tags, $tag);
  798. }
  799. }
  800. }
  801. }
  802. // Skip boring tags
  803. $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
  804. 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
  805. $filtered_tags = array();
  806. $tags_to_cache = array();
  807. if ($entry_tags && is_array($entry_tags)) {
  808. foreach ($entry_tags as $tag) {
  809. if (array_search($tag, $boring_tags) === false) {
  810. array_push($filtered_tags, $tag);
  811. }
  812. }
  813. }
  814. $filtered_tags = array_unique($filtered_tags);
  815. if ($debug_enabled) {
  816. _debug("filtered article tags:", $debug_enabled);
  817. print_r($filtered_tags);
  818. }
  819. // Save article tags in the database
  820. if (count($filtered_tags) > 0) {
  821. $tsth = $pdo->prepare("SELECT id FROM ttrss_tags
  822. WHERE tag_name = ? AND post_int_id = ? AND
  823. owner_uid = ? LIMIT 1");
  824. $usth = $pdo->prepare("INSERT INTO ttrss_tags
  825. (owner_uid,tag_name,post_int_id)
  826. VALUES (?, ?, ?)");
  827. foreach ($filtered_tags as $tag) {
  828. $tag = sanitize_tag($tag);
  829. if (!tag_is_valid($tag)) continue;
  830. $tsth->execute([$tag, $entry_int_id, $owner_uid]);
  831. if (!$tsth->fetch()) {
  832. $usth->execute([$owner_uid, $tag, $entry_int_id]);
  833. }
  834. array_push($tags_to_cache, $tag);
  835. }
  836. /* update the cache */
  837. $tags_to_cache = array_unique($tags_to_cache);
  838. $tags_str = join(",", $tags_to_cache);
  839. $tsth = $pdo->prepare("UPDATE ttrss_user_entries
  840. SET tag_cache = ? WHERE ref_id = ?
  841. AND owner_uid = ?");
  842. $tsth->execute([$tags_str, $entry_ref_id, $owner_uid]);
  843. }
  844. _debug("article processed", $debug_enabled);
  845. $pdo->commit();
  846. }
  847. _debug("purging feed...", $debug_enabled);
  848. purge_feed($feed, 0, $debug_enabled);
  849. $sth = $pdo->prepare("UPDATE ttrss_feeds
  850. SET last_updated = NOW(), last_unconditional = NOW(), last_error = '' WHERE id = ?");
  851. $sth->execute([$feed]);
  852. } else {
  853. $error_msg = mb_substr($rss->error(), 0, 245);
  854. _debug("fetch error: $error_msg", $debug_enabled);
  855. if (count($rss->errors()) > 1) {
  856. foreach ($rss->errors() as $error) {
  857. _debug("+ $error");
  858. }
  859. }
  860. $sth = $pdo->prepare("UPDATE ttrss_feeds SET last_error = ?,
  861. last_updated = NOW(), last_unconditional = NOW() WHERE id = ?");
  862. $sth->execute([$error_msg, $feed]);
  863. unset($rss);
  864. return false;
  865. }
  866. _debug("done", $debug_enabled);
  867. return true;
  868. }
  869. static function cache_enclosures($enclosures, $site_url, $debug) {
  870. foreach ($enclosures as $enc) {
  871. if (preg_match("/(image|audio|video)/", $enc[1])) {
  872. $src = rewrite_relative_url($site_url, $enc[0]);
  873. $local_filename = CACHE_DIR . "/images/" . sha1($src);
  874. if ($debug) _debug("cache_enclosures: downloading: $src to $local_filename");
  875. if (!file_exists($local_filename)) {
  876. $file_content = fetch_file_contents($src);
  877. if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
  878. file_put_contents($local_filename, $file_content);
  879. }
  880. } else {
  881. touch($local_filename);
  882. }
  883. }
  884. }
  885. }
  886. static function cache_media($html, $site_url, $debug) {
  887. libxml_use_internal_errors(true);
  888. $charset_hack = '<head>
  889. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  890. </head>';
  891. $doc = new DOMDocument();
  892. $doc->loadHTML($charset_hack . $html);
  893. $xpath = new DOMXPath($doc);
  894. $entries = $xpath->query('(//img[@src])|(//video/source[@src])|(//audio/source[@src])');
  895. foreach ($entries as $entry) {
  896. if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
  897. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  898. $local_filename = CACHE_DIR . "/images/" . sha1($src);
  899. if ($debug) _debug("cache_media: downloading: $src to $local_filename");
  900. if (!file_exists($local_filename)) {
  901. $file_content = fetch_file_contents($src);
  902. if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
  903. file_put_contents($local_filename, $file_content);
  904. }
  905. } else {
  906. touch($local_filename);
  907. }
  908. }
  909. }
  910. }
  911. static function expire_error_log($debug) {
  912. if ($debug) _debug("Removing old error log entries...");
  913. $pdo = Db::pdo();
  914. if (DB_TYPE == "pgsql") {
  915. $pdo->query("DELETE FROM ttrss_error_log
  916. WHERE created_at < NOW() - INTERVAL '7 days'");
  917. } else {
  918. $pdo->query("DELETE FROM ttrss_error_log
  919. WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
  920. }
  921. }
  922. static function expire_lock_files($debug) {
  923. //if ($debug) _debug("Removing old lock files...");
  924. $num_deleted = 0;
  925. if (is_writable(LOCK_DIRECTORY)) {
  926. $files = glob(LOCK_DIRECTORY . "/*.lock");
  927. if ($files) {
  928. foreach ($files as $file) {
  929. if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
  930. unlink($file);
  931. ++$num_deleted;
  932. }
  933. }
  934. }
  935. }
  936. if ($debug) _debug("Removed $num_deleted old lock files.");
  937. }
  938. static function expire_cached_files($debug) {
  939. foreach (array("simplepie", "images", "export", "upload") as $dir) {
  940. $cache_dir = CACHE_DIR . "/$dir";
  941. // if ($debug) _debug("Expiring $cache_dir");
  942. $num_deleted = 0;
  943. if (is_writable($cache_dir)) {
  944. $files = glob("$cache_dir/*");
  945. if ($files) {
  946. foreach ($files as $file) {
  947. if (time() - filemtime($file) > 86400*CACHE_MAX_DAYS) {
  948. unlink($file);
  949. ++$num_deleted;
  950. }
  951. }
  952. }
  953. }
  954. if ($debug) _debug("$cache_dir: removed $num_deleted files.");
  955. }
  956. }
  957. /**
  958. * Source: http://www.php.net/manual/en/function.parse-url.php#104527
  959. * Returns the url query as associative array
  960. *
  961. * @param string query
  962. * @return array params
  963. */
  964. static function convertUrlQuery($query) {
  965. $queryParts = explode('&', $query);
  966. $params = array();
  967. foreach ($queryParts as $param) {
  968. $item = explode('=', $param);
  969. $params[$item[0]] = $item[1];
  970. }
  971. return $params;
  972. }
  973. static function get_article_filters($filters, $title, $content, $link, $author, $tags, &$matched_rules = false) {
  974. $matches = array();
  975. foreach ($filters as $filter) {
  976. $match_any_rule = $filter["match_any_rule"];
  977. $inverse = $filter["inverse"];
  978. $filter_match = false;
  979. foreach ($filter["rules"] as $rule) {
  980. $match = false;
  981. $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
  982. $rule_inverse = $rule["inverse"];
  983. if (!$reg_exp)
  984. continue;
  985. switch ($rule["type"]) {
  986. case "title":
  987. $match = @preg_match("/$reg_exp/iu", $title);
  988. break;
  989. case "content":
  990. // we don't need to deal with multiline regexps
  991. $content = preg_replace("/[\r\n\t]/", "", $content);
  992. $match = @preg_match("/$reg_exp/iu", $content);
  993. break;
  994. case "both":
  995. // we don't need to deal with multiline regexps
  996. $content = preg_replace("/[\r\n\t]/", "", $content);
  997. $match = (@preg_match("/$reg_exp/iu", $title) || @preg_match("/$reg_exp/iu", $content));
  998. break;
  999. case "link":
  1000. $match = @preg_match("/$reg_exp/iu", $link);
  1001. break;
  1002. case "author":
  1003. $match = @preg_match("/$reg_exp/iu", $author);
  1004. break;
  1005. case "tag":
  1006. foreach ($tags as $tag) {
  1007. if (@preg_match("/$reg_exp/iu", $tag)) {
  1008. $match = true;
  1009. break;
  1010. }
  1011. }
  1012. break;
  1013. }
  1014. if ($rule_inverse) $match = !$match;
  1015. if ($match_any_rule) {
  1016. if ($match) {
  1017. $filter_match = true;
  1018. break;
  1019. }
  1020. } else {
  1021. $filter_match = $match;
  1022. if (!$match) {
  1023. break;
  1024. }
  1025. }
  1026. }
  1027. if ($inverse) $filter_match = !$filter_match;
  1028. if ($filter_match) {
  1029. if (is_array($matched_rules)) array_push($matched_rules, $rule);
  1030. foreach ($filter["actions"] AS $action) {
  1031. array_push($matches, $action);
  1032. // if Stop action encountered, perform no further processing
  1033. if (isset($action["type"]) && $action["type"] == "stop") return $matches;
  1034. }
  1035. }
  1036. }
  1037. return $matches;
  1038. }
  1039. static function find_article_filter($filters, $filter_name) {
  1040. foreach ($filters as $f) {
  1041. if ($f["type"] == $filter_name) {
  1042. return $f;
  1043. };
  1044. }
  1045. return false;
  1046. }
  1047. static function find_article_filters($filters, $filter_name) {
  1048. $results = array();
  1049. foreach ($filters as $f) {
  1050. if ($f["type"] == $filter_name) {
  1051. array_push($results, $f);
  1052. };
  1053. }
  1054. return $results;
  1055. }
  1056. static function calculate_article_score($filters) {
  1057. $score = 0;
  1058. foreach ($filters as $f) {
  1059. if ($f["type"] == "score") {
  1060. $score += $f["param"];
  1061. };
  1062. }
  1063. return $score;
  1064. }
  1065. static function labels_contains_caption($labels, $caption) {
  1066. foreach ($labels as $label) {
  1067. if ($label[1] == $caption) {
  1068. return true;
  1069. }
  1070. }
  1071. return false;
  1072. }
  1073. static function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
  1074. foreach ($filters as $f) {
  1075. if ($f["type"] == "label") {
  1076. if (!RSSUtils::labels_contains_caption($article_labels, $f["param"])) {
  1077. Labels::add_article($id, $f["param"], $owner_uid);
  1078. }
  1079. }
  1080. }
  1081. }
  1082. static function make_guid_from_title($title) {
  1083. return preg_replace("/[ \"\',.:;]/", "-",
  1084. mb_strtolower(strip_tags($title), 'utf-8'));
  1085. }
  1086. static function cleanup_counters_cache($debug) {
  1087. $pdo = Db::pdo();
  1088. $res = $pdo->query("DELETE FROM ttrss_counters_cache
  1089. WHERE feed_id > 0 AND
  1090. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  1091. id = feed_id AND
  1092. ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
  1093. $frows = $res->rowCount();
  1094. $res = $pdo->query("DELETE FROM ttrss_cat_counters_cache
  1095. WHERE feed_id > 0 AND
  1096. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  1097. id = feed_id AND
  1098. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
  1099. $crows = $res->rowCount();
  1100. if ($debug) _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
  1101. }
  1102. static function housekeeping_user($owner_uid) {
  1103. $tmph = new PluginHost();
  1104. load_user_plugins($owner_uid, $tmph);
  1105. $tmph->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
  1106. }
  1107. static function housekeeping_common($debug) {
  1108. RSSUtils::expire_cached_files($debug);
  1109. RSSUtils::expire_lock_files($debug);
  1110. RSSUtils::expire_error_log($debug);
  1111. $count = RSSUtils::update_feedbrowser_cache();
  1112. _debug("Feedbrowser updated, $count feeds processed.");
  1113. Article::purge_orphans( true);
  1114. RSSUtils::cleanup_counters_cache($debug);
  1115. //$rc = cleanup_tags( 14, 50000);
  1116. //_debug("Cleaned $rc cached tags.");
  1117. PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
  1118. }
  1119. static function check_feed_favicon($site_url, $feed) {
  1120. # print "FAVICON [$site_url]: $favicon_url\n";
  1121. $icon_file = ICONS_DIR . "/$feed.ico";
  1122. if (!file_exists($icon_file)) {
  1123. $favicon_url = get_favicon_url($site_url);
  1124. if ($favicon_url) {
  1125. // Limiting to "image" type misses those served with text/plain
  1126. $contents = fetch_file_contents($favicon_url); // , "image");
  1127. if ($contents) {
  1128. // Crude image type matching.
  1129. // Patterns gleaned from the file(1) source code.
  1130. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  1131. // 0 string \000\000\001\000 MS Windows icon resource
  1132. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  1133. }
  1134. elseif (preg_match('/^GIF8/', $contents)) {
  1135. // 0 string GIF8 GIF image data
  1136. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  1137. }
  1138. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  1139. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  1140. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  1141. }
  1142. elseif (preg_match('/^\xff\xd8/', $contents)) {
  1143. // 0 beshort 0xffd8 JPEG image data
  1144. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  1145. }
  1146. elseif (preg_match('/^BM/', $contents)) {
  1147. // 0 string BM PC bitmap (OS2, Windows BMP files)
  1148. //error_log("check_feed_favicon, favicon_url=$favicon_url isa BMP image");
  1149. }
  1150. else {
  1151. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  1152. $contents = "";
  1153. }
  1154. }
  1155. if ($contents) {
  1156. $fp = @fopen($icon_file, "w");
  1157. if ($fp) {
  1158. fwrite($fp, $contents);
  1159. fclose($fp);
  1160. chmod($icon_file, 0644);
  1161. }
  1162. }
  1163. }
  1164. return $icon_file;
  1165. }
  1166. }
  1167. }