rssutils.php 53 KB

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