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