]> git.wh0rd.org - tt-rss.git/blame - functions.php
Merge branch 'master' of github.com:gothfox/Tiny-Tiny-RSS
[tt-rss.git] / functions.php
CommitLineData
1d3a17c7 1<?php
f1a80dae 2
324944f3 3 date_default_timezone_set('UTC');
8a7f5767
CW
4 if (defined('E_DEPRECATED')) {
5 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
6 } else {
7 error_reporting(E_ALL & ~E_NOTICE);
8 }
cce28758 9
40d13c28 10 require_once 'config.php';
cc17c205 11
fc2b26a6
AD
12 if (DB_TYPE == "pgsql") {
13 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 } else {
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
16 }
17
0c425dc7
AD
18 define('THEME_VERSION_REQUIRED', 1.1);
19
9632f884
AD
20 /**
21 * Return available translations names.
8d505d78 22 *
9632f884
AD
23 * @access public
24 * @return array A array of available translations.
25 */
f8c612d4 26 function get_translations() {
6a214f92 27 $tr = array(
8d505d78 28 "auto" => "Detect automatically",
a3162add 29 "ca_CA" => "Català",
6a214f92 30 "en_US" => "English",
36d0510c 31 "es_ES" => "Español",
a927fe7b 32 "de_DE" => "Deutsch",
6a214f92 33 "fr_FR" => "Français",
e78fd196 34 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 35 "it_IT" => "Italiano",
1d004f12 36 "ja_JP" => "日本語 (Japanese)",
592535d7 37 "nb_NO" => "Norwegian bokmål",
6a214f92 38 "ru_RU" => "Русский",
9a063469 39 "pt_BR" => "Portuguese/Brazil",
6a214f92 40 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
41
42 return $tr;
43 }
44
7b26a148
AD
45 require_once "lib/accept-to-gettext.php";
46 require_once "lib/gettext/gettext.inc";
aba609e0 47
7b26a148 48 function startup_gettext() {
8d505d78 49
7b26a148
AD
50 # Get locale from Accept-Language header
51 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 52
7b26a148
AD
53 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
54 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
55 }
89cb787e 56
7b26a148
AD
57 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
58 $lang = $_COOKIE["ttrss_lang"];
59 }
68659d98 60
7b26a148
AD
61 /* In login action of mobile version */
62 if ($_POST["language"] && defined('MOBILE_VERSION')) {
63 $lang = $_POST["language"];
64 $_COOKIE["ttrss_lang"] = $lang;
65 }
7c33dbd4 66
7b26a148
AD
67 if ($lang) {
68 if (defined('LC_MESSAGES')) {
69 _setlocale(LC_MESSAGES, $lang);
70 } else if (defined('LC_ALL')) {
71 _setlocale(LC_ALL, $lang);
8d039718 72 }
aba609e0 73
7b26a148
AD
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
76 } else {
77 _bindtextdomain("messages", "locale");
78 }
865220a4 79
7b26a148
AD
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 82 }
7b26a148
AD
83 }
84
85 startup_gettext();
cc17c205 86
be35798b
AD
87 if (defined('MEMCACHE_SERVER')) {
88 $memcache = new Memcache;
89 $memcache->connect(MEMCACHE_SERVER, 11211);
90 }
91
b619ff15 92 require_once 'db-prefs.php';
af106b0e 93 require_once 'errors.php';
8911ac8b 94 require_once 'version.php';
40d13c28 95
d134e3a3 96 require_once 'lib/phpmailer/class.phpmailer.php';
e4f7f8df 97 require_once 'lib/sphinxapi.php';
54a3dd8d 98 require_once 'lib/tmhoauth/tmhOAuth.php';
a8931123 99
a18a4f38 100 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
a3ee2a38
AD
101 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
102
a18a4f38
AD
103 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
104 define('MAGPIE_USER_AGENT', SELF_USER_AGENT);
105
500943a4
AD
106 ini_set('user_agent', SELF_USER_AGENT);
107
5ef03f15 108 require_once "lib/simplepie/simplepie.inc";
816cdfb7
AD
109 require_once "lib/magpierss/rss_fetch.inc";
110 require_once 'lib/magpierss/rss_utils.inc';
f45a286b 111 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
b0f379df 112 require_once 'lib/pubsubhubbub/publisher.php';
5ab9791f 113 require_once 'lib/pubsubhubbub/subscriber.php';
49f9c923 114
35ffb5b9
AD
115 $config = HTMLPurifier_Config::createDefault();
116
a58fd801 117 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
35ffb5b9 118
f4f0f80d 119 $config->set('HTML.SafeObject', true);
1849a788 120 @$config->set('HTML', 'Allowed', $allowed);
f4f0f80d
AD
121 $config->set('Output.FlashCompat', true);
122 $config->set('Attr.EnableID', true);
b9fca867
AD
123 if (!defined('MOBILE_VERSION')) {
124 @$config->set('Cache', 'SerializerPath', CACHE_DIR . "/htmlpurifier");
125 } else {
126 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR . "/htmlpurifier");
127 }
f4f0f80d 128
35ffb5b9
AD
129 $purifier = new HTMLPurifier($config);
130
7d96bfcd
AD
131 $tz_offset = -1;
132 $utc_tz = new DateTimeZone('UTC');
133 $schema_version = false;
134
45004d43
AD
135 /**
136 * Print a timestamped debug message.
8d505d78 137 *
45004d43
AD
138 * @param string $msg The debug message.
139 * @return void
140 */
6f9e33e4
AD
141 function _debug($msg) {
142 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
143 if (function_exists('posix_getpid')) {
144 $ts = "$ts/" . posix_getpid();
145 }
6f9e33e4 146 print "[$ts] $msg\n";
45004d43 147 } // function _debug
6f9e33e4 148
9632f884
AD
149 /**
150 * Purge a feed old posts.
8d505d78 151 *
9632f884
AD
152 * @param mixed $link A database connection.
153 * @param mixed $feed_id The id of the purged feed.
154 * @param mixed $purge_interval Olderness of purged posts.
155 * @param boolean $debug Set to True to enable the debug. False by default.
156 * @access public
157 * @return void
158 */
ad507f85
AD
159 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
160
07d0efe9 161 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
8d505d78 162
ad507f85 163 $rows = -1;
4c193675 164
8d505d78 165 $result = db_query($link,
07d0efe9
AD
166 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
167
168 $owner_uid = false;
169
170 if (db_num_rows($result) == 1) {
171 $owner_uid = db_fetch_result($result, 0, "owner_uid");
172 }
173
ab954dff
AD
174 if ($purge_interval == -1 || !$purge_interval) {
175 if ($owner_uid) {
176 ccache_update($link, $feed_id, $owner_uid);
177 }
178 return;
179 }
180
07d0efe9
AD
181 if (!$owner_uid) return;
182
3907ef71
AD
183 if (FORCE_ARTICLE_PURGE == 0) {
184 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
185 $owner_uid, false);
186 } else {
187 $purge_unread = true;
188 $purge_interval = FORCE_ARTICLE_PURGE;
189 }
07d0efe9
AD
190
191 if (!$purge_unread) $query_limit = " unread = false AND ";
192
fefa6ca3 193 if (DB_TYPE == "pgsql") {
6e7f8d26
AD
194 $pg_version = get_pgsql_version($link);
195
196 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 197
8d505d78
AD
198 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
199 ttrss_entries.id = ref_id AND
200 marked = false AND
201 feed_id = '$feed_id' AND
07d0efe9 202 $query_limit
25ea2805 203 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
204
205 } else {
206
8d505d78
AD
207 $result = db_query($link, "DELETE FROM ttrss_user_entries
208 USING ttrss_entries
209 WHERE ttrss_entries.id = ref_id AND
210 marked = false AND
211 feed_id = '$feed_id' AND
07d0efe9 212 $query_limit
25ea2805 213 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 214 }
ad507f85
AD
215
216 $rows = pg_affected_rows($result);
8d505d78 217
fefa6ca3 218 } else {
8d505d78 219
30f1746f 220/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 221 marked = false AND feed_id = '$feed_id' AND
8d505d78 222 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
223 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
224
8d505d78
AD
225 $result = db_query($link, "DELETE FROM ttrss_user_entries
226 USING ttrss_user_entries, ttrss_entries
227 WHERE ttrss_entries.id = ref_id AND
228 marked = false AND
229 feed_id = '$feed_id' AND
07d0efe9 230 $query_limit
25ea2805 231 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
8d505d78 232
ad507f85
AD
233 $rows = mysql_affected_rows($link);
234
235 }
236
ced46404
AD
237 ccache_update($link, $feed_id, $owner_uid);
238
ad507f85 239 if ($debug) {
6f9e33e4 240 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 241 }
9632f884 242 } // function purge_feed
fefa6ca3 243
07d0efe9
AD
244 function feed_purge_interval($link, $feed_id) {
245
8d505d78 246 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
247 WHERE id = '$feed_id'");
248
249 if (db_num_rows($result) == 1) {
250 $purge_interval = db_fetch_result($result, 0, "purge_interval");
251 $owner_uid = db_fetch_result($result, 0, "owner_uid");
252
8d505d78 253 if ($purge_interval == 0) $purge_interval = get_pref($link,
863be6ca 254 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
255
256 return $purge_interval;
257
258 } else {
259 return -1;
260 }
261 }
262
a2d79981
AD
263 function purge_orphans($link, $do_output = false) {
264
71604ca4 265 // purge orphaned posts in main content table
8d505d78 266 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4 267 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
268
269 if ($do_output) {
270 $rows = db_affected_rows($link, $result);
271 _debug("Purged $rows orphaned posts.");
272 }
c3a8d71a
AD
273 }
274
c7d57b66
AD
275 function get_feed_update_interval($link, $feed_id) {
276 $result = db_query($link, "SELECT owner_uid, update_interval FROM
277 ttrss_feeds WHERE id = '$feed_id'");
278
279 if (db_num_rows($result) == 1) {
280 $update_interval = db_fetch_result($result, 0, "update_interval");
281 $owner_uid = db_fetch_result($result, 0, "owner_uid");
282
283 if ($update_interval != 0) {
284 return $update_interval;
285 } else {
286 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
287 }
288
289 } else {
290 return -1;
291 }
292 }
293
ae5f7bb1 294 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
8d505d78
AD
295 $login = urlencode($login);
296 $pass = urlencode($pass);
297
3610b48b 298 if (function_exists('curl_init') && !ini_get("open_basedir")) {
4065b60b 299 $ch = curl_init($url);
a1af1574
AD
300
301 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
302 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
303 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
304 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
305 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
306 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
8d505d78 307 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
5f6804bc 308 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
19929bbe 309 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
268a06dc 310 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
8d505d78 311
ae5f7bb1
AD
312 if ($post_query) {
313 curl_setopt($ch, CURLOPT_POST, true);
314 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
315 }
316
8d505d78
AD
317 if ($login && $pass)
318 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 319
fb074239 320 $contents = @curl_exec($ch);
268a06dc 321
a1af1574
AD
322 if ($contents === false) {
323 curl_close($ch);
324 return false;
4065b60b
AD
325 }
326
8d505d78 327 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
a1af1574
AD
328 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
329 curl_close($ch);
4065b60b 330
8d505d78 331 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
a1af1574
AD
332 return false;
333 }
4065b60b 334
a1af1574 335 return $contents;
4065b60b 336 } else {
9949bd15 337 if ($login && $pass ){
8d505d78
AD
338 $url_parts = array();
339
340 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
341
342 if ($url_parts[1] && $url_parts[2]) {
343 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
344 }
345 }
346
fb074239 347 return @file_get_contents($url);
4065b60b
AD
348 }
349
350 }
78800912 351
9632f884
AD
352 /**
353 * Try to determine the favicon URL for a feed.
354 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
355 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
8d505d78 356 *
9632f884
AD
357 * @param string $url A feed or page URL
358 * @access public
359 * @return mixed The favicon URL, or false if none was found.
360 */
4065b60b 361 function get_favicon_url($url) {
99331724 362
ed214298
AD
363 $favicon_url = false;
364
4065b60b 365 if ($html = @fetch_file_contents($url)) {
78800912 366
ed214298 367 libxml_use_internal_errors(true);
c798704b 368
ed214298
AD
369 $doc = new DOMDocument();
370 $doc->loadHTML($html);
371 $xpath = new DOMXPath($doc);
717f5e64 372
a712429e
AD
373 $base = $xpath->query('/html/head/base');
374 foreach ($base as $b) {
375 $url = $b->getAttribute("href");
376 break;
377 }
378
379 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
380 if (count($entries) > 0) {
381 foreach ($entries as $entry) {
382 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
383 break;
384 }
8d505d78 385 }
4065b60b 386 }
c798704b 387
ed214298
AD
388 if (!$favicon_url)
389 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
390
014d3ad8 391 return $favicon_url;
9632f884 392 } // function get_favicon_url
4065b60b 393
4065b60b 394 function check_feed_favicon($site_url, $feed, $link) {
4065b60b
AD
395# print "FAVICON [$site_url]: $favicon_url\n";
396
4065b60b
AD
397 $icon_file = ICONS_DIR . "/$feed.ico";
398
c83a5aec
AD
399 if (!file_exists($icon_file)) {
400 $favicon_url = get_favicon_url($site_url);
401
402 if ($favicon_url) {
403 $contents = fetch_file_contents($favicon_url, "image");
404
405 if ($contents) {
e894e97f 406 $fp = @fopen($icon_file, "w");
78800912 407
c83a5aec
AD
408 if ($fp) {
409 fwrite($fp, $contents);
410 fclose($fp);
411 chmod($icon_file, 0644);
412 }
a1af1574 413 }
4065b60b 414 }
78800912
AD
415 }
416 }
417
5ab9791f 418 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
c633e370
AD
419
420 global $memcache;
421
422 /* Update all feeds with the same URL to utilize memcache */
423
424 if ($memcache) {
8d505d78
AD
425 $result = db_query($link, "SELECT f1.id
426 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
c633e370
AD
427 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
428
429 while ($line = db_fetch_assoc($result)) {
5ab9791f 430 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
c633e370
AD
431 }
432 } else {
5ab9791f 433 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
c633e370
AD
434 }
435 }
436
55ad314e
AD
437 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
438 $override_url = false) {
40d13c28 439
602690e5
AD
440 global $memcache;
441
412d258d
AD
442 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
443
b4e75b2a 444 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
45004d43 445 return false;
21cfcdf2
AD
446 }
447
412d258d 448 if ($debug_enabled) {
34e420fb 449 _debug("update_rss_feed: start");
219bd8fc
AD
450 }
451
39a52499
AD
452 if (!$ignore_daemon) {
453
454 if (DB_TYPE == "pgsql") {
455 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
456 } else {
457 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
8d505d78
AD
458 }
459
39a52499 460 $result = db_query($link, "SELECT id,update_interval,auth_login,
16211ddb 461 auth_pass,cache_images,update_method
39a52499 462 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
02008cb1 463
39a52499
AD
464 } else {
465
466 $result = db_query($link, "SELECT id,update_interval,auth_login,
57e24c82 467 feed_url,auth_pass,cache_images,update_method,last_updated,
5ab9791f
AD
468 mark_unread_on_update, owner_uid, update_on_checksum_change,
469 pubsub_state
39a52499
AD
470 FROM ttrss_feeds WHERE id = '$feed'");
471
472 }
a88c1f36 473
5370d37f 474 if (db_num_rows($result) == 0) {
412d258d 475 if ($debug_enabled) {
c633e370 476 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
8d505d78 477 }
45004d43 478 return false;
5370d37f
AD
479 }
480
16211ddb 481 $update_method = db_fetch_result($result, 0, "update_method");
50b2db96 482 $last_updated = db_fetch_result($result, 0, "last_updated");
57e24c82 483 $owner_uid = db_fetch_result($result, 0, "owner_uid");
30a2fe5a
AD
484 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
485 0, "mark_unread_on_update"));
486 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
487 0, "update_on_checksum_change"));
5ab9791f 488 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
16211ddb 489
3c50da83
AD
490 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
491 WHERE id = '$feed'");
492
464bd61e
AD
493 $auth_login = db_fetch_result($result, 0, "auth_login");
494 $auth_pass = db_fetch_result($result, 0, "auth_pass");
495
b3009bcd
AD
496 if ($update_method == 0)
497 $update_method = DEFAULT_UPDATE_METHOD + 1;
498
499 // 1 - Magpie
500 // 2 - SimplePie
501 // 3 - Twitter OAuth
502
503 if ($update_method == 2)
504 $use_simplepie = true;
505 else
506 $use_simplepie = false;
16211ddb 507
412d258d 508 if ($debug_enabled) {
b3009bcd 509 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
16211ddb
AD
510 }
511
b3009bcd 512 if ($update_method == 1) {
464bd61e
AD
513 $auth_login = urlencode($auth_login);
514 $auth_pass = urlencode($auth_pass);
515 }
47c6c988 516
a88c1f36 517 $update_interval = db_fetch_result($result, 0, "update_interval");
bc0f0785 518 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
c633e370 519 $fetch_url = db_fetch_result($result, 0, "feed_url");
a88c1f36 520
9949bd15 521 if ($update_interval < 0) { return false; }
a88c1f36 522
ab3d0b99
AD
523 $feed = db_escape_string($feed);
524
9949bd15 525 if ($auth_login && $auth_pass ){
47c6c988
AD
526 $url_parts = array();
527 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
528
529 if ($url_parts[1] && $url_parts[2]) {
530 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
531 }
532
533 }
ab3d0b99 534
55ad314e
AD
535 if ($override_url)
536 $fetch_url = $override_url;
537
412d258d 538 if ($debug_enabled) {
ca872b9d 539 _debug("update_rss_feed: fetching [$fetch_url]...");
219bd8fc
AD
540 }
541
e656b9f7 542 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
6e4f0519 543
c633e370 544 if ($memcache && $obj = $memcache->get($obj_id)) {
6e4f0519 545
412d258d 546 if ($debug_enabled) {
c633e370 547 _debug("update_rss_feed: data found in memcache.");
6e4f0519
AD
548 }
549
c633e370
AD
550 $rss = $obj;
551
552 } else {
553
b3009bcd 554 if ($update_method == 3) {
57e24c82 555 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
5ab9791f
AD
556 } else if ($update_method == 1) {
557
558 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
559 define('MAGPIE_CACHE_ON', !$no_cache);
61e420e9
AD
560 define('MAGPIE_FETCH_TIME_OUT', 60);
561 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
5ab9791f 562
fb074239 563 $rss = @fetch_rss($fetch_url);
c633e370 564 } else {
61e420e9
AD
565 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
566
567 if (!is_dir($simplepie_cache_dir)) {
568 mkdir($simplepie_cache_dir);
c633e370 569 }
8d505d78 570
c633e370 571 $rss = new SimplePie();
a18a4f38 572 $rss->set_useragent(SELF_USER_AGENT);
c633e370
AD
573 # $rss->set_timeout(10);
574 $rss->set_feed_url($fetch_url);
575 $rss->set_output_encoding('UTF-8');
a19d7722 576 $rss->force_feed(true);
8d505d78 577
c633e370 578 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
9fcbc76f 579
412d258d 580 if ($debug_enabled) {
b8998470 581 _debug("enabling image cache");
c633e370 582 }
9fcbc76f 583
b8998470 584 $rss->set_image_handler("image.php", 'i');
c633e370 585 }
8d505d78 586
412d258d 587 if ($debug_enabled) {
c633e370
AD
588 _debug("feed update interval (sec): " .
589 get_feed_update_interval($link, $feed)*60);
590 }
8d505d78 591
5ab9791f
AD
592 $rss->enable_cache(!$no_cache);
593
594 if (!$no_cache) {
61e420e9 595 $rss->set_cache_location($simplepie_cache_dir);
c633e370
AD
596 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
597 }
8d505d78 598
c633e370 599 $rss->init();
6e4f0519
AD
600 }
601
c633e370 602 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
9fdf7824
AD
603 }
604
605// print_r($rss);
219bd8fc 606
412d258d 607 if ($debug_enabled) {
34e420fb 608 _debug("update_rss_feed: fetch done, parsing...");
219bd8fc
AD
609 }
610
b6eefba5 611 $feed = db_escape_string($feed);
dcee8f61 612
b3009bcd 613 if ($update_method == 2) {
ca872b9d
AD
614 $fetch_ok = !$rss->error();
615 } else {
616 $fetch_ok = !!$rss;
617 }
618
619 if ($fetch_ok) {
50b62214 620
412d258d 621 if ($debug_enabled) {
50b62214
AD
622 _debug("update_rss_feed: processing feed data...");
623 }
624
44e241cb 625// db_query($link, "BEGIN");
dd8c76a9 626
a88c1f36 627 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
f324892e 628 FROM ttrss_feeds WHERE id = '$feed'");
331900c6 629
b6eefba5
AD
630 $registered_title = db_fetch_result($result, 0, "title");
631 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
f324892e 632 $orig_site_url = db_fetch_result($result, 0, "site_url");
331900c6 633
7fed1940
AD
634 $owner_uid = db_fetch_result($result, 0, "owner_uid");
635
16211ddb 636 if ($use_simplepie) {
9fdf7824
AD
637 $site_url = $rss->get_link();
638 } else {
639 $site_url = $rss->channel["link"];
640 }
641
68a57364
AD
642 $site_url = rewrite_relative_url($fetch_url, $site_url);
643
412d258d 644 if ($debug_enabled) {
85a92289 645 _debug("update_rss_feed: checking favicon...");
a2770077
AD
646 }
647
85a92289
AD
648 check_feed_favicon($site_url, $feed, $link);
649
746b249f 650 if (!$registered_title || $registered_title == "[Unknown]") {
4bc64807 651
16211ddb 652 if ($use_simplepie) {
c2f8aac4 653 $feed_title = db_escape_string($rss->get_title());
fb486a33
AD
654 } else {
655 $feed_title = db_escape_string($rss->channel["title"]);
656 }
4bc64807 657
412d258d 658 if ($debug_enabled) {
4bc64807
AD
659 _debug("update_rss_feed: registering title: $feed_title");
660 }
8d505d78
AD
661
662 db_query($link, "UPDATE ttrss_feeds SET
f324892e
AD
663 title = '$feed_title' WHERE id = '$feed'");
664 }
665
49f9c923 666 // weird, weird Magpie
16211ddb 667 if (!$use_simplepie) {
9fdf7824
AD
668 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
669 }
147f7691
AD
670
671 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
8d505d78 672 db_query($link, "UPDATE ttrss_feeds SET
f324892e 673 site_url = '$site_url' WHERE id = '$feed'");
331900c6 674 }
40d13c28 675
b7f4bda2
AD
676// print "I: " . $rss->channel["image"]["url"];
677
16211ddb 678 if (!$use_simplepie) {
98833033 679 $icon_url = db_escape_string($rss->image["url"]);
9fdf7824 680 } else {
98833033 681 $icon_url = db_escape_string($rss->get_image_url());
9fdf7824 682 }
b7f4bda2 683
0526ffdd
AD
684 $icon_url = substr($icon_url, 0, 250);
685
8d505d78 686 if ($icon_url && $orig_icon_url != $icon_url) {
014d3ad8 687 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
b7f4bda2
AD
688 }
689
412d258d 690 if ($debug_enabled) {
50b62214
AD
691 _debug("update_rss_feed: loading filters...");
692 }
e6155a06 693
5daa24f2 694 $filters = load_filters($link, $feed, $owner_uid);
e6155a06 695
412d258d
AD
696// if ($debug_enabled) {
697// print_r($filters);
698// }
0569a712 699
16211ddb 700 if ($use_simplepie) {
9fdf7824
AD
701 $iterator = $rss->get_items();
702 } else {
703 $iterator = $rss->items;
704 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
705 if (!$iterator || !is_array($iterator)) $iterator = $rss;
706 }
c22789da
AD
707
708 if (!is_array($iterator)) {
8d505d78 709 /* db_query($link, "UPDATE ttrss_feeds
75bd0669 710 SET last_error = 'Parse error: can\'t find any articles.'
77f0a2a7
AD
711 WHERE id = '$feed'"); */
712
713 // clear any errors and mark feed as updated if fetched okay
714 // even if it's blank
715
412d258d 716 if ($debug_enabled) {
844012bc
AD
717 _debug("update_rss_feed: entry iterator is not an array, no articles?");
718 }
719
8d505d78 720 db_query($link, "UPDATE ttrss_feeds
77f0a2a7
AD
721 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
722
723 return; // no articles
c22789da 724 }
ddb68b81 725
65eebd13 726 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
5ab9791f 727
dd50b552 728 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
c57983b1 729
5ab9791f
AD
730 $feed_hub_url = false;
731 if ($use_simplepie) {
732 $links = $rss->get_links('hub');
733
a9ac55ea
AD
734 if ($links && is_array($links)) {
735 foreach ($links as $l) {
736 $feed_hub_url = $l;
737 break;
738 }
5ab9791f
AD
739 }
740
741 } else {
742 $atom = $rss->channel['atom'];
743
744 if ($atom) {
745 if ($atom['link@rel'] == 'hub') {
746 $feed_hub_url = $atom['link@href'];
747 }
748
749 if (!$feed_hub_url && $atom['link#'] > 1) {
750 for ($i = 2; $i <= $atom['link#']; $i++) {
751 if ($atom["link#$i@rel"] == 'hub') {
752 $feed_hub_url = $atom["link#$i@href"];
a9ac55ea 753 break;
5ab9791f
AD
754 }
755 }
756 }
757 } else {
758 $feed_hub_url = $rss->channel['link_hub'];
759 }
760 }
761
dd50b552 762 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
c57983b1 763
3610b48b
AD
764 if ($feed_hub_url && function_exists('curl_init') &&
765 !ini_get("open_basedir")) {
c57983b1 766
5ab9791f 767 $callback_url = get_self_url_prefix() .
e0d91d84 768 "/public.php?op=pubsub&id=$feed";
5ab9791f
AD
769
770 $s = new Subscriber($feed_hub_url, $callback_url);
771
c57983b1
AD
772 $rc = $s->subscribe($fetch_url);
773
dd50b552
AD
774 if ($debug_enabled)
775 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
5ab9791f
AD
776
777 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
778 WHERE id = '$feed'");
779 }
780 }
781
412d258d 782 if ($debug_enabled) {
50b62214
AD
783 _debug("update_rss_feed: processing articles...");
784 }
785
ddb68b81 786 foreach ($iterator as $item) {
7c5a308d 787
b4e75b2a 788 if ($_REQUEST['xdebug'] == 2) {
40ce98f4
AD
789 print_r($item);
790 }
71bd29f6 791
16211ddb 792 if ($use_simplepie) {
9fdf7824
AD
793 $entry_guid = $item->get_id();
794 if (!$entry_guid) $entry_guid = $item->get_link();
795 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
796
797 } else {
798
799 $entry_guid = $item["id"];
34e420fb 800
9fdf7824 801 if (!$entry_guid) $entry_guid = $item["guid"];
530f5cda 802 if (!$entry_guid) $entry_guid = $item["about"];
9fdf7824
AD
803 if (!$entry_guid) $entry_guid = $item["link"];
804 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
805 }
be832a1a 806
412d258d 807 if ($debug_enabled) {
34e420fb
AD
808 _debug("update_rss_feed: guid $entry_guid");
809 }
810
be832a1a
AD
811 if (!$entry_guid) continue;
812
813 $entry_timestamp = "";
814
16211ddb 815 if ($use_simplepie) {
9fdf7824
AD
816 $entry_timestamp = strtotime($item->get_date());
817 } else {
818 $rss_2_date = $item['pubdate'];
819 $rss_1_date = $item['dc']['date'];
820 $atom_date = $item['issued'];
821 if (!$atom_date) $atom_date = $item['updated'];
e9558345 822
9fdf7824
AD
823 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
824 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
825 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
e9558345 826
9fdf7824 827 }
9bb36aa0 828
2e930846 829 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
be832a1a
AD
830 $entry_timestamp = time();
831 $no_orig_date = 'true';
832 } else {
833 $no_orig_date = 'false';
834 }
835
836 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
837
412d258d 838 if ($debug_enabled) {
44d0e774
AD
839 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
840 }
841
16211ddb 842 if ($use_simplepie) {
9fdf7824
AD
843 $entry_title = $item->get_title();
844 } else {
845 $entry_title = trim(strip_tags($item["title"]));
846 }
be832a1a 847
16211ddb 848 if ($use_simplepie) {
9fdf7824
AD
849 $entry_link = $item->get_link();
850 } else {
851 // strange Magpie workaround
852 $entry_link = $item["link_"];
853 if (!$entry_link) $entry_link = $item["link"];
854 }
be832a1a 855
68a57364
AD
856 $entry_link = rewrite_relative_url($site_url, $entry_link);
857
412d258d 858 if ($debug_enabled) {
9bb36aa0 859 _debug("update_rss_feed: title $entry_title");
68a57364 860 _debug("update_rss_feed: link $entry_link");
9bb36aa0
AD
861 }
862
863 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
7d3ab0dd 864
be832a1a 865 $entry_link = strip_tags($entry_link);
7d3ab0dd 866
16211ddb 867 if ($use_simplepie) {
4af7a36a
AD
868 $entry_content = $item->get_content();
869 if (!$entry_content) $entry_content = $item->get_description();
9fdf7824
AD
870 } else {
871 $entry_content = $item["content:escaped"];
872
873 if (!$entry_content) $entry_content = $item["content:encoded"];
e91ab107 874 if (!$entry_content) $entry_content = $item["content"]["encoded"];
9fdf7824 875 if (!$entry_content) $entry_content = $item["content"];
ea322415
AD
876
877 // Magpie bugs are getting ridiculous
878 if (trim($entry_content) == "Array") $entry_content = false;
879
9fdf7824
AD
880 if (!$entry_content) $entry_content = $item["atom_content"];
881 if (!$entry_content) $entry_content = $item["summary"];
e91ab107 882
8d505d78 883 if (!$entry_content ||
e91ab107
AD
884 strlen($entry_content) < strlen($item["description"])) {
885 $entry_content = $item["description"];
886 };
9fdf7824
AD
887
888 // WTF
889 if (is_array($entry_content)) {
890 $entry_content = $entry_content["encoded"];
891 if (!$entry_content) $entry_content = $entry_content["escaped"];
8d505d78 892 }
be832a1a
AD
893 }
894
b4e75b2a 895 if ($_REQUEST["xdebug"] == 2) {
ea322415
AD
896 print "update_rss_feed: content: ";
897 print_r(htmlspecialchars($entry_content));
898 }
be832a1a
AD
899
900 $entry_content_unescaped = $entry_content;
be832a1a 901
16211ddb 902 if ($use_simplepie) {
9fdf7824 903 $entry_comments = strip_tags($item->data["comments"]);
30cf38dd 904 if ($item->get_author()) {
e1d600f0 905 $entry_author_item = $item->get_author();
a0c6eafb
AD
906 $entry_author = $entry_author_item->get_name();
907 if (!$entry_author) $entry_author = $entry_author_item->get_email();
d1ee9106
AD
908
909 $entry_author = db_escape_string($entry_author);
30cf38dd 910 }
9fdf7824
AD
911 } else {
912 $entry_comments = strip_tags($item["comments"]);
8d505d78 913
9fdf7824 914 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
4d6e9157 915
9fdf7824 916 if ($item['author']) {
8d505d78 917
9fdf7824 918 if (is_array($item['author'])) {
8d505d78 919
9fdf7824
AD
920 if (!$entry_author) {
921 $entry_author = db_escape_string(strip_tags($item['author']['name']));
922 }
8d505d78 923
9fdf7824
AD
924 if (!$entry_author) {
925 $entry_author = db_escape_string(strip_tags($item['author']['email']));
926 }
4d6e9157 927 }
8d505d78 928
4d6e9157 929 if (!$entry_author) {
9fdf7824 930 $entry_author = db_escape_string(strip_tags($item['author']));
4d6e9157 931 }
83f114c8 932 }
be832a1a
AD
933 }
934
83f114c8
AD
935 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
936
be832a1a 937 $entry_guid = db_escape_string(strip_tags($entry_guid));
2ad9ee56 938 $entry_guid = mb_substr($entry_guid, 0, 250);
be832a1a 939
8d505d78 940 $result = db_query($link, "SELECT id FROM ttrss_entries
be832a1a
AD
941 WHERE guid = '$entry_guid'");
942
d564f283 943 $entry_content = db_escape_string($entry_content, false);
7e43ad58
AD
944
945 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
946
be832a1a
AD
947 $entry_title = db_escape_string($entry_title);
948 $entry_link = db_escape_string($entry_link);
2544f36b
AD
949 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
950 $entry_author = mb_substr($entry_author, 0, 250);
be832a1a 951
16211ddb 952 if ($use_simplepie) {
9fdf7824
AD
953 $num_comments = 0; #FIXME#
954 } else {
955 $num_comments = db_escape_string($item["slash"]["comments"]);
956 }
be832a1a
AD
957
958 if (!$num_comments) $num_comments = 0;
959
412d258d 960 if ($debug_enabled) {
c3fc5e47
AD
961 _debug("update_rss_feed: looking for tags [1]...");
962 }
963
fefef828 964 // parse <category> entries into tags
be832a1a 965
e75df19d
AD
966 $additional_tags = array();
967
16211ddb 968 if ($use_simplepie) {
be832a1a 969
9fdf7824 970 $additional_tags_src = $item->get_categories();
8d505d78 971
a702e931
AD
972 if (is_array($additional_tags_src)) {
973 foreach ($additional_tags_src as $tobj) {
974 array_push($additional_tags, $tobj->get_term());
975 }
fefef828 976 }
fefef828 977
412d258d 978 if ($debug_enabled) {
6af621c7
AD
979 _debug("update_rss_feed: category tags:");
980 print_r($additional_tags);
981 }
982
9fdf7824 983 } else {
fefef828 984
9fdf7824 985 $t_ctr = $item['category#'];
fefef828 986
9fdf7824 987 if ($t_ctr == 0) {
e75df19d 988 $additional_tags = array();
71bd29f6 989 } else if ($t_ctr > 0) {
9fdf7824 990 $additional_tags = array($item['category']);
71bd29f6
AD
991
992 if ($item['category@term']) {
993 array_push($additional_tags, $item['category@term']);
994 }
995
9fdf7824
AD
996 for ($i = 0; $i <= $t_ctr; $i++ ) {
997 if ($item["category#$i"]) {
998 array_push($additional_tags, $item["category#$i"]);
999 }
71bd29f6
AD
1000
1001 if ($item["category#$i@term"]) {
1002 array_push($additional_tags, $item["category#$i@term"]);
1003 }
9fdf7824
AD
1004 }
1005 }
8d505d78 1006
9fdf7824 1007 // parse <dc:subject> elements
8d505d78 1008
9fdf7824 1009 $t_ctr = $item['dc']['subject#'];
8d505d78 1010
71bd29f6 1011 if ($t_ctr > 0) {
e75df19d 1012 array_push($additional_tags, $item['dc']['subject']);
71bd29f6 1013
9fdf7824
AD
1014 for ($i = 0; $i <= $t_ctr; $i++ ) {
1015 if ($item['dc']["subject#$i"]) {
1016 array_push($additional_tags, $item['dc']["subject#$i"]);
1017 }
fefef828
AD
1018 }
1019 }
1020 }
8add756a 1021
412d258d 1022 if ($debug_enabled) {
c3fc5e47
AD
1023 _debug("update_rss_feed: looking for tags [2]...");
1024 }
e91ab107 1025
c3fc5e47
AD
1026 /* taaaags */
1027 // <a href="..." rel="tag">Xorg</a>, //
e91ab107 1028
c3fc5e47 1029 $entry_tags = null;
e91ab107 1030
c3fc5e47
AD
1031 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1032 $entry_content_unescaped, $entry_tags);
e91ab107 1033
c3fc5e47 1034 $entry_tags = $entry_tags[1];
b652fdae 1035
c3fc5e47 1036 $entry_tags = array_merge($entry_tags, $additional_tags);
1e87951d
AD
1037 $entry_tags = array_unique($entry_tags);
1038
1039 for ($i = 0; $i < count($entry_tags); $i++)
1040 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
b652fdae 1041
412d258d 1042 if ($debug_enabled) {
c3fc5e47
AD
1043 _debug("update_rss_feed: unfiltered tags found:");
1044 print_r($entry_tags);
ce53e200
AD
1045 }
1046
d48d160c 1047 # sanitize content
8d505d78 1048
621ffb00
AD
1049 $entry_content = sanitize_article_content($entry_content);
1050 $entry_title = sanitize_article_content($entry_title);
d48d160c 1051
412d258d 1052 if ($debug_enabled) {
34e420fb
AD
1053 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1054 }
1055
44e241cb
AD
1056 db_query($link, "BEGIN");
1057
4c193675
AD
1058 if (db_num_rows($result) == 0) {
1059
412d258d 1060 if ($debug_enabled) {
34e420fb
AD
1061 _debug("update_rss_feed: base guid not found");
1062 }
1063
4c193675
AD
1064 // base post entry does not exist, create it
1065
4c193675 1066 $result = db_query($link,
8d505d78 1067 "INSERT INTO ttrss_entries
4c193675
AD
1068 (title,
1069 guid,
1070 link,
1071 updated,
1072 content,
1073 content_hash,
1074 no_orig_date,
25ea2805 1075 date_updated,
4c193675 1076 date_entered,
11b0dce2 1077 comments,
b6104dee
AD
1078 num_comments,
1079 author)
4c193675 1080 VALUES
8d505d78
AD
1081 ('$entry_title',
1082 '$entry_guid',
4c193675 1083 '$entry_link',
8d505d78
AD
1084 '$entry_timestamp_fmt',
1085 '$entry_content',
4c193675 1086 '$content_hash',
8d505d78 1087 $no_orig_date,
25ea2805
AD
1088 NOW(),
1089 NOW(),
11b0dce2 1090 '$entry_comments',
b6104dee
AD
1091 '$num_comments',
1092 '$entry_author')");
8926aab8
AD
1093 } else {
1094 // we keep encountering the entry in feeds, so we need to
25ea2805 1095 // update date_updated column so that we don't get horrible
8926aab8
AD
1096 // dupes when the entry gets purged and reinserted again e.g.
1097 // in the case of SLOW SLOW OMG SLOW updating feeds
1098
1099 $base_entry_id = db_fetch_result($result, 0, "id");
1100
25ea2805 1101 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
8926aab8 1102 WHERE id = '$base_entry_id'");
4c193675
AD
1103 }
1104
1105 // now it should exist, if not - bad luck then
1106
8d505d78 1107 $result = db_query($link, "SELECT
6385315d 1108 id,content_hash,no_orig_date,title,
25ea2805 1109 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
2ac6b765 1110 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
11b0dce2 1111 num_comments
8d505d78
AD
1112 FROM
1113 ttrss_entries
6385315d 1114 WHERE guid = '$entry_guid'");
4c193675 1115
ce53e200
AD
1116 $entry_ref_id = 0;
1117 $entry_int_id = 0;
1118
4c193675
AD
1119 if (db_num_rows($result) == 1) {
1120
412d258d 1121 if ($debug_enabled) {
7ca91eb3 1122 _debug("update_rss_feed: base guid found, checking for user record");
34e420fb
AD
1123 }
1124
11b0dce2
AD
1125 // this will be used below in update handler
1126 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1127 $orig_title = db_fetch_result($result, 0, "title");
1128 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
8d505d78 1129 $orig_date_updated = strtotime(db_fetch_result($result,
25ea2805 1130 0, "date_updated"));
6385315d 1131
11b0dce2 1132 $ref_id = db_fetch_result($result, 0, "id");
ce53e200 1133 $entry_ref_id = $ref_id;
4c193675 1134
11b0dce2 1135 // check for user post link to main table
4c193675 1136
11b0dce2 1137 // do we allow duplicate posts with same GUID in different feeds?
8d0ec6fd 1138 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
e04c18a2 1139 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
8d505d78 1140 } else {
11b0dce2
AD
1141 $dupcheck_qpart = "";
1142 }
71604ca4 1143
c3fc5e47
AD
1144 /* Collect article tags here so we could filter by them: */
1145
8d505d78
AD
1146 $article_filters = get_article_filters($filters, $entry_title,
1147 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1e87951d 1148 $entry_tags);
19c9cb11 1149
412d258d 1150 if ($debug_enabled) {
7ca91eb3
AD
1151 _debug("update_rss_feed: article filters: ");
1152 if (count($article_filters) != 0) {
1153 print_r($article_filters);
1154 }
1155 }
1156
f8382011 1157 if (find_article_filter($article_filters, "filter")) {
ee4a9812 1158 db_query($link, "COMMIT"); // close transaction in progress
11b0dce2
AD
1159 continue;
1160 }
19c9cb11 1161
ff6e357a
AD
1162 $score = calculate_article_score($article_filters);
1163
412d258d 1164 if ($debug_enabled) {
ff6e357a
AD
1165 _debug("update_rss_feed: initial score: $score");
1166 }
1167
ef83538d 1168 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
11b0dce2 1169 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
ef83538d
AD
1170 $dupcheck_qpart";
1171
b4e75b2a 1172// if ($_REQUEST["xdebug"]) print "$query\n";
ef83538d
AD
1173
1174 $result = db_query($link, $query);
7ca91eb3 1175
11b0dce2
AD
1176 // okay it doesn't exist - create user entry
1177 if (db_num_rows($result) == 0) {
1178
412d258d 1179 if ($debug_enabled) {
7ca91eb3
AD
1180 _debug("update_rss_feed: user record not found, creating...");
1181 }
1182
24605713 1183 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
11b0dce2
AD
1184 $unread = 'true';
1185 $last_read_qpart = 'NULL';
1186 } else {
1187 $unread = 'false';
1188 $last_read_qpart = 'NOW()';
8d505d78 1189 }
dd7d3187 1190
32d59314 1191 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
dd7d3187
AD
1192 $marked = 'true';
1193 } else {
1194 $marked = 'false';
1195 }
a36c0dfe
AD
1196
1197 if (find_article_filter($article_filters, 'publish')) {
1198 $published = 'true';
1199 } else {
1200 $published = 'false';
1201 }
1202
11b0dce2 1203 $result = db_query($link,
8d505d78
AD
1204 "INSERT INTO ttrss_user_entries
1205 (ref_id, owner_uid, feed_id, unread, last_read, marked,
83cd33fc 1206 published, score, tag_cache, label_cache, uuid)
11b0dce2 1207 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
83cd33fc 1208 $last_read_qpart, $marked, $published, '$score', '', '', '')");
ce53e200 1209
2fcec4c4
AD
1210 if (PUBSUBHUBBUB_HUB && $published == 'true') {
1211 $rss_link = get_self_url_prefix() .
e0d91d84 1212 "/public.php?op=rss&id=-2&key=" .
50332a32 1213 get_feed_access_key($link, -2, false, $owner_uid);
2fcec4c4
AD
1214
1215 $p = new Publisher(PUBSUBHUBBUB_HUB);
1216
1217 $pubsub_result = $p->publish_update($rss_link);
1218 }
1219
8d505d78 1220 $result = db_query($link,
ce53e200
AD
1221 "SELECT int_id FROM ttrss_user_entries WHERE
1222 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1223 feed_id = '$feed' LIMIT 1");
1224
1225 if (db_num_rows($result) == 1) {
1226 $entry_int_id = db_fetch_result($result, 0, "int_id");
1227 }
1228 } else {
412d258d 1229 if ($debug_enabled) {
e04c18a2
AD
1230 _debug("update_rss_feed: user record FOUND");
1231 }
1232
ce53e200
AD
1233 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1234 $entry_int_id = db_fetch_result($result, 0, "int_id");
11b0dce2 1235 }
ce53e200 1236
412d258d 1237 if ($debug_enabled) {
ce53e200
AD
1238 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1239 }
1240
6385315d 1241 $post_needs_update = false;
cdaa1443 1242 $update_insignificant = false;
6385315d 1243
73f168fa 1244 if ($orig_num_comments != $num_comments) {
6385315d 1245 $post_needs_update = true;
73f168fa 1246 $update_insignificant = true;
6385315d
AD
1247 }
1248
73f168fa 1249 if ($content_hash != $orig_content_hash) {
6385315d 1250 $post_needs_update = true;
73f168fa 1251 $update_insignificant = false;
6385315d
AD
1252 }
1253
73f168fa 1254 if (db_escape_string($orig_title) != $entry_title) {
11b0dce2 1255 $post_needs_update = true;
73f168fa 1256 $update_insignificant = false;
11b0dce2
AD
1257 }
1258
8d505d78
AD
1259 // if post needs update, update it and mark all user entries
1260 // linking to this post as updated
6385315d
AD
1261 if ($post_needs_update) {
1262
7ca91eb3
AD
1263 if (defined('DAEMON_EXTENDED_DEBUG')) {
1264 _debug("update_rss_feed: post $entry_guid needs update...");
1265 }
1266
6385315d
AD
1267// print "<!-- post $orig_title needs update : $post_needs_update -->";
1268
8d505d78 1269 db_query($link, "UPDATE ttrss_entries
11b0dce2 1270 SET title = '$entry_title', content = '$entry_content',
7e43ad58 1271 content_hash = '$content_hash',
ad92c6ac 1272 updated = '$entry_timestamp_fmt',
11b0dce2 1273 num_comments = '$num_comments'
6385315d
AD
1274 WHERE id = '$ref_id'");
1275
cdaa1443
AD
1276 if (!$update_insignificant) {
1277 if ($mark_unread_on_update) {
1278 db_query($link, "UPDATE ttrss_user_entries
1279 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1280 } else if ($update_on_checksum_change) {
1281 db_query($link, "UPDATE ttrss_user_entries
1282 SET last_read = null WHERE ref_id = '$ref_id'
1283 AND unread = false");
1284 }
4919fb42 1285 }
6385315d 1286 }
4c193675
AD
1287 }
1288
44e241cb
AD
1289 db_query($link, "COMMIT");
1290
412d258d 1291 if ($debug_enabled) {
ceb30ba4
AD
1292 _debug("update_rss_feed: assigning labels...");
1293 }
1294
1295 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1296 $owner_uid);
1297
412d258d 1298 if ($debug_enabled) {
ce53e200
AD
1299 _debug("update_rss_feed: looking for enclosures...");
1300 }
1301
c3fc5e47
AD
1302 // enclosures
1303
1304 $enclosures = array();
1305
1306 if ($use_simplepie) {
1307 $encs = $item->get_enclosures();
1308
1309 if (is_array($encs)) {
1310 foreach ($encs as $e) {
1311 $e_item = array(
1312 $e->link, $e->type, $e->length);
8d505d78 1313
c3fc5e47
AD
1314 array_push($enclosures, $e_item);
1315 }
1316 }
1317
1318 } else {
1319 // <enclosure>
1320
1321 $e_ctr = $item['enclosure#'];
1322
1323 if ($e_ctr > 0) {
1324 $e_item = array($item['enclosure@url'],
1325 $item['enclosure@type'],
1326 $item['enclosure@length']);
1327
1328 array_push($enclosures, $e_item);
1329
1330 for ($i = 0; $i <= $e_ctr; $i++ ) {
1331
1332 if ($item["enclosure#$i@url"]) {
1333 $e_item = array($item["enclosure#$i@url"],
1334 $item["enclosure#$i@type"],
1335 $item["enclosure#$i@length"]);
1336 array_push($enclosures, $e_item);
1337 }
1338 }
1339 }
1340
1341 // <media:content>
1342 // can there be many of those? yes -fox
1343
1344 $m_ctr = $item['media']['content#'];
1345
1346 if ($m_ctr > 0) {
1347 $e_item = array($item['media']['content@url'],
1348 $item['media']['content@medium'],
1349 $item['media']['content@length']);
1350
1351 array_push($enclosures, $e_item);
1352
1353 for ($i = 0; $i <= $m_ctr; $i++ ) {
1354
1355 if ($item["media"]["content#$i@url"]) {
1356 $e_item = array($item["media"]["content#$i@url"],
1357 $item["media"]["content#$i@medium"],
1358 $item["media"]["content#$i@length"]);
1359 array_push($enclosures, $e_item);
1360 }
1361 }
1362
1363 }
1364 }
1365
1366
412d258d 1367 if ($debug_enabled) {
c3fc5e47 1368 _debug("update_rss_feed: article enclosures:");
ce53e200
AD
1369 print_r($enclosures);
1370 }
1371
1372 db_query($link, "BEGIN");
1373
1374 foreach ($enclosures as $enc) {
1375 $enc_url = db_escape_string($enc[0]);
1376 $enc_type = db_escape_string($enc[1]);
1377 $enc_dur = db_escape_string($enc[2]);
1378
1379 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1380 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1381
1382 if (db_num_rows($result) == 0) {
1383 db_query($link, "INSERT INTO ttrss_enclosures
1384 (content_url, content_type, title, duration, post_id) VALUES
1385 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1386 }
1387 }
1388
1389 db_query($link, "COMMIT");
1390
c3fc5e47 1391 // check for manual tags (we have to do it here since they're loaded from filters)
073ca0e6 1392
4d50f419
AD
1393 foreach ($article_filters as $f) {
1394 if ($f[0] == "tag") {
f8382011 1395
9949bd15 1396 $manual_tags = trim_array(explode(",", $f[1]));
073ca0e6 1397
4d50f419
AD
1398 foreach ($manual_tags as $tag) {
1399 if (tag_is_valid($tag)) {
1400 array_push($entry_tags, $tag);
1401 }
be832a1a
AD
1402 }
1403 }
1404 }
1405
c3fc5e47
AD
1406 // Skip boring tags
1407
9949bd15 1408 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
11c9ea1f 1409 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
8fc70781 1410
c3fc5e47 1411 $filtered_tags = array();
779560b7 1412 $tags_to_cache = array();
c3fc5e47
AD
1413
1414 if ($entry_tags && is_array($entry_tags)) {
1415 foreach ($entry_tags as $tag) {
1416 if (array_search($tag, $boring_tags) === false) {
1417 array_push($filtered_tags, $tag);
073ca0e6
AD
1418 }
1419 }
8d505d78 1420 }
fefef828 1421
779560b7
AD
1422 $filtered_tags = array_unique($filtered_tags);
1423
412d258d 1424 if ($debug_enabled) {
c3fc5e47
AD
1425 _debug("update_rss_feed: filtered article tags:");
1426 print_r($filtered_tags);
9fdf7824
AD
1427 }
1428
c3fc5e47
AD
1429 // Save article tags in the database
1430
1431 if (count($filtered_tags) > 0) {
8d505d78 1432
44e241cb 1433 db_query($link, "BEGIN");
8d505d78 1434
779560b7 1435 foreach ($filtered_tags as $tag) {
fefef828 1436
779560b7
AD
1437 $tag = sanitize_tag($tag);
1438 $tag = db_escape_string($tag);
1439
1440 if (!tag_is_valid($tag)) continue;
8d505d78
AD
1441
1442 $result = db_query($link, "SELECT id FROM ttrss_tags
1443 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
779560b7 1444 owner_uid = '$owner_uid' LIMIT 1");
31483fc1 1445
fe99ab12 1446 if ($result && db_num_rows($result) == 0) {
8d505d78
AD
1447
1448 db_query($link, "INSERT INTO ttrss_tags
fe99ab12
AD
1449 (owner_uid,tag_name,post_int_id)
1450 VALUES ('$owner_uid','$tag', '$entry_int_id')");
779560b7 1451 }
490c366d 1452
779560b7
AD
1453 array_push($tags_to_cache, $tag);
1454 }
490c366d 1455
779560b7 1456 /* update the cache */
8d505d78 1457
779560b7 1458 $tags_to_cache = array_unique($tags_to_cache);
8d505d78 1459
779560b7 1460 $tags_str = db_escape_string(join(",", $tags_to_cache));
490c366d 1461
8d505d78 1462 db_query($link, "UPDATE ttrss_user_entries
779560b7
AD
1463 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1464 AND owner_uid = $owner_uid");
ce53e200 1465
44e241cb 1466 db_query($link, "COMMIT");
8d505d78 1467 }
9fdf7824 1468
412d258d 1469 if ($debug_enabled) {
9fdf7824
AD
1470 _debug("update_rss_feed: article processed");
1471 }
8d505d78 1472 }
40d13c28 1473
50b2db96 1474 if (!$last_updated) {
412d258d 1475 if ($debug_enabled) {
50b2db96
AD
1476 _debug("update_rss_feed: new feed, catching it up...");
1477 }
c7e51de1 1478 catchup_feed($link, $feed, false, $owner_uid);
50b2db96
AD
1479 }
1480
71344201
AD
1481 if ($debug_enabled) {
1482 _debug("purging feed...");
1483 }
1484
1485 purge_feed($link, $feed, 0, $debug_enabled);
3907ef71 1486
8d505d78 1487 db_query($link, "UPDATE ttrss_feeds
ab3d0b99 1488 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
eb36b4eb 1489
44e241cb 1490// db_query($link, "COMMIT");
dd8c76a9 1491
ab3d0b99 1492 } else {
ca872b9d 1493
16211ddb 1494 if ($use_simplepie) {
ca872b9d 1495 $error_msg = mb_substr($rss->error(), 0, 250);
9fdf7824 1496 } else {
ca872b9d 1497 $error_msg = mb_substr(magpie_error(), 0, 250);
9fdf7824 1498 }
ca872b9d 1499
412d258d 1500 if ($debug_enabled) {
ca872b9d
AD
1501 _debug("update_rss_feed: error fetching feed: $error_msg");
1502 }
1503
1504 $error_msg = db_escape_string($error_msg);
1505
8d505d78
AD
1506 db_query($link,
1507 "UPDATE ttrss_feeds SET last_error = '$error_msg',
aa5f9f5f 1508 last_updated = NOW() WHERE id = '$feed'");
40d13c28
AD
1509 }
1510
16211ddb 1511 if ($use_simplepie) {
ac6ebdb3
AD
1512 unset($rss);
1513 }
1514
412d258d 1515 if ($debug_enabled) {
34e420fb 1516 _debug("update_rss_feed: done");
219bd8fc
AD
1517 }
1518
40d13c28
AD
1519 }
1520
f175937c 1521 function print_select($id, $default, $values, $attributes = "") {
79f3553b 1522 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
1523 foreach ($values as $v) {
1524 if ($v == $default)
60807300 1525 $sel = "selected=\"1\"";
a0d53889
AD
1526 else
1527 $sel = "";
8d505d78 1528
60807300 1529 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
1530 }
1531 print "</select>";
1532 }
40d13c28 1533
79f3553b
AD
1534 function print_select_hash($id, $default, $values, $attributes = "") {
1535 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
1536 foreach (array_keys($values) as $v) {
1537 if ($v == $default)
74d5c8fa 1538 $sel = 'selected="selected"';
673d54ca
AD
1539 else
1540 $sel = "";
8d505d78 1541
673d54ca
AD
1542 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1543 }
1544
1545 print "</select>";
1546 }
1547
c3fc5e47 1548 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
240054f1 1549 $matches = array();
c2d9322b 1550
240054f1
AD
1551 if ($filters["title"]) {
1552 foreach ($filters["title"] as $filter) {
8d505d78
AD
1553 $reg_exp = $filter["reg_exp"];
1554 $inverse = $filter["inverse"];
1555 if ((!$inverse && @preg_match("/$reg_exp/i", $title)) ||
a9d63d29 1556 ($inverse && !@preg_match("/$reg_exp/i", $title))) {
c2d9322b 1557
240054f1
AD
1558 array_push($matches, array($filter["action"], $filter["action_param"]));
1559 }
1560 }
1561 }
1562
1563 if ($filters["content"]) {
1564 foreach ($filters["content"] as $filter) {
c2d9322b
AD
1565 $reg_exp = $filter["reg_exp"];
1566 $inverse = $filter["inverse"];
1567
8d505d78 1568 if ((!$inverse && @preg_match("/$reg_exp/i", $content)) ||
a9d63d29 1569 ($inverse && !@preg_match("/$reg_exp/i", $content))) {
c2d9322b 1570
240054f1 1571 array_push($matches, array($filter["action"], $filter["action_param"]));
8d505d78 1572 }
240054f1
AD
1573 }
1574 }
1575
1576 if ($filters["both"]) {
8d505d78
AD
1577 foreach ($filters["both"] as $filter) {
1578 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1579 $inverse = $filter["inverse"];
1580
1581 if ($inverse) {
a9d63d29 1582 if (!@preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
c2d9322b
AD
1583 array_push($matches, array($filter["action"], $filter["action_param"]));
1584 }
1585 } else {
a9d63d29 1586 if (@preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
c2d9322b
AD
1587 array_push($matches, array($filter["action"], $filter["action_param"]));
1588 }
240054f1
AD
1589 }
1590 }
1591 }
1592
1593 if ($filters["link"]) {
1594 $reg_exp = $filter["reg_exp"];
1595 foreach ($filters["link"] as $filter) {
1596 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1597 $inverse = $filter["inverse"];
1598
8d505d78 1599 if ((!$inverse && @preg_match("/$reg_exp/i", $link)) ||
a9d63d29 1600 ($inverse && !@preg_match("/$reg_exp/i", $link))) {
8d505d78 1601
240054f1
AD
1602 array_push($matches, array($filter["action"], $filter["action_param"]));
1603 }
1604 }
1605 }
1606
44d0e774
AD
1607 if ($filters["date"]) {
1608 $reg_exp = $filter["reg_exp"];
1609 foreach ($filters["date"] as $filter) {
1610 $date_modifier = $filter["filter_param"];
1611 $inverse = $filter["inverse"];
1612 $check_timestamp = strtotime($filter["reg_exp"]);
1613
1614 # no-op when timestamp doesn't parse to prevent misfires
1615
1616 if ($check_timestamp) {
1617 $match_ok = false;
1618
1619 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1620 $date_modifier == "after" && $timestamp > $check_timestamp) {
1621 $match_ok = true;
1622 }
1623
1624 if ($inverse) $match_ok = !$match_ok;
1625
1626 if ($match_ok) {
1627 array_push($matches, array($filter["action"], $filter["action_param"]));
1628 }
1629 }
1630 }
8d505d78 1631 }
44d0e774 1632
fa3317be
AD
1633 if ($filters["author"]) {
1634 foreach ($filters["author"] as $filter) {
8d505d78
AD
1635 $reg_exp = $filter["reg_exp"];
1636 $inverse = $filter["inverse"];
1637 if ((!$inverse && @preg_match("/$reg_exp/i", $author)) ||
a9d63d29 1638 ($inverse && !@preg_match("/$reg_exp/i", $author))) {
fa3317be
AD
1639
1640 array_push($matches, array($filter["action"], $filter["action_param"]));
1641 }
1642 }
1643 }
1644
c3fc5e47
AD
1645 if ($filters["tag"]) {
1646
1647 $tag_string = join(",", $tags);
1648
1649 foreach ($filters["tag"] as $filter) {
1650 $reg_exp = $filter["reg_exp"];
1651 $inverse = $filter["inverse"];
1652
8d505d78 1653 if ((!$inverse && @preg_match("/$reg_exp/i", $tag_string)) ||
a9d63d29 1654 ($inverse && !@preg_match("/$reg_exp/i", $tag_string))) {
c3fc5e47
AD
1655
1656 array_push($matches, array($filter["action"], $filter["action_param"]));
8d505d78 1657 }
c3fc5e47
AD
1658 }
1659 }
1660
1661
240054f1
AD
1662 return $matches;
1663 }
1664
f8382011
AD
1665 function find_article_filter($filters, $filter_name) {
1666 foreach ($filters as $f) {
1667 if ($f[0] == $filter_name) {
1668 return $f;
1669 };
1670 }
1671 return false;
1672 }
1673
ff6e357a
AD
1674 function calculate_article_score($filters) {
1675 $score = 0;
1676
1677 foreach ($filters as $f) {
1678 if ($f[0] == "score") {
1679 $score += $f[1];
1680 };
1681 }
1682 return $score;
1683 }
1684
ceb30ba4
AD
1685 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1686 foreach ($filters as $f) {
1687 if ($f[0] == "label") {
1688 label_add_article($link, $id, $f[1], $owner_uid);
1689 };
1690 }
1691 }
ff6e357a 1692
406d9489
AD
1693 function getmicrotime() {
1694 list($usec, $sec) = explode(" ",microtime());
1695 return ((float)$usec + (float)$sec);
1696 }
1697
f541eb78 1698 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 1699 foreach ($values as $v) {
8d505d78 1700
77e96719 1701 if ($v == $default)
5da169d9 1702 $sel = "checked";
77e96719 1703 else
5da169d9
AD
1704 $sel = "";
1705
f541eb78 1706 if ($v == $true_is) {
5da169d9
AD
1707 $sel .= " value=\"1\"";
1708 } else {
1709 $sel .= " value=\"0\"";
1710 }
8d505d78
AD
1711
1712 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 1713 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
1714
1715 }
1716 }
1717
d9084cf2 1718 function initialize_user_prefs($link, $uid, $profile = false) {
ff485f1d
AD
1719
1720 $uid = db_escape_string($uid);
1721
d9084cf2
AD
1722 if (!$profile) {
1723 $profile = "NULL";
f9aa6a89 1724 $profile_qpart = "AND profile IS NULL";
d9084cf2 1725 } else {
f9aa6a89 1726 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
1727 }
1728
f9aa6a89
AD
1729 if (get_schema_version($link) < 63) $profile_qpart = "";
1730
ff485f1d
AD
1731 db_query($link, "BEGIN");
1732
1733 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78
AD
1734
1735 $u_result = db_query($link, "SELECT pref_name
f9aa6a89 1736 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
1737
1738 $active_prefs = array();
1739
1740 while ($line = db_fetch_assoc($u_result)) {
8d505d78 1741 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
1742 }
1743
1744 while ($line = db_fetch_assoc($result)) {
1745 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1746// print "adding " . $line["pref_name"] . "<br>";
1747
f9aa6a89
AD
1748 if (get_schema_version($link) < 63) {
1749 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 1750 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
1751 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1752
1753 } else {
1754 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 1755 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
1756 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1757 }
ff485f1d
AD
1758
1759 }
1760 }
1761
1762 db_query($link, "COMMIT");
1763
1764 }
956c7629 1765
8de8bfb8
AD
1766 function get_ssl_certificate_id() {
1767 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1768 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1769 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1770 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1771 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1772 }
1773 return "";
1774 }
1775
3d72afa1
AD
1776 function get_login_by_ssl_certificate($link) {
1777
8de8bfb8 1778 $cert_serial = db_escape_string(get_ssl_certificate_id());
3d72afa1
AD
1779
1780 if ($cert_serial) {
1781 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1782 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1783 owner_uid = ttrss_users.id");
1784
1785 if (db_num_rows($result) != 0) {
1786 return db_escape_string(db_fetch_result($result, 0, "login"));
1787 }
1788 }
1789
1790 return "";
1791 }
1792
bf9fc060 1793 function get_remote_user($link) {
f98252f2 1794
3d72afa1 1795 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH) {
bf9fc060 1796 return db_escape_string($_SERVER["REMOTE_USER"]);
3d72afa1 1797 }
f98252f2 1798
bf9fc060 1799 return db_escape_string(get_login_by_ssl_certificate($link));
f98252f2
AD
1800 }
1801
bf9fc060
AD
1802 function get_remote_fakepass($link) {
1803 if (get_remote_user($link))
f98252f2
AD
1804 return "******";
1805 else
1806 return "";
1807 }
1808
461766f3 1809 function authenticate_user($link, $login, $password, $force_auth = false) {
c8437f35 1810
131b01b3 1811 if (!SINGLE_USER_MODE) {
c8437f35 1812
1a9f4d3c
AD
1813 $pwd_hash1 = encrypt_password($password);
1814 $pwd_hash2 = encrypt_password($password, $login);
2d969845 1815 $login = db_escape_string($login);
461766f3 1816
bf9fc060 1817 $remote_user = get_remote_user($link);
66917e70 1818
c9b63492 1819 if ($remote_user && $remote_user == $login && $login != "admin") {
3d72afa1
AD
1820
1821 $login = $remote_user;
66917e70 1822
73f5f114 1823 $query = "SELECT id,login,access_level,pwd_hash
461766f3 1824 FROM ttrss_users WHERE
66917e70
AD
1825 login = '$login'";
1826
42315f8d
AD
1827 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1828 && $_SERVER["REMOTE_USER"]) {
1829 $result = db_query($link, $query);
1830
1831 // First login ?
1832 if (db_num_rows($result) == 0) {
6ad2bbbc 1833 $query2 = "INSERT INTO ttrss_users
42315f8d
AD
1834 (login,access_level,last_login,created)
1835 VALUES ('$login', 0, null, NOW())";
6ad2bbbc 1836 db_query($link, $query2);
42315f8d
AD
1837 }
1838 }
1839
461766f3 1840 } else {
1a9f4d3c 1841 $query = "SELECT id,login,access_level,pwd_hash
461766f3 1842 FROM ttrss_users WHERE
1a9f4d3c
AD
1843 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1844 pwd_hash = '$pwd_hash2')";
461766f3
AD
1845 }
1846
1847 $result = db_query($link, $query);
8d505d78 1848
131b01b3
AD
1849 if (db_num_rows($result) == 1) {
1850 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1851 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1852 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
8d505d78
AD
1853
1854 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 1855 $_SESSION["uid"]);
8d505d78 1856
42315f8d
AD
1857
1858 // LemonLDAP can send user informations via HTTP HEADER
1859 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER){
1860 // update user name
8efb5f62
AD
1861 $fullname = $_SERVER['HTTP_USER_NAME'] ? $_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1862 if ($fullname){
1863 $fullname = db_escape_string($fullname);
42315f8d
AD
1864 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1865 $_SESSION["uid"]);
1866 }
1867 // update user mail
8efb5f62
AD
1868 $email = $_SERVER['HTTP_USER_MAIL'] ? $_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1869 if ($email){
1870 $email = db_escape_string($email);
42315f8d
AD
1871 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1872 $_SESSION["uid"]);
1873 }
1874 }
1875
131b01b3 1876 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 1877 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
1878
1879 $_SESSION["last_version_check"] = time();
8d505d78 1880
131b01b3 1881 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 1882
131b01b3
AD
1883 return true;
1884 }
8d505d78 1885
131b01b3 1886 return false;
503eb349 1887
131b01b3 1888 } else {
503eb349 1889
131b01b3
AD
1890 $_SESSION["uid"] = 1;
1891 $_SESSION["name"] = "admin";
f557cd78 1892
0bbba72d 1893 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 1894
0bbba72d 1895 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 1896
c8437f35
AD
1897 return true;
1898 }
c8437f35
AD
1899 }
1900
e6cb77a0
AD
1901 function make_password($length = 8) {
1902
1903 $password = "";
8d505d78
AD
1904 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1905
1906 $i = 0;
1907
1908 while ($i < $length) {
e6cb77a0 1909 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
8d505d78
AD
1910
1911 if (!strstr($password, $char)) {
e6cb77a0
AD
1912 $password .= $char;
1913 $i++;
1914 }
1915 }
1916 return $password;
1917 }
1918
1919 // this is called after user is created to initialize default feeds, labels
1920 // or whatever else
8d505d78 1921
e6cb77a0
AD
1922 // user preferences are checked on every login, not here
1923
1924 function initialize_user($link, $uid) {
1925
e6cb77a0 1926 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 1927 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 1928 'http://tt-rss.org/releases.rss')");
3b0feb9b 1929
cd2cd415
AD
1930 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1931 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 1932 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 1933 }
e6cb77a0 1934
b8aa49bc 1935 function logout_user() {
5ccc1cf5
AD
1936 session_destroy();
1937 if (isset($_COOKIE[session_name()])) {
1938 setcookie(session_name(), '', time()-42000, '/');
1939 }
b8aa49bc
AD
1940 }
1941
916f788a 1942 function validate_session($link) {
0f41fce8
AD
1943 if (SINGLE_USER_MODE) return true;
1944
1945 $check_ip = $_SESSION['ip_address'];
1946
1947 switch (SESSION_CHECK_ADDRESS) {
1948 case 0:
1949 $check_ip = '';
1950 break;
1951 case 1:
1952 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1953 break;
1954 case 2:
1955 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1956 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1957 break;
1958 };
1959
d769a0f7 1960 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
8d505d78 1961 $_SESSION["login_error_msg"] =
d769a0f7
AD
1962 __("Session failed to validate (incorrect IP)");
1963 return false;
1964 }
0f41fce8
AD
1965
1966 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
05044a59 1967 return false;
05044a59 1968
e6684130
AD
1969 if ($_SESSION["uid"]) {
1970
8d505d78 1971 $result = db_query($link,
e6684130
AD
1972 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1973
1974 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1975
1976 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1977 return false;
1978 }
1979 }
1980
a885f0ec 1981/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 1982
8e849206 1983 //print_r($_SESSION);
d620cfe7
AD
1984
1985 if (time() > $_SESSION["cookie_lifetime"]) {
1986 return false;
1987 }
a885f0ec
AD
1988 } */
1989
916f788a
AD
1990 return true;
1991 }
1992
793185a9 1993 function login_sequence($link, $mobile = false) {
c648997b
AD
1994 $_SESSION["prefs_cache"] = array();
1995
b8aa49bc 1996 if (!SINGLE_USER_MODE) {
75836f33 1997
7f0acba7 1998 $login_action = $_POST["login_action"];
a885f0ec 1999
8d505d78 2000 # try to authenticate user if called from login form
7f0acba7 2001 if ($login_action == "do_login") {
92decf4f 2002 $login = db_escape_string($_POST["login"]);
4044a5fa 2003 $password = $_POST["password"];
d620cfe7 2004 $remember_me = $_POST["remember_me"];
f557cd78 2005
01a87dff
AD
2006 if (authenticate_user($link, $login, $password)) {
2007 $_POST["password"] = "";
d620cfe7 2008
f8c612d4 2009 $_SESSION["language"] = $_POST["language"];
05044a59 2010 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
a598370d 2011 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
f8c612d4 2012
d9084cf2
AD
2013 if ($_POST["profile"]) {
2014
2015 $profile = db_escape_string($_POST["profile"]);
2016
2017 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2018 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2019
2020 if (db_num_rows($result) != 0) {
2021 $_SESSION["profile"] = $profile;
2022 $_SESSION["prefs_cache"] = array();
2023 }
2024 }
2025
6615cc36
AD
2026 if ($_REQUEST['return']) {
2027 header("Location: " . $_REQUEST['return']);
2028 } else {
2029 header("Location: " . $_SERVER["REQUEST_URI"]);
2030 }
2031
d620cfe7
AD
2032 exit;
2033
01a87dff 2034 return;
7f0acba7 2035 } else {
af163b85 2036 $_SESSION["login_error_msg"] = __("Incorrect username or password");
01a87dff
AD
2037 }
2038 }
2039
7f0acba7 2040 if (!$_SESSION["uid"] || !validate_session($link)) {
3d72afa1 2041
bf9fc060
AD
2042 if (get_remote_user($link) && AUTO_LOGIN) {
2043 authenticate_user($link, get_remote_user($link), null);
12df6592
AD
2044 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2045 } else {
2046 render_login_form($link, $mobile);
2047 //header("Location: login.php");
2048 exit;
2049 }
d3687e7a
AD
2050 } else {
2051 /* bump login timestamp */
8d505d78 2052 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
d3687e7a 2053 $_SESSION["uid"]);
019bd5a9 2054
d54780bc 2055 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
8d505d78 2056 setcookie("ttrss_lang", $_SESSION["language"],
019bd5a9
AD
2057 time() + SESSION_COOKIE_LIFETIME);
2058 }
3261ca58
AD
2059
2060 // try to remove possible duplicates from feed counter cache
147f5632 2061// ccache_cleanup($link, $_SESSION["uid"]);
b8aa49bc 2062 }
d620cfe7 2063
b8aa49bc 2064 } else {
0bbba72d 2065 return authenticate_user($link, "admin", null);
b8aa49bc
AD
2066 }
2067 }
3547842a 2068
411fe209 2069 function truncate_string($str, $max_len, $suffix = '&hellip;') {
12db369c 2070 if (mb_strlen($str, "utf-8") > $max_len - 3) {
411fe209 2071 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
2072 } else {
2073 return $str;
2074 }
2075 }
54a60e1a 2076
e9823609 2077 function theme_image($link, $filename) {
883fee8d
AD
2078 if ($link) {
2079 $theme_path = get_user_theme_path($link);
e9823609 2080
883fee8d
AD
2081 if ($theme_path && is_file($theme_path.$filename)) {
2082 return $theme_path.$filename;
2083 } else {
2084 return $filename;
2085 }
e9823609
AD
2086 } else {
2087 return $filename;
2088 }
2089 }
2090
dce46cad 2091 function get_user_theme($link) {
e4c51a6c 2092
b92fbcd8 2093 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
b97e6e02
AD
2094 $theme_name = get_pref($link, "_THEME_ID");
2095 if (is_dir("themes/$theme_name")) {
2096 return $theme_name;
2097 } else {
2098 return '';
2099 }
e4c51a6c 2100 } else {
b97e6e02 2101 return '';
e4c51a6c 2102 }
d9084cf2 2103
dce46cad
AD
2104 }
2105
2106 function get_user_theme_path($link) {
c3fddd05 2107 $theme_path = '';
dce46cad 2108
b92fbcd8 2109 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
dce46cad
AD
2110 $theme_name = get_pref($link, "_THEME_ID");
2111
b97e6e02 2112 if ($theme_name && is_dir("themes/$theme_name")) {
dce46cad 2113 $theme_path = "themes/$theme_name/";
6ba50622 2114 } else {
dce46cad 2115 $theme_name = '';
6ba50622 2116 }
54a60e1a 2117 } else {
dce46cad
AD
2118 $theme_path = '';
2119 }
2120
0c425dc7 2121 if ($theme_path) {
8d3cb8c0
AD
2122 if (is_file("$theme_path/theme.ini")) {
2123 $ini = parse_ini_file("$theme_path/theme.ini", true);
2124 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
0c425dc7
AD
2125 return $theme_path;
2126 }
2127 }
2128 }
2129 return '';
dce46cad
AD
2130 }
2131
e71f2610
AD
2132 function get_user_theme_options($link) {
2133 $t = get_user_theme_path($link);
2134
2135 if ($t) {
2136 if (is_file("$t/theme.ini")) {
2137 $ini = parse_ini_file("$t/theme.ini", true);
2138 if ($ini['theme']['version']) {
2139 return $ini['theme']['options'];
2140 }
2141 }
2142 }
f1f3a642 2143 return '';
e71f2610
AD
2144 }
2145
8d3cb8c0
AD
2146 function print_theme_includes($link) {
2147
2148 $t = get_user_theme_path($link);
2149 $time = time();
2150
2151 if ($t) {
8d505d78 2152 print "<link rel=\"stylesheet\" type=\"text/css\"
8d3cb8c0
AD
2153 href=\"$t/theme.css?$time \">";
2154 if (file_exists("$t/theme.js")) {
2155 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2156 </script>";
2157 }
2158 }
2159 }
e71f2610 2160
dce46cad
AD
2161 function get_all_themes() {
2162 $themes = glob("themes/*");
2163
b97e6e02
AD
2164 asort($themes);
2165
dce46cad
AD
2166 $rv = array();
2167
2168 foreach ($themes as $t) {
2169 if (is_file("$t/theme.ini")) {
2170 $ini = parse_ini_file("$t/theme.ini", true);
8d505d78 2171 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
0c425dc7 2172 !$ini['theme']['disabled']) {
dce46cad
AD
2173 $entry = array();
2174 $entry["path"] = $t;
2175 $entry["base"] = basename($t);
2176 $entry["name"] = $ini['theme']['name'];
2177 $entry["version"] = $ini['theme']['version'];
2178 $entry["author"] = $ini['theme']['author'];
e71f2610 2179 $entry["options"] = $ini['theme']['options'];
dce46cad
AD
2180 array_push($rv, $entry);
2181 }
2182 }
54a60e1a 2183 }
dce46cad
AD
2184
2185 return $rv;
54a60e1a 2186 }
be773442 2187
ab4b768f
AD
2188 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2189
2190 try {
2191 $source_tz = new DateTimeZone($source_tz);
2192 } catch (Exception $e) {
2193 $source_tz = new DateTimeZone('UTC');
2194 }
2195
2196 try {
2197 $dest_tz = new DateTimeZone($dest_tz);
2198 } catch (Exception $e) {
2199 $dest_tz = new DateTimeZone('UTC');
2200 }
2201
2202 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2203 return $dt->format('U') + $dest_tz->getOffset($dt);
2204 }
2205
324944f3
AD
2206 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2207 $no_smart_dt = false) {
2208
2209 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2210 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2211
7d96bfcd
AD
2212 global $utc_tz;
2213 global $tz_offset;
324944f3 2214
7d96bfcd
AD
2215 # We store date in UTC internally
2216 $dt = new DateTime($timestamp, $utc_tz);
2217
2218 if ($tz_offset == -1) {
2219
2220 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2221
2222 try {
2223 $user_tz = new DateTimeZone($user_tz_string);
2224 } catch (Exception $e) {
2225 $user_tz = $utc_tz;
2226 }
2227
2228 $tz_offset = $user_tz->getOffset($dt);
324944f3
AD
2229 }
2230
7d96bfcd 2231 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 2232
1dc52ae7 2233 if (!$no_smart_dt) {
8d505d78 2234 return smart_date_time($link, $user_timestamp,
7d96bfcd 2235 $tz_offset, $owner_uid);
324944f3
AD
2236 } else {
2237 if ($long)
2238 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2239 else
2240 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2241
2242 return date($format, $user_timestamp);
2243 }
2244 }
2245
2a5c136e
AD
2246 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2247 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2248
2249 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 2250 return date("G:i", $timestamp);
2a5c136e
AD
2251 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
2252 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2253 return date($format, $timestamp);
be773442 2254 } else {
2a5c136e
AD
2255 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2256 return date($format, $timestamp);
be773442
AD
2257 }
2258 }
2259
e3c99f3b 2260 function sql_bool_to_bool($s) {
36184020 2261 if ($s == "t" || $s == "1" || $s == "true") {
e3c99f3b
AD
2262 return true;
2263 } else {
2264 return false;
2265 }
2266 }
8d505d78 2267
badac687
AD
2268 function bool_to_sql_bool($s) {
2269 if ($s) {
2270 return "true";
2271 } else {
2272 return "false";
2273 }
2274 }
e3c99f3b 2275
fcfa9ef1
AD
2276 // Session caching removed due to causing wrong redirects to upgrade
2277 // script when get_schema_version() is called on an obsolete session
2278 // created on a previous schema version.
199db684 2279 function get_schema_version($link, $nocache = false) {
7d96bfcd
AD
2280 global $schema_version;
2281
2282 if (!$schema_version) {
199db684
AD
2283 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2284 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 2285 $schema_version = $version;
199db684 2286 return $version;
7d96bfcd
AD
2287 } else {
2288 return $schema_version;
2289 }
e4c51a6c
AD
2290 }
2291
6043fb7e 2292 function sanity_check($link) {
9cbca41f 2293
ebb948c2
AD
2294 global $ERRORS;
2295
6043fb7e 2296 $error_code = 0;
7d96bfcd 2297 $schema_version = get_schema_version($link, true);
6043fb7e
AD
2298
2299 if ($schema_version != SCHEMA_VERSION) {
2300 $error_code = 5;
2301 }
2302
aec3ce39
AD
2303 if (DB_TYPE == "mysql") {
2304 $result = db_query($link, "SELECT true", false);
2305 if (db_num_rows($result) != 1) {
2306 $error_code = 10;
2307 }
2308 }
2309
f29ba148
AD
2310 if (db_escape_string("testTEST") != "testTEST") {
2311 $error_code = 12;
2312 }
2313
ebb948c2 2314 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
2315 }
2316
27981ca3 2317 function file_is_locked($filename) {
31a6d42d 2318 if (function_exists('flock')) {
fb074239 2319 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
2320 if ($fp) {
2321 if (flock($fp, LOCK_EX | LOCK_NB)) {
2322 flock($fp, LOCK_UN);
2323 fclose($fp);
2324 return false;
2325 }
27981ca3 2326 fclose($fp);
31a6d42d 2327 return true;
e89aed7b
AD
2328 } else {
2329 return false;
27981ca3 2330 }
27981ca3 2331 }
c1fb4a5e 2332 return true; // consider the file always locked and skip the test
27981ca3
AD
2333 }
2334
fcb4c0c9 2335 function make_lockfile($filename) {
cfa43e02 2336 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 2337
82acc36d 2338 if (flock($fp, LOCK_EX | LOCK_NB)) {
4c59adb1
AD
2339 if (function_exists('posix_getpid')) {
2340 fwrite($fp, posix_getpid() . "\n");
2341 }
fcb4c0c9
AD
2342 return $fp;
2343 } else {
2344 return false;
2345 }
2346 }
2347
bf7fcde8 2348 function make_stampfile($filename) {
cfa43e02 2349 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 2350
8e00ae9b 2351 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 2352 fwrite($fp, time() . "\n");
8e00ae9b 2353 flock($fp, LOCK_UN);
bf7fcde8
AD
2354 fclose($fp);
2355 return true;
2356 } else {
2357 return false;
2358 }
2359 }
2360
894ebcf5
AD
2361 function sql_random_function() {
2362 if (DB_TYPE == "mysql") {
2363 return "RAND()";
2364 } else {
2365 return "RANDOM()";
2366 }
2367 }
2368
d36f5607 2369 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
c7e51de1
AD
2370
2371 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 2372
37c03d3a 2373 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 2374
37c03d3a 2375 if (is_numeric($feed)) {
23aa0d16
AD
2376 if ($cat_view) {
2377
72a2f4f5 2378 if ($feed >= 0) {
f9fca8cb
AD
2379
2380 if ($feed > 0) {
2381 $cat_qpart = "cat_id = '$feed'";
2382 } else {
2383 $cat_qpart = "cat_id IS NULL";
2384 }
8d505d78
AD
2385
2386 $tmp_result = db_query($link, "SELECT id
c7e51de1 2387 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
f9fca8cb
AD
2388
2389 while ($tmp_line = db_fetch_assoc($tmp_result)) {
23aa0d16 2390
f9fca8cb 2391 $tmp_feed = $tmp_line["id"];
23aa0d16 2392
8d505d78
AD
2393 db_query($link, "UPDATE ttrss_user_entries
2394 SET unread = false,last_read = NOW()
c7e51de1 2395 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
f9fca8cb
AD
2396 }
2397 } else if ($feed == -2) {
23aa0d16 2398
8d505d78
AD
2399 db_query($link, "UPDATE ttrss_user_entries
2400 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2401 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
c7e51de1 2402 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
2403 }
2404
2405 } else if ($feed > 0) {
2406
8d505d78
AD
2407 db_query($link, "UPDATE ttrss_user_entries
2408 SET unread = false,last_read = NOW()
c7e51de1 2409 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2410
23aa0d16
AD
2411 } else if ($feed < 0 && $feed > -10) { // special, like starred
2412
2413 if ($feed == -1) {
8d505d78 2414 db_query($link, "UPDATE ttrss_user_entries
23aa0d16 2415 SET unread = false,last_read = NOW()
c7e51de1 2416 WHERE marked = true AND owner_uid = $owner_uid");
23aa0d16 2417 }
e4f4b46f
AD
2418
2419 if ($feed == -2) {
8d505d78 2420 db_query($link, "UPDATE ttrss_user_entries
e4f4b46f 2421 SET unread = false,last_read = NOW()
c7e51de1 2422 WHERE published = true AND owner_uid = $owner_uid");
e4f4b46f
AD
2423 }
2424
2d24f032
AD
2425 if ($feed == -3) {
2426
c1d7e6c3
AD
2427 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2428
2d24f032 2429 if (DB_TYPE == "pgsql") {
8d505d78 2430 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2431 } else {
8d505d78 2432 $match_part = "updated > DATE_SUB(NOW(),
c1d7e6c3 2433 INTERVAL $intl HOUR) ";
2d24f032
AD
2434 }
2435
8d505d78 2436 $result = db_query($link, "SELECT id FROM ttrss_entries,
1f3335dc
AD
2437 ttrss_user_entries WHERE $match_part AND
2438 unread = true AND
8d505d78 2439 ttrss_user_entries.ref_id = ttrss_entries.id AND
c7e51de1 2440 owner_uid = $owner_uid");
1f3335dc
AD
2441
2442 $affected_ids = array();
2443
2444 while ($line = db_fetch_assoc($result)) {
2445 array_push($affected_ids, $line["id"]);
2446 }
2447
2448 catchupArticlesById($link, $affected_ids, 0);
2d24f032
AD
2449 }
2450
3584cb11 2451 if ($feed == -4) {
8d505d78 2452 db_query($link, "UPDATE ttrss_user_entries
3584cb11 2453 SET unread = false,last_read = NOW()
c7e51de1 2454 WHERE owner_uid = $owner_uid");
3584cb11
AD
2455 }
2456
23aa0d16
AD
2457 } else if ($feed < -10) { // label
2458
23aa0d16
AD
2459 $label_id = -$feed - 11;
2460
8d505d78
AD
2461 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2462 SET unread = false, last_read = NOW()
338c238d 2463 WHERE label_id = '$label_id' AND unread = true
c7e51de1 2464 AND owner_uid = '$owner_uid' AND ref_id = article_id");
23aa0d16 2465
23aa0d16 2466 }
ad0056a8 2467
c7e51de1 2468 ccache_update($link, $feed, $owner_uid, $cat_view);
ad0056a8 2469
23aa0d16
AD
2470 } else { // tag
2471 db_query($link, "BEGIN");
2472
2473 $tag_name = db_escape_string($feed);
2474
2475 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
c7e51de1 2476 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
23aa0d16
AD
2477
2478 while ($line = db_fetch_assoc($result)) {
2479 db_query($link, "UPDATE ttrss_user_entries SET
8d505d78 2480 unread = false, last_read = NOW()
23aa0d16
AD
2481 WHERE int_id = " . $line["post_int_id"]);
2482 }
2483 db_query($link, "COMMIT");
2484 }
2485 }
2486
4ffa126e 2487 function getAllCounters($link, $omode = "flc", $active_feed = false) {
cf4d339c 2488
e33fe293 2489 if (!$omode) $omode = "flc";
0a6e5382 2490
6a7817c1 2491 $data = getGlobalCounters($link);
8d505d78 2492
6a7817c1
AD
2493 $data = array_merge($data, getVirtCounters($link));
2494
2495 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2496 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2497 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
798f5a64 2498 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
6a7817c1
AD
2499
2500 return $data;
8d505d78 2501 }
a9cb1f83
AD
2502
2503 function getCategoryCounters($link) {
6a7817c1 2504 $ret_arr = array();
bba7c4bf 2505
6a7817c1 2506 /* Labels category */
bba7c4bf 2507
8acc449c 2508 $cv = array("id" => -2, "kind" => "cat",
6a7817c1 2509 "counter" => getCategoryUnread($link, -2));
bba7c4bf 2510
6a7817c1 2511 array_push($ret_arr, $cv);
bba7c4bf 2512
14073c0a
AD
2513 $age_qpart = getMaxAgeSubquery();
2514
8d505d78
AD
2515 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2516 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2517 WHERE ttrss_cat_counters_cache.feed_id = id AND
31375163 2518 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
2519
2520 while ($line = db_fetch_assoc($result)) {
22fdebff 2521 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 2522
8acc449c 2523 $cv = array("id" => $line["cat_id"], "kind" => "cat",
6a7817c1
AD
2524 "counter" => $line["unread"]);
2525
2526 array_push($ret_arr, $cv);
a9cb1f83 2527 }
d232a40f
AD
2528
2529 /* Special case: NULL category doesn't actually exist in the DB */
2530
9798b2b4 2531 $cv = array("id" => 0, "kind" => "cat",
6a7817c1 2532 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
d232a40f 2533
6a7817c1
AD
2534 array_push($ret_arr, $cv);
2535
2536 return $ret_arr;
a9cb1f83
AD
2537 }
2538
b6d486a3
AD
2539 function getCategoryUnread($link, $cat, $owner_uid = false) {
2540
2541 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 2542
bba7c4bf 2543 if ($cat >= 0) {
18664970 2544
bba7c4bf
AD
2545 if ($cat != 0) {
2546 $cat_query = "cat_id = '$cat'";
2547 } else {
2548 $cat_query = "cat_id IS NULL";
2549 }
14073c0a
AD
2550
2551 $age_qpart = getMaxAgeSubquery();
2552
8d505d78 2553 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 2554 AND owner_uid = " . $owner_uid);
8d505d78 2555
bba7c4bf
AD
2556 $cat_feeds = array();
2557 while ($line = db_fetch_assoc($result)) {
2558 array_push($cat_feeds, "feed_id = " . $line["id"]);
2559 }
8d505d78 2560
bba7c4bf 2561 if (count($cat_feeds) == 0) return 0;
8d505d78 2562
bba7c4bf 2563 $match_part = implode(" OR ", $cat_feeds);
8d505d78
AD
2564
2565 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2566 FROM ttrss_user_entries,ttrss_entries
2567 WHERE unread = true AND ($match_part) AND id = ref_id
b6d486a3 2568 AND $age_qpart AND owner_uid = " . $owner_uid);
8d505d78 2569
bba7c4bf 2570 $unread = 0;
8d505d78 2571
bba7c4bf
AD
2572 # this needs to be rewritten
2573 while ($line = db_fetch_assoc($result)) {
2574 $unread += $line["unread"];
2575 }
8d505d78 2576
bba7c4bf
AD
2577 return $unread;
2578 } else if ($cat == -1) {
59e15af4 2579 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
bba7c4bf 2580 } else if ($cat == -2) {
f295c368 2581
b2531a28 2582 $result = db_query($link, "
8d505d78
AD
2583 SELECT COUNT(unread) AS unread FROM
2584 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2585 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
b2531a28 2586 ttrss_labels2.owner_uid = '$owner_uid'
117335bf 2587 AND unread = true AND feed_id = ttrss_feeds.id
b2531a28 2588 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 2589
b2531a28 2590 $unread = db_fetch_result($result, 0, "unread");
f295c368 2591
b2531a28 2592 return $unread;
f295c368 2593
8d505d78 2594 }
f295c368
AD
2595 }
2596
14073c0a
AD
2597 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2598 if (DB_TYPE == "pgsql") {
8d505d78 2599 return "ttrss_entries.date_updated >
14073c0a
AD
2600 NOW() - INTERVAL '$days days'";
2601 } else {
8d505d78 2602 return "ttrss_entries.date_updated >
14073c0a
AD
2603 DATE_SUB(NOW(), INTERVAL $days DAY)";
2604 }
2605 }
2606
f295c368 2607 function getFeedUnread($link, $feed, $is_cat = false) {
2627f2d0 2608 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
2609 }
2610
ceb30ba4
AD
2611 function getLabelUnread($link, $label_id, $owner_uid = false) {
2612 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2613
2614 $result = db_query($link, "
8d505d78
AD
2615 SELECT COUNT(unread) AS unread FROM
2616 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2617 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
b0f24af1 2618 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
117335bf 2619 AND unread = true AND feed_id = ttrss_feeds.id
933ba4ee 2620 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4
AD
2621
2622 if (db_num_rows($result) != 0) {
2623 return db_fetch_result($result, 0, "unread");
2624 } else {
2625 return 0;
2626 }
2627 }
2628
2627f2d0
AD
2629 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2630 $owner_uid = false) {
2631
22fdebff 2632 $n_feed = (int) $feed;
f295c368 2633
2627f2d0
AD
2634 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2635
bdb7369b
AD
2636 if ($unread_only) {
2637 $unread_qpart = "unread = true";
2638 } else {
2639 $unread_qpart = "true";
2640 }
2641
14073c0a
AD
2642 $age_qpart = getMaxAgeSubquery();
2643
f295c368 2644 if ($is_cat) {
8d505d78 2645 return getCategoryUnread($link, $n_feed, $owner_uid);
326469fc
AD
2646 } if ($feed != "0" && $n_feed == 0) {
2647
c5701e70
AD
2648 $feed = db_escape_string($feed);
2649
326469fc 2650 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
8d505d78 2651 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
326469fc 2652 AND ref_id = id AND $age_qpart
8d505d78 2653 AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
2654 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2655 return db_fetch_result($result, 0, "count");
2656
f295c368 2657 } else if ($n_feed == -1) {
a9cb1f83 2658 $match_part = "marked = true";
e4f4b46f
AD
2659 } else if ($n_feed == -2) {
2660 $match_part = "published = true";
2d24f032 2661 } else if ($n_feed == -3) {
cd2cc43d 2662 $match_part = "unread = true AND score >= 0";
2d24f032 2663
b71e188e 2664 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2665
2d24f032 2666 if (DB_TYPE == "pgsql") {
8d505d78 2667 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2668 } else {
7608b38a 2669 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 2670 }
b2531a28
AD
2671 } else if ($n_feed == -4) {
2672 $match_part = "true";
e04c18a2 2673 } else if ($n_feed >= 0) {
831ff047 2674
6e63a7c3
AD
2675 if ($n_feed != 0) {
2676 $match_part = "feed_id = '$n_feed'";
831ff047 2677 } else {
6e63a7c3 2678 $match_part = "feed_id IS NULL";
831ff047 2679 }
6e63a7c3 2680
a9cb1f83 2681 } else if ($feed < -10) {
318260cc 2682
a9cb1f83
AD
2683 $label_id = -$feed - 11;
2684
ceb30ba4 2685 return getLabelUnread($link, $label_id, $owner_uid);
a9cb1f83 2686
a9cb1f83
AD
2687 }
2688
2689 if ($match_part) {
e04c18a2
AD
2690
2691 if ($n_feed != 0) {
2692 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
117335bf 2693 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2694 } else {
2695 $from_qpart = "ttrss_user_entries,ttrss_entries";
c3fddd05 2696 $feeds_qpart = '';
e04c18a2
AD
2697 }
2698
8d505d78 2699 $query = "SELECT count(int_id) AS unread
e04c18a2 2700 FROM $from_qpart WHERE
8d505d78 2701 ttrss_user_entries.ref_id = ttrss_entries.id AND
14073c0a 2702 $age_qpart AND
dbfc4365
AD
2703 $feeds_qpart
2704 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2705
2706 $result = db_query($link, $query);
8d505d78 2707
a9cb1f83 2708 } else {
8d505d78 2709
a9cb1f83 2710 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
8d505d78
AD
2711 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2712 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
bdb7369b 2713 AND $unread_qpart AND $age_qpart AND
2627f2d0 2714 ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 2715 }
8d505d78 2716
a9cb1f83 2717 $unread = db_fetch_result($result, 0, "unread");
cfb02131 2718
a9cb1f83
AD
2719 return $unread;
2720 }
2721
f3acc32e
AD
2722 function getGlobalUnread($link, $user_id = false) {
2723
2724 if (!$user_id) {
2725 $user_id = $_SESSION["uid"];
2726 }
2727
8a4c759e
AD
2728 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2729 WHERE owner_uid = '$user_id' AND feed_id > 0");
2730
8d505d78 2731 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 2732
a9cb1f83
AD
2733 return $c_id;
2734 }
2735
2736 function getGlobalCounters($link, $global_unread = -1) {
6a7817c1
AD
2737 $ret_arr = array();
2738
8d505d78 2739 if ($global_unread == -1) {
a9cb1f83
AD
2740 $global_unread = getGlobalUnread($link);
2741 }
6a7817c1 2742
8d505d78 2743 $cv = array("id" => "global-unread",
6a7817c1
AD
2744 "counter" => $global_unread);
2745
2746 array_push($ret_arr, $cv);
7bf7e4d3 2747
8d505d78 2748 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
2749 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2750
2751 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2752
8d505d78 2753 $cv = array("id" => "subscribed-feeds",
6a7817c1 2754 "counter" => $subscribed_feeds);
7bf7e4d3 2755
6a7817c1
AD
2756 array_push($ret_arr, $cv);
2757
2758 return $ret_arr;
a9cb1f83
AD
2759 }
2760
3809b278 2761 function getTagCounters($link) {
8d505d78 2762
6a7817c1 2763 $ret_arr = array();
a9cb1f83 2764
14073c0a
AD
2765 $age_qpart = getMaxAgeSubquery();
2766
8d505d78
AD
2767 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2768 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
14073c0a 2769 AND ref_id = id AND $age_qpart
8d505d78
AD
2770 AND unread = true)) AS count FROM ttrss_tags
2771 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
ef1ac7c7 2772 ORDER BY count DESC LIMIT 55");
8d505d78 2773
a9cb1f83
AD
2774 $tags = array();
2775
2776 while ($line = db_fetch_assoc($result)) {
2777 $tags[$line["tag_name"]] += $line["count"];
2778 }
2779
2780 foreach (array_keys($tags) as $tag) {
8d505d78 2781 $unread = $tags[$tag];
a9cb1f83 2782 $tag = htmlspecialchars($tag);
6a7817c1
AD
2783
2784 $cv = array("id" => $tag,
8acc449c 2785 "kind" => "tag",
6a7817c1
AD
2786 "counter" => $unread);
2787
2788 array_push($ret_arr, $cv);
2789 }
2790
8d505d78 2791 return $ret_arr;
a9cb1f83
AD
2792 }
2793
6a7817c1 2794 function getVirtCounters($link) {
a9cb1f83 2795
ef393de7 2796 $ret_arr = array();
bdb7369b 2797
e04c18a2 2798 for ($i = 0; $i >= -4; $i--) {
bdb7369b 2799
ceb30ba4 2800 $count = getFeedUnread($link, $i);
6a7817c1
AD
2801
2802 $cv = array("id" => $i,
2abc7af0 2803 "counter" => $count);
8d505d78 2804
296c8134
AD
2805// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2806// $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
bdb7369b 2807
6a7817c1 2808 array_push($ret_arr, $cv);
8d505d78 2809 }
0a6e5382
AD
2810
2811 return $ret_arr;
2812 }
2813
11232703 2814 function getLabelCounters($link, $descriptions = false) {
6a7817c1
AD
2815
2816 $ret_arr = array();
0a6e5382
AD
2817
2818 $age_qpart = getMaxAgeSubquery();
2819
3809b278 2820 $owner_uid = $_SESSION["uid"];
bdb7369b 2821
3809b278
AD
2822 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2823 WHERE owner_uid = '$owner_uid'");
8d505d78 2824
3809b278 2825 while ($line = db_fetch_assoc($result)) {
2d24f032 2826
3809b278 2827 $id = -$line["id"] - 11;
e4f4b46f 2828
3809b278
AD
2829 $label_name = $line["caption"];
2830 $count = getFeedUnread($link, $id);
3809b278 2831
6a7817c1 2832 $cv = array("id" => $id,
11232703
AD
2833 "counter" => $count);
2834
2835 if ($descriptions)
2836 $cv["description"] = $label_name;
a9cb1f83 2837
296c8134
AD
2838// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2839// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
ef393de7 2840
6a7817c1 2841 array_push($ret_arr, $cv);
3809b278 2842 }
8d505d78 2843
ef393de7 2844 return $ret_arr;
a9cb1f83
AD
2845 }
2846
3809b278 2847 function getFeedCounters($link, $active_feed = false) {
a9cb1f83 2848
6a7817c1
AD
2849 $ret_arr = array();
2850
14073c0a
AD
2851 $age_qpart = getMaxAgeSubquery();
2852
8a4c759e
AD
2853 $query = "SELECT ttrss_feeds.id,
2854 ttrss_feeds.title,
8d505d78 2855 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
2856 last_error, value AS count
2857 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 2858 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
55e01d7e 2859 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 2860
14073c0a 2861 $result = db_query($link, $query);
a9cb1f83
AD
2862 $fctrs_modified = false;
2863
2864 while ($line = db_fetch_assoc($result)) {
8d505d78 2865
a9cb1f83 2866 $id = $line["id"];
de0a2122 2867 $count = $line["count"];
a9cb1f83 2868 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 2869
324944f3 2870 $last_updated = make_local_datetime($link, $line['last_updated'], false);
fb1fb4ab 2871
7defa089 2872 $has_img = feed_has_icon($id);
a9cb1f83 2873
428b704d
AD
2874 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2875 $last_updated = '';
2876
6a7817c1 2877 $cv = array("id" => $id,
21884958 2878 "updated" => $last_updated,
6a7817c1
AD
2879 "counter" => $count,
2880 "has_img" => (int) $has_img);
a9cb1f83 2881
6a7817c1
AD
2882 if ($last_error)
2883 $cv["error"] = $last_error;
4ffa126e 2884
296c8134
AD
2885// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2886// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
bdb7369b 2887
6a7817c1 2888 if ($active_feed && $id == $active_feed)
fbc95c5b 2889 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
2890
2891 array_push($ret_arr, $cv);
a9cb1f83 2892
a9cb1f83 2893 }
6a7817c1
AD
2894
2895 return $ret_arr;
a9cb1f83
AD
2896 }
2897
6e7f8d26
AD
2898 function get_pgsql_version($link) {
2899 $result = db_query($link, "SELECT version() AS version");
9949bd15 2900 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
2901 return $version[1];
2902 }
2903
2b8290cd
CW
2904 /**
2905 * Subscribes the user to the given feed
2906 *
2907 * @param resource $link Database connection
2908 * @param string $url Feed URL to subscribe to
2909 * @param integer $cat_id Category ID the feed shall be added to
2910 * @param string $auth_login (optional) Feed username
2911 * @param string $auth_pass (optional) Feed password
2912 *
2913 * @return integer Status code:
2914 * 0 - OK, Feed already exists
2915 * 1 - OK, Feed added
2916 * 2 - Invalid URL
9a8ce956
CW
2917 * 3 - URL content is HTML, no feeds available
2918 * 4 - URL content is HTML which contains multiple feeds.
2919 * Here you should call extractfeedurls in rpc-backend
2920 * to get all possible feeds.
5414ad4c 2921 * 5 - Couldn't download the URL content.
2b8290cd 2922 */
8d505d78 2923 function subscribe_to_feed($link, $url, $cat_id = 0,
f27de515 2924 $auth_login = '', $auth_pass = '') {
bb0f29a4 2925
f0266f51 2926 $url = fix_url($url);
ec39a02c
AD
2927
2928 if (!$url || !validate_feed_url($url)) return 2;
a5819bb3 2929
b3009bcd
AD
2930 $update_method = 0;
2931
8d505d78 2932 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
aeaa6991
AD
2933 WHERE id = ".$_SESSION['uid']);
2934
2935 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2936
54a3dd8d 2937 if (!$has_oauth || strpos($url, '://api.twitter.com') === false) {
8d505d78 2938 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
57e24c82 2939
8d505d78
AD
2940 if (url_is_html($url, $auth_login, $auth_pass)) {
2941 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
57e24c82
AD
2942 if (count($feedUrls) == 0) {
2943 return 3;
2944 } else if (count($feedUrls) > 1) {
2945 return 4;
2946 }
2947 //use feed url as new URL
2948 $url = key($feedUrls);
f6d8345b 2949 }
f6d8345b 2950
57e24c82 2951 } else {
8d505d78 2952 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
57e24c82 2953 return 5;
b3009bcd
AD
2954
2955 $update_method = 3;
57e24c82 2956 }
956c7629
AD
2957 if ($cat_id == "0" || !$cat_id) {
2958 $cat_qpart = "NULL";
2959 } else {
2960 $cat_qpart = "'$cat_id'";
2961 }
8d505d78 2962
956c7629 2963 $result = db_query($link,
8d505d78 2964 "SELECT id FROM ttrss_feeds
a5819bb3 2965 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 2966
956c7629 2967 if (db_num_rows($result) == 0) {
956c7629 2968 $result = db_query($link,
8d505d78
AD
2969 "INSERT INTO ttrss_feeds
2970 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2971 VALUES ('".$_SESSION["uid"]."', '$url',
b3009bcd 2972 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
8d505d78 2973
956c7629 2974 $result = db_query($link,
8d505d78 2975 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 2976 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 2977
956c7629 2978 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 2979
956c7629 2980 if ($feed_id) {
c633e370 2981 update_rss_feed($link, $feed_id, true);
956c7629
AD
2982 }
2983
a5819bb3 2984 return 1;
956c7629 2985 } else {
a5819bb3 2986 return 0;
956c7629
AD
2987 }
2988 }
2989
8d505d78 2990 function print_feed_select($link, $id, $default_id = "",
673d54ca
AD
2991 $attributes = "", $include_all_feeds = true) {
2992
79f3553b 2993 print "<select id=\"$id\" name=\"$id\" $attributes>";
8d505d78 2994 if ($include_all_feeds) {
89cb787e 2995 print "<option value=\"0\">".__('All feeds')."</option>";
673d54ca 2996 }
8d505d78 2997
673d54ca
AD
2998 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2999 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3000
3001 if (db_num_rows($result) > 0 && $include_all_feeds) {
3002 print "<option disabled>--------</option>";
3003 }
3004
3005 while ($line = db_fetch_assoc($result)) {
3006 if ($line["id"] == $default_id) {
10249c41 3007 $is_selected = "selected=\"1\"";
673d54ca
AD
3008 } else {
3009 $is_selected = "";
3010 }
b1710666
AD
3011
3012 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3013
8d505d78 3014 printf("<option $is_selected value='%d'>%s</option>",
b1710666 3015 $line["id"], $title);
673d54ca 3016 }
8d505d78 3017
673d54ca
AD
3018 print "</select>";
3019 }
3020
8d505d78 3021 function print_feed_cat_select($link, $id, $default_id = "",
673d54ca 3022 $attributes = "", $include_all_cats = true) {
8d505d78 3023
5c7c7da9 3024 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
673d54ca
AD
3025
3026 if ($include_all_cats) {
d1db26aa 3027 print "<option value=\"0\">".__('Uncategorized')."</option>";
673d54ca
AD
3028 }
3029
3030 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3031 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3032
3033 if (db_num_rows($result) > 0 && $include_all_cats) {
c00907f2 3034 print "<option disabled=\"1\">--------</option>";
673d54ca
AD
3035 }
3036
3037 while ($line = db_fetch_assoc($result)) {
3038 if ($line["id"] == $default_id) {
10249c41 3039 $is_selected = "selected=\"1\"";
673d54ca 3040 } else {
8d505d78 3041 $is_selected = "";
673d54ca 3042 }
c00907f2
AD
3043
3044 if ($line["title"])
8d505d78 3045 printf("<option $is_selected value='%d'>%s</option>",
c00907f2 3046 $line["id"], htmlspecialchars($line["title"]));
673d54ca
AD
3047 }
3048
f9c388f5 3049# print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
5c7c7da9 3050
673d54ca
AD
3051 print "</select>";
3052 }
8d505d78 3053
14f69488
AD
3054 function checkbox_to_sql_bool($val) {
3055 return ($val == "on") ? "true" : "false";
3056 }
86b682ce
AD
3057
3058 function getFeedCatTitle($link, $id) {
3059 if ($id == -1) {
d1db26aa 3060 return __("Special");
86b682ce 3061 } else if ($id < -10) {
d1db26aa 3062 return __("Labels");
86b682ce 3063 } else if ($id > 0) {
8d505d78 3064 $result = db_query($link, "SELECT ttrss_feed_categories.title
86b682ce
AD
3065 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3066 cat_id = ttrss_feed_categories.id");
3067 if (db_num_rows($result) == 1) {
3068 return db_fetch_result($result, 0, "title");
3069 } else {
d1db26aa 3070 return __("Uncategorized");
86b682ce
AD
3071 }
3072 } else {
3073 return "getFeedCatTitle($id) failed";
3074 }
3075
3076 }
3077
af88c48a
AD
3078 function getFeedIcon($id) {
3079 switch ($id) {
4bee8b5f
AD
3080 case 0:
3081 return "images/archive.png";
3082 break;
af88c48a 3083 case -1:
f65ffc2d 3084 return "images/mark_set.png";
af88c48a
AD
3085 break;
3086 case -2:
b97e6e02 3087 return "images/pub_set.png";
af88c48a
AD
3088 break;
3089 case -3:
3090 return "images/fresh.png";
3091 break;
3092 case -4:
3093 return "images/tag.png";
3094 break;
3095 default:
4bee8b5f
AD
3096 if ($id < -10) {
3097 return "images/label.png";
3098 } else {
8d505d78 3099 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 3100 return ICONS_URL . "/$id.ico";
4bee8b5f 3101 }
af88c48a
AD
3102 break;
3103 }
3104 }
3105
86b682ce
AD
3106 function getFeedTitle($link, $id) {
3107 if ($id == -1) {
d1db26aa 3108 return __("Starred articles");
945c243e
AD
3109 } else if ($id == -2) {
3110 return __("Published articles");
2d24f032
AD
3111 } else if ($id == -3) {
3112 return __("Fresh articles");
b2531a28
AD
3113 } else if ($id == -4) {
3114 return __("All articles");
80db1113 3115 } else if ($id === 0 || $id === "0") {
e04c18a2 3116 return __("Archived articles");
86b682ce 3117 } else if ($id < -10) {
76626c72 3118 $label_id = -$id - 11;
ceb30ba4 3119 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 3120 if (db_num_rows($result) == 1) {
ceb30ba4 3121 return db_fetch_result($result, 0, "caption");
86b682ce
AD
3122 } else {
3123 return "Unknown label ($label_id)";
3124 }
3125
147f5632 3126 } else if (is_numeric($id) && $id > 0) {
86b682ce
AD
3127 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3128 if (db_num_rows($result) == 1) {
3129 return db_fetch_result($result, 0, "title");
3130 } else {
3131 return "Unknown feed ($id)";
3132 }
3133 } else {
22fdebff 3134 return $id;
86b682ce 3135 }
86b682ce 3136 }
3dd46f19 3137
d8221301 3138 function make_init_params($link) {
f1f3a642 3139 $params = array();
c9268ed5 3140
c4f7ba80
AD
3141 $params["theme"] = get_user_theme($link);
3142 $params["theme_options"] = get_user_theme_options($link);
f6d6e22f 3143
c4f7ba80
AD
3144 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3145 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3146 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3147 $params["sign_info"] = theme_image($link, "images/sign_info.png");
be0801a1 3148
f1f3a642
AD
3149 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3150 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
7d12b6c8 3151 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
30b6ee8c 3152 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 3153
c4f7ba80 3154 $params[strtolower($param)] = (int) get_pref($link, $param);
f1f3a642 3155 }
40496720 3156
c4f7ba80
AD
3157 $params["icons_url"] = ICONS_URL;
3158 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
3159 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3160 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3161 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
c4f7ba80 3162 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
59b223d7 3163
8cd576a1 3164 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
3165 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3166
8cd576a1
AD
3167 $max_feed_id = db_fetch_result($result, 0, "mid");
3168 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 3169
8cd576a1 3170 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 3171 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 3172
c4f7ba80 3173 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
9b7ecc0a 3174
d8221301 3175 return $params;
3ac2b520 3176 }
f54f515f 3177
c4f7ba80 3178 function make_runtime_info($link) {
8cd576a1
AD
3179 $data = array();
3180
3181 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
3182 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3183
8cd576a1
AD
3184 $max_feed_id = db_fetch_result($result, 0, "mid");
3185 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 3186
8cd576a1
AD
3187 $data["max_feed_id"] = (int) $max_feed_id;
3188 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 3189
f8fb4498 3190 $data['last_article_id'] = getLastArticleId($link);
5ae8f858 3191 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
f8fb4498 3192
dbaa4e4a 3193 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
3194
3195 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 3196
9041f58b 3197 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 3198
fb074239 3199 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 3200
8e00ae9b 3201 if ($stamp) {
9041f58b
AD
3202 $stamp_delta = time() - $stamp;
3203
3204 if ($stamp_delta > 1800) {
f6854e44 3205 $stamp_check = 0;
8e00ae9b 3206 } else {
f6854e44
AD
3207 $stamp_check = 1;
3208 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
3209 }
3210
c4f7ba80 3211 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 3212
8e00ae9b
AD
3213 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3214
c4f7ba80 3215 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 3216 }
8e00ae9b 3217 }
71ad883b 3218 }
8e00ae9b 3219
63855db1 3220 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
fb074239 3221 $new_version_details = @check_for_update($link);
d9fa39f1 3222
63855db1 3223 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
3224
3225 $_SESSION["last_version_check"] = time();
d9fa39f1
AD
3226 }
3227
c4f7ba80 3228 return $data;
f54f515f 3229 }
ef393de7 3230
b7d1a163 3231 function search_to_sql($link, $search, $match_on) {
ef393de7 3232
88040f57 3233 $search_query_part = "";
e20c9d88 3234
9949bd15 3235 $keywords = explode(" ", $search);
88040f57 3236 $query_keywords = array();
e20c9d88 3237
ab4b768f
AD
3238 foreach ($keywords as $k) {
3239 if (strpos($k, "-") === 0) {
3240 $k = substr($k, 1);
3241 $not = "NOT";
3242 } else {
3243 $not = "";
88040f57 3244 }
e20c9d88 3245
9949bd15 3246 $commandpair = explode(":", mb_strtolower($k), 2);
53003548
AD
3247
3248 if ($commandpair[0] == "note" && $commandpair[1]) {
3249
3250 if ($commandpair[1] == "true")
3251 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3252 else
3253 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3254
3255 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3256
3257 if ($commandpair[1] == "true")
3258 array_push($query_keywords, "($not (marked = true))");
3259 else
3260 array_push($query_keywords, "($not (marked = false))");
3261
3262 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3263
3264 if ($commandpair[1] == "true")
3265 array_push($query_keywords, "($not (published = true))");
3266 else
3267 array_push($query_keywords, "($not (published = false))");
3268
3269 } else if (strpos($k, "@") === 0) {
e20c9d88 3270
ab4b768f
AD
3271 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3272 $orig_ts = strtotime(substr($k, 1));
ab4b768f 3273 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 3274
53003548
AD
3275 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3276
ab4b768f
AD
3277 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
3278 } else if ($match_on == "both") {
3279 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3280 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3281 } else if ($match_on == "title") {
eb6c7f42 3282 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
ab4b768f 3283 } else if ($match_on == "content") {
eb6c7f42 3284 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
88040f57
AD
3285 }
3286 }
3287
3288 $search_query_part = implode("AND", $query_keywords);
3289
3290 return $search_query_part;
3291 }
3292
147f5632 3293
97e5dbb2 3294 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
c36bf4d5
AD
3295
3296 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 3297
c3fddd05
AD
3298 $ext_tables_part = "";
3299
88040f57 3300 if ($search) {
e4f7f8df
AD
3301
3302 if (SPHINX_ENABLED) {
3303 $ids = join(",", @sphinx_search($search, 0, 500));
3304
8d505d78 3305 if ($ids)
e4f7f8df
AD
3306 $search_query_part = "ref_id IN ($ids) AND ";
3307 else
3308 $search_query_part = "ref_id = -1 AND ";
3309
3310 } else {
b7d1a163 3311 $search_query_part = search_to_sql($link, $search, $match_on);
e4f7f8df 3312 $search_query_part .= " AND ";
8d505d78 3313 }
e20c9d88 3314
ef393de7
AD
3315 } else {
3316 $search_query_part = "";
3317 }
3318
36184020
AD
3319 if ($filter) {
3320 $filter_query_part = filter_to_sql($filter);
3321 } else {
3322 $filter_query_part = "";
3323 }
3324
97e5dbb2
AD
3325 if ($since_id) {
3326 $since_id_part = "ttrss_entries.id > $since_id AND ";
3327 } else {
3328 $since_id_part = "";
3329 }
3330
ef393de7 3331 $view_query_part = "";
8d505d78 3332
7b4d02a8 3333 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
ef393de7
AD
3334 if ($search) {
3335 $view_query_part = " ";
3336 } else if ($feed != -1) {
f295c368 3337 $unread = getFeedUnread($link, $feed, $cat_view);
ef393de7 3338 if ($unread > 0) {
ff863e00 3339 $view_query_part = " unread = true AND ";
ef393de7
AD
3340 }
3341 }
3342 }
8d505d78 3343
ef393de7
AD
3344 if ($view_mode == "marked") {
3345 $view_query_part = " marked = true AND ";
3346 }
23d72f39
AD
3347
3348 if ($view_mode == "published") {
3349 $view_query_part = " published = true AND ";
3350 }
3351
ef393de7
AD
3352 if ($view_mode == "unread") {
3353 $view_query_part = " unread = true AND ";
3354 }
8b09eac8
AD
3355
3356 if ($view_mode == "updated") {
3357 $view_query_part = " (last_read is null and unread = false) AND ";
3358 }
3359
ef393de7
AD
3360 if ($limit > 0) {
3361 $limit_query_part = "LIMIT " . $limit;
8d505d78 3362 }
ef393de7
AD
3363
3364 $vfeed_query_part = "";
8d505d78 3365
ef393de7
AD
3366 // override query strategy and enable feed display when searching globally
3367 if ($search && $search_mode == "all_feeds") {
3368 $query_strategy_part = "ttrss_entries.id > 0";
8d505d78 3369 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 3370 /* tags */
ef393de7
AD
3371 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3372 $query_strategy_part = "ttrss_entries.id > 0";
3373 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3374 id = feed_id) as feed_title,";
e04c18a2 3375 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
8d505d78
AD
3376
3377 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846
AD
3378
3379 $tmp_result = false;
3380
3381 if ($cat_view) {
8d505d78 3382 $tmp_result = db_query($link, "SELECT id
0a6c4846
AD
3383 FROM ttrss_feeds WHERE cat_id = '$feed'");
3384 } else {
3385 $tmp_result = db_query($link, "SELECT id
8d505d78 3386 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
0a6c4846
AD
3387 WHERE id = '$feed') AND id != '$feed'");
3388 }
8d505d78 3389
ef393de7 3390 $cat_siblings = array();
8d505d78 3391
ef393de7
AD
3392 if (db_num_rows($tmp_result) > 0) {
3393 while ($p = db_fetch_assoc($tmp_result)) {
3394 array_push($cat_siblings, "feed_id = " . $p["id"]);
3395 }
8d505d78
AD
3396
3397 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
ef393de7 3398 $feed, implode(" OR ", $cat_siblings));
8d505d78 3399
ef393de7
AD
3400 } else {
3401 $query_strategy_part = "ttrss_entries.id > 0";
3402 }
8d505d78 3403
e04c18a2 3404 } else if ($feed > 0) {
8d505d78 3405
ef393de7 3406 if ($cat_view) {
5c365f60 3407
ef393de7
AD
3408 if ($feed > 0) {
3409 $query_strategy_part = "cat_id = '$feed'";
3410 } else {
3411 $query_strategy_part = "cat_id IS NULL";
3412 }
8d505d78 3413
ef393de7 3414 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 3415
8d505d78 3416 } else {
6e63a7c3 3417 $query_strategy_part = "feed_id = '$feed'";
ef393de7 3418 }
bfe5ddfc 3419 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 3420 $query_strategy_part = "feed_id IS NULL";
bfe5ddfc
AD
3421 } else if ($feed == 0 && $cat_view) { // uncategorized
3422 $query_strategy_part = "cat_id IS NULL";
3423 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
3424 } else if ($feed == -1) { // starred virtual feed
3425 $query_strategy_part = "marked = true";
3426 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
e6a38cde
AD
3427 } else if ($feed == -2) { // published virtual feed OR labels category
3428
3429 if (!$cat_view) {
3430 $query_strategy_part = "published = true";
3431 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3432 } else {
3433 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3434
3435 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 3436
e6a38cde
AD
3437 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3438 ttrss_user_labels2.article_id = ref_id";
3439
3440 }
3441
2d24f032 3442 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 3443 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 3444
7a22dc2a 3445 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 3446
2d24f032 3447 if (DB_TYPE == "pgsql") {
8d505d78 3448 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 3449 } else {
7608b38a 3450 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
3451 }
3452
b2531a28
AD
3453 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3454 } else if ($feed == -4) { // all articles virtual feed
3455 $query_strategy_part = "true";
e4f4b46f 3456 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
3457 } else if ($feed <= -10) { // labels
3458 $label_id = -$feed - 11;
3de0261a 3459
ceb30ba4
AD
3460 $query_strategy_part = "label_id = '$label_id' AND
3461 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3462 ttrss_user_labels2.article_id = ref_id";
3de0261a 3463
ef393de7 3464 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 3465 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 3466
ef393de7
AD
3467 } else {
3468 $query_strategy_part = "id > 0"; // dumb
3469 }
d6e5706d 3470
b3990c92
AD
3471 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3472 $date_sort_field = "updated";
3473 } else {
3474 $date_sort_field = "date_entered";
3475 }
3476
7a22dc2a 3477 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
b3990c92 3478 $order_by = "$date_sort_field";
8d505d78 3479 } else {
b3990c92 3480 $order_by = "$date_sort_field DESC";
d6e5706d 3481 }
e939722a 3482
7b4d02a8
AD
3483 if ($view_mode != "noscores") {
3484 $order_by = "score DESC, $order_by";
3485 }
48b0c4ec 3486
e939722a
AD
3487 if ($override_order) {
3488 $order_by = $override_order;
3489 }
8d505d78 3490
ef393de7
AD
3491 $feed_title = "";
3492
22fdebff
AD
3493 if ($search) {
3494 $feed_title = "Search results";
3495 } else {
ef393de7 3496 if ($cat_view) {
22fdebff 3497 $feed_title = getCategoryTitle($link, $feed);
ef393de7 3498 } else {
147f5632 3499 if (is_numeric($feed) && $feed > 0) {
8d505d78 3500 $result = db_query($link, "SELECT title,site_url,last_error
22fdebff 3501 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 3502
22fdebff
AD
3503 $feed_title = db_fetch_result($result, 0, "title");
3504 $feed_site_url = db_fetch_result($result, 0, "site_url");
3505 $last_error = db_fetch_result($result, 0, "last_error");
3506 } else {
3507 $feed_title = getFeedTitle($link, $feed);
8d505d78 3508 }
88040f57 3509 }
ef393de7
AD
3510 }
3511
62129e67
AD
3512 $content_query_part = "content as content_preview,";
3513
ef393de7 3514 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
8d505d78 3515
ef393de7
AD
3516 if ($feed >= 0) {
3517 $feed_kind = "Feeds";
3518 } else {
3519 $feed_kind = "Labels";
3520 }
8d505d78 3521
95a82c08
AD
3522 if ($limit_query_part) {
3523 $offset_query_part = "OFFSET $offset";
3524 }
3525
d00f22ac 3526 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 3527 if (!$override_order) {
8d505d78 3528 $order_by = "ttrss_feeds.title, $order_by";
43fc671f 3529 }
6cfea5c7
AD
3530 }
3531
e04c18a2
AD
3532 if ($feed != "0") {
3533 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 3534 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
3535
3536 } else {
3537 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3538 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3539 }
3540
8d505d78 3541 $query = "SELECT DISTINCT
f9b2d27c 3542 date_entered,
1f64b1be 3543 guid,
ef393de7 3544 ttrss_entries.id,ttrss_entries.title,
46921916 3545 updated,
9c506873
AD
3546 label_cache,
3547 tag_cache,
c0644ee4 3548 always_display_enclosures,
d1fc2f92 3549 site_url,
c7e51de1 3550 note,
13992673
AD
3551 num_comments,
3552 comments,
db16ae50 3553 int_id,
494a64ea 3554 unread,feed_id,marked,published,link,last_read,orig_feed_id,
fc2b26a6 3555 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
ef393de7
AD
3556 $vfeed_query_part
3557 $content_query_part
fc2b26a6 3558 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
ff6e357a 3559 author,score
ef393de7 3560 FROM
e04c18a2 3561 $from_qpart
ef393de7 3562 WHERE
e04c18a2 3563 $feed_check_qpart
ef393de7 3564 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 3565 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 3566 $search_query_part
36184020 3567 $filter_query_part
ef393de7 3568 $view_query_part
97e5dbb2 3569 $since_id_part
ef393de7 3570 $query_strategy_part ORDER BY $order_by
95a82c08 3571 $limit_query_part $offset_query_part";
4bc311fc 3572
b4e75b2a 3573 if ($_REQUEST["debug"]) print $query;
4bc311fc
AD
3574
3575 $result = db_query($link, $query);
8d505d78 3576
ef393de7
AD
3577 } else {
3578 // browsing by tag
8d505d78 3579
147f5632
CM
3580 $select_qpart = "SELECT DISTINCT " .
3581 "date_entered," .
3582 "guid," .
3583 "note," .
3584 "ttrss_entries.id as id," .
3585 "title," .
3586 "updated," .
3587 "unread," .
3588 "feed_id," .
3589 "orig_feed_id," .
d1fc2f92
AD
3590 "site_url," .
3591 "always_display_enclosures, ".
147f5632 3592 "marked," .
d1fc2f92
AD
3593 "num_comments, " .
3594 "comments, " .
c0644ee4
AD
3595 "tag_cache," .
3596 "label_cache," .
147f5632
CM
3597 "link," .
3598 "last_read," .
3599 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
97e5dbb2 3600 $since_id_part .
147f5632
CM
3601 $vfeed_query_part .
3602 $content_query_part .
3603 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
3604 "score ";
3605
ef393de7 3606 $feed_kind = "Tags";
147f5632
CM
3607 $all_tags = explode(",", $feed);
3608 if ($search_mode == 'any') {
3609 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3610 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3611 $where_qpart = " WHERE " .
3612 "ref_id = ttrss_entries.id AND " .
3613 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3614 "post_int_id = int_id AND $tag_sql AND " .
3615 $view_query_part .
3616 $search_query_part .
3617 $query_strategy_part . " ORDER BY $order_by " .
3618 $limit_query_part;
8d505d78 3619
147f5632
CM
3620 } else {
3621 $i = 1;
3622 $sub_selects = array();
3623 $sub_ands = array();
3624 foreach ($all_tags as $term) {
3625 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
3626 $i++;
3627 }
3628 if ($i > 2) {
3629 $x = 1;
3630 $y = 2;
3631 do {
3632 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3633 $x++;
3634 $y++;
3635 } while ($y < $i);
3636 }
3637 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3638 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3639 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3640 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3641 }
3642 // error_log("TAG SQL: " . $tag_sql);
3643 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3644
3645 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3646 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
ef393de7
AD
3647 }
3648
c7188969 3649 return array($result, $feed_title, $feed_site_url, $last_error);
8d505d78 3650
ef393de7
AD
3651 }
3652
c36bf4d5 3653 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
23d72f39 3654 $limit, $search, $search_mode, $match_on, $view_mode = false) {
ead2715d 3655
20e43935
AD
3656 require_once "lib/MiniTemplator.class.php";
3657
fcfa9ef1
AD
3658 $note_style = "background-color : #fff7d5;
3659 border-width : 1px; ".
c7e51de1 3660 "padding : 5px; border-style : dashed; border-color : #e7d796;".
db54143e 3661 "margin-bottom : 1em; color : #9a8c59;";
c7e51de1 3662
ead2715d 3663 if (!$limit) $limit = 30;
18664970 3664
b3990c92
AD
3665 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3666 $date_sort_field = "updated";
3667 } else {
3668 $date_sort_field = "date_entered";
3669 }
3670
8d505d78
AD
3671 $qfh_ret = queryFeedHeadlines($link, $feed,
3672 $limit, $view_mode, $is_cat, $search, $search_mode,
b3990c92 3673 $match_on, "$date_sort_field DESC", 0, $owner_uid);
18664970
AD
3674
3675 $result = $qfh_ret[0];
59e2aab4 3676 $feed_title = htmlspecialchars($qfh_ret[1]);
18664970
AD
3677 $feed_site_url = $qfh_ret[2];
3678 $last_error = $qfh_ret[3];
3679
20e43935 3680 $feed_self_url = get_self_url_prefix() .
e0d91d84 3681 "/public.php?op=rss&id=-2&key=" .
20e43935
AD
3682 get_feed_access_key($link, -2, false);
3683
b0f379df 3684 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
4bc64807 3685
20e43935
AD
3686 $tpl = new MiniTemplator;
3687
3688 $tpl->readTemplateFromFile("templates/generated_feed.txt");
b0f379df 3689
20e43935
AD
3690 $tpl->setVariable('FEED_TITLE', $feed_title);
3691 $tpl->setVariable('VERSION', VERSION);
3692 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3693
364e3c85 3694 if (PUBSUBHUBBUB_HUB && $feed == -2) {
20e43935
AD
3695 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB));
3696 $tpl->addBlock('feed_hub');
b0f379df
AD
3697 }
3698
20e43935 3699 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
8d505d78 3700
3baeeeca 3701 while ($line = db_fetch_assoc($result)) {
20e43935
AD
3702 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3703 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3704 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3705 $tpl->setVariable('ARTICLE_EXCERPT',
3706 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
9b1a7081
AD
3707
3708 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3709
3710 if ($line['note']) {
fcfa9ef1 3711 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
9b1a7081
AD
3712 $content;
3713 }
3714
3715 $tpl->setVariable('ARTICLE_CONTENT', $content);
20e43935
AD
3716
3717 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3718 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
0c3d1c68 3719
bc976a8c 3720 $tags = get_article_tags($link, $line["id"], $owner_uid);
0c3d1c68
AD
3721
3722 foreach ($tags as $tag) {
20e43935
AD
3723 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3724 $tpl->addBlock('category');
2f0903a6 3725 }
8d505d78 3726
c7845467
AD
3727 $enclosures = get_article_enclosures($link, $line["id"]);
3728
3729 foreach ($enclosures as $e) {
3730 $type = htmlspecialchars($e['content_type']);
3731 $url = htmlspecialchars($e['content_url']);
3732 $length = $e['duration'];
20e43935
AD
3733
3734 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3735 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3736 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3737
3738 $tpl->addBlock('enclosure');
c7845467
AD
3739 }
3740
20e43935
AD
3741 $tpl->addBlock('entry');
3742 }
3743
3744 $tmp = "";
8d505d78 3745
20e43935
AD
3746 $tpl->addBlock('feed');
3747 $tpl->generateOutputToString($tmp);
18664970 3748
20e43935 3749 print $tmp;
18664970
AD
3750 }
3751
0a6c4846
AD
3752 function getCategoryTitle($link, $cat_id) {
3753
bba7c4bf
AD
3754 if ($cat_id == -1) {
3755 return __("Special");
3756 } else if ($cat_id == -2) {
3757 return __("Labels");
0a6c4846 3758 } else {
bba7c4bf
AD
3759
3760 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3761 id = '$cat_id'");
3762
3763 if (db_num_rows($result) == 1) {
3764 return db_fetch_result($result, 0, "title");
3765 } else {
3766 return "Uncategorized";
3767 }
0a6c4846
AD
3768 }
3769 }
3770
8cc3c778 3771 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
35ffb5b9 3772 global $purifier;
8cc3c778 3773
ceb0cab5
AD
3774 if (!$owner) $owner = $_SESSION["uid"];
3775
96811a55
AD
3776 $res = trim($str); if (!$res) return '';
3777
388c645a
AD
3778// if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3779 $res = $purifier->purify($res);
3780// }
f826eee1 3781
ceb0cab5 3782 if (get_pref($link, "STRIP_IMAGES", $owner)) {
8dccabed 3783 $res = preg_replace('/<img[^>]+>/is', '', $res);
7514749d 3784 }
8dccabed 3785
46137483
AD
3786 if (strpos($res, "href=") === false)
3787 $res = rewrite_urls($res);
533c0ea6 3788
8cc3c778
AD
3789 $charset_hack = '<head>
3790 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3791 </head>';
3792
96811a55
AD
3793 $res = trim($res); if (!$res) return '';
3794
8cc3c778
AD
3795 libxml_use_internal_errors(true);
3796
3797 $doc = new DOMDocument();
3798 $doc->loadHTML($charset_hack . $res);
3799 $xpath = new DOMXPath($doc);
8d505d78 3800
8cc3c778 3801 $entries = $xpath->query('(//a[@href]|//img[@src])');
3f770c87 3802 $br_inserted = 0;
8cc3c778
AD
3803
3804 foreach ($entries as $entry) {
3805
3806 if ($site_url) {
3807
3808 if ($entry->hasAttribute('href'))
3809 $entry->setAttribute('href',
3810 rewrite_relative_url($site_url, $entry->getAttribute('href')));
8d505d78 3811
8cc3c778 3812 if ($entry->hasAttribute('src'))
8d505d78 3813 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
b8998470
AD
3814 $entry->setAttribute('src',
3815 rewrite_relative_url($site_url, $entry->getAttribute('src')));
8cc3c778
AD
3816 }
3817
fa403733 3818 if (strtolower($entry->nodeName) == "a") {
c401d5c9 3819 $entry->setAttribute("target", "_blank");
fa403733
AD
3820 }
3821
3f770c87 3822 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
fa403733
AD
3823 $br = $doc->createElement("br");
3824
3f770c87 3825 if ($entry->parentNode->nextSibling) {
fa403733 3826 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3f770c87
AD
3827 $br_inserted = 1;
3828 }
fa403733 3829
8cc3c778 3830 }
8dccabed 3831 }
8d505d78 3832
1f6131f5 3833 $node = $doc->getElementsByTagName('body')->item(0);
8dccabed 3834
8d505d78 3835 return $doc->saveXML($node);
183ad07b 3836 }
b72c3ef8 3837
45004d43
AD
3838 /**
3839 * Send by mail a digest of last articles.
8d505d78 3840 *
45004d43
AD
3841 * @param mixed $link The database connection.
3842 * @param integer $limit The maximum number of articles by digest.
3843 * @return boolean Return false if digests are not enabled.
3844 */
9cd7c995
AD
3845 function send_headlines_digests($link, $limit = 100) {
3846
1ddba275
AD
3847 if (!DIGEST_ENABLE) return false;
3848
9cd7c995 3849 $user_limit = DIGEST_EMAIL_LIMIT;
5430c959 3850 $days = 1;
9cd7c995
AD
3851
3852 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3853
3854 if (DB_TYPE == "pgsql") {
3855 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3856 } else if (DB_TYPE == "mysql") {
3857 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3858 }
3859
8d505d78 3860 $result = db_query($link, "SELECT id,email FROM ttrss_users
9cd7c995
AD
3861 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3862
3863 while ($line = db_fetch_assoc($result)) {
dc85be2b 3864
9cd7c995
AD
3865 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3866 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3867
dc85be2b
AD
3868 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3869
9cd7c995
AD
3870 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3871 $digest = $tuple[0];
3872 $headlines_count = $tuple[1];
dc85be2b 3873 $affected_ids = $tuple[2];
c62a2c21 3874 $digest_text = $tuple[3];
9cd7c995
AD
3875
3876 if ($headlines_count > 0) {
a8931123 3877
c62a2c21 3878 $mail = new PHPMailer();
a8931123 3879
d134e3a3
AD
3880 $mail->PluginDir = "lib/phpmailer/";
3881 $mail->SetLanguage("en", "lib/phpmailer/language/");
a8931123 3882
c62a2c21 3883 $mail->CharSet = "UTF-8";
a8931123 3884
c62a2c21
AD
3885 $mail->From = DIGEST_FROM_ADDRESS;
3886 $mail->FromName = DIGEST_FROM_NAME;
3887 $mail->AddAddress($line["email"], $line["login"]);
c7ddac5c 3888
c62a2c21 3889 if (DIGEST_SMTP_HOST) {
a8931123
AD
3890 $mail->Host = DIGEST_SMTP_HOST;
3891 $mail->Mailer = "smtp";
19a1da0d 3892 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
a8931123
AD
3893 $mail->Username = DIGEST_SMTP_LOGIN;
3894 $mail->Password = DIGEST_SMTP_PASSWORD;
c62a2c21 3895 }
a8931123 3896
c62a2c21 3897 $mail->IsHTML(true);
163a295e 3898 $mail->Subject = DIGEST_SUBJECT;
c62a2c21
AD
3899 $mail->Body = $digest;
3900 $mail->AltBody = $digest_text;
a8931123 3901
c62a2c21 3902 $rc = $mail->Send();
a8931123 3903
c62a2c21 3904 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
a8931123 3905
9cd7c995 3906 print "RC=$rc\n";
a8931123 3907
c62a2c21 3908 if ($rc && $do_catchup) {
dc85be2b 3909 print "Marking affected articles as read...\n";
9968d46f 3910 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
dc85be2b 3911 }
9cd7c995
AD
3912 } else {
3913 print "No headlines\n";
3914 }
019dd98d 3915
8d505d78 3916 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
019dd98d 3917 WHERE id = " . $line["id"]);
9cd7c995
AD
3918 }
3919 }
3920
cedd3e89
AD
3921 print "All done.\n";
3922
9cd7c995
AD
3923 }
3924
7e3634d9 3925 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
c62a2c21 3926
fe7537b5 3927 require_once "lib/MiniTemplator.class.php";
c62a2c21
AD
3928
3929 $tpl = new MiniTemplator;
3930 $tpl_t = new MiniTemplator;
3931
3932 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3933 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3934
3935 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3936 $tpl->setVariable('CUR_TIME', date('G:i'));
3937
3938 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3939 $tpl_t->setVariable('CUR_TIME', date('G:i'));
7e3634d9 3940
dc85be2b
AD
3941 $affected_ids = array();
3942
7e3634d9 3943 if (DB_TYPE == "pgsql") {
25ea2805 3944 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
7e3634d9 3945 } else if (DB_TYPE == "mysql") {
25ea2805 3946 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
7e3634d9
AD
3947 }
3948
3949 $result = db_query($link, "SELECT ttrss_entries.title,
3950 ttrss_feeds.title AS feed_title,
25ea2805 3951 date_updated,
dc85be2b 3952 ttrss_user_entries.ref_id,
7e3634d9 3953 link,
c62a2c21 3954 SUBSTRING(content, 1, 120) AS excerpt,
fc2b26a6 3955 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
3956 FROM
3957 ttrss_user_entries,ttrss_entries,ttrss_feeds
3958 WHERE
3959 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3dd9183c 3960 AND include_in_digest = true
7e3634d9 3961 AND $interval_query
448b0abd 3962 AND ttrss_user_entries.owner_uid = $user_id
8d505d78 3963 AND unread = true
25ea2805 3964 ORDER BY ttrss_feeds.title, date_updated DESC
7e3634d9
AD
3965 LIMIT $limit");
3966
3967 $cur_feed_title = "";
3968
9cd7c995
AD
3969 $headlines_count = db_num_rows($result);
3970
c62a2c21
AD
3971 $headlines = array();
3972
7e3634d9 3973 while ($line = db_fetch_assoc($result)) {
c62a2c21
AD
3974 array_push($headlines, $line);
3975 }
3976
8d505d78 3977 for ($i = 0; $i < sizeof($headlines); $i++) {
c62a2c21
AD
3978
3979 $line = $headlines[$i];
dc85be2b
AD
3980
3981 array_push($affected_ids, $line["ref_id"]);
3982
324944f3
AD
3983 $updated = make_local_datetime($link, $line['last_updated'], false,
3984 $user_id);
7e3634d9 3985
c62a2c21
AD
3986 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3987 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3988 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3989 $tpl->setVariable('ARTICLE_UPDATED', $updated);
8d505d78 3990 $tpl->setVariable('ARTICLE_EXCERPT',
163a295e 3991 truncate_string(strip_tags($line["excerpt"]), 100));
7e3634d9 3992
c62a2c21
AD
3993 $tpl->addBlock('article');
3994
3995 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3996 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3997 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3998 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
8d505d78 3999// $tpl_t->setVariable('ARTICLE_EXCERPT',
c62a2c21
AD
4000// truncate_string(strip_tags($line["excerpt"]), 100));
4001
4002 $tpl_t->addBlock('article');
4003
4004 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
4005 $tpl->addBlock('feed');
4006 $tpl_t->addBlock('feed');
7e3634d9
AD
4007 }
4008
7e3634d9
AD
4009 }
4010
c62a2c21
AD
4011 $tpl->addBlock('digest');
4012 $tpl->generateOutputToString($tmp);
4013
4014 $tpl_t->addBlock('digest');
4015 $tpl_t->generateOutputToString($tmp_t);
7e3634d9 4016
c62a2c21 4017 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
7e3634d9
AD
4018 }
4019
73495fd1 4020 function check_for_update($link) {
63855db1
AD
4021 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
4022 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
b72c3ef8 4023
63855db1 4024 $version_data = @fetch_file_contents($version_url);
b72c3ef8 4025
63855db1
AD
4026 if ($version_data) {
4027 $version_data = json_decode($version_data, true);
8d505d78 4028 if ($version_data && $version_data['version']) {
f67d9754 4029
63855db1 4030 if (version_compare(VERSION, $version_data['version']) == -1) {
e91ad1e9 4031 return $version_data;
63855db1
AD
4032 }
4033 }
f67d9754 4034 }
b72c3ef8 4035 }
63855db1 4036 return false;
b72c3ef8 4037 }
472782e8 4038
18eddb2c
AD
4039 function markArticlesById($link, $ids, $cmode) {
4040
4041 $tmp_ids = array();
4042
4043 foreach ($ids as $id) {
4044 array_push($tmp_ids, "ref_id = '$id'");
4045 }
4046
4047 $ids_qpart = join(" OR ", $tmp_ids);
4048
4049 if ($cmode == 0) {
8d505d78 4050 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4051 marked = false,last_read = NOW()
4052 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4053 } else if ($cmode == 1) {
8d505d78 4054 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4055 marked = true
4056 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4057 } else {
8d505d78 4058 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4059 marked = NOT marked,last_read = NOW()
4060 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4061 }
4062 }
4063
e4f4b46f
AD
4064 function publishArticlesById($link, $ids, $cmode) {
4065
4066 $tmp_ids = array();
4067
4068 foreach ($ids as $id) {
4069 array_push($tmp_ids, "ref_id = '$id'");
4070 }
4071
4072 $ids_qpart = join(" OR ", $tmp_ids);
4073
4074 if ($cmode == 0) {
8d505d78 4075 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4076 published = false,last_read = NOW()
4077 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4078 } else if ($cmode == 1) {
8d505d78 4079 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4080 published = true
4081 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4082 } else {
8d505d78 4083 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4084 published = NOT published,last_read = NOW()
4085 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4086 }
2fcec4c4
AD
4087
4088 if (PUBSUBHUBBUB_HUB) {
4089 $rss_link = get_self_url_prefix() .
e0d91d84 4090 "/public.php?op=rss&id=-2&key=" .
2fcec4c4
AD
4091 get_feed_access_key($link, -2, false);
4092
4093 $p = new Publisher(PUBSUBHUBBUB_HUB);
4094
4095 $pubsub_result = $p->publish_update($rss_link);
4096 }
e4f4b46f
AD
4097 }
4098
9968d46f
AD
4099 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4100
4101 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 4102 if (count($ids) == 0) return;
472782e8
AD
4103
4104 $tmp_ids = array();
4105
4106 foreach ($ids as $id) {
4107 array_push($tmp_ids, "ref_id = '$id'");
4108 }
4109
4110 $ids_qpart = join(" OR ", $tmp_ids);
4111
4112 if ($cmode == 0) {
8d505d78 4113 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4114 unread = false,last_read = NOW()
9968d46f 4115 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4116 } else if ($cmode == 1) {
8d505d78 4117 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4118 unread = true
9968d46f 4119 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4120 } else {
8d505d78 4121 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4122 unread = NOT unread,last_read = NOW()
9968d46f 4123 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4124 }
0737b95a
AD
4125
4126 /* update ccache */
4127
4128 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4129 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4130
4131 while ($line = db_fetch_assoc($result)) {
4132 ccache_update($link, $line["feed_id"], $owner_uid);
4133 }
472782e8
AD
4134 }
4135
e097e8be
AD
4136 function catchupArticleById($link, $id, $cmode) {
4137
4138 if ($cmode == 0) {
8d505d78 4139 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4140 unread = false,last_read = NOW()
4141 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4142 } else if ($cmode == 1) {
8d505d78 4143 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4144 unread = true
4145 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4146 } else {
8d505d78 4147 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4148 unread = NOT unread,last_read = NOW()
4149 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4150 }
ab197ae1
AD
4151
4152 $feed_id = getArticleFeed($link, $id);
4153 ccache_update($link, $feed_id, $_SESSION["uid"]);
e097e8be
AD
4154 }
4155
1f64b1be 4156 function make_guid_from_title($title) {
8d505d78 4157 return preg_replace("/[ \"\',.:;]/", "-",
fefef828 4158 mb_strtolower(strip_tags($title), 'utf-8'));
1f64b1be
AD
4159 }
4160
bd202c3f 4161 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
0ef68e6f 4162 $feed_id, $is_cat, $search, $match_on,
26a1e185 4163 $search_mode, $view_mode, $error) {
e6c115b2 4164
bd202c3f
AD
4165 $page_prev_link = "viewFeedGoPage(-1)";
4166 $page_next_link = "viewFeedGoPage(1)";
4167 $page_first_link = "viewFeedGoPage(0)";
203de776 4168
bd202c3f
AD
4169 $catchup_page_link = "catchupPage()";
4170 $catchup_feed_link = "catchupCurrentFeed()";
4171 $catchup_sel_link = "catchupSelection()";
c6008b62 4172
bd202c3f
AD
4173 $archive_sel_link = "archiveSelection()";
4174 $delete_sel_link = "deleteSelection()";
e04c18a2 4175
bd202c3f
AD
4176 $sel_all_link = "selectArticles('all')";
4177 $sel_unread_link = "selectArticles('unread')";
4178 $sel_none_link = "selectArticles('none')";
4179 $sel_inv_link = "selectArticles('invert')";
11befbb2 4180
bd202c3f
AD
4181 $tog_unread_link = "selectionToggleUnread()";
4182 $tog_marked_link = "selectionToggleMarked()";
4183 $tog_published_link = "selectionTogglePublished()";
fcf70c51 4184
bd202c3f 4185 $reply = "<div id=\"subtoolbar_main\">";
fcf70c51 4186
bd202c3f
AD
4187 $reply .= __('Select:')."
4188 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4189 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4190 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4191 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
fcf70c51 4192
bd202c3f 4193 $reply .= " ";
fcf70c51 4194
bd202c3f
AD
4195 $reply .= "<select dojoType=\"dijit.form.Select\"
4196 onchange=\"headlineActionsChange(this)\">";
4197 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
fcf70c51 4198
bd202c3f 4199 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
fcf70c51 4200
bd202c3f
AD
4201 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4202 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4203 <option value=\"$tog_published_link\">".__('Published')."</option>";
fcf70c51 4204
bd202c3f 4205 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
fcf70c51 4206
bd202c3f 4207 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
fcf70c51 4208
bd202c3f
AD
4209 if ($feed_id != "0") {
4210 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4211 } else {
4212 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4213 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
fcf70c51 4214
bd202c3f 4215 }
fcf70c51 4216
bd202c3f
AD
4217 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4218 "</option>";
fcf70c51 4219
b0f379df
AD
4220 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4221
9d9faf6d
AD
4222 if ($search) {
4223 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4224 } else {
4225 $search_q = "";
4226 }
4227
bd202c3f 4228 $rss_link = htmlspecialchars(get_self_url_prefix() .
e0d91d84 4229 "/public.php?op=rss&id=$feed_id$cat_q$search_q");
0f9b4a60 4230
bd202c3f 4231 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
176b8ba6 4232
bd202c3f 4233 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
fcf70c51 4234
bd202c3f 4235 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
fcf70c51 4236
bd202c3f 4237 $reply .= "</select>";
c6008b62 4238
bd202c3f 4239 $reply .= "</div>";
0ef68e6f 4240
bd202c3f 4241 $reply .= "<div id=\"subtoolbar_ftitle\">";
26a1e185 4242
bd202c3f
AD
4243 if ($feed_site_url) {
4244 $target = "target=\"_blank\"";
4245 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4246 truncate_string($feed_title,30)."</a>";
26a1e185 4247
bd202c3f
AD
4248 if ($error) {
4249 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4250 }
5163fc70 4251
bd202c3f
AD
4252 } else {
4253 if ($feed_id < -10) {
4254 $label_id = -11-$feed_id;
5163fc70 4255
bd202c3f
AD
4256 $result = db_query($link, "SELECT fg_color, bg_color
4257 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4258 $_SESSION["uid"]);
5163fc70 4259
bd202c3f
AD
4260 if (db_num_rows($result) != 0) {
4261 $fg_color = db_fetch_result($result, 0, "fg_color");
4262 $bg_color = db_fetch_result($result, 0, "bg_color");
5163fc70 4263
9949bd15 4264 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
bd202c3f
AD
4265 $reply .= $feed_title;
4266 $reply .= "</span>";
5163fc70 4267 } else {
bd202c3f 4268 $reply .= $feed_title;
5163fc70 4269 }
0ef68e6f 4270
c3fddd05 4271 } else {
bd202c3f 4272 $reply .= $feed_title;
0ef68e6f 4273 }
bd202c3f 4274 }
0ef68e6f 4275
bd202c3f
AD
4276 $reply .= "
4277 <a href=\"#\"
4278 title=\"".__("View as RSS feed")."\"
4279 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4280 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
ceb30ba4 4281
bd202c3f
AD
4282 $reply .= "</div>";
4283
4284 return $reply;
4285 }
8d505d78 4286
1985a5e0 4287 function outputFeedList($link, $special = true) {
f407c086 4288
13e785e0
AD
4289 $feedlist = array();
4290
4291 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4292
4293 $feedlist['identifier'] = 'id';
4294 $feedlist['label'] = 'name';
4295 $feedlist['items'] = array();
f407c086
AD
4296
4297 $owner_uid = $_SESSION["uid"];
4298
cf4d339c 4299 /* virtual feeds */
f407c086 4300
1985a5e0 4301 if ($special) {
e4f4b46f 4302
1985a5e0
AD
4303 if ($enable_cats) {
4304 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4305 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4306 } else {
4307 $cat['items'] = array();
4308 }
8d505d78 4309
1985a5e0
AD
4310 foreach (array(-4, -3, -1, -2, 0) as $i) {
4311 array_push($cat['items'], feedlist_init_feed($link, $i));
4312 }
8d505d78 4313
1985a5e0
AD
4314 if ($enable_cats) {
4315 array_push($feedlist['items'], $cat);
4316 } else {
4317 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4318 }
8d505d78 4319
1985a5e0
AD
4320 $result = db_query($link, "SELECT * FROM
4321 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
9fe80bcd 4322
d4f46bc1 4323 if (db_num_rows($result) > 0) {
9fe80bcd 4324
d4f46bc1
AD
4325 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4326 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4327 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4328 } else {
4329 $cat['items'] = array();
4330 }
9fe80bcd 4331
d4f46bc1 4332 while ($line = db_fetch_assoc($result)) {
8d505d78 4333
d4f46bc1
AD
4334 $label_id = -$line['id'] - 11;
4335 $count = getFeedUnread($link, $label_id);
8d505d78 4336
d4f46bc1 4337 $feed = feedlist_init_feed($link, $label_id, false, $count);
8d505d78 4338
d4f46bc1
AD
4339 $feed['fg_color'] = $line['fg_color'];
4340 $feed['bg_color'] = $line['bg_color'];
8d505d78 4341
d4f46bc1
AD
4342 array_push($cat['items'], $feed);
4343 }
8d505d78 4344
d4f46bc1
AD
4345 if ($enable_cats) {
4346 array_push($feedlist['items'], $cat);
4347 } else {
4348 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4349 }
1985a5e0 4350 }
9c99281f 4351 }
8d505d78 4352
76657c46 4353/* if (get_pref($link, 'ENABLE_FEED_CATS')) {
9c99281f
AD
4354 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4355 $order_by_qpart = "order_id,category,unread DESC,title";
13e785e0 4356 } else {
9c99281f 4357 $order_by_qpart = "order_id,category,title";
f407c086 4358 }
9c99281f
AD
4359 } else {
4360 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4361 $order_by_qpart = "unread DESC,title";
8d505d78 4362 } else {
9c99281f 4363 $order_by_qpart = "title";
f407c086 4364 }
76657c46
AD
4365 } */
4366
4d65b7df
AD
4367 /* real feeds */
4368
76657c46 4369 if ($enable_cats)
7b8a143f
AD
4370 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4371 ttrss_feeds.order_id,title";
76657c46
AD
4372 else
4373 $order_by_qpart = "title";
f407c086 4374
9c99281f 4375 $age_qpart = getMaxAgeSubquery();
f407c086 4376
9c99281f
AD
4377 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4378 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4379 cat_id,last_error,
4380 ttrss_feed_categories.title AS category,
4381 ttrss_feed_categories.collapsed,
8d505d78 4382 value AS unread
9c99281f 4383 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
8d505d78
AD
4384 ON (ttrss_feed_categories.id = cat_id)
4385 LEFT JOIN ttrss_counters_cache
9c99281f
AD
4386 ON
4387 (ttrss_feeds.id = feed_id)
8d505d78 4388 WHERE
9c99281f 4389 ttrss_feeds.owner_uid = '$owner_uid'
8d505d78 4390 ORDER BY $order_by_qpart";
13e785e0 4391
9c99281f 4392 $result = db_query($link, $query);
13e785e0 4393
9c99281f 4394 $actid = $_REQUEST["actid"];
0f39ae20 4395
4d65b7df 4396 if (db_num_rows($result) > 0) {
f407c086 4397
4d65b7df 4398 $category = "";
8d505d78
AD
4399
4400 if (!$enable_cats)
4d65b7df
AD
4401 $cat['items'] = array();
4402 else
4403 $cat = false;
8d505d78 4404
4d65b7df 4405 while ($line = db_fetch_assoc($result)) {
8d505d78 4406
4d65b7df 4407 $feed = htmlspecialchars(trim($line["title"]));
8d505d78 4408
4d65b7df 4409 if (!$feed) $feed = "[Untitled]";
8d505d78
AD
4410
4411 $feed_id = $line["id"];
4d65b7df 4412 $unread = $line["unread"];
8d505d78 4413
4d65b7df
AD
4414 $cat_id = $line["cat_id"];
4415 $tmp_category = $line["category"];
4416 if (!$tmp_category) $tmp_category = __("Uncategorized");
8d505d78 4417
4d65b7df 4418 if ($category != $tmp_category && $enable_cats) {
8d505d78 4419
4d65b7df 4420 $category = $tmp_category;
8d505d78 4421
4d65b7df 4422 $collapsed = sql_bool_to_bool($line["collapsed"]);
8d505d78 4423
4d65b7df
AD
4424 // workaround for NULL category
4425 if ($category == __("Uncategorized")) {
4426 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4427 }
8d505d78 4428
4d65b7df 4429 if ($cat) array_push($feedlist['items'], $cat);
8d505d78 4430
4d65b7df 4431 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
f0855b88 4432 }
8d505d78
AD
4433
4434 $updated = make_local_datetime($link, $line["updated_noms"], false);
4435
4436 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4d65b7df
AD
4437 $feed, $unread, $line['last_error'], $updated));
4438 }
8d505d78 4439
4d65b7df
AD
4440 if ($enable_cats) {
4441 array_push($feedlist['items'], $cat);
8d505d78 4442 } else {
4d65b7df 4443 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
f407c086
AD
4444 }
4445
9c99281f 4446 }
13e785e0
AD
4447
4448 return $feedlist;
f407c086
AD
4449 }
4450
ca5133cb 4451 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
0b126ac2 4452
bd3f2ade
AD
4453 global $memcache;
4454
0b126ac2
AD
4455 $a_id = db_escape_string($id);
4456
bc976a8c
AD
4457 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4458
8d505d78 4459 $query = "SELECT DISTINCT tag_name,
0c3d1c68 4460 owner_uid as owner FROM
0b126ac2 4461 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 4462 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 4463
bd3f2ade 4464 $obj_id = md5("TAGS:$owner_uid:$id");
8d505d78 4465 $tags = array();
bd3f2ade
AD
4466
4467 if ($memcache && $obj = $memcache->get($obj_id)) {
4468 $tags = $obj;
4469 } else {
490c366d
AD
4470 /* check cache first */
4471
ca5133cb
AD
4472 if ($tag_cache === false) {
4473 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4474 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
490c366d 4475
ca5133cb
AD
4476 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4477 }
490c366d
AD
4478
4479 if ($tag_cache) {
4480 $tags = explode(",", $tag_cache);
4481 } else {
bd3f2ade 4482
490c366d
AD
4483 /* do it the hard way */
4484
4485 $tmp_result = db_query($link, $query);
4486
4487 while ($tmp_line = db_fetch_assoc($tmp_result)) {
8d505d78 4488 array_push($tags, $tmp_line["tag_name"]);
490c366d
AD
4489 }
4490
4491 /* update the cache */
4492
4493 $tags_str = db_escape_string(join(",", $tags));
4494
8d505d78 4495 db_query($link, "UPDATE ttrss_user_entries
490c366d
AD
4496 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4497 AND owner_uid = " . $_SESSION["uid"]);
bd3f2ade
AD
4498 }
4499
4500 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
0b126ac2
AD
4501 }
4502
4503 return $tags;
4504 }
4505
d62a3b63
AD
4506 function trim_array($array) {
4507 $tmp = $array;
3415b075 4508 array_walk($tmp, 'trim');
d62a3b63
AD
4509 return $tmp;
4510 }
4511
be832a1a 4512 function tag_is_valid($tag) {
ef063748
AD
4513 if ($tag == '') return false;
4514 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 4515 if (mb_strlen($tag) > 250) return false;
ef063748 4516
31365729
AD
4517 if (function_exists('iconv')) {
4518 $tag = iconv("utf-8", "utf-8", $tag);
4519 }
4520
ef063748
AD
4521 if (!$tag) return false;
4522
4523 return true;
be832a1a
AD
4524 }
4525
afb12ed0
AD
4526 function render_login_form($link, $mobile = 0) {
4527 switch ($mobile) {
4528 case 0:
793185a9 4529 require_once "login_form.php";
afb12ed0
AD
4530 break;
4531 case 1:
793185a9 4532 require_once "mobile/login_form.php";
afb12ed0
AD
4533 break;
4534 case 2:
4535 require_once "mobile/classic/login_form.php";
793185a9 4536 }
01a87dff
AD
4537 }
4538
dc56b3b7
AD
4539 // from http://developer.apple.com/internet/safari/faq.html
4540 function no_cache_incantation() {
4541 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4542 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4543 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4544 header("Cache-Control: post-check=0, pre-check=0", false);
4545 header("Pragma: no-cache"); // HTTP/1.0
4546 }
4547
42395d28 4548 function format_warning($msg, $id = "") {
883fee8d 4549 global $link;
8d505d78 4550 return "<div class=\"warning\" id=\"$id\">
883fee8d 4551 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
0d32b41e
AD
4552 }
4553
08ac193a 4554 function format_notice($msg, $id = "") {
883fee8d 4555 global $link;
8d505d78 4556 return "<div class=\"notice\" id=\"$id\">
883fee8d 4557 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
0d32b41e
AD
4558 }
4559
08ac193a 4560 function format_error($msg, $id = "") {
883fee8d 4561 global $link;
8d505d78 4562 return "<div class=\"error\" id=\"$id\">
883fee8d 4563 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
68d2f95e
AD
4564 }
4565
4dccf1ed
AD
4566 function print_notice($msg) {
4567 return print format_notice($msg);
4568 }
4569
4570 function print_warning($msg) {
4571 return print format_warning($msg);
4572 }
4573
68d2f95e
AD
4574 function print_error($msg) {
4575 return print format_error($msg);
4576 }
4577
4578
4dccf1ed
AD
4579 function T_sprintf() {
4580 $args = func_get_args();
4581 return vsprintf(__(array_shift($args)), $args);
4582 }
4583
51682b23
AD
4584 function format_inline_player($link, $url, $ctype) {
4585
4586 $entry = "";
4587
8d505d78 4588 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
4589
4590 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
8d505d78 4591 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
c3edc667
AD
4592 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4593
4594 $id = 'AUDIO-' . uniqid();
4595
4596 $entry .= "<audio id=\"$id\"\">
4597 <source src=\"$url\"></source>
8d505d78 4598 </audio>";
c3edc667 4599
8d505d78 4600 $entry .= "<span onclick=\"player(this)\"
c3edc667
AD
4601 title=\"".__("Click to play")."\" status=\"0\"
4602 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4603
4604 } else {
8d505d78
AD
4605
4606 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 4607 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
4608 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4609 <param name=\"movie\"
ad95edc2 4610 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 4611 </object>";
c3edc667 4612 }
51682b23
AD
4613 }
4614
c3edc667
AD
4615 $filename = substr($url, strrpos($url, "/")+1);
4616
4617 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4618 $filename . " (" . $ctype . ")" . "</a>";
4619
51682b23
AD
4620 return $entry;
4621 }
4622
9949bd15 4623 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
3de0261a 4624
009646d2
AD
4625 $rv = array();
4626
4627 $rv['id'] = $id;
4628
10eb9da8 4629 /* we can figure out feed_id from article id anyway, why do we
e04c18a2 4630 * pass feed_id here? let's ignore the argument :( */
10eb9da8
AD
4631
4632 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4633 WHERE ref_id = '$id'");
4634
e04c18a2 4635 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 4636
009646d2
AD
4637 $rv['feed_id'] = $feed_id;
4638
4639 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 4640
54e61a68 4641 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3de0261a
AD
4642 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4643
4644 if (db_num_rows($result) == 1) {
4645 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
54e61a68 4646 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3de0261a
AD
4647 } else {
4648 $rtl_content = false;
54e61a68 4649 $always_display_enclosures = false;
3de0261a
AD
4650 }
4651
4652 if ($rtl_content) {
4653 $rtl_tag = "dir=\"RTL\"";
4654 $rtl_class = "RTL";
4655 } else {
4656 $rtl_tag = "";
4657 $rtl_class = "";
4658 }
4659
4660 if ($mark_as_read) {
8d505d78
AD
4661 $result = db_query($link, "UPDATE ttrss_user_entries
4662 SET unread = false,last_read = NOW()
3de0261a 4663 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
8a4c759e
AD
4664
4665 ccache_update($link, $feed_id, $_SESSION["uid"]);
3de0261a
AD
4666 }
4667
4668 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
fc2b26a6 4669 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3de0261a 4670 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
8cc3c778 4671 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3de0261a 4672 num_comments,
9c506873 4673 tag_cache,
c7e51de1 4674 author,
ef83538d 4675 orig_feed_id,
c7e51de1 4676 note
3de0261a
AD
4677 FROM ttrss_entries,ttrss_user_entries
4678 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4679
4680 if ($result) {
4681
3de0261a
AD
4682 $line = db_fetch_assoc($result);
4683
4684 if ($line["icon_url"]) {
8e289ca1 4685 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3de0261a
AD
4686 } else {
4687 $feed_icon = "&nbsp;";
4688 }
4689
8cc3c778
AD
4690 $feed_site_url = $line['site_url'];
4691
3de0261a
AD
4692 $num_comments = $line["num_comments"];
4693 $entry_comments = "";
4694
4695 if ($num_comments > 0) {
4696 if ($line["comments"]) {
4697 $comments_url = $line["comments"];
4698 } else {
4699 $comments_url = $line["link"];
4700 }
7514749d 4701 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3de0261a
AD
4702 } else {
4703 if ($line["comments"] && $line["link"] != $line["comments"]) {
7514749d 4704 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
8d505d78 4705 }
3de0261a
AD
4706 }
4707
eedfb635
AD
4708 if ($zoom_mode) {
4709 header("Content-Type: text/html");
009646d2 4710 $rv['content'] .= "<html><head>
5bb0cc8e 4711 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
eedfb635
AD
4712 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4713 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4714 </head><body>";
4715 }
4716
009646d2 4717 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
6f3976c9 4718 truncate_string(strip_tags($line['title']), 15) . "</div>";
eedfb635 4719
009646d2 4720 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 4721
009646d2 4722 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
bc372fe3 4723 class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
4724
4725 $entry_author = $line["author"];
4726
4727 if ($entry_author) {
60164936 4728 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
4729 }
4730
8d505d78 4731 $parsed_updated = make_local_datetime($link, $line["updated"], true,
324944f3
AD
4732 false, true);
4733
009646d2 4734 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3de0261a
AD
4735
4736 if ($line["link"]) {
009646d2 4737 $rv['content'] .= "<div clear='both'><a target='_blank'
a64029e5 4738 title=\"".htmlspecialchars($line['title'])."\"
8d505d78
AD
4739 href=\"" .
4740 $line["link"] . "\">" .
4741 truncate_string($line["title"], 100) .
a64029e5 4742 "<span class='author'>$entry_author</span></a></div>";
3de0261a 4743 } else {
009646d2 4744 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
4745 }
4746
9c506873
AD
4747 $tag_cache = $line["tag_cache"];
4748
4749 if (!$tag_cache)
4750 $tags = get_article_tags($link, $id);
4751 else
4752 $tags = explode(",", $tag_cache);
4753
0780f4f4
AD
4754 $tags_str = format_tags_string($tags, $id);
4755 $tags_str_full = join(", ", $tags);
4756
4757 if (!$tags_str_full) $tags_str_full = __("no tags");
e7544143 4758
3de0261a
AD
4759 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4760
009646d2 4761 $rv['content'] .= "<div style='float : right'>
8d505d78 4762 <img src='".theme_image($link, 'images/tag.png')."'
e9823609 4763 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
4764
4765 if (!$zoom_mode) {
009646d2 4766 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 4767 <a title=\"".__('Edit tags for this article')."\"
31a53903 4768 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 4769
0780f4f4
AD
4770 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4771 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4772 position=\"below\">$tags_str_full</div>";
4773
009646d2 4774 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
9ed0b90f 4775 class='tagsPic' style=\"cursor : pointer\"
ca07f49e 4776 onclick=\"postOpenInNewTab(event, $id)\"
6f3976c9 4777 alt='Zoom' title='".__('Open article in new tab')."'>";
c7e51de1 4778
741b6090 4779 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
c7e51de1 4780
009646d2 4781 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
9ed0b90f 4782 class='tagsPic' style=\"cursor : pointer\"
741b6090
AD
4783 onclick=\"editArticleNote($id)\"
4784 alt='PubNote' title='".__('Edit article note')."'>";
c7e51de1 4785
31a53903 4786 if (DIGEST_ENABLE) {
009646d2 4787 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
9ed0b90f 4788 class='tagsPic' style=\"cursor : pointer\"
31a53903
AD
4789 onclick=\"emailArticle($id)\"
4790 alt='Zoom' title='".__('Forward by email')."'>";
4791 }
4792
411fe209 4793 if (ENABLE_TWEET_BUTTON) {
009646d2 4794 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
411fe209
AD
4795 class='tagsPic' style=\"cursor : pointer\"
4796 onclick=\"tweetArticle($id)\"
4797 alt='Zoom' title='".__('Share on Twitter')."'>";
4798 }
4799
83cd33fc
AD
4800 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
4801 class='tagsPic' style=\"cursor : pointer\"
4802 onclick=\"shareArticle(".$line['int_id'].")\"
4803 alt='Zoom' title='".__('Share by URL')."'>";
4804
009646d2 4805 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
6f3976c9 4806 class='tagsPic' style=\"cursor : pointer\"
e3387e2d 4807 onclick=\"closeArticlePanel($id)\"
6f3976c9
AD
4808 alt='Zoom' title='".__('Close this panel')."'>";
4809
24ecbcae
AD
4810 } else {
4811 $tags_str = strip_tags($tags_str);
009646d2 4812 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
eedfb635 4813 }
009646d2
AD
4814 $rv['content'] .= "</div>";
4815 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3de0261a 4816
ef83538d
AD
4817 if ($line["orig_feed_id"]) {
4818
4819 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4820 WHERE id = ".$line["orig_feed_id"]);
4821
4822 if (db_num_rows($tmp_result) != 0) {
4823
009646d2
AD
4824 $rv['content'] .= "<div clear='both'>";
4825 $rv['content'] .= __("Originally from:");
ef83538d 4826
009646d2 4827 $rv['content'] .= "&nbsp;";
ef83538d
AD
4828
4829 $tmp_line = db_fetch_assoc($tmp_result);
4830
009646d2 4831 $rv['content'] .= "<a target='_blank'
ef83538d
AD
4832 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4833 $tmp_line['title'] . "</a>";
4834
009646d2 4835 $rv['content'] .= "&nbsp;";
ef83538d 4836
009646d2
AD
4837 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4838 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
ef83538d 4839
009646d2 4840 $rv['content'] .= "</div>";
ef83538d
AD
4841 }
4842 }
4843
009646d2 4844 $rv['content'] .= "</div>";
3de0261a 4845
009646d2 4846 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 4847 if ($line['note']) {
009646d2 4848 $rv['content'] .= format_article_note($id, $line['note']);
c7e51de1 4849 }
009646d2 4850 $rv['content'] .= "</div>";
c7e51de1 4851
fcfa9ef1
AD
4852 $rv['content'] .= "<div class=\"postIcon\">" .
4853 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4854 href=\"".htmlspecialchars($feed_site_url)."\">".
4855 $feed_icon . "</a></div>";
4856
009646d2 4857 $rv['content'] .= "<div class=\"postContent\">";
741b6090
AD
4858
4859 $article_content = sanitize_rss($link, $line["content"], false, false,
4860 $feed_site_url);
4861
009646d2 4862 $rv['content'] .= $article_content;
db54143e 4863
009646d2
AD
4864 $rv['content'] .= format_article_enclosures($link, $id,
4865 $always_display_enclosures, $article_content);
ce53e200 4866
009646d2 4867 $rv['content'] .= "</div>";
dad14b51 4868
009646d2 4869 $rv['content'] .= "</div>";
3de0261a
AD
4870
4871 }
4872
009646d2
AD
4873 if ($zoom_mode) {
4874 $rv['content'] .= "
eedfb635 4875 <div style=\"text-align : center\">
2ae69126
AD
4876 <button onclick=\"return window.close()\">".
4877 __("Close this window")."</button></div>";
009646d2 4878 $rv['content'] .= "</body></html>";
eedfb635 4879 }
3de0261a 4880
009646d2
AD
4881 return $rv;
4882
3de0261a
AD
4883 }
4884
bd202c3f 4885 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
8d505d78 4886 $next_unread_feed, $offset, $vgr_last_feed = false,
7b4d02a8 4887 $override_order = false) {
3de0261a 4888
52d7e7da
AD
4889 $disable_cache = false;
4890
bd202c3f
AD
4891 $reply = array();
4892
46921916
AD
4893 $timing_info = getmicrotime();
4894
961f4c73
AD
4895 $topmost_article_ids = array();
4896
71317973 4897 if (!$offset) $offset = 0;
3de0261a
AD
4898 if ($subop == "undefined") $subop = "";
4899
9949bd15 4900 $subop_split = explode(":", $subop);
a9bcfb8f 4901
b9d54789 4902/* if ($subop == "CatchupSelected") {
9949bd15 4903 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
b4e75b2a 4904 $cmode = sprintf("%d", $_REQUEST["cmode"]);
3de0261a
AD
4905
4906 catchupArticlesById($link, $ids, $cmode);
b9d54789 4907 } */
3de0261a 4908
147f5632 4909 if ($subop == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
0569a712
AD
4910 update_rss_feed($link, $feed, true);
4911 }
4912
3de0261a
AD
4913 if ($subop == "MarkAllRead") {
4914 catchup_feed($link, $feed, $cat_view);
4915
4916 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4917 if ($next_unread_feed) {
4918 $feed = $next_unread_feed;
4919 }
4920 }
4921 }
4922
a9bcfb8f
AD
4923 if ($subop_split[0] == "MarkAllReadGR") {
4924 catchup_feed($link, $subop_split[1], false);
4925 }
4926
c3fddd05 4927 // FIXME: might break tag display?
a9bcfb8f 4928
147f5632 4929 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
3de0261a
AD
4930 $result = db_query($link,
4931 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
8d505d78 4932
3de0261a 4933 if (db_num_rows($result) == 0) {
bd202c3f 4934 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
3de0261a
AD
4935 }
4936 }
4937
4938 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
10eb9da8 4939
3de0261a
AD
4940 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4941 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4942
4943 if (db_num_rows($result) == 1) {
4944 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4945 } else {
4946 $rtl_content = false;
4947 }
8d505d78 4948
3de0261a
AD
4949 if ($rtl_content) {
4950 $rtl_tag = "dir=\"RTL\"";
4951 } else {
4952 $rtl_tag = "";
4953 }
4954 } else {
4955 $rtl_tag = "";
4956 $rtl_content = false;
4957 }
4958
c3fddd05 4959 @$search = db_escape_string($_REQUEST["query"]);
52d7e7da 4960
8d505d78 4961 if ($search) {
52d7e7da
AD
4962 $disable_cache = true;
4963 }
4964
c3fddd05
AD
4965 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4966 @$match_on = db_escape_string($_REQUEST["match_on"]);
3de0261a
AD
4967
4968 if (!$match_on) {
4969 $match_on = "both";
4970 }
4971
b4e75b2a 4972 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
46921916 4973
147f5632
CM
4974// error_log("format_headlines_list: [" . $feed . "] subop [" . $subop . "]");
4975 if( $search_mode == '' && $subop != '' ){
4976 $search_mode = $subop;
4977 }
4978// error_log("search_mode: " . $search_mode);
8d505d78 4979 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
71317973 4980 $search, $search_mode, $match_on, $override_order, $offset);
3de0261a 4981
b4e75b2a 4982 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
46921916 4983
3de0261a
AD
4984 $result = $qfh_ret[0];
4985 $feed_title = $qfh_ret[1];
4986 $feed_site_url = $qfh_ret[2];
4987 $last_error = $qfh_ret[3];
f56e3080 4988
081e527d
AD
4989 $vgroup_last_feed = $vgr_last_feed;
4990
78b2c6ce 4991// if (!$offset) {
3de0261a 4992
6b32516b 4993 if (db_num_rows($result) > 0) {
b9d54789
AD
4994 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
4995 $feed_title,
8d505d78 4996 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
26a1e185 4997 $last_error);
6b32516b 4998 }
78b2c6ce 4999// }
3de0261a 5000
29dfb258
AD
5001 $headlines_count = db_num_rows($result);
5002
3de0261a
AD
5003 if (db_num_rows($result) > 0) {
5004
e56beb95 5005 $lnum = $offset;
4ab4d364 5006
3de0261a 5007 $num_unread = 0;
6cfea5c7
AD
5008 $cur_feed_title = '';
5009
784ac51f
AD
5010 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5011
7d96bfcd
AD
5012 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5013
3de0261a
AD
5014 while ($line = db_fetch_assoc($result)) {
5015
5016 $class = ($lnum % 2) ? "even" : "odd";
8d505d78 5017
3de0261a
AD
5018 $id = $line["id"];
5019 $feed_id = $line["feed_id"];
9c506873
AD
5020 $label_cache = $line["label_cache"];
5021 $labels = false;
5022
5023 if ($label_cache) {
5024 $label_cache = json_decode($label_cache, true);
961f4c73 5025
9c506873
AD
5026 if ($label_cache) {
5027 if ($label_cache["no-labels"] == 1)
5028 $labels = array();
5029 else
5030 $labels = $label_cache;
5031 }
5032 }
5033
5034 if (!is_array($labels)) $labels = get_article_labels($link, $id);
e2549229 5035
2eb9c95c
AD
5036 $labels_str = "<span id=\"HLLCTR-$id\">";
5037 $labels_str .= format_article_labels($labels, $id);
f9247195 5038 $labels_str .= "</span>";
8d505d78 5039
905ff52a 5040 if (count($topmost_article_ids) < 3) {
961f4c73
AD
5041 array_push($topmost_article_ids, $id);
5042 }
5043
784ac51f 5044 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
8d505d78 5045
883fee8d 5046 $update_pic = "<img id='FUPDPIC-$id' src=\"".
8d505d78 5047 theme_image($link, 'images/updated.png')."\"
3de0261a
AD
5048 alt=\"Updated\">";
5049 } else {
8d505d78 5050 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
3de0261a
AD
5051 alt=\"Updated\">";
5052 }
784ac51f 5053
8d505d78 5054 if (sql_bool_to_bool($line["unread"]) &&
784ac51f
AD
5055 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5056
e9823609
AD
5057 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5058 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
784ac51f 5059 }
8d505d78 5060
3de0261a 5061 if ($line["unread"] == "t" || $line["unread"] == "1") {
ca8e3d75 5062 $class .= " Unread";
3de0261a
AD
5063 ++$num_unread;
5064 $is_unread = true;
5065 } else {
5066 $is_unread = false;
5067 }
abd8a516 5068
3de0261a 5069 if ($line["marked"] == "t" || $line["marked"] == "1") {
8d505d78
AD
5070 $marked_pic = "<img id=\"FMPIC-$id\"
5071 src=\"".theme_image($link, 'images/mark_set.png')."\"
5072 class=\"markedPic\" alt=\"Unstar article\"
b167df5e 5073 onclick='javascript:toggleMark($id)'>";
3de0261a 5074 } else {
8d505d78
AD
5075 $marked_pic = "<img id=\"FMPIC-$id\"
5076 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5077 class=\"markedPic\" alt=\"Star article\"
b167df5e 5078 onclick='javascript:toggleMark($id)'>";
3de0261a
AD
5079 }
5080
e4f4b46f 5081 if ($line["published"] == "t" || $line["published"] == "1") {
8d505d78
AD
5082 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5083 'images/pub_set.png')."\"
e4f4b46f 5084 class=\"markedPic\"
b167df5e 5085 alt=\"Unpublish article\" onclick='javascript:togglePub($id)'>";
e4f4b46f 5086 } else {
e9823609 5087 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
8d505d78 5088 'images/pub_unset.png')."\"
e4f4b46f 5089 class=\"markedPic\"
b167df5e 5090 alt=\"Publish article\" onclick='javascript:togglePub($id)'>";
e4f4b46f
AD
5091 }
5092
e944346c 5093# $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
3de0261a
AD
5094# $line["title"] . "</a>";
5095
8d505d78 5096# $content_link = "<a
f0971fc1
AD
5097# href=\"" . htmlspecialchars($line["link"]) . "\"
5098# onclick=\"view($id,$feed_id);\">" .
5099# $line["title"] . "</a>";
3de0261a
AD
5100
5101# $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5102# $line["title"] . "</a>";
5103
8d505d78 5104 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
3de0261a
AD
5105
5106 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
8d505d78 5107 $content_preview = truncate_string(strip_tags($line["content_preview"]),
3de0261a
AD
5108 100);
5109 }
5110
ff6e357a
AD
5111 $score = $line["score"];
5112
8d505d78 5113 $score_pic = theme_image($link,
883fee8d 5114 "images/" . get_score_pic($score));
546499a9 5115
9bf3f101 5116/* $score_title = __("(Click to change)");
8d505d78 5117 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
9bf3f101 5118 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
546499a9 5119
8d505d78 5120 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
9bf3f101 5121 title=\"$score\">";
ff6e357a 5122
5daa24f2
AD
5123 if ($score > 500) {
5124 $hlc_suffix = "H";
5125 } else if ($score < -100) {
5126 $hlc_suffix = "L";
5127 } else {
5128 $hlc_suffix = "";
5129 }
5130
3de0261a
AD
5131 $entry_author = $line["author"];
5132
5133 if ($entry_author) {
60164936 5134 $entry_author = " - $entry_author";
3de0261a
AD
5135 }
5136
7defa089 5137 $has_feed_icon = feed_has_icon($feed_id);
bd51294a
AD
5138
5139 if ($has_feed_icon) {
5140 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5141 } else {
da4fb53f 5142 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
bd51294a
AD
5143 }
5144
3de0261a 5145 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
6cfea5c7 5146
d00f22ac 5147 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
bb031f91 5148 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
a9bcfb8f
AD
5149
5150 $cur_feed_title = $line["feed_title"];
081e527d 5151 $vgroup_last_feed = $feed_id;
a9bcfb8f 5152
962d8ba4 5153 $cur_feed_title = htmlspecialchars($cur_feed_title);
43fc671f 5154
af163b85 5155 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
a9bcfb8f 5156
bd202c3f 5157 $reply['content'] .= "<div class='cdmFeedTitle'>".
dc803347 5158 "<div style=\"float : right\">$feed_icon_img</div>".
4169bb67 5159 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
8cc5e965
AD
5160 $line["feed_title"]."</a> $vf_catchup_link</div>";
5161
6cfea5c7
AD
5162 }
5163 }
314fcd2b 5164
8d505d78 5165 $mouseover_attrs = "onmouseover='postMouseIn($id)'
314fcd2b
AD
5166 onmouseout='postMouseOut($id)'";
5167
bd202c3f 5168 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
8cc5e965 5169
bd202c3f 5170 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
8cc5e965 5171
bd202c3f 5172 $reply['content'] .= "<div class='hlLeft'>";
8cc5e965 5173
bd202c3f 5174 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
8cc5e965 5175 id=\"RCHK-$id\">";
8d505d78 5176
bd202c3f
AD
5177 $reply['content'] .= "$marked_pic";
5178 $reply['content'] .= "$published_pic";
3de0261a 5179
bd202c3f 5180 $reply['content'] .= "</div>";
df456bb0 5181
bd202c3f 5182 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
8cc5e965 5183 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
bd202c3f 5184 $reply['content'] .= "<a id=\"RTITLE-$id\"
f0971fc1 5185 href=\"" . htmlspecialchars($line["link"]) . "\"
ccdddcc2 5186 onclick=\"\">" .
d6571825 5187 truncate_string($line["title"], 200);
df456bb0
AD
5188
5189 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5190 if ($content_preview) {
bd202c3f 5191 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
3de0261a 5192 }
3de0261a 5193 }
df456bb0 5194
bd202c3f 5195 $reply['content'] .= "</a></span>";
df456bb0 5196
bd202c3f 5197 $reply['content'] .= $labels_str;
e2549229 5198
52c8007d
AD
5199 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5200 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
8d505d78 5201 if (@$line["feed_title"]) {
52c8007d 5202 $reply['content'] .= "<span class=\"hlFeed\">
4169bb67 5203 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
6cfea5c7
AD
5204 $line["feed_title"]."</a>)
5205 </span>";
5206 }
52c8007d 5207 }
6e35a862 5208
bd202c3f 5209 $reply['content'] .= "</div>";
7b5e74c7 5210
bd202c3f 5211 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
6edeede3
AD
5212 $reply['content'] .= "<div class=\"hlRight\">";
5213
bd202c3f 5214 $reply['content'] .= $score_pic;
546499a9 5215
8cc5e965 5216 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
bd51294a 5217
bd202c3f 5218 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
4a06f46d 5219 style=\"cursor : pointer\"
8cc5e965
AD
5220 title=\"".htmlspecialchars($line['feed_title'])."\">
5221 $feed_icon_img<span>";
bd51294a
AD
5222 }
5223
bd202c3f
AD
5224 $reply['content'] .= "</div>";
5225 $reply['content'] .= "</div>";
3de0261a
AD
5226
5227 } else {
6cfea5c7 5228
bb031f91 5229 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
081e527d
AD
5230 if ($feed_id != $vgroup_last_feed) {
5231
5232 $cur_feed_title = $line["feed_title"];
5233 $vgroup_last_feed = $feed_id;
5234
962d8ba4
AD
5235 $cur_feed_title = htmlspecialchars($cur_feed_title);
5236
af163b85 5237 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
081e527d 5238
7defa089 5239 $has_feed_icon = feed_has_icon($feed_id);
dc803347
AD
5240
5241 if ($has_feed_icon) {
5242 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5243 } else {
5244 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5245 }
5246
bd202c3f 5247 $reply['content'] .= "<div class='cdmFeedTitle'>".
dc803347 5248 "<div style=\"float : right\">$feed_icon_img</div>".
4169bb67 5249 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
081e527d 5250 $line["feed_title"]."</a> $vf_catchup_link</div>";
6cfea5c7
AD
5251 }
5252 }
5253
0cacc891 5254 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
0cacc891 5255
8d505d78 5256 $mouseover_attrs = "onmouseover='postMouseIn($id)'
314fcd2b
AD
5257 onmouseout='postMouseOut($id)'";
5258
bd202c3f 5259 $reply['content'] .= "<div class=\"$class\"
dd4c8697 5260 id=\"RROW-$id\" $mouseover_attrs'>";
3de0261a 5261
bd202c3f 5262 $reply['content'] .= "<div class=\"cdmHeader\">";
3de0261a 5263
915b61ef 5264 $reply['content'] .= "<div>";
8d505d78 5265
bd202c3f 5266 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
ca8e3d75 5267 'RROW-$id')\" id=\"RCHK-$id\"/>";
5daa24f2 5268
bd202c3f
AD
5269 $reply['content'] .= "$marked_pic";
5270 $reply['content'] .= "$published_pic";
a7f003e0 5271
915b61ef
AD
5272 $reply['content'] .= "</div>";
5273
bd202c3f 5274 $reply['content'] .= "<span id=\"RTITLE-$id\"
dd4c8697 5275 onclick=\"return cdmClicked(event, $id);\"
dad14b51
AD
5276 class=\"titleWrap$hlc_suffix\">
5277 <a class=\"title\"
a64029e5 5278 title=\"".htmlspecialchars($line['title'])."\"
96d44601 5279 target=\"_blank\" href=\"".
a64029e5 5280 htmlspecialchars($line["link"])."\">".
8d505d78 5281 truncate_string($line["title"], 100) .
2547c9ec 5282 " $entry_author</a>";
0cacc891 5283
bd202c3f 5284 $reply['content'] .= $labels_str;
0cacc891 5285
52c8007d
AD
5286 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5287 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5288 if (@$line["feed_title"]) {
5289 $reply['content'] .= "<span class=\"hlFeed\">
5290 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5291 $line["feed_title"]."</a>)
5292 </span>";
5293 }
5294 }
5295
02ef7e02 5296 if (!$expand_cdm)
dad14b51
AD
5297 $content_hidden = "style=\"display : none\"";
5298 else
5299 $excerpt_hidden = "style=\"display : none\"";
3de0261a 5300
bd202c3f 5301 $reply['content'] .= "<span $excerpt_hidden
dad14b51 5302 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
3de0261a 5303
bd202c3f 5304 $reply['content'] .= "</span>";
dd4c8697 5305
915b61ef
AD
5306 $reply['content'] .= "<div>";
5307 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5308 $reply['content'] .= "$score_pic";
5309
5310 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5311 $reply['content'] .= "<span style=\"cursor : pointer\"
5312 title=\"".htmlspecialchars($line["feed_title"])."\"
5313 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5314 }
5315 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5316 $reply['content'] .= "</div>";
5317
bd202c3f 5318 $reply['content'] .= "</div>";
c9efd838 5319
bd202c3f 5320 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
dd4c8697 5321 onclick=\"return cdmClicked(event, $id);\"
dad14b51 5322 id=\"CICD-$id\">";
c9efd838 5323
bd202c3f 5324 $reply['content'] .= "<div class=\"cdmContentInner\">";
a04c8e8d 5325
dad14b51 5326 if ($line["orig_feed_id"]) {
494a64ea 5327
dad14b51
AD
5328 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5329 WHERE id = ".$line["orig_feed_id"]);
494a64ea
AD
5330
5331 if (db_num_rows($tmp_result) != 0) {
8d505d78 5332
bd202c3f
AD
5333 $reply['content'] .= "<div clear='both'>";
5334 $reply['content'] .= __("Originally from:");
8d505d78 5335
bd202c3f 5336 $reply['content'] .= "&nbsp;";
8d505d78 5337
dad14b51 5338 $tmp_line = db_fetch_assoc($tmp_result);
8d505d78 5339
bd202c3f 5340 $reply['content'] .= "<a target='_blank'
dad14b51
AD
5341 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5342 $tmp_line['title'] . "</a>";
8d505d78 5343
bd202c3f 5344 $reply['content'] .= "&nbsp;";
8d505d78 5345
bd202c3f
AD
5346 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5347 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
8d505d78 5348
bd202c3f 5349 $reply['content'] .= "</div>";
dad14b51 5350 }
494a64ea 5351 }
494a64ea 5352
d1fc2f92 5353 $feed_site_url = $line["site_url"];
9d3c031d 5354
b67897bf 5355 $article_content = sanitize_rss($link, $line["content_preview"],
62b800b4 5356 false, false, $feed_site_url);
621ffb00 5357
bd202c3f 5358 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 5359 if ($line['note']) {
bd202c3f 5360 $reply['content'] .= format_article_note($id, $line['note']);
c7e51de1 5361 }
bd202c3f 5362 $reply['content'] .= "</div>";
c7e51de1 5363
b67897bf
AD
5364 $reply['content'] .= "<span id=\"CWRAP-$id\">";
5365 $reply['content'] .= $expand_cdm ? $article_content : '';
5366 $reply['content'] .= "</span>";
a3eeb471 5367
c0644ee4 5368/* $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
dad14b51 5369 ttrss_feeds WHERE id = ".
8d505d78 5370 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
c0644ee4 5371 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
54e61a68 5372
8d505d78 5373 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
c0644ee4
AD
5374 0, "always_display_enclosures")); */
5375
5376 $always_display_enclosures = sql_bool_to_bool($line["always_display_enclosures"]);
a04c8e8d 5377
bd202c3f 5378 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51 5379 $article_content);
a04c8e8d 5380
bd202c3f 5381 $reply['content'] .= "</div>";
3de0261a 5382
bd202c3f 5383 $reply['content'] .= "<div class=\"cdmFooter\">";
3de0261a 5384
9c506873
AD
5385 $tag_cache = $line["tag_cache"];
5386
ca5133cb
AD
5387 $tags_str = format_tags_string(
5388 get_article_tags($link, $id, $_SESSION["uid"], $tag_cache),
5389 $id);
dad14b51 5390
bd202c3f 5391 $reply['content'] .= "<img src='".theme_image($link,
dad14b51
AD
5392 'images/tag.png')."' alt='Tags' title='Tags'>
5393 <span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 5394 <a title=\"".__('Edit tags for this article')."\"
4169bb67 5395 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
3de0261a 5396
13992673
AD
5397 $num_comments = $line["num_comments"];
5398 $entry_comments = "";
5399
5400 if ($num_comments > 0) {
5401 if ($line["comments"]) {
5402 $comments_url = $line["comments"];
5403 } else {
5404 $comments_url = $line["link"];
5405 }
5406 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
5407 } else {
5408 if ($line["comments"] && $line["link"] != $line["comments"]) {
5409 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
5410 }
5411 }
5412
5413 if ($entry_comments) $reply['content'] .= "&nbsp;($entry_comments)";
5414
bd202c3f 5415 $reply['content'] .= "<div style=\"float : right\">";
3de0261a 5416
bd202c3f 5417 $reply['content'] .= "<img src=\"images/art-zoom.png\"
8a6702ad 5418 onclick=\"zoomToArticle(event, $id)\"
eedfb635 5419 style=\"cursor : pointer\"
8d505d78 5420 alt='Zoom'
6f3976c9 5421 title='".__('Open article in new tab')."'>";
dad14b51 5422
741b6090 5423 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
411fe209 5424
bd202c3f 5425 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
411fe209 5426 style=\"cursor : pointer\" style=\"cursor : pointer\"
741b6090
AD
5427 onclick=\"editArticleNote($id)\"
5428 alt='PubNote' title='".__('Edit article note')."'>";
411fe209 5429
dad14b51 5430 if (DIGEST_ENABLE) {
bd202c3f 5431 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
dad14b51
AD
5432 style=\"cursor : pointer\"
5433 onclick=\"emailArticle($id)\"
5434 alt='Zoom' title='".__('Forward by email')."'>";
5435 }
c7e51de1 5436
411fe209 5437 if (ENABLE_TWEET_BUTTON) {
bd202c3f 5438 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
411fe209
AD
5439 class='tagsPic' style=\"cursor : pointer\"
5440 onclick=\"tweetArticle($id)\"
5441 alt='Zoom' title='".__('Share on Twitter')."'>";
5442 }
c7e51de1 5443
db16ae50
AD
5444 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
5445 class='tagsPic' style=\"cursor : pointer\"
5446 onclick=\"shareArticle(".$line['int_id'].")\"
5447 alt='Zoom' title='".__('Share by URL')."'>";
5448
bd202c3f 5449 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
dad14b51 5450 style=\"cursor : pointer\" style=\"cursor : pointer\"
1ede5814 5451 onclick=\"dismissArticle($id)\"
dad14b51 5452 alt='Dismiss' title='".__('Dismiss article')."'>";
3de0261a 5453
bd202c3f
AD
5454 $reply['content'] .= "</div>";
5455 $reply['content'] .= "</div>";
3de0261a 5456
bd202c3f 5457 $reply['content'] .= "</div>";
3de0261a 5458
bd202c3f 5459 $reply['content'] .= "</div>";
3de0261a 5460
8d505d78
AD
5461 }
5462
3de0261a 5463 ++$lnum;
8d505d78 5464 }
3de0261a 5465
7d96bfcd
AD
5466 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5467
3de0261a 5468 } else {
93c841c4
AD
5469 $message = "";
5470
5471 switch ($view_mode) {
5472 case "unread":
5473 $message = __("No unread articles found to display.");
5474 break;
8b09eac8
AD
5475 case "updated":
5476 $message = __("No updated articles found to display.");
5477 break;
93c841c4
AD
5478 case "marked":
5479 $message = __("No starred articles found to display.");
5480 break;
5481 default:
215af892
AD
5482 if ($feed < -10) {
5483 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5484 } else {
5485 $message = __("No articles found to display.");
5486 }
93c841c4
AD
5487 }
5488
8f7c631e 5489 if (!$offset && $message) {
bd202c3f 5490 $reply['content'] .= "<div class='whiteBox'>$message";
8f7c631e 5491
bd202c3f 5492 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
8f7c631e
AD
5493
5494 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5495 WHERE owner_uid = " . $_SESSION['uid']);
8d505d78 5496
8f7c631e
AD
5497 $last_updated = db_fetch_result($result, 0, "last_updated");
5498 $last_updated = make_local_datetime($link, $last_updated, false);
8d505d78 5499
bd202c3f 5500 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
8d505d78 5501
8f7c631e
AD
5502 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5503 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 5504
8f7c631e 5505 $num_errors = db_fetch_result($result, 0, "num_errors");
8d505d78 5506
8f7c631e 5507 if ($num_errors > 0) {
bd202c3f
AD
5508 $reply['content'] .= "<br/>";
5509 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
8f7c631e
AD
5510 __('Some feeds have update errors (click for details)')."</a>";
5511 }
bd202c3f 5512 $reply['content'] .= "</span></p></div>";
8f7c631e 5513 }
3de0261a
AD
5514 }
5515
7d96bfcd
AD
5516 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5517
bd202c3f 5518 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
7d96bfcd 5519 $vgroup_last_feed, $reply);
3de0261a 5520 }
0979b696
AD
5521
5522// from here: http://www.roscripts.com/Create_tag_cloud-71.html
5523
5524 function printTagCloud($link) {
35a03bdd 5525
8d505d78
AD
5526 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5527 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
b31af972 5528 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
0979b696
AD
5529
5530 $result = db_query($link, $query);
5531
5532 $tags = array();
5533
5534 while ($line = db_fetch_assoc($result)) {
5535 $tags[$line["tag_name"]] = $line["count"];
5536 }
5537
9949bd15
CM
5538 if( count($tags) == 0 ){ return; }
5539
0979b696
AD
5540 ksort($tags);
5541
5542 $max_size = 32; // max font size in pixels
4548a580 5543 $min_size = 11; // min font size in pixels
8d505d78 5544
0979b696
AD
5545 // largest and smallest array values
5546 $max_qty = max(array_values($tags));
5547 $min_qty = min(array_values($tags));
8d505d78 5548
0979b696
AD
5549 // find the range of values
5550 $spread = $max_qty - $min_qty;
5551 if ($spread == 0) { // we don't want to divide by zero
5552 $spread = 1;
5553 }
8d505d78 5554
0979b696
AD
5555 // set the font-size increment
5556 $step = ($max_size - $min_size) / ($spread);
8d505d78 5557
0979b696
AD
5558 // loop through the tag array
5559 foreach ($tags as $key => $value) {
5560 // calculate font-size
5561 // find the $value in excess of $min_qty
5562 // multiply by the font-size increment ($size)
5563 // and add the $min_size set above
5564 $size = round($min_size + (($value - $min_qty) * $step));
546ffab4
AD
5565
5566 $key_escaped = str_replace("'", "\\'", $key);
5567
8d505d78
AD
5568 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5569 $size . "px\" title=\"$value articles tagged with " .
0979b696
AD
5570 $key . '">' . $key . '</a> ';
5571 }
5572 }
46921916
AD
5573
5574 function print_checkpoint($n, $s) {
8d505d78 5575 $ts = getmicrotime();
46921916
AD
5576 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5577 return $ts;
5578 }
14b6c54b
AD
5579
5580 function sanitize_tag($tag) {
5581 $tag = trim($tag);
5582
5583 $tag = mb_strtolower($tag, 'utf-8');
5584
78ccac0b 5585 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
0c3d1c68 5586
8d505d78
AD
5587// $tag = str_replace('"', "", $tag);
5588// $tag = str_replace("+", " ", $tag);
14b6c54b
AD
5589 $tag = str_replace("technorati tag: ", "", $tag);
5590
5591 return $tag;
5592 }
e4f4b46f 5593
8801fb01 5594 function get_self_url_prefix() {
ed102aa0 5595 return SELF_URL_PATH;
8801fb01 5596 }
b9d54789 5597
8801fb01 5598 function opml_publish_url($link){
e0dc56d4 5599
8801fb01 5600 $url_path = get_self_url_prefix();
8d505d78 5601 $url_path .= "/opml.php?op=publish&key=" .
2e7f046f 5602 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
e0dc56d4
MK
5603
5604 return $url_path;
5605 }
f56e3080 5606
45004d43
AD
5607 /**
5608 * Purge a feed contents, marked articles excepted.
8d505d78 5609 *
45004d43
AD
5610 * @param mixed $link The database connection.
5611 * @param integer $id The id of the feed to purge.
5612 * @return void
5613 */
d1f0c584 5614 function clear_feed_articles($link, $id) {
e04c18a2
AD
5615
5616 if ($id != 0) {
5617 $result = db_query($link, "DELETE FROM ttrss_user_entries
a8ae1b9a 5618 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
e04c18a2
AD
5619 } else {
5620 $result = db_query($link, "DELETE FROM ttrss_user_entries
5621 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5622 }
d1f0c584 5623
8d505d78 5624 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
d1f0c584 5625 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
ced46404
AD
5626
5627 ccache_update($link, $id, $_SESSION['uid']);
45004d43
AD
5628 } // function clear_feed_articles
5629
5630 /**
5631 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5632 *
5633 * @return string The Mozilla Firefox feed adding URL.
5634 */
5635 function add_feed_url() {
ed102aa0
AD
5636 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5637
5638 $url_path = get_self_url_prefix() .
5639 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
755a43ee 5640 return $url_path;
45004d43
AD
5641 } // function add_feed_url
5642
5643 /**
5644 * Encrypt a password in SHA1.
8d505d78 5645 *
45004d43
AD
5646 * @param string $pass The password to encrypt.
5647 * @param string $login A optionnal login.
5648 * @return string The encrypted password.
5649 */
1a9f4d3c
AD
5650 function encrypt_password($pass, $login = '') {
5651 if ($login) {
5652 return "SHA1X:" . sha1("$login:$pass");
5653 } else {
5654 return "SHA1:" . sha1($pass);
5655 }
45004d43
AD
5656 } // function encrypt_password
5657
5658 /**
5659 * Update a feed batch.
5660 * Used by daemons to update n feeds by run.
5661 * Only update feed needing a update, and not being processed
5662 * by another process.
8d505d78 5663 *
45004d43
AD
5664 * @param mixed $link Database link
5665 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5666 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5667 * @param boolean $debug Set to false to disable debug output. Default to true.
5668 * @return void
5669 */
5670 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5671 // Process all other feeds using last_updated and interval parameters
5672
5673 // Test if the user has loggued in recently. If not, it does not update its feeds.
5674 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5675 if (DB_TYPE == "pgsql") {
5676 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5677 } else {
5678 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
8d505d78 5679 }
45004d43
AD
5680 } else {
5681 $login_thresh_qpart = "";
5682 }
5683
5684 // Test if the feed need a update (update interval exceded).
5685 if (DB_TYPE == "pgsql") {
5686 $update_limit_qpart = "AND ((
5687 ttrss_feeds.update_interval = 0
5688 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5689 ) OR (
5690 ttrss_feeds.update_interval > 0
5691 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
da4caf5d 5692 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5693 } else {
5694 $update_limit_qpart = "AND ((
5695 ttrss_feeds.update_interval = 0
5696 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5697 ) OR (
5698 ttrss_feeds.update_interval > 0
5699 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
da4caf5d 5700 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5701 }
5702
5703 // Test if feed is currently being updated by another process.
5704 if (DB_TYPE == "pgsql") {
359fc686 5705 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
45004d43 5706 } else {
359fc686 5707 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
45004d43
AD
5708 }
5709
5710 // Test if there is a limit to number of updated feeds
5711 $query_limit = "";
5712 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5713
51b8c957
AD
5714 $random_qpart = sql_random_function();
5715
45004d43
AD
5716 // We search for feed needing update.
5717 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
fc2b26a6 5718 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
8d505d78
AD
5719 ttrss_feeds.update_interval
5720 FROM
45004d43
AD
5721 ttrss_feeds, ttrss_users, ttrss_user_prefs
5722 WHERE
5723 ttrss_feeds.owner_uid = ttrss_users.id
5724 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5725 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5726 $login_thresh_qpart $update_limit_qpart
51b8c957
AD
5727 $updstart_thresh_qpart
5728 ORDER BY $random_qpart $query_limit");
45004d43
AD
5729
5730 $user_prefs_cache = array();
5731
5732 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5733
5734 // Here is a little cache magic in order to minimize risk of double feed updates.
5735 $feeds_to_update = array();
5736 while ($line = db_fetch_assoc($result)) {
5737 $feeds_to_update[$line['id']] = $line;
5738 }
5739
5740 // We update the feed last update started date before anything else.
5741 // There is no lag due to feed contents downloads
5742 // It prevent an other process to update the same feed.
5743 $feed_ids = array_keys($feeds_to_update);
5744 if($feed_ids) {
5745 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5746 WHERE id IN (%s)", implode(',', $feed_ids)));
5747 }
5748
5749 // For each feed, we call the feed update function.
5750 while ($line = array_pop($feeds_to_update)) {
5751
5752 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5753
cce9822a
AD
5754 update_rss_feed($link, $line["id"], true);
5755
45004d43
AD
5756 sleep(1); // prevent flood (FIXME make this an option?)
5757 }
5758
0e0dd486
AD
5759 // Send feed digests by email if needed.
5760 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5761
45004d43 5762 } // function update_daemon_common
1a9f4d3c 5763
621ffb00
AD
5764 function sanitize_article_content($text) {
5765 # we don't support CDATA sections in articles, they break our own escaping
5766 $text = preg_replace("/\[\[CDATA/", "", $text);
5767 $text = preg_replace("/\]\]\>/", "", $text);
5768 return $text;
5769 }
fee840fb
AD
5770
5771 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5772 $filters = array();
5773
b8ffa322 5774 global $memcache;
fee840fb 5775
1f011328
AD
5776 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5777
b8ffa322
AD
5778 if ($memcache && $obj = $memcache->get($obj_id)) {
5779
b8ffa322
AD
5780 return $obj;
5781
5782 } else {
fee840fb 5783
b8ffa322 5784 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
8d505d78 5785
b8ffa322
AD
5786 $result = db_query($link, "SELECT reg_exp,
5787 ttrss_filter_types.name AS name,
5788 ttrss_filter_actions.name AS action,
5789 inverse,
5790 action_param,
5791 filter_param
8d505d78 5792 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
b8ffa322
AD
5793 enabled = true AND
5794 $ftype_query_part
5795 owner_uid = $owner_uid AND
5796 ttrss_filter_types.id = filter_type AND
5797 ttrss_filter_actions.id = action_id AND
5798 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
8d505d78 5799
b8ffa322
AD
5800 while ($line = db_fetch_assoc($result)) {
5801 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5802 $filter["reg_exp"] = $line["reg_exp"];
5803 $filter["action"] = $line["action"];
5804 $filter["action_param"] = $line["action_param"];
5805 $filter["filter_param"] = $line["filter_param"];
5806 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
8d505d78 5807
b8ffa322
AD
5808 array_push($filters[$line["name"]], $filter);
5809 }
5810
5811 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5812
5813 return $filters;
5814 }
fee840fb 5815 }
1e36af0c
AD
5816
5817 function get_score_pic($score) {
8d505d78
AD
5818 if ($score > 100) {
5819 return "score_high.png";
5820 } else if ($score > 0) {
883fee8d 5821 return "score_half_high.png";
1cce3aca 5822 } else if ($score < -100) {
883fee8d 5823 return "score_low.png";
1cce3aca 5824 } else if ($score < 0) {
883fee8d 5825 return "score_half_low.png";
8d505d78 5826 } else {
883fee8d 5827 return "score_neutral.png";
1e36af0c
AD
5828 }
5829 }
ec92c9d1 5830
7defa089
AD
5831 function feed_has_icon($id) {
5832 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5833 }
f29ba148
AD
5834
5835 function init_connection($link) {
5836 if (DB_TYPE == "pgsql") {
6fc720fd 5837 pg_query($link, "set client_encoding = 'UTF-8'");
f29ba148 5838 pg_set_client_encoding("UNICODE");
045d0ab8 5839 pg_query($link, "set datestyle = 'ISO, european'");
324944f3 5840 pg_query($link, "set TIME ZONE 0");
f29ba148 5841 } else {
324944f3
AD
5842 db_query($link, "SET time_zone = '+0:0'");
5843
f29ba148
AD
5844 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5845 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5846 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5847 }
5848 }
5849 }
5e96ca9d
AD
5850
5851 function update_feedbrowser_cache($link) {
5852
109662e1 5853 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
8d505d78
AD
5854 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5855 WHERE tf.feed_url = ttrss_feeds.feed_url
d206ae1d 5856 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
109662e1 5857 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
8d505d78 5858
5e96ca9d 5859 db_query($link, "BEGIN");
8d505d78 5860
5e96ca9d 5861 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
8d505d78 5862
5e96ca9d 5863 $count = 0;
8d505d78 5864
5e96ca9d
AD
5865 while ($line = db_fetch_assoc($result)) {
5866 $subscribers = db_escape_string($line["subscribers"]);
5867 $feed_url = db_escape_string($line["feed_url"]);
931dcbc1 5868 $title = db_escape_string($line["title"]);
109662e1 5869 $site_url = db_escape_string($line["site_url"]);
931dcbc1
AD
5870
5871 $tmp_result = db_query($link, "SELECT subscribers FROM
5872 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5873
5874 if (db_num_rows($tmp_result) == 0) {
5875
8d505d78 5876 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
109662e1
AD
5877 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5878 '$site_url', '$title', '$subscribers')");
931dcbc1
AD
5879
5880 ++$count;
5881
5882 }
8d505d78 5883
5e96ca9d 5884 }
8d505d78 5885
5e96ca9d
AD
5886 db_query($link, "COMMIT");
5887
5888 return $count;
5889
5890 }
2627f2d0 5891
0bfbf1c2 5892 /* function ccache_zero($link, $feed_id, $owner_uid) {
2627f2d0
AD
5893 db_query($link, "UPDATE ttrss_counters_cache SET
5894 value = 0, updated = NOW() WHERE
5895 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
0bfbf1c2 5896 } */
2627f2d0 5897
ad0056a8
AD
5898 function ccache_zero_all($link, $owner_uid) {
5899 db_query($link, "UPDATE ttrss_counters_cache SET
5900 value = 0 WHERE owner_uid = '$owner_uid'");
5901
5902 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5903 value = 0 WHERE owner_uid = '$owner_uid'");
5904 }
5905
c7e51de1
AD
5906 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5907
5908 if (!$is_cat) {
5909 $table = "ttrss_counters_cache";
5910 } else {
5911 $table = "ttrss_cat_counters_cache";
5912 }
5913
5914 db_query($link, "DELETE FROM $table WHERE
5915 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5916
5917 }
5918
5f4f7adf
AD
5919 function ccache_update_all($link, $owner_uid) {
5920
5921 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5922
5923 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5924 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5925
5926 while ($line = db_fetch_assoc($result)) {
5927 ccache_update($link, $line["feed_id"], $owner_uid, true);
5928 }
5929
c5ffeb61
AD
5930 /* We have to manually include category 0 */
5931
5932 ccache_update($link, 0, $owner_uid, true);
5933
8a4c759e 5934 } else {
5f4f7adf
AD
5935 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5936 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
8a4c759e 5937
5f4f7adf
AD
5938 while ($line = db_fetch_assoc($result)) {
5939 print ccache_update($link, $line["feed_id"], $owner_uid);
5940
5941 }
5942
5943 }
5944 }
2627f2d0 5945
8d505d78 5946 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd 5947 $no_update = false) {
8a4c759e 5948
5c432ba4
AD
5949 if (!is_numeric($feed_id)) return;
5950
8a4c759e
AD
5951 if (!$is_cat) {
5952 $table = "ttrss_counters_cache";
32d2181b 5953 if ($feed_id > 0) {
8d505d78 5954 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
32d2181b
AD
5955 WHERE id = '$feed_id'");
5956 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5957 }
8a4c759e
AD
5958 } else {
5959 $table = "ttrss_cat_counters_cache";
5960 }
5961
5962 if (DB_TYPE == "pgsql") {
5963 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5964 } else if (DB_TYPE == "mysql") {
5965 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5966 }
5967
5968 $result = db_query($link, "SELECT value FROM $table
8d505d78 5969 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
37fb651d 5970 LIMIT 1");
2627f2d0
AD
5971
5972 if (db_num_rows($result) == 1) {
5973 return db_fetch_result($result, 0, "value");
5974 } else {
6b49a3dd
AD
5975 if ($no_update) {
5976 return -1;
5977 } else {
5978 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5979 }
2627f2d0
AD
5980 }
5981
5982 }
5983
8d505d78 5984 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd
AD
5985 $update_pcat = true) {
5986
5c432ba4
AD
5987 if (!is_numeric($feed_id)) return;
5988
32d2181b 5989 if (!$is_cat && $feed_id > 0) {
8d505d78 5990 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
2e93b64c
AD
5991 WHERE id = '$feed_id'");
5992 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5993 }
5994
43ead405
AD
5995 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5996
5997 /* When updating a label, all we need to do is recalculate feed counters
5998 * because labels are not cached */
c98e43db
AD
5999
6000 if ($feed_id < 0) {
43ead405
AD
6001 ccache_update_all($link, $owner_uid);
6002 return;
c98e43db
AD
6003 }
6004
8a4c759e
AD
6005 if (!$is_cat) {
6006 $table = "ttrss_counters_cache";
6007 } else {
6008 $table = "ttrss_cat_counters_cache";
6009 }
6010
b6d486a3 6011 if ($is_cat && $feed_id >= 0) {
37fb651d
AD
6012 if ($feed_id != 0) {
6013 $cat_qpart = "cat_id = '$feed_id'";
6014 } else {
6015 $cat_qpart = "cat_id IS NULL";
6016 }
6017
6b49a3dd
AD
6018 /* Recalculate counters for child feeds */
6019
6020 $result = db_query($link, "SELECT id FROM ttrss_feeds
6021 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6022
6023 while ($line = db_fetch_assoc($result)) {
6024 ccache_update($link, $line["id"], $owner_uid, false, false);
6025 }
6026
8d505d78
AD
6027 $result = db_query($link, "SELECT SUM(value) AS sv
6028 FROM ttrss_counters_cache, ttrss_feeds
6029 WHERE id = feed_id AND $cat_qpart AND
37fb651d
AD
6030 ttrss_feeds.owner_uid = '$owner_uid'");
6031
51e196de 6032 $unread = (int) db_fetch_result($result, 0, "sv");
37fb651d 6033
f55b0b12
AD
6034 } else {
6035 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
37fb651d 6036 }
2627f2d0 6037
c7e51de1
AD
6038 db_query($link, "BEGIN");
6039
8a4c759e 6040 $result = db_query($link, "SELECT feed_id FROM $table
2627f2d0
AD
6041 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6042
6043 if (db_num_rows($result) == 1) {
8a4c759e 6044 db_query($link, "UPDATE $table SET
2627f2d0
AD
6045 value = '$unread', updated = NOW() WHERE
6046 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6047
6048 } else {
8a4c759e 6049 db_query($link, "INSERT INTO $table
8d505d78
AD
6050 (feed_id, value, owner_uid, updated)
6051 VALUES
2627f2d0 6052 ($feed_id, $unread, $owner_uid, NOW())");
2627f2d0
AD
6053 }
6054
c7e51de1
AD
6055 db_query($link, "COMMIT");
6056
6b49a3dd 6057 if ($feed_id > 0 && $prev_unread != $unread) {
8a4c759e 6058
37fb651d 6059 if (!$is_cat) {
8a4c759e 6060
6b49a3dd 6061 /* Update parent category */
8a4c759e 6062
6b49a3dd 6063 if ($update_pcat) {
37fb651d 6064
6b49a3dd
AD
6065 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6066 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
8a4c759e 6067
6b49a3dd 6068 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
37fb651d 6069
6b49a3dd 6070 ccache_update($link, $cat_id, $owner_uid, true);
6c2a9b9e 6071
6c2a9b9e 6072 }
8a4c759e 6073 }
5f4f7adf
AD
6074 } else if ($feed_id < 0) {
6075 ccache_update_all($link, $owner_uid);
8a4c759e
AD
6076 }
6077
6078 return $unread;
2627f2d0 6079 }
ceb30ba4 6080
0bfbf1c2 6081 /* function ccache_cleanup($link, $owner_uid) {
3261ca58 6082
cd9da663
AD
6083 if (DB_TYPE == "pgsql") {
6084 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6085 (SELECT count(*) FROM ttrss_counters_cache AS c2
6086 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6087 AND owner_uid = '$owner_uid'");
6088
6089 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6090 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6091 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3261ca58 6092 AND owner_uid = '$owner_uid'");
cd9da663
AD
6093 } else {
6094 db_query($link, "DELETE c1 FROM
6095 ttrss_counters_cache AS c1,
6096 ttrss_counters_cache AS c2
6097 WHERE
6098 c1.owner_uid = '$owner_uid' AND
6099 c1.owner_uid = c2.owner_uid AND
6100 c1.feed_id = c2.feed_id");
6101
6102 db_query($link, "DELETE c1 FROM
6103 ttrss_cat_counters_cache AS c1,
6104 ttrss_cat_counters_cache AS c2
6105 WHERE
6106 c1.owner_uid = '$owner_uid' AND
6107 c1.owner_uid = c2.owner_uid AND
6108 c1.feed_id = c2.feed_id");
6109
6110 }
0bfbf1c2 6111 } */
3261ca58 6112
ceb30ba4 6113 function label_find_id($link, $label, $owner_uid) {
8d505d78
AD
6114 $result = db_query($link,
6115 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
ceb30ba4
AD
6116 AND owner_uid = '$owner_uid' LIMIT 1");
6117
6118 if (db_num_rows($result) == 1) {
6119 return db_fetch_result($result, 0, "id");
6120 } else {
6121 return 0;
6122 }
6123 }
6124
814bff66 6125 function get_article_labels($link, $id) {
d721a547
AD
6126 global $memcache;
6127
d721a547
AD
6128 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6129
814bff66
AD
6130 $rv = array();
6131
d721a547
AD
6132 if ($memcache && $obj = $memcache->get($obj_id)) {
6133 return $obj;
6134 } else {
905ff52a
AD
6135
6136 $result = db_query($link, "SELECT label_cache FROM
6137 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6138 $_SESSION["uid"]);
6139
6140 $label_cache = db_fetch_result($result, 0, "label_cache");
6141
6142 if ($label_cache) {
6143
6144 $label_cache = json_decode($label_cache, true);
6145
6146 if ($label_cache["no-labels"] == 1)
6147 return $rv;
6148 else
6149 return $label_cache;
6150 }
6151
8d505d78
AD
6152 $result = db_query($link,
6153 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6154 FROM ttrss_labels2, ttrss_user_labels2
6155 WHERE id = label_id
6156 AND article_id = '$id'
905ff52a
AD
6157 AND owner_uid = ".$_SESSION["uid"] . "
6158 ORDER BY caption");
6159
d721a547
AD
6160 while ($line = db_fetch_assoc($result)) {
6161 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6162 $line["bg_color"]);
6163 array_push($rv, $rk);
6164 }
6165 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
905ff52a 6166
8d505d78 6167 if (count($rv) > 0)
905ff52a
AD
6168 label_update_cache($link, $id, $rv);
6169 else
6170 label_update_cache($link, $id, array("no-labels" => 1));
814bff66
AD
6171 }
6172
6173 return $rv;
6174 }
6175
6176
b8a637f3 6177 function label_find_caption($link, $label, $owner_uid) {
8d505d78
AD
6178 $result = db_query($link,
6179 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
b8a637f3
AD
6180 AND owner_uid = '$owner_uid' LIMIT 1");
6181
6182 if (db_num_rows($result) == 1) {
6183 return db_fetch_result($result, 0, "caption");
6184 } else {
6185 return "";
6186 }
6187 }
6188
905ff52a
AD
6189 function label_update_cache($link, $id, $labels = false, $force = false) {
6190
6191 if ($force)
6192 label_clear_cache($link, $id);
6193
8d505d78 6194 if (!$labels)
905ff52a
AD
6195 $labels = get_article_labels($link, $id);
6196
6197 $labels = db_escape_string(json_encode($labels));
6198
6199 db_query($link, "UPDATE ttrss_user_entries SET
6200 label_cache = '$labels' WHERE ref_id = '$id'");
6201
6202 }
6203
6204 function label_clear_cache($link, $id) {
6205
6206 db_query($link, "UPDATE ttrss_user_entries SET
6207 label_cache = '' WHERE ref_id = '$id'");
6208
6209 }
6210
933ba4ee
AD
6211 function label_remove_article($link, $id, $label, $owner_uid) {
6212
6213 $label_id = label_find_id($link, $label, $owner_uid);
6214
6215 if (!$label_id) return;
6216
8d505d78 6217 $result = db_query($link,
933ba4ee 6218 "DELETE FROM ttrss_user_labels2
8d505d78 6219 WHERE
933ba4ee
AD
6220 label_id = '$label_id' AND
6221 article_id = '$id'");
905ff52a
AD
6222
6223 label_clear_cache($link, $id);
933ba4ee
AD
6224 }
6225
ceb30ba4
AD
6226 function label_add_article($link, $id, $label, $owner_uid) {
6227
d721a547
AD
6228 global $memcache;
6229
6230 if ($memcache) {
6231 $obj_id = md5("LABELS:$id:$owner_uid");
6232 $memcache->delete($obj_id);
6233 }
6234
ceb30ba4
AD
6235 $label_id = label_find_id($link, $label, $owner_uid);
6236
6237 if (!$label_id) return;
6238
8d505d78
AD
6239 $result = db_query($link,
6240 "SELECT
ceb30ba4 6241 article_id FROM ttrss_labels2, ttrss_user_labels2
8d505d78
AD
6242 WHERE
6243 label_id = id AND
ceb30ba4
AD
6244 label_id = '$label_id' AND
6245 article_id = '$id' AND owner_uid = '$owner_uid'
6246 LIMIT 1");
6247
6248 if (db_num_rows($result) == 0) {
8d505d78 6249 db_query($link, "INSERT INTO ttrss_user_labels2
ceb30ba4
AD
6250 (label_id, article_id) VALUES ('$label_id', '$id')");
6251 }
905ff52a 6252
8d505d78 6253 label_clear_cache($link, $id);
905ff52a 6254
ceb30ba4 6255 }
1380f8ee
AD
6256
6257 function label_remove($link, $id, $owner_uid) {
d721a547
AD
6258 global $memcache;
6259
905ff52a
AD
6260 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6261
d721a547
AD
6262 if ($memcache) {
6263 $obj_id = md5("LABELS:$id:$owner_uid");
6264 $memcache->delete($obj_id);
6265 }
1380f8ee
AD
6266
6267 db_query($link, "BEGIN");
6268
6269 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6270 WHERE id = '$id'");
6271
6272 $caption = db_fetch_result($result, 0, "caption");
6273
6274 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
905ff52a 6275 AND owner_uid = " . $owner_uid);
1380f8ee
AD
6276
6277 if (db_affected_rows($link, $result) != 0 && $caption) {
6278
8801fb01
AD
6279 /* Remove access key for the label */
6280
6281 $ext_id = -11 - $id;
6282
6283 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6284 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6285
1380f8ee 6286 /* Disable filters that reference label being removed */
8d505d78 6287
1380f8ee
AD
6288 db_query($link, "UPDATE ttrss_filters SET
6289 enabled = false WHERE action_param = '$caption'
6290 AND action_id = 7
905ff52a
AD
6291 AND owner_uid = " . $owner_uid);
6292
6293 /* Remove cached data */
6294
6295 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6296 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6297
6298 }
1380f8ee
AD
6299
6300 db_query($link, "COMMIT");
6301 }
79c88e11 6302
6b2ee18d
AD
6303 function label_create($link, $caption) {
6304
6305 db_query($link, "BEGIN");
6306
6307 $result = false;
6308
6309 $result = db_query($link, "SELECT id FROM ttrss_labels2
6310 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6311
6312 if (db_num_rows($result) == 0) {
6313 $result = db_query($link,
8d505d78 6314 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6b2ee18d
AD
6315 VALUES ('$caption', '".$_SESSION["uid"]."')");
6316
6317 $result = db_affected_rows($link, $result) != 0;
6318 }
6319
6320 db_query($link, "COMMIT");
6321
6322 return $result;
6323 }
6324
307d187c
AD
6325 function format_tags_string($tags, $id) {
6326
6327 $tags_str = "";
6328 $tags_nolinks_str = "";
6329
6330 $num_tags = 0;
6331
d9084cf2 6332 $tag_limit = 6;
307d187c
AD
6333
6334 $formatted_tags = array();
6335
6336 foreach ($tags as $tag) {
6337 $num_tags++;
6338 $tag_escaped = str_replace("'", "\\'", $tag);
6339
275a0af2
AD
6340 if (mb_strlen($tag) > 30) {
6341 $tag = truncate_string($tag, 30);
6342 }
6343
307d187c
AD
6344 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6345
6346 array_push($formatted_tags, $tag_str);
275a0af2
AD
6347
6348 $tmp_tags_str = implode(", ", $formatted_tags);
8d505d78 6349
275a0af2 6350 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
307d187c
AD
6351 break;
6352 }
6353 }
6354
6355 $tags_str = implode(", ", $formatted_tags);
6356
6357 if ($num_tags < count($tags)) {
6358 $tags_str .= ", &hellip;";
6359 }
6360
6361 if ($num_tags == 0) {
6362 $tags_str = __("no tags");
6363 }
6364
6365 return $tags_str;
6366
6367 }
2eb9c95c
AD
6368
6369 function format_article_labels($labels, $id) {
6370
6371 $labels_str = "";
6372
6373 foreach ($labels as $l) {
8d505d78 6374 $labels_str .= sprintf("<span class='hlLabelRef'
2eb9c95c
AD
6375 style='color : %s; background-color : %s'>%s</span>",
6376 $l[2], $l[3], $l[1]);
6377 }
6378
6379 return $labels_str;
6380
6381 }
c7e51de1
AD
6382
6383 function format_article_note($id, $note) {
6384
fcfa9ef1
AD
6385 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6386 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6387 __('(edit note)')."</div>$note</div>";
c7e51de1
AD
6388
6389 return $str;
6390 }
7f969260 6391
fcf70c51 6392 function toggle_collapse_cat($link, $cat_id, $mode) {
7f969260 6393 if ($cat_id > 0) {
fcf70c51
AD
6394 $mode = bool_to_sql_bool($mode);
6395
7f969260 6396 db_query($link, "UPDATE ttrss_feed_categories SET
8d505d78 6397 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
7f969260
AD
6398 $_SESSION["uid"]);
6399 } else {
6400 $pref_name = '';
6401
6402 switch ($cat_id) {
6403 case -1:
6404 $pref_name = '_COLLAPSED_SPECIAL';
6405 break;
6406 case -2:
6407 $pref_name = '_COLLAPSED_LABELS';
6408 break;
6409 case 0:
6410 $pref_name = '_COLLAPSED_UNCAT';
6411 break;
6412 }
6413
6414 if ($pref_name) {
fcf70c51 6415 if ($mode) {
7f969260 6416 set_pref($link, $pref_name, 'true');
fcf70c51
AD
6417 } else {
6418 set_pref($link, $pref_name, 'false');
7f969260
AD
6419 }
6420 }
6421 }
6422 }
7e329f13
AD
6423
6424 function remove_feed($link, $id, $owner_uid) {
6425
6426 if ($id > 0) {
e04c18a2
AD
6427
6428 /* save starred articles in Archived feed */
6429
6430 db_query($link, "BEGIN");
6431
8056ec50
AD
6432 /* prepare feed if necessary */
6433
6434 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6435 WHERE id = '$id'");
6436
6437 if (db_num_rows($result) == 0) {
8d505d78 6438 db_query($link, "INSERT INTO ttrss_archived_feeds
8056ec50
AD
6439 (id, owner_uid, title, feed_url, site_url)
6440 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6441 WHERE id = '$id'");
6442 }
6443
74d22f0c 6444 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
8d505d78 6445 orig_feed_id = '$id' WHERE feed_id = '$id' AND
e04c18a2
AD
6446 marked = true AND owner_uid = $owner_uid");
6447
8801fb01
AD
6448 /* Remove access key for the feed */
6449
6450 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6451 feed_id = '$id' AND owner_uid = $owner_uid");
6452
e04c18a2
AD
6453 /* remove the feed */
6454
8d505d78 6455 db_query($link, "DELETE FROM ttrss_feeds
7e329f13
AD
6456 WHERE id = '$id' AND owner_uid = $owner_uid");
6457
e04c18a2
AD
6458 db_query($link, "COMMIT");
6459
6d634e00 6460 if (file_exists(ICONS_DIR . "/$id.ico")) {
7e329f13 6461 unlink(ICONS_DIR . "/$id.ico");
6d634e00 6462 }
7e329f13
AD
6463
6464 ccache_remove($link, $id, $owner_uid);
6465
6466 } else {
6467 label_remove($link, -11-$id, $owner_uid);
6468 ccache_remove($link, -11-$id, $owner_uid);
6469 }
6470 }
6471
5c7c7da9 6472 function add_feed_category($link, $feed_cat) {
c00907f2
AD
6473
6474 if (!$feed_cat) return false;
6475
5c7c7da9
AD
6476 db_query($link, "BEGIN");
6477
6478 $result = db_query($link,
6479 "SELECT id FROM ttrss_feed_categories
6480 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6481
6482 if (db_num_rows($result) == 0) {
8d505d78 6483
5c7c7da9 6484 $result = db_query($link,
8d505d78 6485 "INSERT INTO ttrss_feed_categories (owner_uid,title)
5c7c7da9
AD
6486 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6487
6488 db_query($link, "COMMIT");
6489
6490 return true;
6491 }
6492
6493 return false;
8d505d78 6494 }
5c7c7da9 6495
7e329f13
AD
6496 function remove_feed_category($link, $id, $owner_uid) {
6497
6498 db_query($link, "DELETE FROM ttrss_feed_categories
6499 WHERE id = '$id' AND owner_uid = $owner_uid");
6500
6501 ccache_remove($link, $id, $owner_uid, true);
6502 }
6503
16fdac16
AD
6504 function archive_article($link, $id, $owner_uid) {
6505 db_query($link, "BEGIN");
6506
6507 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6508 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6509
6510 if (db_num_rows($result) != 0) {
6511
6512 /* prepare the archived table */
6513
6514 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6515
6516 if ($feed_id) {
6517 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6518 WHERE id = '$feed_id'");
6519
6520 if (db_num_rows($result) == 0) {
8d505d78 6521 db_query($link, "INSERT INTO ttrss_archived_feeds
16fdac16
AD
6522 (id, owner_uid, title, feed_url, site_url)
6523 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6524 WHERE id = '$feed_id'");
6525 }
6526
8d505d78 6527 db_query($link, "UPDATE ttrss_user_entries
16fdac16
AD
6528 SET orig_feed_id = feed_id, feed_id = NULL
6529 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6530 }
6531 }
6532
6533 db_query($link, "COMMIT");
6534 }
ab197ae1
AD
6535
6536 function getArticleFeed($link, $id) {
8d505d78 6537 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
a545dc31 6538 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
ab197ae1
AD
6539
6540 if (db_num_rows($result) != 0) {
6541 return db_fetch_result($result, 0, "feed_id");
6542 } else {
6543 return 0;
6544 }
6545 }
a5819bb3 6546
f2c6c008
CW
6547 /**
6548 * Fixes incomplete URLs by prepending "http://".
f0266f51
CW
6549 * Also replaces feed:// with http://, and
6550 * prepends a trailing slash if the url is a domain name only.
f2c6c008
CW
6551 *
6552 * @param string $url Possibly incomplete URL
6553 *
6554 * @return string Fixed URL.
6555 */
6556 function fix_url($url) {
6557 if (strpos($url, '://') === false) {
6558 $url = 'http://' . $url;
f0266f51
CW
6559 } else if (substr($url, 0, 5) == 'feed:') {
6560 $url = 'http:' . substr($url, 5);
6561 }
6562
6563 //prepend slash if the URL has no slash in it
6564 // "http://www.example" -> "http://www.example/"
44453773 6565 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
f0266f51 6566 $url .= '/';
f2c6c008 6567 }
ec39a02c
AD
6568
6569 if ($url != "http:///")
6570 return $url;
6571 else
6572 return '';
f2c6c008
CW
6573 }
6574
a5819bb3
AD
6575 function validate_feed_url($url) {
6576 $parts = parse_url($url);
6577
6578 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6579
6580 }
d9084cf2 6581
be35798b
AD
6582 function get_article_enclosures($link, $id) {
6583
6584 global $memcache;
6585
8d505d78 6586 $query = "SELECT * FROM ttrss_enclosures
be35798b
AD
6587 WHERE post_id = '$id' AND content_url != ''";
6588
bd3f2ade 6589 $obj_id = md5("ENCLOSURES:$id");
be35798b
AD
6590
6591 $rv = array();
6592
bd3f2ade 6593 if ($memcache && $obj = $memcache->get($obj_id)) {
be35798b
AD
6594 $rv = $obj;
6595 } else {
6596 $result = db_query($link, $query);
6597
6598 if (db_num_rows($result) > 0) {
6599 while ($line = db_fetch_assoc($result)) {
6600 array_push($rv, $line);
6601 }
bd3f2ade 6602 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
be35798b
AD
6603 }
6604 }
6605
6606 return $rv;
6607 }
6608
911d4c08 6609 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
911d4c08
AD
6610
6611 $feeds = array();
6612
911d4c08
AD
6613 /* Labels */
6614
fb8d17f3 6615 if ($cat_id == -4 || $cat_id == -2) {
911d4c08
AD
6616 $counters = getLabelCounters($link, true);
6617
11232703 6618 foreach (array_values($counters) as $cv) {
911d4c08 6619
11232703 6620 $unread = $cv["counter"];
8d505d78 6621
911d4c08 6622 if ($unread || !$unread_only) {
8d505d78 6623
911d4c08 6624 $row = array(
11232703
AD
6625 "id" => $cv["id"],
6626 "title" => $cv["description"],
6627 "unread" => $cv["counter"],
911d4c08
AD
6628 "cat_id" => -2,
6629 );
8d505d78 6630
911d4c08
AD
6631 array_push($feeds, $row);
6632 }
6633 }
6634 }
6635
6636 /* Virtual feeds */
6637
fb8d17f3 6638 if ($cat_id == -4 || $cat_id == -1) {
911d4c08
AD
6639 foreach (array(-1, -2, -3, -4, 0) as $i) {
6640 $unread = getFeedUnread($link, $i);
6641
6642 if ($unread || !$unread_only) {
6643 $title = getFeedTitle($link, $i);
6644
6645 $row = array(
6646 "id" => $i,
6647 "title" => $title,
6648 "unread" => $unread,
6649 "cat_id" => -1,
6650 );
6651 array_push($feeds, $row);
6652 }
6653
8d505d78 6654 }
911d4c08 6655 }
b41c2549
AD
6656
6657 /* Real feeds */
6658
6659 if ($limit) {
6660 $limit_qpart = "LIMIT $limit OFFSET $offset";
6661 } else {
6662 $limit_qpart = "";
6663 }
6664
fb8d17f3 6665 if ($cat_id == -4 || $cat_id == -3) {
8d505d78 6666 $result = db_query($link, "SELECT
b41c2549
AD
6667 id, feed_url, cat_id, title, ".
6668 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78 6669 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
6670 " ORDER BY cat_id, title " . $limit_qpart);
6671 } else {
fb8d17f3
AD
6672
6673 if ($cat_id)
6674 $cat_qpart = "cat_id = '$cat_id'";
6675 else
6676 $cat_qpart = "cat_id IS NULL";
6677
8d505d78 6678 $result = db_query($link, "SELECT
b41c2549
AD
6679 id, feed_url, cat_id, title, ".
6680 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
6681 FROM ttrss_feeds WHERE
6682 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
6683 " ORDER BY cat_id, title " . $limit_qpart);
6684 }
6685
6686 while ($line = db_fetch_assoc($result)) {
6687
6688 $unread = getFeedUnread($link, $line["id"]);
6689
6690 $has_icon = feed_has_icon($line['id']);
6691
6692 if ($unread || !$unread_only) {
6693
6694 $row = array(
6695 "feed_url" => $line["feed_url"],
6696 "title" => $line["title"],
6697 "id" => (int)$line["id"],
6698 "unread" => (int)$unread,
6699 "has_icon" => $has_icon,
6700 "cat_id" => (int)$line["cat_id"],
6701 "last_updated" => strtotime($line["last_updated"])
6702 );
8d505d78 6703
b41c2549
AD
6704 array_push($feeds, $row);
6705 }
6706 }
6707
911d4c08
AD
6708 return $feeds;
6709 }
6710
6711 function api_get_headlines($link, $feed_id, $limit, $offset,
a0e580b0 6712 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
97e5dbb2 6713 $include_attachments, $since_id) {
911d4c08
AD
6714
6715 /* do not rely on params below */
6716
6717 $search = db_escape_string($_REQUEST["search"]);
6718 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6719 $match_on = db_escape_string($_REQUEST["match_on"]);
8d505d78
AD
6720
6721 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
911d4c08 6722 $view_mode, $is_cat, $search, $search_mode, $match_on,
97e5dbb2 6723 $order, $offset, 0, false, $since_id);
911d4c08
AD
6724
6725 $result = $qfh_ret[0];
6726 $feed_title = $qfh_ret[1];
6727
6728 $headlines = array();
6729
6730 while ($line = db_fetch_assoc($result)) {
8d505d78 6731 $is_updated = ($line["last_read"] == "" &&
911d4c08
AD
6732 ($line["unread"] != "t" && $line["unread"] != "1"));
6733
97a3b9f0
AD
6734 $tags = explode(",", $line["tag_cache"]);
6735 $labels = json_decode($line["label_cache"], true);
6736
6737 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
6738 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
6739
911d4c08
AD
6740 $headline_row = array(
6741 "id" => (int)$line["id"],
6742 "unread" => sql_bool_to_bool($line["unread"]),
6743 "marked" => sql_bool_to_bool($line["marked"]),
9ed133e7 6744 "published" => sql_bool_to_bool($line["published"]),
911d4c08
AD
6745 "updated" => strtotime($line["updated"]),
6746 "is_updated" => $is_updated,
6747 "title" => $line["title"],
6748 "link" => $line["link"],
6749 "feed_id" => $line["feed_id"],
97a3b9f0 6750 "tags" => $tags,
911d4c08
AD
6751 );
6752
a0e580b0
AD
6753 if ($include_attachments)
6754 $headline_row['attachments'] = get_article_enclosures($link,
6755 $line['id']);
6756
911d4c08
AD
6757 if ($show_excerpt) {
6758 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6759 $headline_row["excerpt"] = $excerpt;
6760 }
6761
6762 if ($show_content) {
6763 $headline_row["content"] = $line["content_preview"];
6764 }
6765
97a3b9f0
AD
6766 // unify label output to ease parsing
6767 if ($labels["no-labels"] == 1) $labels = array();
6768
6769 $headline_row["labels"] = $labels;
6770
911d4c08
AD
6771 array_push($headlines, $headline_row);
6772 }
6773
6774 return $headlines;
6775 }
6776
bd202c3f
AD
6777 function generate_error_feed($link, $error) {
6778 $reply = array();
6779
6780 $reply['headlines']['id'] = -6;
6781 $reply['headlines']['is_cat'] = false;
6782
6783 $reply['headlines']['toolbar'] = '';
6784 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6785
6786 $reply['headlines-info'] = array("count" => 0,
6787 "vgroup_last_feed" => '',
6788 "unread" => 0,
6789 "disable_cache" => true);
6790
6791 return $reply;
6792 }
fe1087fb 6793
13e785e0 6794
bd202c3f
AD
6795 function generate_dashboard_feed($link) {
6796 $reply = array();
6797
6798 $reply['headlines']['id'] = -5;
6799 $reply['headlines']['is_cat'] = false;
fe1087fb 6800
bd202c3f
AD
6801 $reply['headlines']['toolbar'] = '';
6802 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
fe1087fb 6803
bd202c3f 6804 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5d128c95
AD
6805
6806 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6807 WHERE owner_uid = " . $_SESSION['uid']);
6808
6809 $last_updated = db_fetch_result($result, 0, "last_updated");
324944f3 6810 $last_updated = make_local_datetime($link, $last_updated, false);
5d128c95 6811
bd202c3f 6812 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5d128c95 6813
fe1087fb
AD
6814 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6815 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6816
6817 $num_errors = db_fetch_result($result, 0, "num_errors");
6818
6819 if ($num_errors > 0) {
bd202c3f
AD
6820 $reply['headlines']['content'] .= "<br/>";
6821 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
fe1087fb
AD
6822 __('Some feeds have update errors (click for details)')."</a>";
6823 }
bd202c3f 6824 $reply['headlines']['content'] .= "</span></p>";
fe1087fb 6825
bd202c3f 6826 $reply['headlines-info'] = array("count" => 0,
ffbe082d
AD
6827 "vgroup_last_feed" => '',
6828 "unread" => 0,
6829 "disable_cache" => true);
6830
bd202c3f 6831 return $reply;
fe1087fb 6832 }
31a53903
AD
6833
6834 function save_email_address($link, $email) {
6835 // FIXME: implement persistent storage of emails
6836
8d505d78 6837 if (!$_SESSION['stored_emails'])
31a53903
AD
6838 $_SESSION['stored_emails'] = array();
6839
6840 if (!in_array($email, $_SESSION['stored_emails']))
6841 array_push($_SESSION['stored_emails'], $email);
6842 }
8801fb01
AD
6843
6844 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6845 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6846
6847 $sql_is_cat = bool_to_sql_bool($is_cat);
6848
8d505d78
AD
6849 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6850 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6851 AND owner_uid = " . $owner_uid);
6852
6853 if (db_num_rows($result) == 1) {
6854 $key = db_escape_string(sha1(uniqid(rand(), true)));
6855
6856 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
8d505d78 6857 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6858 AND owner_uid = " . $owner_uid);
6859
6860 return $key;
6861
6862 } else {
6863 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6864 }
6865 }
6866
6867 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6868
6869 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6870
6871 $sql_is_cat = bool_to_sql_bool($is_cat);
6872
8d505d78
AD
6873 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6874 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6875 AND owner_uid = " . $owner_uid);
6876
6877 if (db_num_rows($result) == 1) {
6878 return db_fetch_result($result, 0, "access_key");
6879 } else {
6880 $key = db_escape_string(sha1(uniqid(rand(), true)));
6881
8d505d78 6882 $result = db_query($link, "INSERT INTO ttrss_access_keys
8801fb01
AD
6883 (access_key, feed_id, is_cat, owner_uid)
6884 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6885
6886 return $key;
6887 }
6888 return false;
6889 }
f0266f51
CW
6890
6891 /**
6892 * Extracts RSS/Atom feed URLs from the given HTML URL.
6893 *
6894 * @param string $url HTML page URL
6895 *
6896 * @return array Array of feeds. Key is the full URL, value the title
6897 */
8d505d78 6898 function get_feeds_from_html($url, $login = false, $pass = false)
f0266f51
CW
6899 {
6900 $url = fix_url($url);
6901 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
6902
fb074239
AD
6903 libxml_use_internal_errors(true);
6904
8d505d78
AD
6905 $content = @fetch_file_contents($url, false, $login, $pass);
6906
f0266f51 6907 $doc = new DOMDocument();
8d505d78 6908 $doc->loadHTML($content);
f0266f51
CW
6909 $xpath = new DOMXPath($doc);
6910 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6911 $feedUrls = array();
6912 foreach ($entries as $entry) {
6913 if ($entry->hasAttribute('href')) {
6914 $title = $entry->getAttribute('title');
6915 if ($title == '') {
6916 $title = $entry->getAttribute('type');
6917 }
923818fc
CW
6918 $feedUrl = rewrite_relative_url(
6919 $baseUrl, $entry->getAttribute('href')
6920 );
f0266f51
CW
6921 $feedUrls[$feedUrl] = $title;
6922 }
6923 }
6924 return $feedUrls;
6925 }
6926
f33479da
CW
6927 /**
6928 * Checks if the content behind the given URL is a HTML file
6929 *
6930 * @param string $url URL to check
6931 *
6932 * @return boolean True if the URL contains HTML content
6933 */
8d505d78
AD
6934 function url_is_html($url, $login = false, $pass = false) {
6935 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6936
24eb4c78
CW
6937 if (stripos($content, '<html>') === false
6938 && stripos($content, '<html ') === false
f33479da
CW
6939 ) {
6940 return false;
6941 }
6942
6943 return true;
6944 }
24e2bb3a 6945
d90868d7 6946 function print_label_select($link, $name, $value, $attributes = "") {
24e2bb3a
AD
6947
6948 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6949 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6950
8d505d78 6951 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
d90868d7 6952 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
24e2bb3a
AD
6953
6954 while ($line = db_fetch_assoc($result)) {
6955
6956 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
6957
d90868d7
AD
6958 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6959 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
24e2bb3a
AD
6960
6961 }
6962
d90868d7 6963# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
24e2bb3a
AD
6964
6965 print "</select>";
6966
6967
6968 }
6969
009646d2 6970 function format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51
AD
6971 $article_content) {
6972
6973 $result = get_article_enclosures($link, $id);
009646d2 6974 $rv = '';
8d505d78 6975
dad14b51 6976 if (count($result) > 0) {
8d505d78 6977
dad14b51
AD
6978 $entries_html = array();
6979 $entries = array();
8d505d78 6980
dad14b51 6981 foreach ($result as $line) {
8d505d78 6982
dad14b51
AD
6983 $url = $line["content_url"];
6984 $ctype = $line["content_type"];
8d505d78 6985
dad14b51 6986 if (!$ctype) $ctype = __("unknown type");
8d505d78 6987
c3edc667 6988# $filename = substr($url, strrpos($url, "/")+1);
8d505d78 6989
dad14b51 6990 $entry = format_inline_player($link, $url, $ctype);
8d505d78 6991
c3edc667
AD
6992# $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6993# $filename . " (" . $ctype . ")" . "</a>";
8d505d78 6994
dad14b51 6995 array_push($entries_html, $entry);
8d505d78 6996
dad14b51 6997 $entry = array();
8d505d78 6998
dad14b51
AD
6999 $entry["type"] = $ctype;
7000 $entry["filename"] = $filename;
7001 $entry["url"] = $url;
8d505d78 7002
dad14b51
AD
7003 array_push($entries, $entry);
7004 }
8d505d78 7005
009646d2 7006 $rv .= "<div class=\"postEnclosures\">";
8d505d78 7007
dad14b51
AD
7008 if (!get_pref($link, "STRIP_IMAGES")) {
7009 if ($always_display_enclosures ||
7010 !preg_match("/<img/i", $article_content)) {
8d505d78 7011
dad14b51 7012 foreach ($entries as $entry) {
8d505d78 7013
dad14b51
AD
7014 if (preg_match("/image/", $entry["type"]) ||
7015 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
8d505d78 7016
009646d2 7017 $rv .= "<p><img
dad14b51
AD
7018 alt=\"".htmlspecialchars($entry["filename"])."\"
7019 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7020 }
7021 }
7022 }
7023 }
8d505d78 7024
905ff52a 7025 if (count($entries) == 1) {
009646d2 7026 $rv .= __("Attachment:") . " ";
dad14b51 7027 } else {
009646d2 7028 $rv .= __("Attachments:") . " ";
dad14b51 7029 }
8d505d78 7030
009646d2 7031 $rv .= join(", ", $entries_html);
8d505d78 7032
009646d2 7033 $rv .= "</div>";
dad14b51 7034 }
009646d2
AD
7035
7036 return $rv;
dad14b51
AD
7037 }
7038
f8fb4498
AD
7039 function getLastArticleId($link) {
7040 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7041 WHERE owner_uid = " . $_SESSION["uid"]);
7042
7043 if (db_num_rows($result) == 1) {
7044 return db_fetch_result($result, 0, "id");
7045 } else {
7046 return -1;
7047 }
7048 }
8cc3c778
AD
7049
7050 function build_url($parts) {
7051 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7052 }
7053
f679105c
CW
7054 /**
7055 * Converts a (possibly) relative URL to a absolute one.
7056 *
7057 * @param string $url Base URL (i.e. from where the document is)
7058 * @param string $rel_url Possibly relative URL in the document
7059 *
7060 * @return string Absolute URL
7061 */
8cc3c778
AD
7062 function rewrite_relative_url($url, $rel_url) {
7063 if (strpos($rel_url, "://") !== false) {
7064 return $rel_url;
8d505d78 7065 } else if (strpos($rel_url, "/") === 0)
8cc3c778
AD
7066 {
7067 $parts = parse_url($url);
7068 $parts['path'] = $rel_url;
7069
7070 return build_url($parts);
7071
7072 } else {
7073 $parts = parse_url($url);
f679105c
CW
7074 if (!isset($parts['path'])) {
7075 $parts['path'] = '/';
7076 }
7077 $dir = $parts['path'];
7078 if (substr($dir, -1) !== '/') {
7079 $dir = dirname($parts['path']);
7080 $dir !== '/' && $dir .= '/';
7081 }
7082 $parts['path'] = $dir . $rel_url;
8cc3c778
AD
7083
7084 return build_url($parts);
7085 }
7086 }
7087
e4f7f8df
AD
7088 function sphinx_search($query, $offset = 0, $limit = 30) {
7089 $sphinxClient = new SphinxClient();
7090
7091 $sphinxClient->SetServer('localhost', 9312);
7092 $sphinxClient->SetConnectTimeout(1);
7093
8d505d78 7094 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
e4f7f8df
AD
7095 'feed_title' => 20));
7096
7097 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
7098 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
7099 $sphinxClient->SetLimits($offset, $limit, 1000);
7100 $sphinxClient->SetArrayResult(false);
7101 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
8d505d78 7102
e4f7f8df
AD
7103 $result = $sphinxClient->Query($query, SPHINX_INDEX);
7104
7105 $ids = array();
7106
7107 if (is_array($result['matches'])) {
7108 foreach (array_keys($result['matches']) as $int_id) {
7109 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7110 array_push($ids, $ref_id);
7111 }
7112 }
7113
7114 return $ids;
7115 }
7116
868650e4
AD
7117 function cleanup_tags($link, $days = 14, $limit = 1000) {
7118
7119 if (DB_TYPE == "pgsql") {
7120 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7121 } else if (DB_TYPE == "mysql") {
7122 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7123 }
7124
b5ec13fa 7125 $tags_deleted = 0;
868650e4 7126
b5ec13fa
AD
7127 while ($limit > 0) {
7128 $limit_part = 500;
7129
8d505d78
AD
7130 $query = "SELECT ttrss_tags.id AS id
7131 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
b5ec13fa
AD
7132 WHERE post_int_id = int_id AND $interval_query AND
7133 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
8d505d78 7134
b5ec13fa
AD
7135 $result = db_query($link, $query);
7136
7137 $ids = array();
7138
7139 while ($line = db_fetch_assoc($result)) {
7140 array_push($ids, $line['id']);
7141 }
7142
7143 if (count($ids) > 0) {
7144 $ids = join(",", $ids);
7145 print ".";
7146
7147 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7148 $tags_deleted += db_affected_rows($link, $tmp_result);
7149 } else {
7150 break;
7151 }
7152
7153 $limit -= $limit_part;
7154 }
7155
7156 print "\n";
868650e4 7157
b5ec13fa 7158 return $tags_deleted;
868650e4
AD
7159 }
7160
13e785e0
AD
7161 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7162 $obj = array();
db34e084 7163 $cat_id = (int) $cat_id;
13e785e0
AD
7164
7165 if ($cat_id > 0) {
7166 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7167 } else if ($cat_id == 0 || $cat_id == -2) {
7168 $cat_unread = getCategoryUnread($link, $cat_id);
7169 }
7170
1985a5e0 7171 $obj['id'] = 'CAT:' . $cat_id;
13e785e0
AD
7172 $obj['items'] = array();
7173 $obj['name'] = getCategoryTitle($link, $cat_id);
7174 $obj['type'] = 'feed';
7175 $obj['unread'] = (int) $cat_unread;
7176 $obj['hidden'] = $hidden;
1985a5e0 7177 $obj['bare_id'] = $cat_id;
13e785e0
AD
7178
7179 return $obj;
7180 }
7181
fcf70c51 7182 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
13e785e0 7183 $obj = array();
1985a5e0 7184 $feed_id = (int) $feed_id;
13e785e0 7185
8d505d78 7186 if (!$title)
13e785e0
AD
7187 $title = getFeedTitle($link, $feed_id, false);
7188
cd1bb36d 7189 if ($unread === false)
13e785e0
AD
7190 $unread = getFeedUnread($link, $feed_id, false);
7191
7192 $obj['id'] = 'FEED:' . $feed_id;
7193 $obj['name'] = $title;
7194 $obj['unread'] = (int) $unread;
7195 $obj['type'] = 'feed';
fcf70c51
AD
7196 $obj['error'] = $error;
7197 $obj['updated'] = $updated;
2ef5c21f 7198 $obj['icon'] = getFeedIcon($feed_id);
1985a5e0 7199 $obj['bare_id'] = $feed_id;
13e785e0
AD
7200
7201 return $obj;
7202 }
7203
54a3dd8d 7204
57e24c82 7205 function fetch_twitter_rss($link, $url, $owner_uid) {
8d505d78 7206 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
57e24c82
AD
7207 WHERE id = $owner_uid");
7208
7209 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
54a3dd8d 7210 $url_escaped = db_escape_string($url);
57e24c82
AD
7211
7212 if ($access_token) {
57e24c82 7213
54a3dd8d
AD
7214 $tmhOAuth = new tmhOAuth(array(
7215 'consumer_key' => CONSUMER_KEY,
7216 'consumer_secret' => CONSUMER_SECRET,
7217 'user_token' => $access_token['oauth_token'],
7218 'user_secret' => $access_token['oauth_token_secret'],
7219 ));
7220
7221 $code = $tmhOAuth->request('GET', $url);
7222
7223 if ($code == 200) {
7224
7225 $content = $tmhOAuth->response['response'];
7226
5ab9791f
AD
7227 define('MAGPIE_CACHE_ON', false);
7228
8d505d78 7229 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING,
54a3dd8d
AD
7230 MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
7231
7232 return $rss;
7233
7234 } else {
7235
8d505d78 7236 db_query($link, "UPDATE ttrss_feeds
54a3dd8d
AD
7237 SET last_error = 'OAuth authorization failed ($code).'
7238 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7239 }
57e24c82 7240
57e24c82 7241 } else {
54a3dd8d 7242
8d505d78 7243 db_query($link, "UPDATE ttrss_feeds
54a3dd8d 7244 SET last_error = 'OAuth information not found.'
dc891b12 7245 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
54a3dd8d 7246
57e24c82
AD
7247 return false;
7248 }
7249 }
7250
88e4e597
AD
7251 function print_user_stylesheet($link) {
7252 $value = get_pref($link, 'USER_STYLESHEET');
7253
7254 if ($value) {
7255 print "<style type=\"text/css\">";
5823f9fb 7256 print str_replace("<br/>", "\n", $value);
88e4e597
AD
7257 print "</style>";
7258 }
7259
7260 }
7261
533c0ea6
AD
7262 function rewrite_urls($line) {
7263 global $url_regex;
7264
7265 $urls = null;
7266
8d505d78 7267 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
533c0ea6
AD
7268 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7269
7270 return $result;
7271 }
7272
36184020
AD
7273 function filter_to_sql($filter) {
7274 $query = "";
7275
7276 if (DB_TYPE == "pgsql")
7277 $reg_qpart = "~";
7278 else
7279 $reg_qpart = "REGEXP";
7280
7281 switch ($filter["type"]) {
7282 case "title":
7283 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7284 $filter['reg_exp'] . "')";
7285 break;
7286 case "content":
7287 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7288 $filter['reg_exp'] . "')";
7289 break;
7290 case "both":
7291 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7292 $filter['reg_exp'] . "') OR LOWER(" .
7293 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7294 break;
7295 case "tag":
7296 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7297 $filter['reg_exp'] . "')";
7298 break;
7299 case "link":
7300 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7301 $filter['reg_exp'] . "')";
7302 break;
7303 case "date":
7304
7305 if ($filter["filter_param"] == "before")
7306 $cmp_qpart = "<";
7307 else
7308 $cmp_qpart = ">=";
7309
7310 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7311 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7312 break;
7313 case "author":
7314 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7315 $filter['reg_exp'] . "')";
7316 break;
7317 }
7318
7319 if ($filter["inverse"])
7320 $query = "NOT ($query)";
7321
6338b16f
AD
7322 if ($query) {
7323 if (DB_TYPE == "pgsql") {
6b8b3af8 7324 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
6338b16f 7325 } else {
decf742e 7326 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
6338b16f 7327 }
36184020 7328 $query .= " AND ";
6338b16f 7329 }
36184020 7330
6b8b3af8 7331
36184020
AD
7332 return $query;
7333 }
ae5f7bb1
AD
7334
7335 // Status codes:
7336 // -1 - never connected
7337 // 0 - no data received
7338 // 1 - data received successfully
7339 // 2 - did not receive valid data
7340 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7341
7342 function get_linked_feeds($link, $instance_id = false) {
7343 if ($instance_id)
7344 $instance_qpart = "id = '$instance_id' AND ";
7345 else
7346 $instance_qpart = "";
7347
7348 if (DB_TYPE == "pgsql") {
414d0d1f 7349 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
ae5f7bb1 7350 } else {
81731791 7351 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
ae5f7bb1
AD
7352 }
7353
7354 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7355 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7356
7357 while ($line = db_fetch_assoc($result)) {
7358 $id = $line['id'];
7359
7360 _debug("Updating: " . $line['access_url'] . " ($id)");
7361
e0d91d84 7362 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
ae5f7bb1
AD
7363 $post_query = 'key=' . $line['access_key'];
7364
7365 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7366
e0d91d84
AD
7367 // try doing it the old way
7368 if (!$feeds) {
7369 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7370 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7371 }
7372
ae5f7bb1
AD
7373 if ($feeds) {
7374 $feeds = json_decode($feeds, true);
7375
7376 if ($feeds) {
7377 if ($feeds['error']) {
7378 $status = $feeds['error']['code'] + 10;
7379 } else {
7380 $status = 1;
7381
7382 if (count($feeds['feeds']) > 0) {
7383
7384 db_query($link, "DELETE FROM ttrss_linked_feeds
7385 WHERE instance_id = '$id'");
7386
7387 foreach ($feeds['feeds'] as $feed) {
7388 $feed_url = db_escape_string($feed['feed_url']);
7389 $title = db_escape_string($feed['title']);
7390 $subscribers = db_escape_string($feed['subscribers']);
2b9c4bae 7391 $site_url = db_escape_string($feed['site_url']);
ae5f7bb1
AD
7392
7393 db_query($link, "INSERT INTO ttrss_linked_feeds
d61063c7 7394 (feed_url, site_url, title, subscribers, instance_id, created, updated)
ae5f7bb1 7395 VALUES
d61063c7 7396 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
ae5f7bb1
AD
7397 }
7398 } else {
7399 // received 0 feeds, this might indicate that
7400 // the instance on the other hand is rebuilding feedbrowser cache
7401 // we will try again later
7402
7403 // TODO: maybe perform expiration based on updated here?
7404 }
7405
7406 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7407 }
7408 } else {
7409 $status = 2;
7410 }
7411
7412 } else {
7413 $status = 0;
7414 }
7415
7416 _debug("Status: $status");
7417
7418 db_query($link, "UPDATE ttrss_linked_instances SET
7419 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
7420
7421 }
e0d91d84
AD
7422 }
7423
7424 function handle_public_request($link, $op) {
7425 switch ($op) {
7426
7427 case "getUnread":
7428 $login = db_escape_string($_REQUEST["login"]);
7429 $fresh = $_REQUEST["fresh"] == "1";
7430
7431 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$login'");
7432
7433 if (db_num_rows($result) == 1) {
7434 $uid = db_fetch_result($result, 0, "id");
7435
7436 print getGlobalUnread($link, $uid);
7437
7438 if ($fresh) {
7439 print ";";
7440 print getFeedArticles($link, -3, false, true, $uid);
7441 }
7442
7443 } else {
7444 print "-1;User not found";
7445 }
7446
7447 break; // getUnread
7448
7449 case "getProfiles":
7450 $login = db_escape_string($_REQUEST["login"]);
7451 $password = db_escape_string($_REQUEST["password"]);
7452
7453 if (authenticate_user($link, $login, $password)) {
7454 $result = db_query($link, "SELECT * FROM ttrss_settings_profiles
7455 WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY title");
7456
7457 print "<select style='width: 100%' name='profile'>";
7458
7459 print "<option value='0'>" . __("Default profile") . "</option>";
7460
7461 while ($line = db_fetch_assoc($result)) {
7462 $id = $line["id"];
7463 $title = $line["title"];
7464
7465 print "<option value='$id'>$title</option>";
7466 }
7467
7468 print "</select>";
7469
7470 $_SESSION = array();
7471 }
7472 break; // getprofiles
7473
7474 case "pubsub":
7475 $mode = db_escape_string($_REQUEST['hub_mode']);
7476 $feed_id = (int) db_escape_string($_REQUEST['id']);
7477 $feed_url = db_escape_string($_REQUEST['hub_topic']);
7478
7479 if (!PUBSUBHUBBUB_ENABLED) {
7480 header('HTTP/1.0 404 Not Found');
7481 echo "404 Not found";
7482 return;
7483 }
7484
7485 // TODO: implement hub_verifytoken checking
7486
7487 $result = db_query($link, "SELECT feed_url FROM ttrss_feeds
7488 WHERE id = '$feed_id'");
7489
7490 if (db_num_rows($result) != 0) {
7491
7492 $check_feed_url = db_fetch_result($result, 0, "feed_url");
7493
7494 if ($check_feed_url && ($check_feed_url == $feed_url || !$feed_url)) {
7495 if ($mode == "subscribe") {
7496
7497 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 2
7498 WHERE id = '$feed_id'");
7499
7500 print $_REQUEST['hub_challenge'];
7501 return;
7502
7503 } else if ($mode == "unsubscribe") {
7504
7505 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 0
7506 WHERE id = '$feed_id'");
7507
7508 print $_REQUEST['hub_challenge'];
7509 return;
7510
7511 } else if (!$mode) {
7512
7513 // Received update ping, schedule feed update.
7514 //update_rss_feed($link, $feed_id, true, true);
7515
7516 db_query($link, "UPDATE ttrss_feeds SET
7517 last_update_started = '1970-01-01',
5b54efce 7518 last_updated = '1970-01-01' WHERE id = '$feed_id'");
e0d91d84
AD
7519
7520 }
7521 } else {
7522 header('HTTP/1.0 404 Not Found');
7523 echo "404 Not found";
7524 }
7525 } else {
7526 header('HTTP/1.0 404 Not Found');
7527 echo "404 Not found";
7528 }
7529
7530 break; // pubsub
7531
7532 case "logout":
7533 logout_user();
7534 header("Location: tt-rss.php");
7535 break; // logout
7536
7537 case "fbexport":
7538
7539 $access_key = db_escape_string($_POST["key"]);
7540
7541 // TODO: rate limit checking using last_connected
7542 $result = db_query($link, "SELECT id FROM ttrss_linked_instances
7543 WHERE access_key = '$access_key'");
7544
7545 if (db_num_rows($result) == 1) {
7546
7547 $instance_id = db_fetch_result($result, 0, "id");
7548
7549 $result = db_query($link, "SELECT feed_url, site_url, title, subscribers
7550 FROM ttrss_feedbrowser_cache ORDER BY subscribers DESC LIMIT 100");
7551
7552 $feeds = array();
7553
7554 while ($line = db_fetch_assoc($result)) {
7555 array_push($feeds, $line);
7556 }
7557
7558 db_query($link, "UPDATE ttrss_linked_instances SET
7559 last_status_in = 1 WHERE id = '$instance_id'");
7560
7561 print json_encode(array("feeds" => $feeds));
7562 } else {
7563 print json_encode(array("error" => array("code" => 6)));
7564 }
7565 break; // fbexport
7566
7567 case "share":
7568 $uuid = db_escape_string($_REQUEST["key"]);
7569
7570 $result = db_query($link, "SELECT ref_id, owner_uid FROM ttrss_user_entries WHERE
7571 uuid = '$uuid'");
7572
7573 if (db_num_rows($result) != 0) {
7574 header("Content-Type: text/html");
7575
7576 $id = db_fetch_result($result, 0, "ref_id");
7577 $owner_uid = db_fetch_result($result, 0, "owner_uid");
7578
7579 $_SESSION["uid"] = $owner_uid;
7580 $article = format_article($link, $id, false, true);
7581 $_SESSION["uid"] = "";
ae5f7bb1 7582
e0d91d84
AD
7583 print_r($article['content']);
7584
7585 } else {
7586 print "Article not found.";
7587 }
7588
7589 break;
7590
7591 case "rss":
7592 $feed = db_escape_string($_REQUEST["id"]);
7593 $key = db_escape_string($_REQUEST["key"]);
7594 $is_cat = $_REQUEST["is_cat"] != false;
7595 $limit = (int)db_escape_string($_REQUEST["limit"]);
7596
7597 $search = db_escape_string($_REQUEST["q"]);
7598 $match_on = db_escape_string($_REQUEST["m"]);
7599 $search_mode = db_escape_string($_REQUEST["smode"]);
7600 $view_mode = db_escape_string($_REQUEST["view-mode"]);
7601
7602 if (SINGLE_USER_MODE) {
7603 authenticate_user($link, "admin", null);
7604 }
7605
7606 $owner_id = false;
7607
7608 if ($key) {
7609 $result = db_query($link, "SELECT owner_uid FROM
7610 ttrss_access_keys WHERE access_key = '$key' AND feed_id = '$feed'");
7611
7612 if (db_num_rows($result) == 1)
7613 $owner_id = db_fetch_result($result, 0, "owner_uid");
7614 }
7615
7616 if ($owner_id) {
7617 $_SESSION['uid'] = $owner_id;
7618
7619 generate_syndicated_feed($link, 0, $feed, $is_cat, $limit,
7620 $search, $search_mode, $match_on, $view_mode);
7621 } else {
7622 header('HTTP/1.1 403 Forbidden');
7623 }
7624 break; // rss
7625
7626
7627 case "globalUpdateFeeds":
7628 // Update all feeds needing a update.
7629 update_daemon_common($link, 0, true, true);
7630 break; // globalUpdateFeeds
7631
7632
7633 default:
7634 header("Content-Type: text/plain");
7635 print json_encode(array("error" => array("code" => 7)));
7636 break; // fallback
7637
7638 }
ae5f7bb1 7639 }
40d13c28 7640?>