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