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