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