rssfuncs.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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);
  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. foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
  207. $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass);
  208. }
  209. // try cache
  210. if (!$feed_data &&
  211. file_exists($cache_filename) &&
  212. is_readable($cache_filename) &&
  213. !$auth_login && !$auth_pass &&
  214. filemtime($cache_filename) > time() - 30) {
  215. _debug("using local cache [$cache_filename].", $debug_enabled);
  216. @$feed_data = file_get_contents($cache_filename);
  217. if ($feed_data) {
  218. $rss_hash = sha1($feed_data);
  219. }
  220. } else {
  221. _debug("local cache will not be used for this feed", $debug_enabled);
  222. }
  223. // fetch feed from source
  224. if (!$feed_data) {
  225. _debug("fetching [$fetch_url]...", $debug_enabled);
  226. _debug("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $last_article_timestamp), $debug_enabled);
  227. $feed_data = fetch_file_contents($fetch_url, false,
  228. $auth_login, $auth_pass, false,
  229. $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
  230. $force_refetch ? 0 : $last_article_timestamp);
  231. global $fetch_curl_used;
  232. if (!$fetch_curl_used) {
  233. $tmp = @gzdecode($feed_data);
  234. if ($tmp) $feed_data = $tmp;
  235. }
  236. $feed_data = trim($feed_data);
  237. _debug("fetch done.", $debug_enabled);
  238. /* if ($feed_data) {
  239. $error = verify_feed_xml($feed_data);
  240. if ($error) {
  241. _debug("error verifying XML, code: " . $error->code, $debug_enabled);
  242. if ($error->code == 26) {
  243. _debug("got error 26, trying to decode entities...", $debug_enabled);
  244. $feed_data = html_entity_decode($feed_data, ENT_COMPAT, 'UTF-8');
  245. $error = verify_feed_xml($feed_data);
  246. if ($error) $feed_data = '';
  247. }
  248. }
  249. } */
  250. // cache vanilla feed data for re-use
  251. if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
  252. $new_rss_hash = sha1($feed_data);
  253. if ($new_rss_hash != $rss_hash) {
  254. _debug("saving $cache_filename", $debug_enabled);
  255. @file_put_contents($cache_filename, $feed_data);
  256. }
  257. }
  258. }
  259. if (!$feed_data) {
  260. global $fetch_last_error;
  261. global $fetch_last_error_code;
  262. _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
  263. $error_escaped = '';
  264. // If-Modified-Since
  265. if ($fetch_last_error_code != 304) {
  266. $error_escaped = db_escape_string($fetch_last_error);
  267. } else {
  268. _debug("source claims data not modified, nothing to do.", $debug_enabled);
  269. }
  270. db_query(
  271. "UPDATE ttrss_feeds SET last_error = '$error_escaped',
  272. last_updated = NOW() WHERE id = '$feed'");
  273. return;
  274. }
  275. }
  276. foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
  277. $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
  278. }
  279. // set last update to now so if anything *simplepie* crashes later we won't be
  280. // continuously failing on the same feed
  281. //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
  282. if (!$rss) {
  283. $rss = new FeedParser($feed_data);
  284. $rss->init();
  285. }
  286. if (DETECT_ARTICLE_LANGUAGE) {
  287. require_once "lib/languagedetect/LanguageDetect.php";
  288. $lang = new Text_LanguageDetect();
  289. $lang->setNameMode(2);
  290. }
  291. // print_r($rss);
  292. $feed = db_escape_string($feed);
  293. if (!$rss->error()) {
  294. // We use local pluginhost here because we need to load different per-user feed plugins
  295. $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
  296. _debug("processing feed data...", $debug_enabled);
  297. // db_query("BEGIN");
  298. if (DB_TYPE == "pgsql") {
  299. $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
  300. } else {
  301. $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
  302. }
  303. $result = db_query("SELECT title,site_url,owner_uid,favicon_avg_color,
  304. (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
  305. favicon_needs_check
  306. FROM ttrss_feeds WHERE id = '$feed'");
  307. $registered_title = db_fetch_result($result, 0, "title");
  308. $orig_site_url = db_fetch_result($result, 0, "site_url");
  309. $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
  310. "favicon_needs_check"));
  311. $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
  312. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  313. $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
  314. _debug("site_url: $site_url", $debug_enabled);
  315. _debug("feed_title: " . $rss->get_title(), $debug_enabled);
  316. if ($favicon_needs_check || $force_refetch) {
  317. /* terrible hack: if we crash on floicon shit here, we won't check
  318. * the icon avgcolor again (unless the icon got updated) */
  319. $favicon_file = ICONS_DIR . "/$feed.ico";
  320. $favicon_modified = @filemtime($favicon_file);
  321. _debug("checking favicon...", $debug_enabled);
  322. check_feed_favicon($site_url, $feed);
  323. $favicon_modified_new = @filemtime($favicon_file);
  324. if ($favicon_modified_new > $favicon_modified)
  325. $favicon_avg_color = '';
  326. if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
  327. require_once "colors.php";
  328. db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
  329. id = '$feed'");
  330. $favicon_color = db_escape_string(
  331. calculate_avg_color($favicon_file));
  332. $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
  333. } else if ($favicon_avg_color == 'fail') {
  334. _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
  335. }
  336. db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
  337. $favicon_colorstring
  338. WHERE id = '$feed'");
  339. }
  340. if (!$registered_title || $registered_title == "[Unknown]") {
  341. $feed_title = db_escape_string($rss->get_title());
  342. if ($feed_title) {
  343. _debug("registering title: $feed_title", $debug_enabled);
  344. db_query("UPDATE ttrss_feeds SET
  345. title = '$feed_title' WHERE id = '$feed'");
  346. }
  347. }
  348. if ($site_url && $orig_site_url != $site_url) {
  349. db_query("UPDATE ttrss_feeds SET
  350. site_url = '$site_url' WHERE id = '$feed'");
  351. }
  352. _debug("loading filters & labels...", $debug_enabled);
  353. $filters = load_filters($feed, $owner_uid);
  354. $labels = get_all_labels($owner_uid);
  355. _debug("" . count($filters) . " filters loaded.", $debug_enabled);
  356. $items = $rss->get_items();
  357. if (!is_array($items)) {
  358. _debug("no articles found.", $debug_enabled);
  359. db_query("UPDATE ttrss_feeds
  360. SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
  361. return; // no articles
  362. }
  363. if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
  364. _debug("checking for PUSH hub...", $debug_enabled);
  365. $feed_hub_url = false;
  366. $links = $rss->get_links('hub');
  367. if ($links && is_array($links)) {
  368. foreach ($links as $l) {
  369. $feed_hub_url = $l;
  370. break;
  371. }
  372. }
  373. _debug("feed hub url: $feed_hub_url", $debug_enabled);
  374. $feed_self_url = $fetch_url;
  375. $links = $rss->get_links('self');
  376. if ($links && is_array($links)) {
  377. foreach ($links as $l) {
  378. $feed_self_url = $l;
  379. break;
  380. }
  381. }
  382. _debug("feed self url = $feed_self_url");
  383. if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
  384. !ini_get("open_basedir")) {
  385. require_once 'lib/pubsubhubbub/subscriber.php';
  386. $callback_url = get_self_url_prefix() .
  387. "/public.php?op=pubsub&id=$feed";
  388. $s = new Subscriber($feed_hub_url, $callback_url);
  389. $rc = $s->subscribe($feed_self_url);
  390. _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
  391. db_query("UPDATE ttrss_feeds SET pubsub_state = 1
  392. WHERE id = '$feed'");
  393. }
  394. }
  395. _debug("processing articles...", $debug_enabled);
  396. foreach ($items as $item) {
  397. if ($_REQUEST['xdebug'] == 3) {
  398. print_r($item);
  399. }
  400. $entry_guid = $item->get_id();
  401. if (!$entry_guid) $entry_guid = $item->get_link();
  402. if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
  403. _debug("f_guid $entry_guid", $debug_enabled);
  404. if (!$entry_guid) continue;
  405. $entry_guid = "$owner_uid,$entry_guid";
  406. $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
  407. _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
  408. $entry_timestamp = "";
  409. $entry_timestamp = $item->get_date();
  410. _debug("orig date: " . $item->get_date(), $debug_enabled);
  411. if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
  412. $entry_timestamp = time();
  413. }
  414. $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
  415. _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
  416. // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
  417. // $entry_title = decode_numeric_entities($entry_title);
  418. $entry_title = $item->get_title();
  419. $entry_link = rewrite_relative_url($site_url, $item->get_link());
  420. _debug("title $entry_title", $debug_enabled);
  421. _debug("link $entry_link", $debug_enabled);
  422. if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
  423. $entry_content = $item->get_content();
  424. if (!$entry_content) $entry_content = $item->get_description();
  425. if ($_REQUEST["xdebug"] == 2) {
  426. print "content: ";
  427. print $entry_content;
  428. print "\n";
  429. }
  430. $entry_language = "";
  431. if (DETECT_ARTICLE_LANGUAGE) {
  432. $entry_language = $lang->detect($entry_title . " " . $entry_content, 1);
  433. if (count($entry_language) > 0) {
  434. $entry_language = array_keys($entry_language);
  435. // the fuck?
  436. if (is_array($entry_language))
  437. $entry_language = "";
  438. else
  439. $entry_language = db_escape_string(substr($entry_language[0], 0, 2));
  440. _debug("detected language: $entry_language", $debug_enabled);
  441. } else {
  442. $entry_language = "";
  443. }
  444. }
  445. $entry_comments = $item->get_comments_url();
  446. $entry_author = $item->get_author();
  447. $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
  448. $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
  449. $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
  450. $num_comments = (int) $item->get_comments_count();
  451. _debug("author $entry_author", $debug_enabled);
  452. _debug("num_comments: $num_comments", $debug_enabled);
  453. _debug("looking for tags...", $debug_enabled);
  454. // parse <category> entries into tags
  455. $additional_tags = array();
  456. $additional_tags_src = $item->get_categories();
  457. if (is_array($additional_tags_src)) {
  458. foreach ($additional_tags_src as $tobj) {
  459. array_push($additional_tags, $tobj);
  460. }
  461. }
  462. $entry_tags = array_unique($additional_tags);
  463. for ($i = 0; $i < count($entry_tags); $i++)
  464. $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
  465. _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
  466. _debug("done collecting data.", $debug_enabled);
  467. // TODO: less memory-hungry implementation
  468. _debug("applying plugin filters..", $debug_enabled);
  469. // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
  470. $result = db_query("SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries
  471. WHERE ref_id = id AND (guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed') AND owner_uid = $owner_uid");
  472. if (db_num_rows($result) != 0) {
  473. $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
  474. $stored_article = array("title" => db_fetch_result($result, 0, "title"),
  475. "content" => db_fetch_result($result, 0, "content"),
  476. "link" => db_fetch_result($result, 0, "link"),
  477. "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")),
  478. "author" => db_fetch_result($result, 0, "author"));
  479. } else {
  480. $entry_plugin_data = "";
  481. $stored_article = array();
  482. }
  483. $article = array("owner_uid" => $owner_uid, // read only
  484. "guid" => $entry_guid, // read only
  485. "title" => $entry_title,
  486. "content" => $entry_content,
  487. "link" => $entry_link,
  488. "tags" => $entry_tags,
  489. "plugin_data" => $entry_plugin_data,
  490. "author" => $entry_author,
  491. "stored" => $stored_article,
  492. "feed" => array("id" => $feed,
  493. "fetch_url" => $fetch_url,
  494. "site_url" => $site_url)
  495. );
  496. foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
  497. $article = $plugin->hook_article_filter($article);
  498. }
  499. $entry_tags = $article["tags"];
  500. $entry_guid = db_escape_string($entry_guid);
  501. $entry_title = db_escape_string($article["title"]);
  502. $entry_author = db_escape_string($article["author"]);
  503. $entry_link = db_escape_string($article["link"]);
  504. $entry_plugin_data = db_escape_string($article["plugin_data"]);
  505. $entry_content = $article["content"]; // escaped below
  506. _debug("plugin data: $entry_plugin_data", $debug_enabled);
  507. if ($cache_images && is_writable(CACHE_DIR . '/images'))
  508. cache_images($entry_content, $site_url, $debug_enabled);
  509. $entry_content = db_escape_string($entry_content, false);
  510. $content_hash = "SHA1:" . sha1($entry_content);
  511. db_query("BEGIN");
  512. $result = db_query("SELECT id FROM ttrss_entries
  513. WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
  514. if (db_num_rows($result) == 0) {
  515. _debug("base guid [$entry_guid] not found", $debug_enabled);
  516. // base post entry does not exist, create it
  517. $result = db_query(
  518. "INSERT INTO ttrss_entries
  519. (title,
  520. guid,
  521. link,
  522. updated,
  523. content,
  524. content_hash,
  525. no_orig_date,
  526. date_updated,
  527. date_entered,
  528. comments,
  529. num_comments,
  530. plugin_data,
  531. lang,
  532. author)
  533. VALUES
  534. ('$entry_title',
  535. '$entry_guid_hashed',
  536. '$entry_link',
  537. '$entry_timestamp_fmt',
  538. '$entry_content',
  539. '$content_hash',
  540. false,
  541. NOW(),
  542. '$date_feed_processed',
  543. '$entry_comments',
  544. '$num_comments',
  545. '$entry_plugin_data',
  546. '$entry_language',
  547. '$entry_author')");
  548. $article_labels = array();
  549. } else {
  550. // we keep encountering the entry in feeds, so we need to
  551. // update date_updated column so that we don't get horrible
  552. // dupes when the entry gets purged and reinserted again e.g.
  553. // in the case of SLOW SLOW OMG SLOW updating feeds
  554. $base_entry_id = db_fetch_result($result, 0, "id");
  555. db_query("UPDATE ttrss_entries SET date_updated = NOW()
  556. WHERE id = '$base_entry_id'");
  557. $article_labels = get_article_labels($base_entry_id, $owner_uid);
  558. }
  559. // now it should exist, if not - bad luck then
  560. $result = db_query("SELECT
  561. id,content_hash,title,plugin_data,guid,
  562. num_comments
  563. FROM
  564. ttrss_entries
  565. WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
  566. $entry_ref_id = 0;
  567. $entry_int_id = 0;
  568. if (db_num_rows($result) == 1) {
  569. _debug("base guid found, checking for user record", $debug_enabled);
  570. // this will be used below in update handler
  571. $orig_content_hash = db_fetch_result($result, 0, "content_hash");
  572. $orig_title = db_fetch_result($result, 0, "title");
  573. $orig_num_comments = db_fetch_result($result, 0, "num_comments");
  574. $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
  575. $ref_id = db_fetch_result($result, 0, "id");
  576. $entry_ref_id = $ref_id;
  577. /* $stored_guid = db_fetch_result($result, 0, "guid");
  578. if ($stored_guid != $entry_guid_hashed) {
  579. if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
  580. db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
  581. id = '$ref_id'");
  582. } */
  583. // check for user post link to main table
  584. // do we allow duplicate posts with same GUID in different feeds?
  585. if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
  586. $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
  587. } else {
  588. $dupcheck_qpart = "";
  589. }
  590. /* Collect article tags here so we could filter by them: */
  591. $article_filters = get_article_filters($filters, $entry_title,
  592. $entry_content, $entry_link, $entry_timestamp, $entry_author,
  593. $entry_tags);
  594. if ($debug_enabled) {
  595. _debug("article filters: ", $debug_enabled);
  596. if (count($article_filters) != 0) {
  597. print_r($article_filters);
  598. }
  599. }
  600. if (find_article_filter($article_filters, "filter")) {
  601. db_query("COMMIT"); // close transaction in progress
  602. continue;
  603. }
  604. $score = calculate_article_score($article_filters);
  605. _debug("initial score: $score", $debug_enabled);
  606. $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
  607. ref_id = '$ref_id' AND owner_uid = '$owner_uid'
  608. $dupcheck_qpart";
  609. // if ($_REQUEST["xdebug"]) print "$query\n";
  610. $result = db_query($query);
  611. // okay it doesn't exist - create user entry
  612. if (db_num_rows($result) == 0) {
  613. _debug("user record not found, creating...", $debug_enabled);
  614. if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
  615. $unread = 'true';
  616. $last_read_qpart = 'NULL';
  617. } else {
  618. $unread = 'false';
  619. $last_read_qpart = 'NOW()';
  620. }
  621. if (find_article_filter($article_filters, 'mark') || $score > 1000) {
  622. $marked = 'true';
  623. } else {
  624. $marked = 'false';
  625. }
  626. if (find_article_filter($article_filters, 'publish')) {
  627. $published = 'true';
  628. } else {
  629. $published = 'false';
  630. }
  631. // N-grams
  632. if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
  633. $result = db_query("SELECT COUNT(*) AS similar FROM
  634. ttrss_entries,ttrss_user_entries
  635. WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
  636. AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
  637. AND owner_uid = $owner_uid");
  638. $ngram_similar = db_fetch_result($result, 0, "similar");
  639. _debug("N-gram similar results: $ngram_similar", $debug_enabled);
  640. if ($ngram_similar > 0) {
  641. $unread = 'false';
  642. }
  643. }
  644. $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
  645. $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
  646. $result = db_query(
  647. "INSERT INTO ttrss_user_entries
  648. (ref_id, owner_uid, feed_id, unread, last_read, marked,
  649. published, score, tag_cache, label_cache, uuid,
  650. last_marked, last_published)
  651. VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
  652. $last_read_qpart, $marked, $published, '$score', '', '',
  653. '', $last_marked, $last_published)");
  654. if (PUBSUBHUBBUB_HUB && $published == 'true') {
  655. $rss_link = get_self_url_prefix() .
  656. "/public.php?op=rss&id=-2&key=" .
  657. get_feed_access_key(-2, false, $owner_uid);
  658. $p = new Publisher(PUBSUBHUBBUB_HUB);
  659. /* $pubsub_result = */ $p->publish_update($rss_link);
  660. }
  661. $result = db_query(
  662. "SELECT int_id FROM ttrss_user_entries WHERE
  663. ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
  664. feed_id = '$feed' LIMIT 1");
  665. if (db_num_rows($result) == 1) {
  666. $entry_int_id = db_fetch_result($result, 0, "int_id");
  667. }
  668. } else {
  669. _debug("user record FOUND", $debug_enabled);
  670. $entry_ref_id = db_fetch_result($result, 0, "ref_id");
  671. $entry_int_id = db_fetch_result($result, 0, "int_id");
  672. }
  673. _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
  674. $post_needs_update = false;
  675. $update_insignificant = false;
  676. if ($orig_num_comments != $num_comments) {
  677. $post_needs_update = true;
  678. $update_insignificant = true;
  679. }
  680. if ($entry_plugin_data != $orig_plugin_data) {
  681. $post_needs_update = true;
  682. $update_insignificant = true;
  683. }
  684. if ($content_hash != $orig_content_hash) {
  685. $post_needs_update = true;
  686. $update_insignificant = false;
  687. }
  688. if (db_escape_string($orig_title) != $entry_title) {
  689. $post_needs_update = true;
  690. $update_insignificant = false;
  691. }
  692. // if post needs update, update it and mark all user entries
  693. // linking to this post as updated
  694. if ($post_needs_update) {
  695. if (defined('DAEMON_EXTENDED_DEBUG')) {
  696. _debug("post $entry_guid_hashed needs update...", $debug_enabled);
  697. }
  698. // print "<!-- post $orig_title needs update : $post_needs_update -->";
  699. db_query("UPDATE ttrss_entries
  700. SET title = '$entry_title', content = '$entry_content',
  701. content_hash = '$content_hash',
  702. updated = '$entry_timestamp_fmt',
  703. num_comments = '$num_comments',
  704. plugin_data = '$entry_plugin_data'
  705. WHERE id = '$ref_id'");
  706. if (!$update_insignificant) {
  707. if ($mark_unread_on_update) {
  708. db_query("UPDATE ttrss_user_entries
  709. SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
  710. }
  711. }
  712. }
  713. }
  714. db_query("COMMIT");
  715. _debug("assigning labels...", $debug_enabled);
  716. assign_article_to_label_filters($entry_ref_id, $article_filters,
  717. $owner_uid, $article_labels);
  718. _debug("looking for enclosures...", $debug_enabled);
  719. // enclosures
  720. $enclosures = array();
  721. $encs = $item->get_enclosures();
  722. if (is_array($encs)) {
  723. foreach ($encs as $e) {
  724. $e_item = array(
  725. $e->link, $e->type, $e->length, $e->title);
  726. array_push($enclosures, $e_item);
  727. }
  728. }
  729. if ($debug_enabled) {
  730. _debug("article enclosures:", $debug_enabled);
  731. print_r($enclosures);
  732. }
  733. db_query("BEGIN");
  734. // debugging
  735. // db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
  736. foreach ($enclosures as $enc) {
  737. $enc_url = db_escape_string($enc[0]);
  738. $enc_type = db_escape_string($enc[1]);
  739. $enc_dur = db_escape_string($enc[2]);
  740. $enc_title = db_escape_string($enc[3]);
  741. $result = db_query("SELECT id FROM ttrss_enclosures
  742. WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
  743. if (db_num_rows($result) == 0) {
  744. db_query("INSERT INTO ttrss_enclosures
  745. (content_url, content_type, title, duration, post_id) VALUES
  746. ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id')");
  747. }
  748. }
  749. db_query("COMMIT");
  750. // check for manual tags (we have to do it here since they're loaded from filters)
  751. foreach ($article_filters as $f) {
  752. if ($f["type"] == "tag") {
  753. $manual_tags = trim_array(explode(",", $f["param"]));
  754. foreach ($manual_tags as $tag) {
  755. if (tag_is_valid($tag)) {
  756. array_push($entry_tags, $tag);
  757. }
  758. }
  759. }
  760. }
  761. // Skip boring tags
  762. $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
  763. 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
  764. $filtered_tags = array();
  765. $tags_to_cache = array();
  766. if ($entry_tags && is_array($entry_tags)) {
  767. foreach ($entry_tags as $tag) {
  768. if (array_search($tag, $boring_tags) === false) {
  769. array_push($filtered_tags, $tag);
  770. }
  771. }
  772. }
  773. $filtered_tags = array_unique($filtered_tags);
  774. if ($debug_enabled) {
  775. _debug("filtered article tags:", $debug_enabled);
  776. print_r($filtered_tags);
  777. }
  778. // Save article tags in the database
  779. if (count($filtered_tags) > 0) {
  780. db_query("BEGIN");
  781. foreach ($filtered_tags as $tag) {
  782. $tag = sanitize_tag($tag);
  783. $tag = db_escape_string($tag);
  784. if (!tag_is_valid($tag)) continue;
  785. $result = db_query("SELECT id FROM ttrss_tags
  786. WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
  787. owner_uid = '$owner_uid' LIMIT 1");
  788. if ($result && db_num_rows($result) == 0) {
  789. db_query("INSERT INTO ttrss_tags
  790. (owner_uid,tag_name,post_int_id)
  791. VALUES ('$owner_uid','$tag', '$entry_int_id')");
  792. }
  793. array_push($tags_to_cache, $tag);
  794. }
  795. /* update the cache */
  796. $tags_to_cache = array_unique($tags_to_cache);
  797. $tags_str = db_escape_string(join(",", $tags_to_cache));
  798. db_query("UPDATE ttrss_user_entries
  799. SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
  800. AND owner_uid = $owner_uid");
  801. db_query("COMMIT");
  802. }
  803. if (get_pref("AUTO_ASSIGN_LABELS", $owner_uid, false)) {
  804. _debug("auto-assigning labels...", $debug_enabled);
  805. foreach ($labels as $label) {
  806. $caption = preg_quote($label["caption"]);
  807. if ($caption && preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
  808. if (!labels_contains_caption($article_labels, $caption)) {
  809. label_add_article($entry_ref_id, $caption, $owner_uid);
  810. }
  811. }
  812. }
  813. }
  814. _debug("article processed", $debug_enabled);
  815. }
  816. _debug("purging feed...", $debug_enabled);
  817. purge_feed($feed, 0, $debug_enabled);
  818. db_query("UPDATE ttrss_feeds
  819. SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
  820. // db_query("COMMIT");
  821. } else {
  822. $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
  823. _debug("fetch error: $error_msg", $debug_enabled);
  824. if (count($rss->errors()) > 1) {
  825. foreach ($rss->errors() as $error) {
  826. _debug("+ $error");
  827. }
  828. }
  829. db_query(
  830. "UPDATE ttrss_feeds SET last_error = '$error_msg',
  831. last_updated = NOW() WHERE id = '$feed'");
  832. unset($rss);
  833. }
  834. _debug("done", $debug_enabled);
  835. return $rss;
  836. }
  837. function cache_images($html, $site_url, $debug) {
  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. ?>