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