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