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