rssfuncs.php 40 KB

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