rssutils.php 46 KB

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