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