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