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