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