]> git.wh0rd.org - tt-rss.git/blame - include/rssfuncs.php
simplify article filter chaining mechanism, do not try to process already stored...
[tt-rss.git] / include / rssfuncs.php
CommitLineData
2c08214a 1<?php
fce451a4
AD
2 define_default('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define_default('DAEMON_FEED_LIMIT', 500);
e2cf81e2 4 define_default('DAEMON_SLEEP_INTERVAL', 120);
a3d50184 5 define_default('_MIN_CACHE_IMAGE_SIZE', 1024);
09e8bdfd 6
b1840673
AD
7 function calculate_article_hash($article) {
8 $ph = PluginHost::getInstance();
9 return sha1(implode(":", $ph->get_plugin_names()) . serialize($article));
10 }
11
6322ac79 12 function update_feedbrowser_cache() {
79178062 13
a42c55f0 14 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
79178062
AD
15 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
16 WHERE tf.feed_url = ttrss_feeds.feed_url
17 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
18 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
19
a42c55f0 20 db_query("BEGIN");
79178062 21
a42c55f0 22 db_query("DELETE FROM ttrss_feedbrowser_cache");
79178062
AD
23
24 $count = 0;
25
26 while ($line = db_fetch_assoc($result)) {
a42c55f0
AD
27 $subscribers = db_escape_string($line["subscribers"]);
28 $feed_url = db_escape_string($line["feed_url"]);
29 $title = db_escape_string($line["title"]);
30 $site_url = db_escape_string($line["site_url"]);
79178062 31
a42c55f0 32 $tmp_result = db_query("SELECT subscribers FROM
79178062
AD
33 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
34
35 if (db_num_rows($tmp_result) == 0) {
36
a42c55f0 37 db_query("INSERT INTO ttrss_feedbrowser_cache
79178062
AD
38 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
39 '$site_url', '$title', '$subscribers')");
40
41 ++$count;
42
43 }
44
45 }
46
a42c55f0 47 db_query("COMMIT");
79178062
AD
48
49 return $count;
50
51 }
52
53
2c08214a
AD
54 /**
55 * Update a feed batch.
56 * Used by daemons to update n feeds by run.
57 * Only update feed needing a update, and not being processed
58 * by another process.
59 *
60 * @param mixed $link Database link
61 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
62 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
63 * @param boolean $debug Set to false to disable debug output. Default to true.
64 * @return void
65 */
a42c55f0 66 function update_daemon_common($limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
2c08214a
AD
67 // Process all other feeds using last_updated and interval parameters
68
6322ac79 69 $schema_version = get_schema_version();
857efe49
AD
70
71 if ($schema_version != SCHEMA_VERSION) {
72 die("Schema version is wrong, please upgrade the database.\n");
73 }
74
61c1812f
AD
75 define('PREFS_NO_CACHE', true);
76
2c08214a 77 // Test if the user has loggued in recently. If not, it does not update its feeds.
09e8bdfd 78 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
2c08214a
AD
79 if (DB_TYPE == "pgsql") {
80 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
81 } else {
82 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
83 }
84 } else {
85 $login_thresh_qpart = "";
86 }
87
537eca40 88 // Test if the feed need a update (update interval exceeded).
2c08214a
AD
89 if (DB_TYPE == "pgsql") {
90 $update_limit_qpart = "AND ((
91 ttrss_feeds.update_interval = 0
ee0542ce 92 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
93 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
94 ) OR (
95 ttrss_feeds.update_interval > 0
96 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
f08426e3
AD
97 ) OR (ttrss_feeds.last_updated IS NULL
98 AND ttrss_user_prefs.value != '-1')
99 OR (last_updated = '1970-01-01 00:00:00'
100 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
101 } else {
102 $update_limit_qpart = "AND ((
103 ttrss_feeds.update_interval = 0
ee0542ce 104 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
105 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
106 ) OR (
107 ttrss_feeds.update_interval > 0
108 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
f08426e3
AD
109 ) OR (ttrss_feeds.last_updated IS NULL
110 AND ttrss_user_prefs.value != '-1')
111 OR (last_updated = '1970-01-01 00:00:00'
112 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
113 }
114
115 // Test if feed is currently being updated by another process.
116 if (DB_TYPE == "pgsql") {
566417c4 117 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
2c08214a 118 } else {
566417c4 119 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
2c08214a
AD
120 }
121
122 // Test if there is a limit to number of updated feeds
123 $query_limit = "";
124 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
125
fce451a4 126 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
2c08214a
AD
127 FROM
128 ttrss_feeds, ttrss_users, ttrss_user_prefs
f4ae0f05 129 WHERE
2c08214a 130 ttrss_feeds.owner_uid = ttrss_users.id
f08426e3 131 AND ttrss_user_prefs.profile IS NULL
2c08214a
AD
132 AND ttrss_users.id = ttrss_user_prefs.owner_uid
133 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
134 $login_thresh_qpart $update_limit_qpart
1c4421fc 135 $updstart_thresh_qpart
fce451a4
AD
136 ORDER BY last_updated $query_limit";
137
138 // We search for feed needing update.
139 $result = db_query($query);
2c08214a 140
ca5ff2d9 141 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
2c08214a
AD
142
143 // Here is a little cache magic in order to minimize risk of double feed updates.
144 $feeds_to_update = array();
145 while ($line = db_fetch_assoc($result)) {
a42c55f0 146 array_push($feeds_to_update, db_escape_string($line['feed_url']));
2c08214a
AD
147 }
148
149 // We update the feed last update started date before anything else.
150 // There is no lag due to feed contents downloads
151 // It prevent an other process to update the same feed.
1c4421fc
AD
152
153 if(count($feeds_to_update) > 0) {
154 $feeds_quoted = array();
155
156 foreach ($feeds_to_update as $feed) {
a42c55f0 157 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
1c4421fc
AD
158 }
159
a42c55f0 160 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
1c4421fc 161 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
2c08214a
AD
162 }
163
8292d05b
AD
164 $nf = 0;
165
2c08214a 166 // For each feed, we call the feed update function.
1c4421fc
AD
167 foreach ($feeds_to_update as $feed) {
168 if($debug) _debug("Base feed: $feed");
2c08214a 169
a42c55f0 170 //update_rss_feed($line["id"], true);
2c08214a 171
1c4421fc
AD
172 // since we have the data cached, we can deal with other feeds with the same url
173
15c762be 174 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
ee0542ce
AD
175 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
176 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
177 ttrss_users.id = ttrss_user_prefs.owner_uid AND
178 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
f08426e3 179 ttrss_user_prefs.profile IS NULL AND
a42c55f0 180 feed_url = '".db_escape_string($feed)."' AND
ee0542ce
AD
181 (ttrss_feeds.update_interval > 0 OR
182 ttrss_user_prefs.value != '-1')
1c4421fc 183 $login_thresh_qpart
5929a0c1 184 ORDER BY ttrss_feeds.id $query_limit");
1c4421fc
AD
185
186 if (db_num_rows($tmp_result) > 0) {
88edaa93
AD
187 $rss = false;
188
1c4421fc 189 while ($tline = db_fetch_assoc($tmp_result)) {
15c762be 190 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
f08426e3 191
f77c7203 192 $rss = update_rss_feed($tline["id"], true, false);
4f71d743 193 _debug_suppress(false);
8292d05b 194 ++$nf;
1c4421fc
AD
195 }
196 }
2c08214a
AD
197 }
198
f1611683
AD
199 require_once "digest.php";
200
2c08214a 201 // Send feed digests by email if needed.
a42c55f0 202 send_headlines_digests($debug);
2c08214a 203
8292d05b
AD
204 return $nf;
205
2c08214a
AD
206 } // function update_daemon_common
207
87764a50 208 // ignore_daemon is not used
88edaa93 209 function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false) {
2c08214a 210
2c08214a
AD
211 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
212
4f71d743 213 _debug_suppress(!$debug_enabled);
68cccafc 214 _debug("start", $debug_enabled);
2c08214a 215
a42c55f0 216 $result = db_query("SELECT id,update_interval,auth_login,
5ba1ddd4 217 feed_url,auth_pass,cache_images,
5321e775 218 mark_unread_on_update, owner_uid,
90e5f4f1
AD
219 pubsub_state, auth_pass_encrypted,
220 (SELECT max(date_entered) FROM
221 ttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '$feed') AS last_article_timestamp
87764a50 222 FROM ttrss_feeds WHERE id = '$feed'");
2c08214a
AD
223
224 if (db_num_rows($result) == 0) {
68cccafc 225 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
2c08214a
AD
226 return false;
227 }
228
90e5f4f1 229 $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
5d0d3887
AD
230
231 if (defined('_DISABLE_HTTP_304'))
232 $last_article_timestamp = 0;
233
2c08214a
AD
234 $owner_uid = db_fetch_result($result, 0, "owner_uid");
235 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
236 0, "mark_unread_on_update"));
2c08214a 237 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
044cff2d
AD
238 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
239 0, "auth_pass_encrypted"));
2c08214a 240
a42c55f0 241 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
2c08214a
AD
242 WHERE id = '$feed'");
243
244 $auth_login = db_fetch_result($result, 0, "auth_login");
245 $auth_pass = db_fetch_result($result, 0, "auth_pass");
246
044cff2d
AD
247 if ($auth_pass_encrypted) {
248 require_once "crypt.php";
249 $auth_pass = decrypt_string($auth_pass);
250 }
251
2c08214a
AD
252 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
253 $fetch_url = db_fetch_result($result, 0, "feed_url");
254
a42c55f0 255 $feed = db_escape_string($feed);
2c08214a 256
f074ffe9 257 $date_feed_processed = date('Y-m-d H:i');
2c08214a 258
865a3ed6 259 $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
f074ffe9 260
ee65bef4
AD
261 $pluginhost = new PluginHost();
262 $pluginhost->set_debug($debug_enabled);
263 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
264
265 $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
266 $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
267 $pluginhost->load_data();
268
88edaa93
AD
269 if ($rss && is_object($rss) && get_class($rss) == "FeedParser") {
270 _debug("using previously initialized parser object");
271 } else {
272 $rss_hash = false;
4f9cbdff 273
88edaa93 274 $force_refetch = isset($_REQUEST["force_refetch"]);
687a4f59 275
95beaa14 276 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
01465325 277 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass);
95beaa14
RA
278 }
279
280 // try cache
281 if (!$feed_data &&
282 file_exists($cache_filename) &&
88edaa93
AD
283 is_readable($cache_filename) &&
284 !$auth_login && !$auth_pass &&
285 filemtime($cache_filename) > time() - 30) {
2c08214a 286
15d0528a 287 _debug("using local cache [$cache_filename].", $debug_enabled);
be574731 288
88edaa93 289 @$feed_data = file_get_contents($cache_filename);
52637d3b 290
88edaa93
AD
291 if ($feed_data) {
292 $rss_hash = sha1($feed_data);
293 }
f074ffe9 294
88edaa93
AD
295 } else {
296 _debug("local cache will not be used for this feed", $debug_enabled);
297 }
ee65bef4 298
95beaa14 299 // fetch feed from source
fd687300
AD
300 if (!$feed_data) {
301 _debug("fetching [$fetch_url]...", $debug_enabled);
302 _debug("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $last_article_timestamp), $debug_enabled);
96f98cb0 303
fd687300
AD
304 $feed_data = fetch_file_contents($fetch_url, false,
305 $auth_login, $auth_pass, false,
306 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
307 $force_refetch ? 0 : $last_article_timestamp);
3f6f0857 308
fd687300 309 global $fetch_curl_used;
3f6f0857 310
fd687300
AD
311 if (!$fetch_curl_used) {
312 $tmp = @gzdecode($feed_data);
3f6f0857 313
fd687300
AD
314 if ($tmp) $feed_data = $tmp;
315 }
1367bc3f 316
fd687300 317 $feed_data = trim($feed_data);
017401dd 318
fd687300
AD
319 _debug("fetch done.", $debug_enabled);
320
d1f3fa97 321 /* if ($feed_data) {
fd687300 322 $error = verify_feed_xml($feed_data);
ebec81a6 323
fd687300
AD
324 if ($error) {
325 _debug("error verifying XML, code: " . $error->code, $debug_enabled);
ebec81a6 326
fd687300
AD
327 if ($error->code == 26) {
328 _debug("got error 26, trying to decode entities...", $debug_enabled);
ebec81a6 329
fd687300 330 $feed_data = html_entity_decode($feed_data, ENT_COMPAT, 'UTF-8');
ebec81a6 331
fd687300 332 $error = verify_feed_xml($feed_data);
ebec81a6 333
fd687300
AD
334 if ($error) $feed_data = '';
335 }
ebec81a6 336 }
d1f3fa97 337 } */
95beaa14
RA
338
339 // cache vanilla feed data for re-use
340 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
341 $new_rss_hash = sha1($feed_data);
342
343 if ($new_rss_hash != $rss_hash) {
344 _debug("saving $cache_filename", $debug_enabled);
345 @file_put_contents($cache_filename, $feed_data);
346 }
347 }
4f9cbdff 348 }
017401dd 349
fd687300
AD
350 if (!$feed_data) {
351 global $fetch_last_error;
352 global $fetch_last_error_code;
f074ffe9 353
fd687300 354 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
f074ffe9 355
fd687300 356 $error_escaped = '';
7a01dc77 357
fd687300
AD
358 // If-Modified-Since
359 if ($fetch_last_error_code != 304) {
360 $error_escaped = db_escape_string($fetch_last_error);
361 } else {
362 _debug("source claims data not modified, nothing to do.", $debug_enabled);
363 }
4f9cbdff 364
fd687300
AD
365 db_query(
366 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
367 last_updated = NOW() WHERE id = '$feed'");
4f9cbdff 368
fd687300
AD
369 return;
370 }
f074ffe9
AD
371 }
372
1ffe3391 373 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
6791af0c 374 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
017401dd
AD
375 }
376
5ef84097
AD
377 // set last update to now so if anything *simplepie* crashes later we won't be
378 // continuously failing on the same feed
5de40104 379 //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
5ef84097 380
4f9cbdff 381 if (!$rss) {
cd07592c
AD
382 $rss = new FeedParser($feed_data);
383 $rss->init();
5de51df7
AD
384 }
385
5ddd2705
AD
386 if (DETECT_ARTICLE_LANGUAGE) {
387 require_once "lib/languagedetect/LanguageDetect.php";
6b461797 388
5ddd2705
AD
389 $lang = new Text_LanguageDetect();
390 $lang->setNameMode(2);
391 }
6b461797 392
2c08214a
AD
393// print_r($rss);
394
a42c55f0 395 $feed = db_escape_string($feed);
2c08214a 396
19b3992b 397 if (!$rss->error()) {
2c08214a 398
d2a421e3 399 // We use local pluginhost here because we need to load different per-user feed plugins
1ffe3391 400 $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
4412b877 401
68cccafc 402 _debug("processing feed data...", $debug_enabled);
2c08214a 403
a42c55f0 404// db_query("BEGIN");
2c08214a 405
382268c6
AD
406 if (DB_TYPE == "pgsql") {
407 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
408 } else {
409 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
410 }
411
36490f11 412 $result = db_query("SELECT title,site_url,owner_uid,favicon_avg_color,
382268c6
AD
413 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
414 favicon_needs_check
2c08214a
AD
415 FROM ttrss_feeds WHERE id = '$feed'");
416
417 $registered_title = db_fetch_result($result, 0, "title");
2c08214a 418 $orig_site_url = db_fetch_result($result, 0, "site_url");
382268c6
AD
419 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
420 "favicon_needs_check"));
36490f11 421 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
2c08214a
AD
422
423 $owner_uid = db_fetch_result($result, 0, "owner_uid");
424
a42c55f0 425 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
2c08214a 426
cd07592c
AD
427 _debug("site_url: $site_url", $debug_enabled);
428 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
429
687a4f59 430 if ($favicon_needs_check || $force_refetch) {
36490f11
AD
431
432 /* terrible hack: if we crash on floicon shit here, we won't check
560cbd8c 433 * the icon avgcolor again (unless the icon got updated) */
36490f11 434
560cbd8c
AD
435 $favicon_file = ICONS_DIR . "/$feed.ico";
436 $favicon_modified = @filemtime($favicon_file);
437
68cccafc 438 _debug("checking favicon...", $debug_enabled);
687a4f59 439
6f7798b6 440 check_feed_favicon($site_url, $feed);
560cbd8c
AD
441 $favicon_modified_new = @filemtime($favicon_file);
442
443 if ($favicon_modified_new > $favicon_modified)
444 $favicon_avg_color = '';
687a4f59 445
6ee0d4b0 446 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
bc7a144d 447 require_once "colors.php";
687a4f59 448
aafd55ba
AD
449 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
450 id = '$feed'");
451
6322ac79 452 $favicon_color = db_escape_string(
bc7a144d 453 calculate_avg_color($favicon_file));
63c323f7 454
bc7a144d 455 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
36490f11 456 } else if ($favicon_avg_color == 'fail') {
84ceb6bd 457 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
6ac722d5 458 }
687a4f59 459
a42c55f0 460 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
bc7a144d 461 $favicon_colorstring
f2798eb6
AD
462 WHERE id = '$feed'");
463 }
2c08214a
AD
464
465 if (!$registered_title || $registered_title == "[Unknown]") {
466
a42c55f0 467 $feed_title = db_escape_string($rss->get_title());
2c08214a 468
852d4ac8
AD
469 if ($feed_title) {
470 _debug("registering title: $feed_title", $debug_enabled);
2c08214a 471
852d4ac8
AD
472 db_query("UPDATE ttrss_feeds SET
473 title = '$feed_title' WHERE id = '$feed'");
474 }
2c08214a
AD
475 }
476
0cf81637 477 if ($site_url && $orig_site_url != $site_url) {
a42c55f0 478 db_query("UPDATE ttrss_feeds SET
2c08214a
AD
479 site_url = '$site_url' WHERE id = '$feed'");
480 }
481
68cccafc 482 _debug("loading filters & labels...", $debug_enabled);
2c08214a 483
a42c55f0
AD
484 $filters = load_filters($feed, $owner_uid);
485 $labels = get_all_labels($owner_uid);
2c08214a 486
68cccafc 487 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
2c08214a 488
19b3992b 489 $items = $rss->get_items();
2c08214a 490
19b3992b 491 if (!is_array($items)) {
68cccafc 492 _debug("no articles found.", $debug_enabled);
2c08214a 493
a42c55f0 494 db_query("UPDATE ttrss_feeds
2c08214a
AD
495 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
496
497 return; // no articles
498 }
499
500 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
501
68cccafc 502 _debug("checking for PUSH hub...", $debug_enabled);
2c08214a
AD
503
504 $feed_hub_url = false;
2c08214a 505
19b3992b 506 $links = $rss->get_links('hub');
2c08214a 507
19b3992b
AD
508 if ($links && is_array($links)) {
509 foreach ($links as $l) {
510 $feed_hub_url = $l;
511 break;
2c08214a
AD
512 }
513 }
514
68cccafc 515 _debug("feed hub url: $feed_hub_url", $debug_enabled);
2c08214a 516
d8179cb9
AD
517 $feed_self_url = $fetch_url;
518
519 $links = $rss->get_links('self');
520
521 if ($links && is_array($links)) {
522 foreach ($links as $l) {
523 $feed_self_url = $l;
524 break;
525 }
526 }
527
528 _debug("feed self url = $feed_self_url");
529
530 if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
2c08214a
AD
531 !ini_get("open_basedir")) {
532
533 require_once 'lib/pubsubhubbub/subscriber.php';
534
535 $callback_url = get_self_url_prefix() .
536 "/public.php?op=pubsub&id=$feed";
537
538 $s = new Subscriber($feed_hub_url, $callback_url);
539
d8179cb9 540 $rc = $s->subscribe($feed_self_url);
2c08214a 541
5ba1ddd4 542 _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
2c08214a 543
a42c55f0 544 db_query("UPDATE ttrss_feeds SET pubsub_state = 1
2c08214a
AD
545 WHERE id = '$feed'");
546 }
547 }
548
68cccafc 549 _debug("processing articles...", $debug_enabled);
2c08214a 550
19b3992b 551 foreach ($items as $item) {
5d56d100 552 if ($_REQUEST['xdebug'] == 3) {
2c08214a
AD
553 print_r($item);
554 }
555
19b3992b
AD
556 $entry_guid = $item->get_id();
557 if (!$entry_guid) $entry_guid = $item->get_link();
558 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
2c08214a 559
cd07592c
AD
560 _debug("f_guid $entry_guid", $debug_enabled);
561
2c08214a
AD
562 if (!$entry_guid) continue;
563
3a4c8973
AD
564 $entry_guid = "$owner_uid,$entry_guid";
565
a42c55f0 566 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
5e3d5480 567
68cccafc 568 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
5e3d5480 569
2c08214a
AD
570 $entry_timestamp = "";
571
04d2f9c8
AD
572 $entry_timestamp = $item->get_date();
573
574 _debug("orig date: " . $item->get_date(), $debug_enabled);
2c08214a 575
30123fe6 576 if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
2c08214a 577 $entry_timestamp = time();
2c08214a
AD
578 }
579
580 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
581
68cccafc 582 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
2c08214a 583
99429e57
AD
584// $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
585// $entry_title = decode_numeric_entities($entry_title);
586 $entry_title = $item->get_title();
1b35d30c 587
5d56d100 588 $entry_link = rewrite_relative_url($site_url, $item->get_link());
2c08214a 589
68cccafc
AD
590 _debug("title $entry_title", $debug_enabled);
591 _debug("link $entry_link", $debug_enabled);
2c08214a
AD
592
593 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
594
19b3992b
AD
595 $entry_content = $item->get_content();
596 if (!$entry_content) $entry_content = $item->get_description();
2c08214a
AD
597
598 if ($_REQUEST["xdebug"] == 2) {
9ec10352 599 print "content: ";
487f0750 600 print $entry_content;
3c696512 601 print "\n";
2c08214a
AD
602 }
603
5ddd2705
AD
604 $entry_language = "";
605
606 if (DETECT_ARTICLE_LANGUAGE) {
607 $entry_language = $lang->detect($entry_title . " " . $entry_content, 1);
6b461797 608
5ddd2705
AD
609 if (count($entry_language) > 0) {
610 $entry_language = array_keys($entry_language);
5a450b87
AD
611
612 // the fuck?
613 if (is_array($entry_language))
614 $entry_language = "";
615 else
616 $entry_language = db_escape_string(substr($entry_language[0], 0, 2));
6b461797 617
5ddd2705 618 _debug("detected language: $entry_language", $debug_enabled);
e95bb179
AD
619 } else {
620 $entry_language = "";
5ddd2705 621 }
6b461797
AD
622 }
623
cd07592c
AD
624 $entry_comments = $item->get_comments_url();
625 $entry_author = $item->get_author();
2c08214a 626
a42c55f0 627 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
2c08214a 628
ce2b219c
AD
629 $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
630 $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
2c08214a 631
d4992d6b 632 $num_comments = (int) $item->get_comments_count();
2c08214a 633
68cccafc
AD
634 _debug("author $entry_author", $debug_enabled);
635 _debug("num_comments: $num_comments", $debug_enabled);
ee78f81c 636 _debug("looking for tags...", $debug_enabled);
2c08214a
AD
637
638 // parse <category> entries into tags
639
640 $additional_tags = array();
641
19b3992b 642 $additional_tags_src = $item->get_categories();
2c08214a 643
19b3992b
AD
644 if (is_array($additional_tags_src)) {
645 foreach ($additional_tags_src as $tobj) {
cd07592c 646 array_push($additional_tags, $tobj);
2c08214a 647 }
19b3992b 648 }
2c08214a 649
fa6fbd36 650 $entry_tags = array_unique($additional_tags);
2c08214a
AD
651
652 for ($i = 0; $i < count($entry_tags); $i++)
653 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
654
ee78f81c
AD
655 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
656
68cccafc 657 _debug("done collecting data.", $debug_enabled);
2c08214a 658
b1840673
AD
659 $result = db_query("SELECT id, content_hash FROM ttrss_entries
660 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
b30abdad
AD
661
662 if (db_num_rows($result) != 0) {
b1840673
AD
663 $base_entry_id = db_fetch_result($result, 0, "id");
664 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
b30abdad 665 } else {
b1840673
AD
666 $base_entry_id = false;
667 $entry_stored_hash = "";
b30abdad
AD
668 }
669
455b1401 670 $article = array("owner_uid" => $owner_uid, // read only
b30abdad 671 "guid" => $entry_guid, // read only
19b3992b
AD
672 "title" => $entry_title,
673 "content" => $entry_content,
674 "link" => $entry_link,
675 "tags" => $entry_tags,
e02555c1 676 "author" => $entry_author,
f73e03e0
AD
677 "feed" => array("id" => $feed,
678 "fetch_url" => $fetch_url,
679 "site_url" => $site_url)
680 );
cc85704f 681
b1840673
AD
682 $entry_plugin_data = "";
683 $entry_current_hash = calculate_article_hash($article);
684
685 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
686
687 if ($entry_current_hash == $entry_stored_hash) {
688 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
689
690 // we keep encountering the entry in feeds, so we need to
691 // update date_updated column so that we don't get horrible
692 // dupes when the entry gets purged and reinserted again e.g.
693 // in the case of SLOW SLOW OMG SLOW updating feeds
694
695 $base_entry_id = db_fetch_result($result, 0, "id");
696
697 db_query("UPDATE ttrss_entries SET date_updated = NOW()
698 WHERE id = '$base_entry_id'");
699
700 continue;
701 }
702
703 _debug("hash differs, applying plugin filters:", $debug_enabled);
704
1ffe3391 705 foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
b1840673
AD
706 _debug("... " . get_class($plugin), $debug_enabled);
707
708 $start = microtime(true);
19b3992b 709 $article = $plugin->hook_article_filter($article);
0084f0d1 710
b1840673
AD
711 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
712
713 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
cc85704f
AD
714 }
715
b1840673
AD
716 $entry_plugin_data = db_escape_string($entry_plugin_data);
717
718 _debug("plugin data: $entry_plugin_data", $debug_enabled);
719
19b3992b 720 $entry_tags = $article["tags"];
a42c55f0
AD
721 $entry_guid = db_escape_string($entry_guid);
722 $entry_title = db_escape_string($article["title"]);
723 $entry_author = db_escape_string($article["author"]);
724 $entry_link = db_escape_string($article["link"]);
f935d98e
AD
725 $entry_content = $article["content"]; // escaped below
726
0a3fd79b 727 if ($cache_images && is_writable(CACHE_DIR . '/images'))
f0bd8e65 728 cache_images($entry_content, $site_url, $debug_enabled);
0a3fd79b 729
a42c55f0 730 $entry_content = db_escape_string($entry_content, false);
1f45c857 731
a42c55f0 732 db_query("BEGIN");
2c08214a 733
a42c55f0 734 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 735 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
9e222305 736
2c08214a
AD
737 if (db_num_rows($result) == 0) {
738
68cccafc 739 _debug("base guid [$entry_guid] not found", $debug_enabled);
2c08214a
AD
740
741 // base post entry does not exist, create it
742
6322ac79 743 $result = db_query(
2c08214a
AD
744 "INSERT INTO ttrss_entries
745 (title,
746 guid,
747 link,
748 updated,
749 content,
750 content_hash,
751 no_orig_date,
752 date_updated,
753 date_entered,
754 comments,
755 num_comments,
b30abdad 756 plugin_data,
6b461797 757 lang,
2c08214a
AD
758 author)
759 VALUES
760 ('$entry_title',
5e3d5480 761 '$entry_guid_hashed',
2c08214a
AD
762 '$entry_link',
763 '$entry_timestamp_fmt',
764 '$entry_content',
b1840673 765 '$entry_current_hash',
5ba1ddd4 766 false,
2c08214a 767 NOW(),
be574731 768 '$date_feed_processed',
2c08214a
AD
769 '$entry_comments',
770 '$num_comments',
b30abdad 771 '$entry_plugin_data',
6b461797 772 '$entry_language',
2c08214a 773 '$entry_author')");
e8291805
AD
774
775 $article_labels = array();
776
2c08214a 777 } else {
2c08214a
AD
778 $base_entry_id = db_fetch_result($result, 0, "id");
779
a42c55f0 780 $article_labels = get_article_labels($base_entry_id, $owner_uid);
2c08214a
AD
781 }
782
783 // now it should exist, if not - bad luck then
784
b1840673 785 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 786 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
2c08214a
AD
787
788 $entry_ref_id = 0;
789 $entry_int_id = 0;
790
791 if (db_num_rows($result) == 1) {
792
68cccafc 793 _debug("base guid found, checking for user record", $debug_enabled);
2c08214a 794
2c08214a
AD
795 $ref_id = db_fetch_result($result, 0, "id");
796 $entry_ref_id = $ref_id;
797
5e3d5480
AD
798 /* $stored_guid = db_fetch_result($result, 0, "guid");
799 if ($stored_guid != $entry_guid_hashed) {
68cccafc 800 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
5e3d5480 801
a42c55f0 802 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
5e3d5480
AD
803 id = '$ref_id'");
804 } */
805
2c08214a
AD
806 // check for user post link to main table
807
808 // do we allow duplicate posts with same GUID in different feeds?
a42c55f0 809 if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
2c08214a
AD
810 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
811 } else {
812 $dupcheck_qpart = "";
813 }
814
815 /* Collect article tags here so we could filter by them: */
816
817 $article_filters = get_article_filters($filters, $entry_title,
4021d61a 818 $entry_content, $entry_link, $entry_timestamp, $entry_author,
2c08214a
AD
819 $entry_tags);
820
821 if ($debug_enabled) {
68cccafc 822 _debug("article filters: ", $debug_enabled);
2c08214a
AD
823 if (count($article_filters) != 0) {
824 print_r($article_filters);
825 }
826 }
827
828 if (find_article_filter($article_filters, "filter")) {
a42c55f0 829 db_query("COMMIT"); // close transaction in progress
2c08214a
AD
830 continue;
831 }
832
833 $score = calculate_article_score($article_filters);
834
68cccafc 835 _debug("initial score: $score", $debug_enabled);
2c08214a
AD
836
837 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
838 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
839 $dupcheck_qpart";
840
841// if ($_REQUEST["xdebug"]) print "$query\n";
842
a42c55f0 843 $result = db_query($query);
2c08214a
AD
844
845 // okay it doesn't exist - create user entry
846 if (db_num_rows($result) == 0) {
847
68cccafc 848 _debug("user record not found, creating...", $debug_enabled);
2c08214a
AD
849
850 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
851 $unread = 'true';
852 $last_read_qpart = 'NULL';
853 } else {
854 $unread = 'false';
855 $last_read_qpart = 'NOW()';
856 }
857
858 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
859 $marked = 'true';
860 } else {
861 $marked = 'false';
862 }
863
864 if (find_article_filter($article_filters, 'publish')) {
865 $published = 'true';
866 } else {
867 $published = 'false';
868 }
869
2ea9bbfd
AD
870 // N-grams
871
872 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
873
a42c55f0 874 $result = db_query("SELECT COUNT(*) AS similar FROM
2ea9bbfd
AD
875 ttrss_entries,ttrss_user_entries
876 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
877 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
878 AND owner_uid = $owner_uid");
879
880 $ngram_similar = db_fetch_result($result, 0, "similar");
881
68cccafc 882 _debug("N-gram similar results: $ngram_similar", $debug_enabled);
2ea9bbfd
AD
883
884 if ($ngram_similar > 0) {
885 $unread = 'false';
886 }
887 }
888
7873d588
AD
889 $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
890 $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
891
6322ac79 892 $result = db_query(
2c08214a
AD
893 "INSERT INTO ttrss_user_entries
894 (ref_id, owner_uid, feed_id, unread, last_read, marked,
7873d588
AD
895 published, score, tag_cache, label_cache, uuid,
896 last_marked, last_published)
2c08214a 897 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
7873d588
AD
898 $last_read_qpart, $marked, $published, '$score', '', '',
899 '', $last_marked, $last_published)");
2c08214a
AD
900
901 if (PUBSUBHUBBUB_HUB && $published == 'true') {
902 $rss_link = get_self_url_prefix() .
903 "/public.php?op=rss&id=-2&key=" .
a42c55f0 904 get_feed_access_key(-2, false, $owner_uid);
2c08214a
AD
905
906 $p = new Publisher(PUBSUBHUBBUB_HUB);
907
5ba1ddd4 908 /* $pubsub_result = */ $p->publish_update($rss_link);
2c08214a
AD
909 }
910
6322ac79 911 $result = db_query(
2c08214a
AD
912 "SELECT int_id FROM ttrss_user_entries WHERE
913 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
914 feed_id = '$feed' LIMIT 1");
915
916 if (db_num_rows($result) == 1) {
917 $entry_int_id = db_fetch_result($result, 0, "int_id");
918 }
919 } else {
68cccafc 920 _debug("user record FOUND", $debug_enabled);
2c08214a
AD
921
922 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
923 $entry_int_id = db_fetch_result($result, 0, "int_id");
924 }
925
68cccafc 926 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
2c08214a 927
b1840673
AD
928 db_query("UPDATE ttrss_entries
929 SET title = '$entry_title',
930 content = '$entry_content',
931 content_hash = '$entry_current_hash',
932 updated = '$entry_timestamp_fmt',
933 num_comments = '$num_comments',
934 plugin_data = '$entry_plugin_data',
935 author = '$entry_author',
936 lang = '$entry_language'
937 WHERE id = '$ref_id'");
938
939 if ($mark_unread_on_update) {
940 db_query("UPDATE ttrss_user_entries
941 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
2c08214a
AD
942 }
943 }
944
a42c55f0 945 db_query("COMMIT");
2c08214a 946
68cccafc 947 _debug("assigning labels...", $debug_enabled);
2c08214a 948
a42c55f0 949 assign_article_to_label_filters($entry_ref_id, $article_filters,
b24504b1 950 $owner_uid, $article_labels);
2c08214a 951
68cccafc 952 _debug("looking for enclosures...", $debug_enabled);
2c08214a
AD
953
954 // enclosures
955
956 $enclosures = array();
957
19b3992b 958 $encs = $item->get_enclosures();
2c08214a 959
19b3992b
AD
960 if (is_array($encs)) {
961 foreach ($encs as $e) {
962 $e_item = array(
523bd90b 963 $e->link, $e->type, $e->length, $e->title, $e->width, $e->height);
2c08214a 964 array_push($enclosures, $e_item);
2c08214a
AD
965 }
966 }
967
2c08214a 968 if ($debug_enabled) {
68cccafc 969 _debug("article enclosures:", $debug_enabled);
2c08214a
AD
970 print_r($enclosures);
971 }
972
a42c55f0 973 db_query("BEGIN");
2c08214a 974
5c54e683
AD
975// debugging
976// db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
977
2c08214a 978 foreach ($enclosures as $enc) {
a42c55f0
AD
979 $enc_url = db_escape_string($enc[0]);
980 $enc_type = db_escape_string($enc[1]);
981 $enc_dur = db_escape_string($enc[2]);
5c54e683 982 $enc_title = db_escape_string($enc[3]);
523bd90b
FE
983 $enc_width = intval($enc[4]);
984 $enc_height = intval($enc[5]);
2c08214a 985
a42c55f0 986 $result = db_query("SELECT id FROM ttrss_enclosures
2c08214a
AD
987 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
988
989 if (db_num_rows($result) == 0) {
a42c55f0 990 db_query("INSERT INTO ttrss_enclosures
523bd90b
FE
991 (content_url, content_type, title, duration, post_id, width, height) VALUES
992 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
2c08214a
AD
993 }
994 }
995
a42c55f0 996 db_query("COMMIT");
2c08214a
AD
997
998 // check for manual tags (we have to do it here since they're loaded from filters)
999
1000 foreach ($article_filters as $f) {
6aff7845 1001 if ($f["type"] == "tag") {
2c08214a 1002
6aff7845 1003 $manual_tags = trim_array(explode(",", $f["param"]));
2c08214a
AD
1004
1005 foreach ($manual_tags as $tag) {
1006 if (tag_is_valid($tag)) {
1007 array_push($entry_tags, $tag);
1008 }
1009 }
1010 }
1011 }
1012
1013 // Skip boring tags
1014
6322ac79 1015 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
2c08214a
AD
1016 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1017
1018 $filtered_tags = array();
1019 $tags_to_cache = array();
1020
1021 if ($entry_tags && is_array($entry_tags)) {
1022 foreach ($entry_tags as $tag) {
1023 if (array_search($tag, $boring_tags) === false) {
1024 array_push($filtered_tags, $tag);
1025 }
1026 }
1027 }
1028
1029 $filtered_tags = array_unique($filtered_tags);
1030
1031 if ($debug_enabled) {
68cccafc 1032 _debug("filtered article tags:", $debug_enabled);
2c08214a
AD
1033 print_r($filtered_tags);
1034 }
1035
1036 // Save article tags in the database
1037
1038 if (count($filtered_tags) > 0) {
1039
a42c55f0 1040 db_query("BEGIN");
2c08214a
AD
1041
1042 foreach ($filtered_tags as $tag) {
1043
1044 $tag = sanitize_tag($tag);
a42c55f0 1045 $tag = db_escape_string($tag);
2c08214a
AD
1046
1047 if (!tag_is_valid($tag)) continue;
1048
a42c55f0 1049 $result = db_query("SELECT id FROM ttrss_tags
2c08214a
AD
1050 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1051 owner_uid = '$owner_uid' LIMIT 1");
1052
1053 if ($result && db_num_rows($result) == 0) {
1054
a42c55f0 1055 db_query("INSERT INTO ttrss_tags
2c08214a
AD
1056 (owner_uid,tag_name,post_int_id)
1057 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1058 }
1059
1060 array_push($tags_to_cache, $tag);
1061 }
1062
1063 /* update the cache */
1064
1065 $tags_to_cache = array_unique($tags_to_cache);
1066
a42c55f0 1067 $tags_str = db_escape_string(join(",", $tags_to_cache));
2c08214a 1068
a42c55f0 1069 db_query("UPDATE ttrss_user_entries
2c08214a
AD
1070 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1071 AND owner_uid = $owner_uid");
1072
a42c55f0 1073 db_query("COMMIT");
2c08214a
AD
1074 }
1075
a42c55f0 1076 if (get_pref("AUTO_ASSIGN_LABELS", $owner_uid, false)) {
68cccafc 1077 _debug("auto-assigning labels...", $debug_enabled);
b24504b1
AD
1078
1079 foreach ($labels as $label) {
227d5e41 1080 $caption = preg_quote($label["caption"]);
b24504b1 1081
9811276d 1082 if ($caption && preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
b24504b1 1083 if (!labels_contains_caption($article_labels, $caption)) {
a42c55f0 1084 label_add_article($entry_ref_id, $caption, $owner_uid);
b24504b1
AD
1085 }
1086 }
1087 }
1088 }
1089
68cccafc 1090 _debug("article processed", $debug_enabled);
2c08214a
AD
1091 }
1092
68cccafc 1093 _debug("purging feed...", $debug_enabled);
2c08214a 1094
a42c55f0 1095 purge_feed($feed, 0, $debug_enabled);
2c08214a 1096
a42c55f0 1097 db_query("UPDATE ttrss_feeds
f2798eb6 1098 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a 1099
a42c55f0 1100// db_query("COMMIT");
2c08214a
AD
1101
1102 } else {
1103
a42c55f0 1104 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
2c08214a 1105
4ad04ee2
AD
1106 _debug("fetch error: $error_msg", $debug_enabled);
1107
1108 if (count($rss->errors()) > 1) {
1109 foreach ($rss->errors() as $error) {
1110 _debug("+ $error");
1111 }
1112 }
2c08214a 1113
6322ac79 1114 db_query(
2c08214a 1115 "UPDATE ttrss_feeds SET last_error = '$error_msg',
88edaa93 1116 last_updated = NOW() WHERE id = '$feed'");
2c08214a 1117
88edaa93
AD
1118 unset($rss);
1119 }
2c08214a 1120
68cccafc 1121 _debug("done", $debug_enabled);
88edaa93
AD
1122
1123 return $rss;
2c08214a
AD
1124 }
1125
3c696512 1126 function cache_images($html, $site_url, $debug) {
3c696512
AD
1127 libxml_use_internal_errors(true);
1128
1129 $charset_hack = '<head>
1130 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1131 </head>';
1132
1133 $doc = new DOMDocument();
1134 $doc->loadHTML($charset_hack . $html);
1135 $xpath = new DOMXPath($doc);
1136
1137 $entries = $xpath->query('(//img[@src])');
1138
1139 foreach ($entries as $entry) {
1140 if ($entry->hasAttribute('src')) {
1141 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1142
1143 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1144
1145 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1146
1147 if (!file_exists($local_filename)) {
1148 $file_content = fetch_file_contents($src);
1149
a3d50184 1150 if ($file_content && strlen($file_content) > _MIN_CACHE_IMAGE_SIZE) {
3c696512
AD
1151 file_put_contents($local_filename, $file_content);
1152 }
1153 }
1154
2fc4d981 1155 /* if (file_exists($local_filename)) {
3c696512 1156 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
487f0750 1157 base64_encode($src));
2fc4d981 1158 } */
3c696512
AD
1159 }
1160 }
1161
2fc4d981
AD
1162 //$node = $doc->getElementsByTagName('body')->item(0);
1163 //return $doc->saveXML($node);
3c696512
AD
1164 }
1165
a42c55f0 1166 function expire_error_log($debug) {
e2261e17
AD
1167 if ($debug) _debug("Removing old error log entries...");
1168
1169 if (DB_TYPE == "pgsql") {
a42c55f0 1170 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1171 WHERE created_at < NOW() - INTERVAL '7 days'");
1172 } else {
a42c55f0 1173 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1174 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1175 }
1176
1177 }
1178
2a91b6ff 1179 function expire_lock_files($debug) {
65465085 1180 //if ($debug) _debug("Removing old lock files...");
2a91b6ff
AD
1181
1182 $num_deleted = 0;
1183
1184 if (is_writable(LOCK_DIRECTORY)) {
1185 $files = glob(LOCK_DIRECTORY . "/*.lock");
1186
1187 if ($files) {
1188 foreach ($files as $file) {
11344971 1189 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
2a91b6ff
AD
1190 unlink($file);
1191 ++$num_deleted;
1192 }
1193 }
1194 }
1195 }
1196
65465085 1197 if ($debug) _debug("Removed $num_deleted old lock files.");
2a91b6ff
AD
1198 }
1199
3c696512 1200 function expire_cached_files($debug) {
3306daec 1201 foreach (array("simplepie", "images", "export", "upload") as $dir) {
3c696512 1202 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1203
65465085 1204// if ($debug) _debug("Expiring $cache_dir");
2c08214a 1205
3c696512
AD
1206 $num_deleted = 0;
1207
1208 if (is_writable($cache_dir)) {
1209 $files = glob("$cache_dir/*");
1210
2a91b6ff 1211 if ($files) {
2ab20c31
AD
1212 foreach ($files as $file) {
1213 if (time() - filemtime($file) > 86400*7) {
1214 unlink($file);
3c696512 1215
2ab20c31
AD
1216 ++$num_deleted;
1217 }
3c696512
AD
1218 }
1219 }
2a91b6ff 1220 }
3c696512 1221
65465085 1222 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
3c696512
AD
1223 }
1224 }
2c08214a 1225
a3e0bdcf
AD
1226 /**
1227 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1228 * Returns the url query as associative array
1229 *
1230 * @param string query
1231 * @return array params
1232 */
1233 function convertUrlQuery($query) {
1234 $queryParts = explode('&', $query);
1235
1236 $params = array();
1237
1238 foreach ($queryParts as $param) {
1239 $item = explode('=', $param);
1240 $params[$item[0]] = $item[1];
1241 }
1242
1243 return $params;
1244 }
92c14e9d 1245
48cb2536 1246 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
92c14e9d
AD
1247 $matches = array();
1248
1249 foreach ($filters as $filter) {
1250 $match_any_rule = $filter["match_any_rule"];
a3a896a1 1251 $inverse = $filter["inverse"];
92c14e9d
AD
1252 $filter_match = false;
1253
1254 foreach ($filter["rules"] as $rule) {
1255 $match = false;
ffa1bd7b 1256 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
a3a896a1 1257 $rule_inverse = $rule["inverse"];
92c14e9d
AD
1258
1259 if (!$reg_exp)
1260 continue;
1261
1262 switch ($rule["type"]) {
1263 case "title":
1264 $match = @preg_match("/$reg_exp/i", $title);
1265 break;
1266 case "content":
d03ae73e
AD
1267 // we don't need to deal with multiline regexps
1268 $content = preg_replace("/[\r\n\t]/", "", $content);
1269
92c14e9d
AD
1270 $match = @preg_match("/$reg_exp/i", $content);
1271 break;
1272 case "both":
d03ae73e
AD
1273 // we don't need to deal with multiline regexps
1274 $content = preg_replace("/[\r\n\t]/", "", $content);
1275
72d1d067 1276 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
92c14e9d
AD
1277 break;
1278 case "link":
1279 $match = @preg_match("/$reg_exp/i", $link);
1280 break;
1281 case "author":
1282 $match = @preg_match("/$reg_exp/i", $author);
1283 break;
1284 case "tag":
7b80b5e1
DK
1285 foreach ($tags as $tag) {
1286 if (@preg_match("/$reg_exp/i", $tag)) {
1287 $match = true;
1288 break;
1289 }
1290 }
92c14e9d
AD
1291 break;
1292 }
1293
a3a896a1
AD
1294 if ($rule_inverse) $match = !$match;
1295
92c14e9d
AD
1296 if ($match_any_rule) {
1297 if ($match) {
1298 $filter_match = true;
1299 break;
1300 }
1301 } else {
1302 $filter_match = $match;
1303 if (!$match) {
1304 break;
1305 }
1306 }
1307 }
1308
a3a896a1
AD
1309 if ($inverse) $filter_match = !$filter_match;
1310
92c14e9d
AD
1311 if ($filter_match) {
1312 foreach ($filter["actions"] AS $action) {
1313 array_push($matches, $action);
5e736e45
AD
1314
1315 // if Stop action encountered, perform no further processing
1316 if ($action["type"] == "stop") return $matches;
92c14e9d
AD
1317 }
1318 }
1319 }
1320
1321 return $matches;
1322 }
1323
1324 function find_article_filter($filters, $filter_name) {
1325 foreach ($filters as $f) {
1326 if ($f["type"] == $filter_name) {
1327 return $f;
1328 };
1329 }
1330 return false;
1331 }
1332
1333 function find_article_filters($filters, $filter_name) {
1334 $results = array();
1335
1336 foreach ($filters as $f) {
1337 if ($f["type"] == $filter_name) {
1338 array_push($results, $f);
1339 };
1340 }
1341 return $results;
1342 }
1343
1344 function calculate_article_score($filters) {
1345 $score = 0;
1346
1347 foreach ($filters as $f) {
1348 if ($f["type"] == "score") {
1349 $score += $f["param"];
1350 };
1351 }
1352 return $score;
1353 }
1354
b24504b1
AD
1355 function labels_contains_caption($labels, $caption) {
1356 foreach ($labels as $label) {
1357 if ($label[1] == $caption) {
1358 return true;
1359 }
1360 }
1361
1362 return false;
1363 }
1364
a42c55f0 1365 function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
92c14e9d
AD
1366 foreach ($filters as $f) {
1367 if ($f["type"] == "label") {
b24504b1 1368 if (!labels_contains_caption($article_labels, $f["param"])) {
a42c55f0 1369 label_add_article($id, $f["param"], $owner_uid);
b24504b1
AD
1370 }
1371 }
92c14e9d
AD
1372 }
1373 }
87764a50 1374
87d7e850
AD
1375 function make_guid_from_title($title) {
1376 return preg_replace("/[ \"\',.:;]/", "-",
1377 mb_strtolower(strip_tags($title), 'utf-8'));
1378 }
1379
d1f3fa97 1380 /* function verify_feed_xml($feed_data) {
ebec81a6
AD
1381 libxml_use_internal_errors(true);
1382 $doc = new DOMDocument();
1383 $doc->loadXML($feed_data);
1384 $error = libxml_get_last_error();
1385 libxml_clear_errors();
1386 return $error;
d1f3fa97 1387 } */
87d7e850 1388
e2cf81e2
AD
1389 function housekeeping_common($debug) {
1390 expire_cached_files($debug);
1391 expire_lock_files($debug);
1392 expire_error_log($debug);
1393
1394 $count = update_feedbrowser_cache();
1395 _debug("Feedbrowser updated, $count feeds processed.");
1396
1397 purge_orphans( true);
1398 $rc = cleanup_tags( 14, 50000);
1399
1400 _debug("Cleaned $rc cached tags.");
8e470220 1401
00f22824 1402 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
8e470220 1403
e2cf81e2 1404 }
2c08214a 1405?>