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