rssfuncs.php 39 KB

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