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