rssfuncs.php 41 KB

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