rssfuncs.php 41 KB

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