rssfuncs.php 41 KB

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