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