]> git.wh0rd.org - tt-rss.git/blame - functions.php
daemon: select feeds to update randomly (fix)
[tt-rss.git] / functions.php
CommitLineData
1d3a17c7 1<?php
f1a80dae 2
894ebcf5 3/* if ($_GET["debug"]) {
cce28758
AD
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
5 } else {
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
894ebcf5 7 } */
cce28758 8
40d13c28 9 require_once 'config.php';
cc17c205 10
9632f884
AD
11 /**
12 * Return available translations names.
13 *
14 * @access public
15 * @return array A array of available translations.
16 */
f8c612d4 17 function get_translations() {
6a214f92 18 $tr = array(
019bd5a9 19 "auto" => "Detect automatically",
6a214f92
AD
20 "en_US" => "English",
21 "fr_FR" => "Français",
77a9d0af 22 "nb_NO" => "Norsk Bokmål",
6a214f92 23 "ru_RU" => "Русский",
9a063469 24 "pt_BR" => "Portuguese/Brazil",
6a214f92 25 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
26
27 return $tr;
28 }
29
9632f884 30 if (ENABLE_TRANSLATIONS == true) { // If translations are enabled.
865220a4
AD
31 require_once "accept-to-gettext.php";
32 require_once "gettext/gettext.inc";
aba609e0 33
8d039718
AD
34 function startup_gettext() {
35
36 # Get locale from Accept-Language header
6a214f92 37 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e
AD
38
39 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
40 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
41 }
42
672f3f3c 43 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
68659d98
AD
44 $lang = $_COOKIE["ttrss_lang"];
45 }
46
8d039718
AD
47 if ($lang) {
48 _setlocale(LC_MESSAGES, $lang);
49 _bindtextdomain("messages", "locale");
50 _textdomain("messages");
51 _bind_textdomain_codeset("messages", "UTF-8");
52 }
aba609e0 53 }
aba609e0 54
cc17c205 55 startup_gettext();
865220a4 56
9632f884 57 } else { // If translations are enabled.
865220a4
AD
58 function __($msg) {
59 return $msg;
60 }
61 function startup_gettext() {
62 // no-op
63 return true;
64 }
9632f884 65 } // If translations are enabled.
cc17c205 66
b619ff15 67 require_once 'db-prefs.php';
5bc0bd27 68 require_once 'compat.php';
af106b0e 69 require_once 'errors.php';
8911ac8b 70 require_once 'version.php';
40d13c28 71
a8931123
AD
72 require_once 'phpmailer/class.phpmailer.php';
73
49f9c923 74 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
a3ee2a38
AD
75 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
76
16211ddb
AD
77 require_once "simplepie/simplepie.inc";
78 require_once "magpierss/rss_fetch.inc";
79 require_once 'magpierss/rss_utils.inc';
49f9c923 80
45004d43
AD
81 /**
82 * Print a timestamped debug message.
83 *
84 * @param string $msg The debug message.
85 * @return void
86 */
6f9e33e4
AD
87 function _debug($msg) {
88 $ts = strftime("%H:%M:%S", time());
b7ff666f 89 $ts = "$ts/" . posix_getpid();
6f9e33e4 90 print "[$ts] $msg\n";
45004d43 91 } // function _debug
6f9e33e4 92
9632f884
AD
93 /**
94 * Purge a feed old posts.
95 *
96 * @param mixed $link A database connection.
97 * @param mixed $feed_id The id of the purged feed.
98 * @param mixed $purge_interval Olderness of purged posts.
99 * @param boolean $debug Set to True to enable the debug. False by default.
100 * @access public
101 * @return void
102 */
ad507f85
AD
103 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
104
07d0efe9
AD
105 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
106
ad507f85 107 $rows = -1;
4c193675 108
07d0efe9
AD
109 $result = db_query($link,
110 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
111
112 $owner_uid = false;
113
114 if (db_num_rows($result) == 1) {
115 $owner_uid = db_fetch_result($result, 0, "owner_uid");
116 }
117
118 if (!$owner_uid) return;
119
120 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
121 $owner_uid, false);
122
123 if (!$purge_unread) $query_limit = " unread = false AND ";
124
fefa6ca3 125 if (DB_TYPE == "pgsql") {
44e241cb 126/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 127 marked = false AND feed_id = '$feed_id' AND
35d8cf43 128 (SELECT date_entered FROM ttrss_entries WHERE
44e241cb
AD
129 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
130
6e7f8d26
AD
131 $pg_version = get_pgsql_version($link);
132
133 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35
AD
134
135 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
136 ttrss_entries.id = ref_id AND
137 marked = false AND
138 feed_id = '$feed_id' AND
07d0efe9 139 $query_limit
1e59ae35
AD
140 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
141
142 } else {
143
144 $result = db_query($link, "DELETE FROM ttrss_user_entries
145 USING ttrss_entries
146 WHERE ttrss_entries.id = ref_id AND
147 marked = false AND
148 feed_id = '$feed_id' AND
07d0efe9 149 $query_limit
fc774155 150 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 151 }
ad507f85
AD
152
153 $rows = pg_affected_rows($result);
154
fefa6ca3 155 } else {
1e59ae35 156
30f1746f 157/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 158 marked = false AND feed_id = '$feed_id' AND
35d8cf43 159 (SELECT date_entered FROM ttrss_entries WHERE
30f1746f
AD
160 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
161
162 $result = db_query($link, "DELETE FROM ttrss_user_entries
163 USING ttrss_user_entries, ttrss_entries
164 WHERE ttrss_entries.id = ref_id AND
165 marked = false AND
166 feed_id = '$feed_id' AND
07d0efe9 167 $query_limit
30f1746f
AD
168 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
169
ad507f85
AD
170 $rows = mysql_affected_rows($link);
171
172 }
173
174 if ($debug) {
6f9e33e4 175 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 176 }
9632f884 177 } // function purge_feed
fefa6ca3 178
9632f884
AD
179 /**
180 * Purge old posts from old feeds.
181 *
182 * @param mixed $link A database connection
183 * @param boolean $do_output Set to true to enable printed output, false by default.
184 * @param integer $limit The maximal number of removed posts.
185 * @access public
186 * @return void
187 */
44e241cb
AD
188 function global_purge_old_posts($link, $do_output = false, $limit = false) {
189
894ebcf5 190 $random_qpart = sql_random_function();
fefa6ca3 191
44e241cb
AD
192 if ($limit) {
193 $limit_qpart = "LIMIT $limit";
194 } else {
195 $limit_qpart = "";
196 }
197
fefa6ca3 198 $result = db_query($link,
44e241cb
AD
199 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
200 ORDER BY $random_qpart $limit_qpart");
fefa6ca3
AD
201
202 while ($line = db_fetch_assoc($result)) {
203
204 $feed_id = $line["id"];
205 $purge_interval = $line["purge_interval"];
206 $owner_uid = $line["owner_uid"];
207
208 if ($purge_interval == 0) {
209
210 $tmp_result = db_query($link,
211 "SELECT value FROM ttrss_user_prefs WHERE
212 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
213
214 if (db_num_rows($tmp_result) != 0) {
215 $purge_interval = db_fetch_result($tmp_result, 0, "value");
216 }
217 }
218
219 if ($do_output) {
ad507f85 220// print "Feed $feed_id: purge interval = $purge_interval\n";
fefa6ca3
AD
221 }
222
223 if ($purge_interval > 0) {
ad507f85 224 purge_feed($link, $feed_id, $purge_interval, $do_output);
fefa6ca3
AD
225 }
226 }
227
71604ca4 228 // purge orphaned posts in main content table
dab52d7b 229 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4
AD
230 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
231
dab52d7b
AD
232 if ($do_output) {
233 $rows = db_affected_rows($link, $result);
234 _debug("Purged $rows orphaned posts.");
235 }
236
9632f884 237 } // function global_purge_old_posts
fefa6ca3 238
07d0efe9
AD
239 function feed_purge_interval($link, $feed_id) {
240
241 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
242 WHERE id = '$feed_id'");
243
244 if (db_num_rows($result) == 1) {
245 $purge_interval = db_fetch_result($result, 0, "purge_interval");
246 $owner_uid = db_fetch_result($result, 0, "owner_uid");
247
248 if ($purge_interval == 0) $purge_interval = get_pref($link,
249 'PURGE_OLD_DAYS', $user_id);
250
251 return $purge_interval;
252
253 } else {
254 return -1;
255 }
256 }
257
b6eefba5 258 function purge_old_posts($link) {
5d73494a 259
f1a80dae
AD
260 $user_id = $_SESSION["uid"];
261
262 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
263 WHERE owner_uid = '$user_id'");
5d73494a
AD
264
265 while ($line = db_fetch_assoc($result)) {
266
267 $feed_id = $line["id"];
268 $purge_interval = $line["purge_interval"];
269
b619ff15 270 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
5d73494a 271
140aae81 272 if ($purge_interval > 0) {
fefa6ca3 273 purge_feed($link, $feed_id, $purge_interval);
5d73494a
AD
274 }
275 }
71604ca4
AD
276
277 // purge orphaned posts in main content table
278 db_query($link, "DELETE FROM ttrss_entries WHERE
279 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
c3a8d71a
AD
280 }
281
c7d57b66
AD
282 function get_feed_update_interval($link, $feed_id) {
283 $result = db_query($link, "SELECT owner_uid, update_interval FROM
284 ttrss_feeds WHERE id = '$feed_id'");
285
286 if (db_num_rows($result) == 1) {
287 $update_interval = db_fetch_result($result, 0, "update_interval");
288 $owner_uid = db_fetch_result($result, 0, "owner_uid");
289
290 if ($update_interval != 0) {
291 return $update_interval;
292 } else {
293 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
294 }
295
296 } else {
297 return -1;
298 }
299 }
300
1f2b01ed 301 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
40d13c28 302
4769ddaf 303 if (WEB_DEMO_MODE) return;
b0b4abcf 304
a2770077
AD
305 if (!$user_id) {
306 $user_id = $_SESSION["uid"];
307 purge_old_posts($link);
308 }
309
25af8dad 310// db_query($link, "BEGIN");
b82af8c3 311
cbd8650d
AD
312 if (MAX_UPDATE_TIME > 0) {
313 if (DB_TYPE == "mysql") {
314 $q_order = "RAND()";
315 } else {
316 $q_order = "RANDOM()";
317 }
318 } else {
319 $q_order = "last_updated DESC";
320 }
321
d148926e 322 $result = db_query($link, "SELECT feed_url,id,
798f722b 323 SUBSTRING(last_updated,1,19) AS last_updated,
5c563acd 324 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
cbd8650d
AD
325 ORDER BY $q_order");
326
327 $upd_start = time();
40d13c28 328
b6eefba5 329 while ($line = db_fetch_assoc($result)) {
d148926e
AD
330 $upd_intl = $line["update_interval"];
331
b619ff15 332 if (!$upd_intl || $upd_intl == 0) {
e289ca71 333 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
b619ff15 334 }
d148926e 335
c1e202b7
AD
336 if ($upd_intl < 0) {
337 // Updates for this feed are disabled
338 continue;
339 }
340
93d40f50
AD
341 if ($fetch || (!$line["last_updated"] ||
342 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
c5142cca 343
cbd8650d
AD
344// print "<!-- feed: ".$line["feed_url"]." -->";
345
1f2b01ed 346 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
cbd8650d
AD
347
348 $upd_elapsed = time() - $upd_start;
349
350 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
351 return;
352 }
d148926e 353 }
40d13c28
AD
354 }
355
25af8dad 356// db_query($link, "COMMIT");
b82af8c3 357
40d13c28
AD
358 }
359
4065b60b
AD
360 function fetch_file_contents($url) {
361 if (USE_CURL_FOR_ICONS) {
362 $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
363
364 $ch = curl_init($url);
365 $fp = fopen($tmpfile, "w");
366
367 if ($fp) {
368 curl_setopt($ch, CURLOPT_FILE, $fp);
dd966fed
AD
369 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
370 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
4065b60b
AD
371 curl_exec($ch);
372 curl_close($ch);
373 fclose($fp);
374 }
375
376 $contents = file_get_contents($tmpfile);
377 unlink($tmpfile);
378
379 return $contents;
380
381 } else {
382 return file_get_contents($url);
383 }
384
385 }
78800912 386
9632f884
AD
387 /**
388 * Try to determine the favicon URL for a feed.
389 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
390 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
391 *
392 * @param string $url A feed or page URL
393 * @access public
394 * @return mixed The favicon URL, or false if none was found.
395 */
4065b60b 396 function get_favicon_url($url) {
99331724 397
4065b60b 398 if ($html = @fetch_file_contents($url)) {
78800912 399
4065b60b
AD
400 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
401 // Attempt to grab a favicon link from their webpage url
402 $linkUrl = html_entity_decode($matches[1]);
c798704b 403
4065b60b
AD
404 if (substr($linkUrl, 0, 1) == '/') {
405 $urlParts = parse_url($url);
406 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
407 } else if (substr($linkUrl, 0, 7) == 'http://') {
408 $faviconURL = $linkUrl;
409 } else if (substr($url, -1, 1) == '/') {
410 $faviconURL = $url.$linkUrl;
411 } else {
412 $faviconURL = $url.'/'.$linkUrl;
e695fdc8 413 }
717f5e64 414
c798704b 415 } else {
4065b60b
AD
416 // If unsuccessful, attempt to "guess" the favicon location
417 $urlParts = parse_url($url);
418 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
419 }
420 }
c798704b 421
4065b60b
AD
422 // Run a test to see if what we have attempted to get actually exists.
423 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
424 return $faviconURL;
425 } else {
426 return false;
427 }
9632f884 428 } // function get_favicon_url
4065b60b 429
9632f884
AD
430 /**
431 * Check if a link is a valid and working URL.
432 *
433 * @param mixed $link A URL to check
434 * @access public
435 * @return boolean True if the URL is valid, false otherwise.
436 */
4065b60b
AD
437 function url_validate($link) {
438
439 $url_parts = @parse_url($link);
440
441 if ( empty( $url_parts["host"] ) )
442 return false;
443
444 if ( !empty( $url_parts["path"] ) ) {
445 $documentpath = $url_parts["path"];
446 } else {
447 $documentpath = "/";
448 }
449
450 if ( !empty( $url_parts["query"] ) )
451 $documentpath .= "?" . $url_parts["query"];
452
453 $host = $url_parts["host"];
454 $port = $url_parts["port"];
455
456 if ( empty($port) )
457 $port = "80";
458
459 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
460
461 if ( !$socket )
462 return false;
c798704b 463
4065b60b
AD
464 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
465
466 $http_response = fgets( $socket, 22 );
467
468 $responses = "/(200 OK)|(30[0-9] Moved)/";
469 if ( preg_match($responses, $http_response) ) {
470 fclose($socket);
471 return true;
472 } else {
473 return false;
474 }
475
9632f884 476 } // function url_validate
4065b60b
AD
477
478 function check_feed_favicon($site_url, $feed, $link) {
479 $favicon_url = get_favicon_url($site_url);
480
481# print "FAVICON [$site_url]: $favicon_url\n";
482
483 error_reporting(0);
484
485 $icon_file = ICONS_DIR . "/$feed.ico";
486
487 if ($favicon_url && !file_exists($icon_file)) {
488 $contents = fetch_file_contents($favicon_url);
489
490 $fp = fopen($icon_file, "w");
78800912 491
4065b60b
AD
492 if ($fp) {
493 fwrite($fp, $contents);
494 fclose($fp);
495 chmod($icon_file, 0644);
496 }
78800912 497 }
4065b60b
AD
498
499 error_reporting(DEFAULT_ERROR_LEVEL);
500
78800912
AD
501 }
502
ddb68b81 503 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
40d13c28 504
17c0eeba 505 if (!$_GET["daemon"] && !$ignore_daemon) {
45004d43 506 return false;
21cfcdf2
AD
507 }
508
4bc64807 509 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb 510 _debug("update_rss_feed: start");
219bd8fc
AD
511 }
512
39a52499
AD
513 if (!$ignore_daemon) {
514
515 if (DB_TYPE == "pgsql") {
516 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
517 } else {
518 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
519 }
520
521 $result = db_query($link, "SELECT id,update_interval,auth_login,
16211ddb 522 auth_pass,cache_images,update_method
39a52499 523 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
02008cb1 524
39a52499
AD
525 } else {
526
527 $result = db_query($link, "SELECT id,update_interval,auth_login,
16211ddb 528 auth_pass,cache_images,update_method
39a52499
AD
529 FROM ttrss_feeds WHERE id = '$feed'");
530
531 }
a88c1f36 532
5370d37f
AD
533 if (db_num_rows($result) == 0) {
534 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
02008cb1 535 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
5370d37f 536 }
45004d43 537 return false;
5370d37f
AD
538 }
539
16211ddb
AD
540 $update_method = db_fetch_result($result, 0, "update_method");
541
3c50da83
AD
542 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
543 WHERE id = '$feed'");
544
464bd61e
AD
545 $auth_login = db_fetch_result($result, 0, "auth_login");
546 $auth_pass = db_fetch_result($result, 0, "auth_pass");
547
34459667
AD
548 if (ALLOW_SELECT_UPDATE_METHOD) {
549 if (ENABLE_SIMPLEPIE) {
550 $use_simplepie = $update_method != 1;
551 } else {
552 $use_simplepie = $update_method == 2;
553 }
16211ddb 554 } else {
34459667 555 $use_simplepie = ENABLE_SIMPLEPIE;
16211ddb
AD
556 }
557
558 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
559 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
560 }
561
562 if (!$use_simplepie) {
464bd61e
AD
563 $auth_login = urlencode($auth_login);
564 $auth_pass = urlencode($auth_pass);
565 }
47c6c988 566
a88c1f36 567 $update_interval = db_fetch_result($result, 0, "update_interval");
bc0f0785 568 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
a88c1f36
AD
569
570 if ($update_interval < 0) { return; }
571
ab3d0b99
AD
572 $feed = db_escape_string($feed);
573
47c6c988
AD
574 $fetch_url = $feed_url;
575
576 if ($auth_login && $auth_pass) {
577 $url_parts = array();
578 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
579
580 if ($url_parts[1] && $url_parts[2]) {
581 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
582 }
583
584 }
ab3d0b99 585
4bc64807 586 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
ca872b9d 587 _debug("update_rss_feed: fetching [$fetch_url]...");
219bd8fc
AD
588 }
589
9fdf7824 590 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
219bd8fc
AD
591 error_reporting(0);
592 }
593
16211ddb 594 if (!$use_simplepie) {
9fdf7824
AD
595 $rss = fetch_rss($fetch_url);
596 } else {
c7d57b66
AD
597 if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
598 mkdir(SIMPLEPIE_CACHE_DIR);
599 }
600
ca872b9d
AD
601 $rss = new SimplePie();
602 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
16211ddb 603# $rss->set_timeout(10);
ca872b9d
AD
604 $rss->set_feed_url($fetch_url);
605 $rss->set_output_encoding('UTF-8');
c7d57b66 606
bc0f0785
AD
607 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
608 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
609 _debug("enabling image cache");
610 }
611
dab52d7b 612 $rss->set_image_handler('./image.php', 'i');
bc0f0785 613 }
dab52d7b 614
c7d57b66
AD
615 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
616 _debug("feed update interval (sec): " .
617 get_feed_update_interval($link, $feed)*60);
618 }
619
620 if (is_dir(SIMPLEPIE_CACHE_DIR)) {
621 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
622 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
623 }
624
9fdf7824 625 $rss->init();
9fdf7824
AD
626 }
627
628// print_r($rss);
219bd8fc 629
4bc64807 630 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb 631 _debug("update_rss_feed: fetch done, parsing...");
219bd8fc
AD
632 } else {
633 error_reporting (DEFAULT_ERROR_LEVEL);
634 }
635
b6eefba5 636 $feed = db_escape_string($feed);
dcee8f61 637
16211ddb 638 if ($use_simplepie) {
ca872b9d
AD
639 $fetch_ok = !$rss->error();
640 } else {
641 $fetch_ok = !!$rss;
642 }
643
644 if ($fetch_ok) {
50b62214 645
4bc64807 646 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
50b62214
AD
647 _debug("update_rss_feed: processing feed data...");
648 }
649
44e241cb 650// db_query($link, "BEGIN");
dd8c76a9 651
a88c1f36 652 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
f324892e 653 FROM ttrss_feeds WHERE id = '$feed'");
331900c6 654
b6eefba5
AD
655 $registered_title = db_fetch_result($result, 0, "title");
656 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
f324892e 657 $orig_site_url = db_fetch_result($result, 0, "site_url");
331900c6 658
7fed1940
AD
659 $owner_uid = db_fetch_result($result, 0, "owner_uid");
660
16211ddb 661 if ($use_simplepie) {
9fdf7824
AD
662 $site_url = $rss->get_link();
663 } else {
664 $site_url = $rss->channel["link"];
665 }
666
8d0ec6fd 667 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
4bc64807 668 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
50b62214
AD
669 _debug("update_rss_feed: checking favicon...");
670 }
9fdf7824
AD
671
672 check_feed_favicon($site_url, $feed, $link);
a2770077
AD
673 }
674
746b249f 675 if (!$registered_title || $registered_title == "[Unknown]") {
4bc64807 676
16211ddb 677 if ($use_simplepie) {
c2f8aac4 678 $feed_title = db_escape_string($rss->get_title());
fb486a33
AD
679 } else {
680 $feed_title = db_escape_string($rss->channel["title"]);
681 }
4bc64807
AD
682
683 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
684 _debug("update_rss_feed: registering title: $feed_title");
685 }
7c5a308d 686
f324892e
AD
687 db_query($link, "UPDATE ttrss_feeds SET
688 title = '$feed_title' WHERE id = '$feed'");
689 }
690
49f9c923 691 // weird, weird Magpie
16211ddb 692 if (!$use_simplepie) {
9fdf7824
AD
693 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
694 }
147f7691
AD
695
696 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
f324892e
AD
697 db_query($link, "UPDATE ttrss_feeds SET
698 site_url = '$site_url' WHERE id = '$feed'");
331900c6 699 }
40d13c28 700
b7f4bda2
AD
701// print "I: " . $rss->channel["image"]["url"];
702
16211ddb 703 if (!$use_simplepie) {
9fdf7824
AD
704 $icon_url = $rss->image["url"];
705 } else {
706 $icon_url = $rss->get_image_url();
707 }
b7f4bda2 708
147f7691 709 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
b6eefba5
AD
710 $icon_url = db_escape_string($icon_url);
711 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
b7f4bda2
AD
712 }
713
51e456d6 714 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
50b62214
AD
715 _debug("update_rss_feed: loading filters...");
716 }
e6155a06
AD
717
718 $filters = array();
719
4b3dff6e 720 $result = db_query($link, "SELECT reg_exp,
db42b934 721 ttrss_filter_types.name AS name,
073ca0e6 722 ttrss_filter_actions.name AS action,
c2d9322b 723 inverse,
073ca0e6 724 action_param
db42b934 725 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
e8b79d16 726 enabled = true AND
db42b934
AD
727 owner_uid = $owner_uid AND
728 ttrss_filter_types.id = filter_type AND
729 ttrss_filter_actions.id = action_id AND
f8382011 730 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
e6155a06 731
b6eefba5 732 while ($line = db_fetch_assoc($result)) {
e6155a06 733 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
19c9cb11
AD
734
735 $filter["reg_exp"] = $line["reg_exp"];
736 $filter["action"] = $line["action"];
073ca0e6 737 $filter["action_param"] = $line["action_param"];
c2d9322b 738 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
073ca0e6 739
19c9cb11 740 array_push($filters[$line["name"]], $filter);
e6155a06
AD
741 }
742
16211ddb 743 if ($use_simplepie) {
9fdf7824
AD
744 $iterator = $rss->get_items();
745 } else {
746 $iterator = $rss->items;
747 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
748 if (!$iterator || !is_array($iterator)) $iterator = $rss;
749 }
c22789da
AD
750
751 if (!is_array($iterator)) {
39541e74 752 /* db_query($link, "UPDATE ttrss_feeds
75bd0669 753 SET last_error = 'Parse error: can\'t find any articles.'
77f0a2a7
AD
754 WHERE id = '$feed'"); */
755
756 // clear any errors and mark feed as updated if fetched okay
757 // even if it's blank
758
51e456d6 759 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
844012bc
AD
760 _debug("update_rss_feed: entry iterator is not an array, no articles?");
761 }
762
77f0a2a7
AD
763 db_query($link, "UPDATE ttrss_feeds
764 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
765
766 return; // no articles
c22789da 767 }
ddb68b81 768
51e456d6 769 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
50b62214
AD
770 _debug("update_rss_feed: processing articles...");
771 }
772
ddb68b81 773 foreach ($iterator as $item) {
7c5a308d 774
40ce98f4
AD
775 if ($_GET['xdebug']) {
776 print_r($item);
ea322415 777
40ce98f4 778 }
71bd29f6 779
16211ddb 780 if ($use_simplepie) {
9fdf7824
AD
781 $entry_guid = $item->get_id();
782 if (!$entry_guid) $entry_guid = $item->get_link();
783 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
784
785 } else {
786
787 $entry_guid = $item["id"];
34e420fb 788
9fdf7824
AD
789 if (!$entry_guid) $entry_guid = $item["guid"];
790 if (!$entry_guid) $entry_guid = $item["link"];
791 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
792 }
be832a1a 793
9fdf7824 794 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb
AD
795 _debug("update_rss_feed: guid $entry_guid");
796 }
797
be832a1a
AD
798 if (!$entry_guid) continue;
799
800 $entry_timestamp = "";
801
16211ddb 802 if ($use_simplepie) {
9fdf7824
AD
803 $entry_timestamp = strtotime($item->get_date());
804 } else {
805 $rss_2_date = $item['pubdate'];
806 $rss_1_date = $item['dc']['date'];
807 $atom_date = $item['issued'];
808 if (!$atom_date) $atom_date = $item['updated'];
be832a1a 809
9fdf7824
AD
810 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
811 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
812 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
813 }
9bb36aa0
AD
814
815 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
816 _debug("update_rss_feed: date $entry_timestamp");
817 }
818
2e930846 819 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
be832a1a
AD
820 $entry_timestamp = time();
821 $no_orig_date = 'true';
822 } else {
823 $no_orig_date = 'false';
824 }
825
826 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
827
16211ddb 828 if ($use_simplepie) {
9fdf7824
AD
829 $entry_title = $item->get_title();
830 } else {
831 $entry_title = trim(strip_tags($item["title"]));
832 }
be832a1a 833
16211ddb 834 if ($use_simplepie) {
9fdf7824
AD
835 $entry_link = $item->get_link();
836 } else {
837 // strange Magpie workaround
838 $entry_link = $item["link_"];
839 if (!$entry_link) $entry_link = $item["link"];
840 }
be832a1a 841
9bb36aa0
AD
842 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
843 _debug("update_rss_feed: title $entry_title");
844 }
845
846 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
7d3ab0dd 847
be832a1a 848 $entry_link = strip_tags($entry_link);
7d3ab0dd 849
16211ddb 850 if ($use_simplepie) {
9fdf7824
AD
851 $entry_content = $item->get_description();
852 } else {
853 $entry_content = $item["content:escaped"];
854
855 if (!$entry_content) $entry_content = $item["content:encoded"];
856 if (!$entry_content) $entry_content = $item["content"];
ea322415
AD
857
858 // Magpie bugs are getting ridiculous
859 if (trim($entry_content) == "Array") $entry_content = false;
860
9fdf7824
AD
861 if (!$entry_content) $entry_content = $item["atom_content"];
862 if (!$entry_content) $entry_content = $item["summary"];
863 if (!$entry_content) $entry_content = $item["description"];
864
865 // WTF
866 if (is_array($entry_content)) {
867 $entry_content = $entry_content["encoded"];
868 if (!$entry_content) $entry_content = $entry_content["escaped"];
ea322415 869 }
be832a1a
AD
870 }
871
ea322415
AD
872 if ($_GET["xdebug"]) {
873 print "update_rss_feed: content: ";
874 print_r(htmlspecialchars($entry_content));
875 }
be832a1a
AD
876
877 $entry_content_unescaped = $entry_content;
be832a1a 878
16211ddb 879 if ($use_simplepie) {
9fdf7824 880 $entry_comments = strip_tags($item->data["comments"]);
30cf38dd 881 if ($item->get_author()) {
e1d600f0 882 $entry_author_item = $item->get_author();
a0c6eafb
AD
883 $entry_author = $entry_author_item->get_name();
884 if (!$entry_author) $entry_author = $entry_author_item->get_email();
30cf38dd 885 }
9fdf7824
AD
886 } else {
887 $entry_comments = strip_tags($item["comments"]);
888
889 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
4d6e9157 890
9fdf7824
AD
891 if ($item['author']) {
892
893 if (is_array($item['author'])) {
894
895 if (!$entry_author) {
896 $entry_author = db_escape_string(strip_tags($item['author']['name']));
897 }
898
899 if (!$entry_author) {
900 $entry_author = db_escape_string(strip_tags($item['author']['email']));
901 }
4d6e9157 902 }
9fdf7824 903
4d6e9157 904 if (!$entry_author) {
9fdf7824 905 $entry_author = db_escape_string(strip_tags($item['author']));
4d6e9157 906 }
83f114c8 907 }
be832a1a
AD
908 }
909
83f114c8
AD
910 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
911
be832a1a 912 $entry_guid = db_escape_string(strip_tags($entry_guid));
2ad9ee56 913 $entry_guid = mb_substr($entry_guid, 0, 250);
be832a1a
AD
914
915 $result = db_query($link, "SELECT id FROM ttrss_entries
916 WHERE guid = '$entry_guid'");
917
918 $entry_content = db_escape_string($entry_content);
7e43ad58
AD
919
920 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
921
be832a1a
AD
922 $entry_title = db_escape_string($entry_title);
923 $entry_link = db_escape_string($entry_link);
2544f36b
AD
924 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
925 $entry_author = mb_substr($entry_author, 0, 250);
be832a1a 926
16211ddb 927 if ($use_simplepie) {
9fdf7824
AD
928 $num_comments = 0; #FIXME#
929 } else {
930 $num_comments = db_escape_string($item["slash"]["comments"]);
931 }
be832a1a
AD
932
933 if (!$num_comments) $num_comments = 0;
934
fefef828 935 // parse <category> entries into tags
be832a1a 936
16211ddb 937 if ($use_simplepie) {
be832a1a 938
fefef828 939 $additional_tags = array();
9fdf7824 940 $additional_tags_src = $item->get_categories();
3b9e5af4 941
a702e931
AD
942 if (is_array($additional_tags_src)) {
943 foreach ($additional_tags_src as $tobj) {
944 array_push($additional_tags, $tobj->get_term());
945 }
fefef828 946 }
fefef828 947
6af621c7
AD
948 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
949 _debug("update_rss_feed: category tags:");
950 print_r($additional_tags);
951 }
952
9fdf7824 953 } else {
fefef828 954
9fdf7824 955 $t_ctr = $item['category#'];
fefef828 956
9fdf7824
AD
957 $additional_tags = false;
958
959 if ($t_ctr == 0) {
960 $additional_tags = false;
71bd29f6 961 } else if ($t_ctr > 0) {
9fdf7824 962 $additional_tags = array($item['category']);
71bd29f6
AD
963
964 if ($item['category@term']) {
965 array_push($additional_tags, $item['category@term']);
966 }
967
9fdf7824
AD
968 for ($i = 0; $i <= $t_ctr; $i++ ) {
969 if ($item["category#$i"]) {
970 array_push($additional_tags, $item["category#$i"]);
971 }
71bd29f6
AD
972
973 if ($item["category#$i@term"]) {
974 array_push($additional_tags, $item["category#$i@term"]);
975 }
9fdf7824
AD
976 }
977 }
978
979 // parse <dc:subject> elements
980
981 $t_ctr = $item['dc']['subject#'];
982
71bd29f6 983 if ($t_ctr > 0) {
9fdf7824 984 $additional_tags = array($item['dc']['subject']);
71bd29f6 985
9fdf7824
AD
986 for ($i = 0; $i <= $t_ctr; $i++ ) {
987 if ($item['dc']["subject#$i"]) {
988 array_push($additional_tags, $item['dc']["subject#$i"]);
989 }
fefef828
AD
990 }
991 }
992 }
8add756a 993
ce53e200
AD
994 // enclosures
995
996 $enclosures = array();
997
16211ddb 998 if ($use_simplepie) {
ce53e200
AD
999 $encs = $item->get_enclosures();
1000
3b9e5af4
AD
1001 if (is_array($encs)) {
1002 foreach ($encs as $e) {
1003 $e_item = array(
1004 $e->link, $e->type, $e->length);
1005
1006 array_push($enclosures, $e_item);
1007 }
ce53e200
AD
1008 }
1009
1010 } else {
1011 $e_ctr = $item['enclosure#'];
1012
1013 if ($e_ctr > 0) {
1014 $e_item = array($item['enclosure@url'],
1015 $item['enclosure@type'],
1016 $item['enclosure@length']);
1017
1018 array_push($enclosures, $e_item);
1019
71bd29f6
AD
1020 for ($i = 0; $i <= $e_ctr; $i++ ) {
1021
1022 if ($item["enclosure#$i@url"]) {
1023 $e_item = array($item["enclosure#$i@url"],
1024 $item["enclosure#$i@type"],
1025 $item["enclosure#$i@length"]);
1026 array_push($enclosures, $e_item);
1027 }
ce53e200
AD
1028 }
1029 }
1030
1031 }
1032
d48d160c 1033 # sanitize content
183ad07b 1034
007a38d4 1035// $entry_content = sanitize_rss($entry_content);
d48d160c 1036
9fdf7824 1037 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb
AD
1038 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1039 }
1040
44e241cb
AD
1041 db_query($link, "BEGIN");
1042
4c193675
AD
1043 if (db_num_rows($result) == 0) {
1044
9fdf7824 1045 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb
AD
1046 _debug("update_rss_feed: base guid not found");
1047 }
1048
4c193675
AD
1049 // base post entry does not exist, create it
1050
4c193675
AD
1051 $result = db_query($link,
1052 "INSERT INTO ttrss_entries
1053 (title,
1054 guid,
1055 link,
1056 updated,
1057 content,
1058 content_hash,
1059 no_orig_date,
1060 date_entered,
11b0dce2 1061 comments,
b6104dee
AD
1062 num_comments,
1063 author)
4c193675
AD
1064 VALUES
1065 ('$entry_title',
1066 '$entry_guid',
1067 '$entry_link',
1068 '$entry_timestamp_fmt',
1069 '$entry_content',
1070 '$content_hash',
1071 $no_orig_date,
1072 NOW(),
11b0dce2 1073 '$entry_comments',
b6104dee
AD
1074 '$num_comments',
1075 '$entry_author')");
8926aab8
AD
1076 } else {
1077 // we keep encountering the entry in feeds, so we need to
1078 // update date_entered column so that we don't get horrible
1079 // dupes when the entry gets purged and reinserted again e.g.
1080 // in the case of SLOW SLOW OMG SLOW updating feeds
1081
1082 $base_entry_id = db_fetch_result($result, 0, "id");
1083
1084 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1085 WHERE id = '$base_entry_id'");
4c193675
AD
1086 }
1087
1088 // now it should exist, if not - bad luck then
1089
6385315d
AD
1090 $result = db_query($link, "SELECT
1091 id,content_hash,no_orig_date,title,
8926aab8 1092 substring(date_entered,1,19) as date_entered,
11b0dce2
AD
1093 substring(updated,1,19) as updated,
1094 num_comments
6385315d
AD
1095 FROM
1096 ttrss_entries
1097 WHERE guid = '$entry_guid'");
4c193675 1098
ce53e200
AD
1099 $entry_ref_id = 0;
1100 $entry_int_id = 0;
1101
4c193675
AD
1102 if (db_num_rows($result) == 1) {
1103
9fdf7824 1104 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
7ca91eb3 1105 _debug("update_rss_feed: base guid found, checking for user record");
34e420fb
AD
1106 }
1107
11b0dce2
AD
1108 // this will be used below in update handler
1109 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1110 $orig_title = db_fetch_result($result, 0, "title");
1111 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
8926aab8
AD
1112 $orig_date_entered = strtotime(db_fetch_result($result,
1113 0, "date_entered"));
6385315d 1114
11b0dce2 1115 $ref_id = db_fetch_result($result, 0, "id");
ce53e200 1116 $entry_ref_id = $ref_id;
4c193675 1117
11b0dce2 1118 // check for user post link to main table
4c193675 1119
11b0dce2 1120 // do we allow duplicate posts with same GUID in different feeds?
8d0ec6fd 1121 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
11b0dce2
AD
1122 $dupcheck_qpart = "AND feed_id = '$feed'";
1123 } else {
1124 $dupcheck_qpart = "";
1125 }
71604ca4 1126
11b0dce2 1127// error_reporting(0);
19c9cb11 1128
f8382011
AD
1129 $article_filters = get_article_filters($filters, $entry_title,
1130 $entry_content, $entry_link);
19c9cb11 1131
9fdf7824 1132 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
7ca91eb3
AD
1133 _debug("update_rss_feed: article filters: ");
1134 if (count($article_filters) != 0) {
1135 print_r($article_filters);
1136 }
1137 }
1138
f8382011 1139 if (find_article_filter($article_filters, "filter")) {
11b0dce2
AD
1140 continue;
1141 }
19c9cb11 1142
11b0dce2 1143// error_reporting (DEFAULT_ERROR_LEVEL);
3a933f22 1144
11b0dce2 1145 $result = db_query($link,
ce53e200 1146 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
11b0dce2
AD
1147 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1148 $dupcheck_qpart");
7ca91eb3 1149
11b0dce2
AD
1150 // okay it doesn't exist - create user entry
1151 if (db_num_rows($result) == 0) {
1152
9fdf7824 1153 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
7ca91eb3
AD
1154 _debug("update_rss_feed: user record not found, creating...");
1155 }
1156
f8382011 1157 if (!find_article_filter($article_filters, 'catchup')) {
11b0dce2
AD
1158 $unread = 'true';
1159 $last_read_qpart = 'NULL';
1160 } else {
1161 $unread = 'false';
1162 $last_read_qpart = 'NOW()';
1163 }
dd7d3187 1164
f8382011 1165 if (find_article_filter($article_filters, 'mark')) {
dd7d3187
AD
1166 $marked = 'true';
1167 } else {
1168 $marked = 'false';
1169 }
a36c0dfe
AD
1170
1171 if (find_article_filter($article_filters, 'publish')) {
1172 $published = 'true';
1173 } else {
1174 $published = 'false';
1175 }
1176
11b0dce2
AD
1177 $result = db_query($link,
1178 "INSERT INTO ttrss_user_entries
a36c0dfe 1179 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
11b0dce2 1180 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
a36c0dfe 1181 $last_read_qpart, $marked, $published)");
ce53e200
AD
1182
1183 $result = db_query($link,
1184 "SELECT int_id FROM ttrss_user_entries WHERE
1185 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1186 feed_id = '$feed' LIMIT 1");
1187
1188 if (db_num_rows($result) == 1) {
1189 $entry_int_id = db_fetch_result($result, 0, "int_id");
1190 }
1191 } else {
1192 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1193 $entry_int_id = db_fetch_result($result, 0, "int_id");
11b0dce2 1194 }
ce53e200
AD
1195
1196 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1197 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1198 }
1199
6385315d
AD
1200 $post_needs_update = false;
1201
8d0ec6fd 1202 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
6385315d 1203 ($content_hash != $orig_content_hash)) {
7e43ad58 1204// print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
6385315d
AD
1205 $post_needs_update = true;
1206 }
1207
7e43ad58 1208 if (db_escape_string($orig_title) != $entry_title) {
6385315d
AD
1209 $post_needs_update = true;
1210 }
1211
11b0dce2
AD
1212 if ($orig_num_comments != $num_comments) {
1213 $post_needs_update = true;
1214 }
1215
6385315d
AD
1216// this doesn't seem to be very reliable
1217//
1218// if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1219// $post_needs_update = true;
1220// }
1221
1222 // if post needs update, update it and mark all user entries
1c73bc0c 1223 // linking to this post as updated
6385315d
AD
1224 if ($post_needs_update) {
1225
7ca91eb3
AD
1226 if (defined('DAEMON_EXTENDED_DEBUG')) {
1227 _debug("update_rss_feed: post $entry_guid needs update...");
1228 }
1229
6385315d
AD
1230// print "<!-- post $orig_title needs update : $post_needs_update -->";
1231
6385315d 1232 db_query($link, "UPDATE ttrss_entries
11b0dce2 1233 SET title = '$entry_title', content = '$entry_content',
7e43ad58 1234 content_hash = '$content_hash',
11b0dce2 1235 num_comments = '$num_comments'
6385315d
AD
1236 WHERE id = '$ref_id'");
1237
8d0ec6fd 1238 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
4919fb42
AD
1239 db_query($link, "UPDATE ttrss_user_entries
1240 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1241 } else {
1242 db_query($link, "UPDATE ttrss_user_entries
1243 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1244 }
6385315d
AD
1245
1246 }
4c193675
AD
1247 }
1248
44e241cb
AD
1249 db_query($link, "COMMIT");
1250
ce53e200
AD
1251 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1252 _debug("update_rss_feed: looking for enclosures...");
1253 }
1254
1255 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1256 print_r($enclosures);
1257 }
1258
1259 db_query($link, "BEGIN");
1260
1261 foreach ($enclosures as $enc) {
1262 $enc_url = db_escape_string($enc[0]);
1263 $enc_type = db_escape_string($enc[1]);
1264 $enc_dur = db_escape_string($enc[2]);
1265
1266 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1267 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1268
1269 if (db_num_rows($result) == 0) {
1270 db_query($link, "INSERT INTO ttrss_enclosures
1271 (content_url, content_type, title, duration, post_id) VALUES
1272 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1273 }
1274 }
1275
1276 db_query($link, "COMMIT");
1277
9fdf7824 1278 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb
AD
1279 _debug("update_rss_feed: looking for tags...");
1280 }
1281
eb36b4eb 1282 /* taaaags */
40e1a95b 1283 // <a href="..." rel="tag">Xorg</a>, //
eb36b4eb 1284
05732aa0 1285 $entry_tags = null;
eb36b4eb 1286
40e1a95b 1287 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
ee2c3050
AD
1288 $entry_content_unescaped, $entry_tags);
1289
fefef828
AD
1290/* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1291 print_r($entry_tags);
1292 print "<br/></p>"; */
eb36b4eb
AD
1293
1294 $entry_tags = $entry_tags[1];
1295
073ca0e6
AD
1296 # check for manual tags
1297
f8382011
AD
1298 $tag_filter = find_article_filter($article_filters, "tag");
1299
1300 if ($tag_filter) {
073ca0e6 1301
f8382011 1302 $manual_tags = trim_array(split(",", $tag_filter[1]));
073ca0e6 1303
f8382011 1304 foreach ($manual_tags as $tag) {
be832a1a
AD
1305 if (tag_is_valid($tag)) {
1306 array_push($entry_tags, $tag);
1307 }
1308 }
1309 }
1310
11c9ea1f
AD
1311 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1312 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
8fc70781 1313
fefef828
AD
1314 if ($additional_tags && is_array($additional_tags)) {
1315 foreach ($additional_tags as $tag) {
156a785d
AD
1316 if (tag_is_valid($tag) &&
1317 array_search($tag, $boring_tags) === FALSE) {
073ca0e6
AD
1318 array_push($entry_tags, $tag);
1319 }
1320 }
fefef828
AD
1321 }
1322
fcc95e24 1323// print "<p>TAGS: "; print_r($entry_tags); print "</p>";
073ca0e6 1324
9fdf7824
AD
1325 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1326 print_r($entry_tags);
1327 }
1328
eb36b4eb
AD
1329 if (count($entry_tags) > 0) {
1330
44e241cb
AD
1331 db_query($link, "BEGIN");
1332
fe99ab12 1333 foreach ($entry_tags as $tag) {
fefef828 1334
14b6c54b 1335 $tag = sanitize_tag($tag);
fefef828 1336 $tag = db_escape_string($tag);
31483fc1 1337
ef063748
AD
1338 if (!tag_is_valid($tag)) continue;
1339
fe99ab12
AD
1340 $result = db_query($link, "SELECT id FROM ttrss_tags
1341 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1342 owner_uid = '$owner_uid' LIMIT 1");
1343
1344 // print db_fetch_result($result, 0, "id");
1345
1346 if ($result && db_num_rows($result) == 0) {
1347
fe99ab12
AD
1348 db_query($link, "INSERT INTO ttrss_tags
1349 (owner_uid,tag_name,post_int_id)
1350 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1351 }
1352 }
ce53e200 1353
44e241cb 1354 db_query($link, "COMMIT");
05732aa0 1355 }
9fdf7824
AD
1356
1357 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1358 _debug("update_rss_feed: article processed");
1359 }
4c193675 1360 }
40d13c28 1361
ab3d0b99
AD
1362 db_query($link, "UPDATE ttrss_feeds
1363 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
eb36b4eb 1364
44e241cb 1365// db_query($link, "COMMIT");
dd8c76a9 1366
ab3d0b99 1367 } else {
ca872b9d 1368
16211ddb 1369 if ($use_simplepie) {
ca872b9d 1370 $error_msg = mb_substr($rss->error(), 0, 250);
9fdf7824 1371 } else {
ca872b9d 1372 $error_msg = mb_substr(magpie_error(), 0, 250);
9fdf7824 1373 }
ca872b9d
AD
1374
1375 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1376 _debug("update_rss_feed: error fetching feed: $error_msg");
1377 }
1378
1379 $error_msg = db_escape_string($error_msg);
1380
ab3d0b99 1381 db_query($link,
aa5f9f5f
AD
1382 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1383 last_updated = NOW() WHERE id = '$feed'");
40d13c28
AD
1384 }
1385
16211ddb 1386 if ($use_simplepie) {
ac6ebdb3
AD
1387 unset($rss);
1388 }
1389
9fdf7824 1390 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
34e420fb 1391 _debug("update_rss_feed: done");
219bd8fc
AD
1392 }
1393
40d13c28
AD
1394 }
1395
f175937c 1396 function print_select($id, $default, $values, $attributes = "") {
79f3553b 1397 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
1398 foreach ($values as $v) {
1399 if ($v == $default)
1400 $sel = " selected";
1401 else
1402 $sel = "";
1403
1404 print "<option$sel>$v</option>";
1405 }
1406 print "</select>";
1407 }
40d13c28 1408
79f3553b
AD
1409 function print_select_hash($id, $default, $values, $attributes = "") {
1410 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
1411 foreach (array_keys($values) as $v) {
1412 if ($v == $default)
1413 $sel = "selected";
1414 else
1415 $sel = "";
1416
1417 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1418 }
1419
1420 print "</select>";
1421 }
1422
f8382011 1423 function get_article_filters($filters, $title, $content, $link) {
240054f1 1424 $matches = array();
c2d9322b 1425
240054f1
AD
1426 if ($filters["title"]) {
1427 foreach ($filters["title"] as $filter) {
c2d9322b
AD
1428 $reg_exp = $filter["reg_exp"];
1429 $inverse = $filter["inverse"];
1430 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1431 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1432
240054f1
AD
1433 array_push($matches, array($filter["action"], $filter["action_param"]));
1434 }
1435 }
1436 }
1437
1438 if ($filters["content"]) {
1439 foreach ($filters["content"] as $filter) {
c2d9322b
AD
1440 $reg_exp = $filter["reg_exp"];
1441 $inverse = $filter["inverse"];
1442
1443 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1444 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1445
240054f1
AD
1446 array_push($matches, array($filter["action"], $filter["action_param"]));
1447 }
1448 }
1449 }
1450
1451 if ($filters["both"]) {
1452 foreach ($filters["both"] as $filter) {
1453 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1454 $inverse = $filter["inverse"];
1455
1456 if ($inverse) {
1457 if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
1458 array_push($matches, array($filter["action"], $filter["action_param"]));
1459 }
1460 } else {
1461 if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1462 array_push($matches, array($filter["action"], $filter["action_param"]));
1463 }
240054f1
AD
1464 }
1465 }
1466 }
1467
1468 if ($filters["link"]) {
1469 $reg_exp = $filter["reg_exp"];
1470 foreach ($filters["link"] as $filter) {
1471 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1472 $inverse = $filter["inverse"];
1473
1474 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1475 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1476
240054f1
AD
1477 array_push($matches, array($filter["action"], $filter["action_param"]));
1478 }
1479 }
1480 }
1481
1482 return $matches;
1483 }
1484
f8382011
AD
1485 function find_article_filter($filters, $filter_name) {
1486 foreach ($filters as $f) {
1487 if ($f[0] == $filter_name) {
1488 return $f;
1489 };
1490 }
1491 return false;
1492 }
1493
9323147e 1494 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
fb1fb4ab 1495 $rtl_content = false, $last_updated = false, $last_error = false) {
254e0e4b
AD
1496
1497 if (file_exists($icon_file) && filesize($icon_file) > 0) {
023fe037 1498 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
254e0e4b 1499 } else {
023fe037 1500 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
254e0e4b
AD
1501 }
1502
9323147e
AD
1503 if ($rtl_content) {
1504 $rtl_tag = "dir=\"rtl\"";
1505 } else {
1506 $rtl_tag = "dir=\"ltr\"";
1507 }
1508
78d5212c
AD
1509 $error_notify_msg = "";
1510
fb1fb4ab
AD
1511 if ($last_error) {
1512 $link_title = "Error: $last_error ($last_updated)";
78d5212c 1513 $error_notify_msg = "(Error)";
ad780e9c 1514 } else if ($last_updated) {
fb1fb4ab
AD
1515 $link_title = "Updated: $last_updated";
1516 }
1517
7210613a 1518 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
c50e2b30 1519 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
254e0e4b
AD
1520
1521 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
b619ff15 1522 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
254e0e4b
AD
1523 print "$feed_icon";
1524 }
1525
9323147e 1526 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
254e0e4b
AD
1527
1528 if ($unread != 0) {
1529 $fctr_class = "";
1530 } else {
1531 $fctr_class = "class=\"invisible\"";
1532 }
1533
9323147e 1534 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
254e0e4b 1535 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
78d5212c
AD
1536
1537 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1538 print "<div class=\"feedExtInfo\">
1539 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1540 }
1541
254e0e4b
AD
1542 print "</li>";
1543
1544 }
1545
406d9489
AD
1546 function getmicrotime() {
1547 list($usec, $sec) = explode(" ",microtime());
1548 return ((float)$usec + (float)$sec);
1549 }
1550
f541eb78 1551 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719
AD
1552 foreach ($values as $v) {
1553
1554 if ($v == $default)
5da169d9 1555 $sel = "checked";
77e96719 1556 else
5da169d9
AD
1557 $sel = "";
1558
f541eb78 1559 if ($v == $true_is) {
5da169d9
AD
1560 $sel .= " value=\"1\"";
1561 } else {
1562 $sel .= " value=\"0\"";
1563 }
77e96719 1564
69654950
AD
1565 print "<input class=\"noborder\"
1566 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
1567
1568 }
1569 }
1570
ff485f1d
AD
1571 function initialize_user_prefs($link, $uid) {
1572
1573 $uid = db_escape_string($uid);
1574
1575 db_query($link, "BEGIN");
1576
1577 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1578
1579 $u_result = db_query($link, "SELECT pref_name
1580 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1581
1582 $active_prefs = array();
1583
1584 while ($line = db_fetch_assoc($u_result)) {
1585 array_push($active_prefs, $line["pref_name"]);
1586 }
1587
1588 while ($line = db_fetch_assoc($result)) {
1589 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1590// print "adding " . $line["pref_name"] . "<br>";
1591
1592 db_query($link, "INSERT INTO ttrss_user_prefs
1593 (owner_uid,pref_name,value) VALUES
1594 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1595
1596 }
1597 }
1598
1599 db_query($link, "COMMIT");
1600
1601 }
956c7629
AD
1602
1603 function lookup_user_id($link, $user) {
1604
1605 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1606 login = '$login'");
1607
1608 if (db_num_rows($result) == 1) {
1609 return db_fetch_result($result, 0, "id");
1610 } else {
1611 return false;
1612 }
1613 }
1614
18664970
AD
1615 function http_authenticate_user($link) {
1616
4bc64807
AD
1617 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1618
18664970
AD
1619 if (!$_SERVER["PHP_AUTH_USER"]) {
1620
1621 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1622 header('HTTP/1.0 401 Unauthorized');
1623 exit;
1624
1625 } else {
1626 $auth_result = authenticate_user($link,
1627 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1628
1629 if (!$auth_result) {
1630 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1631 header('HTTP/1.0 401 Unauthorized');
1632 exit;
1633 }
1634 }
1635
1636 return true;
1637 }
1638
461766f3 1639 function authenticate_user($link, $login, $password, $force_auth = false) {
c8437f35 1640
131b01b3 1641 if (!SINGLE_USER_MODE) {
c8437f35 1642
1a9f4d3c
AD
1643 $pwd_hash1 = encrypt_password($password);
1644 $pwd_hash2 = encrypt_password($password, $login);
461766f3 1645
66917e70
AD
1646 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1647 && $_SERVER["REMOTE_USER"]) {
1648
1649 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1650
461766f3
AD
1651 $query = "SELECT id,login,access_level
1652 FROM ttrss_users WHERE
66917e70
AD
1653 login = '$login'";
1654
461766f3 1655 } else {
1a9f4d3c 1656 $query = "SELECT id,login,access_level,pwd_hash
461766f3 1657 FROM ttrss_users WHERE
1a9f4d3c
AD
1658 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1659 pwd_hash = '$pwd_hash2')";
461766f3
AD
1660 }
1661
1662 $result = db_query($link, $query);
131b01b3
AD
1663
1664 if (db_num_rows($result) == 1) {
1665 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1666 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1667 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1668
1669 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1670 $_SESSION["uid"]);
1671
1672 $user_theme = get_user_theme_path($link);
1673
1674 $_SESSION["theme"] = $user_theme;
1675 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 1676 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
131b01b3
AD
1677
1678 initialize_user_prefs($link, $_SESSION["uid"]);
1679
1680 return true;
1681 }
1682
1683 return false;
503eb349 1684
131b01b3 1685 } else {
503eb349 1686
131b01b3
AD
1687 $_SESSION["uid"] = 1;
1688 $_SESSION["name"] = "admin";
f557cd78 1689
0bbba72d
AD
1690 $user_theme = get_user_theme_path($link);
1691
1692 $_SESSION["theme"] = $user_theme;
1693 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1694
1695 initialize_user_prefs($link, $_SESSION["uid"]);
1696
c8437f35
AD
1697 return true;
1698 }
c8437f35
AD
1699 }
1700
e6cb77a0
AD
1701 function make_password($length = 8) {
1702
1703 $password = "";
798f722b
AD
1704 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1705
1706 $i = 0;
e6cb77a0
AD
1707
1708 while ($i < $length) {
1709 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1710
1711 if (!strstr($password, $char)) {
1712 $password .= $char;
1713 $i++;
1714 }
1715 }
1716 return $password;
1717 }
1718
1719 // this is called after user is created to initialize default feeds, labels
1720 // or whatever else
1721
1722 // user preferences are checked on every login, not here
1723
1724 function initialize_user($link, $uid) {
1725
1726 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1727 values ('$uid','unread = true', 'Unread articles')");
1728
1729 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1730 values ('$uid','last_read is null and unread = false', 'Updated articles')");
e603a0fa 1731
e6cb77a0 1732 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 1733 values ('$uid', 'Tiny Tiny RSS: New Releases',
628fcd2c 1734 'http://tt-rss.spb.ru/releases.rss')");
3b0feb9b 1735
cd2cd415
AD
1736 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1737 values ('$uid', 'Tiny Tiny RSS: Forum',
1738 'http://tt-rss.spb.ru/forum/rss.php')");
3b0feb9b 1739 }
e6cb77a0 1740
b8aa49bc 1741 function logout_user() {
5ccc1cf5
AD
1742 session_destroy();
1743 if (isset($_COOKIE[session_name()])) {
1744 setcookie(session_name(), '', time()-42000, '/');
1745 }
b8aa49bc
AD
1746 }
1747
75836f33 1748 function get_script_urlpath() {
87a79fa4 1749 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
75836f33
AD
1750 }
1751
916f788a 1752 function validate_session($link) {
741edab2
AD
1753 if (SINGLE_USER_MODE) {
1754 return true;
1755 }
1756
a2e9b457 1757 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
916f788a
AD
1758 if ($_SESSION["ip_address"]) {
1759 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
7f0acba7 1760 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
916f788a
AD
1761 return false;
1762 }
1763 }
1764 }
d620cfe7 1765
e6684130
AD
1766 if ($_SESSION["uid"]) {
1767
1768 $result = db_query($link,
1769 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1770
1771 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1772
1773 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1774 return false;
1775 }
1776 }
1777
a885f0ec 1778/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 1779
8e849206 1780 //print_r($_SESSION);
d620cfe7
AD
1781
1782 if (time() > $_SESSION["cookie_lifetime"]) {
1783 return false;
1784 }
a885f0ec
AD
1785 } */
1786
916f788a
AD
1787 return true;
1788 }
1789
793185a9 1790 function login_sequence($link, $mobile = false) {
b8aa49bc 1791 if (!SINGLE_USER_MODE) {
75836f33 1792
461766f3
AD
1793 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1794 $swu = db_escape_string($_REQUEST["swu"]);
1795 if ($swu) {
1796 $_SESSION["prefs_cache"] = false;
1797 return authenticate_user($link, $swu, null, true);
1798 }
1799 }
1800
7f0acba7 1801 $login_action = $_POST["login_action"];
a885f0ec 1802
01a87dff 1803 # try to authenticate user if called from login form
7f0acba7 1804 if ($login_action == "do_login") {
01a87dff
AD
1805 $login = $_POST["login"];
1806 $password = $_POST["password"];
d620cfe7 1807 $remember_me = $_POST["remember_me"];
f557cd78 1808
01a87dff
AD
1809 if (authenticate_user($link, $login, $password)) {
1810 $_POST["password"] = "";
d620cfe7 1811
f8c612d4
AD
1812 $_SESSION["language"] = $_POST["language"];
1813
d620cfe7
AD
1814 header("Location: " . $_SERVER["REQUEST_URI"]);
1815 exit;
1816
01a87dff 1817 return;
7f0acba7
AD
1818 } else {
1819 $_SESSION["login_error_msg"] = "Incorrect username or password";
01a87dff
AD
1820 }
1821 }
1822
1df0f48b
AD
1823// print session_id();
1824// print_r($_SESSION);
7f0acba7
AD
1825
1826 if (!$_SESSION["uid"] || !validate_session($link)) {
793185a9 1827 render_login_form($link, $mobile);
01a87dff 1828 exit;
d3687e7a
AD
1829 } else {
1830 /* bump login timestamp */
1831 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1832 $_SESSION["uid"]);
019bd5a9 1833
d54780bc 1834 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
019bd5a9
AD
1835 setcookie("ttrss_lang", $_SESSION["language"],
1836 time() + SESSION_COOKIE_LIFETIME);
1837 }
b8aa49bc 1838 }
d620cfe7 1839
b8aa49bc 1840 } else {
0bbba72d 1841 return authenticate_user($link, "admin", null);
b8aa49bc
AD
1842 }
1843 }
3547842a
AD
1844
1845 function truncate_string($str, $max_len) {
12db369c 1846 if (mb_strlen($str, "utf-8") > $max_len - 3) {
66a251f9 1847 return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
3547842a
AD
1848 } else {
1849 return $str;
1850 }
1851 }
54a60e1a
AD
1852
1853 function get_user_theme_path($link) {
798f722b
AD
1854 $result = db_query($link, "SELECT theme_path
1855 FROM
1856 ttrss_themes,ttrss_users
1857 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
54a60e1a
AD
1858 if (db_num_rows($result) != 0) {
1859 return db_fetch_result($result, 0, "theme_path");
1860 } else {
1861 return null;
1862 }
1863 }
be773442
AD
1864
1865 function smart_date_time($timestamp) {
1866 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1867 return date("G:i", $timestamp);
f26450f1 1868 } else if (date("Y", $timestamp) == date("Y")) {
be773442
AD
1869 return date("M d, G:i", $timestamp);
1870 } else {
7d7e0509 1871 return date("Y/m/d, G:i", $timestamp);
be773442
AD
1872 }
1873 }
1874
1875 function smart_date($timestamp) {
1876 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1877 return "Today";
f26450f1 1878 } else if (date("Y", $timestamp) == date("Y")) {
be773442
AD
1879 return date("D m", $timestamp);
1880 } else {
b02111c2 1881 return date("Y/m/d", $timestamp);
be773442
AD
1882 }
1883 }
a654a595
AD
1884
1885 function sql_bool_to_string($s) {
1886 if ($s == "t" || $s == "1") {
1887 return "true";
1888 } else {
1889 return "false";
1890 }
1891 }
e3c99f3b
AD
1892
1893 function sql_bool_to_bool($s) {
1894 if ($s == "t" || $s == "1") {
1895 return true;
1896 } else {
1897 return false;
1898 }
1899 }
0ea4fb50 1900
e3c99f3b 1901
0ea4fb50
AD
1902 function toggleEvenOdd($a) {
1903 if ($a == "even")
1904 return "odd";
1905 else
1906 return "even";
1907 }
6043fb7e
AD
1908
1909 function sanity_check($link) {
9cbca41f 1910
aec3ce39
AD
1911 error_reporting(0);
1912
6043fb7e
AD
1913 $error_code = 0;
1914 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1915 $schema_version = db_fetch_result($result, 0, "schema_version");
1916
1917 if ($schema_version != SCHEMA_VERSION) {
1918 $error_code = 5;
1919 }
1920
aec3ce39
AD
1921 if (DB_TYPE == "mysql") {
1922 $result = db_query($link, "SELECT true", false);
1923 if (db_num_rows($result) != 1) {
1924 $error_code = 10;
1925 }
1926 }
1927
1928 error_reporting (DEFAULT_ERROR_LEVEL);
1929
6043fb7e 1930 if ($error_code != 0) {
aec3ce39 1931 print_error_xml($error_code);
6043fb7e
AD
1932 return false;
1933 } else {
1934 return true;
4220d6b0 1935 }
6043fb7e
AD
1936 }
1937
27981ca3 1938 function file_is_locked($filename) {
31a6d42d
AD
1939 if (function_exists('flock')) {
1940 error_reporting(0);
cfa43e02 1941 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
1942 error_reporting(DEFAULT_ERROR_LEVEL);
1943 if ($fp) {
1944 if (flock($fp, LOCK_EX | LOCK_NB)) {
1945 flock($fp, LOCK_UN);
1946 fclose($fp);
1947 return false;
1948 }
27981ca3 1949 fclose($fp);
31a6d42d 1950 return true;
27981ca3 1951 }
27981ca3
AD
1952 }
1953 return false;
1954 }
1955
fcb4c0c9 1956 function make_lockfile($filename) {
cfa43e02 1957 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9
AD
1958
1959 if (flock($fp, LOCK_EX | LOCK_NB)) {
1960 return $fp;
1961 } else {
1962 return false;
1963 }
1964 }
1965
bf7fcde8 1966 function make_stampfile($filename) {
cfa43e02 1967 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 1968
8e00ae9b 1969 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 1970 fwrite($fp, time() . "\n");
8e00ae9b 1971 flock($fp, LOCK_UN);
bf7fcde8
AD
1972 fclose($fp);
1973 return true;
1974 } else {
1975 return false;
1976 }
1977 }
1978
8e00ae9b
AD
1979 function read_stampfile($filename) {
1980
1981 error_reporting(0);
cfa43e02 1982 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
8e00ae9b
AD
1983 error_reporting (DEFAULT_ERROR_LEVEL);
1984
1985 if (flock($fp, LOCK_EX)) {
1986 $stamp = fgets($fp);
1987 flock($fp, LOCK_UN);
1988 fclose($fp);
1989 return $stamp;
1990 } else {
1991 return false;
1992 }
1993 }
bf7fcde8 1994
894ebcf5
AD
1995 function sql_random_function() {
1996 if (DB_TYPE == "mysql") {
1997 return "RAND()";
1998 } else {
1999 return "RANDOM()";
2000 }
2001 }
2002
23aa0d16 2003 function catchup_feed($link, $feed, $cat_view) {
88040f57
AD
2004
2005 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
23aa0d16
AD
2006
2007 if ($cat_view) {
2008
2009 if ($feed > 0) {
2010 $cat_qpart = "cat_id = '$feed'";
2011 } else {
2012 $cat_qpart = "cat_id IS NULL";
2013 }
2014
2015 $tmp_result = db_query($link, "SELECT id
2016 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2017 $_SESSION["uid"]);
2018
2019 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2020
2021 $tmp_feed = $tmp_line["id"];
2022
2023 db_query($link, "UPDATE ttrss_user_entries
2024 SET unread = false,last_read = NOW()
2025 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2026 }
2027
2028 } else if ($feed > 0) {
2029
2030 $tmp_result = db_query($link, "SELECT id
2031 FROM ttrss_feeds WHERE parent_feed = '$feed'
2032 ORDER BY cat_id,title");
2033
2034 $parent_ids = array();
2035
2036 if (db_num_rows($tmp_result) > 0) {
2037 while ($p = db_fetch_assoc($tmp_result)) {
2038 array_push($parent_ids, "feed_id = " . $p["id"]);
2039 }
2040
2041 $children_qpart = implode(" OR ", $parent_ids);
2042
2043 db_query($link, "UPDATE ttrss_user_entries
2044 SET unread = false,last_read = NOW()
2045 WHERE (feed_id = '$feed' OR $children_qpart)
2046 AND owner_uid = " . $_SESSION["uid"]);
2047
2048 } else {
2049 db_query($link, "UPDATE ttrss_user_entries
2050 SET unread = false,last_read = NOW()
2051 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2052 }
2053
2054 } else if ($feed < 0 && $feed > -10) { // special, like starred
2055
2056 if ($feed == -1) {
2057 db_query($link, "UPDATE ttrss_user_entries
2058 SET unread = false,last_read = NOW()
2059 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2060 }
e4f4b46f
AD
2061
2062 if ($feed == -2) {
2063 db_query($link, "UPDATE ttrss_user_entries
2064 SET unread = false,last_read = NOW()
2065 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2066 }
2067
2d24f032
AD
2068 if ($feed == -3) {
2069
c1d7e6c3
AD
2070 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2071
2d24f032 2072 if (DB_TYPE == "pgsql") {
1f3335dc 2073 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 2074 } else {
1f3335dc 2075 $match_part = "date_entered > DATE_SUB(NOW(),
c1d7e6c3 2076 INTERVAL $intl HOUR) ";
2d24f032
AD
2077 }
2078
1f3335dc
AD
2079 $result = db_query($link, "SELECT id FROM ttrss_entries,
2080 ttrss_user_entries WHERE $match_part AND
2081 unread = true AND
2082 ttrss_user_entries.ref_id = ttrss_entries.id AND
2083 owner_uid = ".$_SESSION["uid"]);
2084
2085 $affected_ids = array();
2086
2087 while ($line = db_fetch_assoc($result)) {
2088 array_push($affected_ids, $line["id"]);
2089 }
2090
2091 catchupArticlesById($link, $affected_ids, 0);
2d24f032
AD
2092 }
2093
23aa0d16
AD
2094 } else if ($feed < -10) { // label
2095
2096 // TODO make this more efficient
2097
2098 $label_id = -$feed - 11;
2099
2100 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2101 WHERE id = '$label_id'");
2102
2103 if ($tmp_result) {
2104 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2105
2106 db_query($link, "BEGIN");
2107
2108 $tmp2_result = db_query($link,
2109 "SELECT
2110 int_id
2111 FROM
88040f57 2112 ttrss_user_entries,ttrss_entries,ttrss_feeds
23aa0d16 2113 WHERE
88040f57
AD
2114 ref_id = ttrss_entries.id AND
2115 ttrss_user_entries.feed_id = ttrss_feeds.id AND
23aa0d16 2116 $sql_exp AND
88040f57 2117 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
23aa0d16
AD
2118
2119 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2120 db_query($link, "UPDATE
2121 ttrss_user_entries
2122 SET
2123 unread = false, last_read = NOW()
2124 WHERE
2125 int_id = " . $tmp_line["int_id"]);
2126 }
2127
2128 db_query($link, "COMMIT");
2129
2130/* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2131 SET unread = false,last_read = NOW()
2132 WHERE $sql_exp
2133 AND ref_id = id
2134 AND owner_uid = ".$_SESSION["uid"]); */
2135 }
2136 }
2137 } else { // tag
2138 db_query($link, "BEGIN");
2139
2140 $tag_name = db_escape_string($feed);
2141
2142 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2143 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2144
2145 while ($line = db_fetch_assoc($result)) {
2146 db_query($link, "UPDATE ttrss_user_entries SET
2147 unread = false, last_read = NOW()
2148 WHERE int_id = " . $line["post_int_id"]);
2149 }
2150 db_query($link, "COMMIT");
2151 }
2152 }
2153
35bf080c 2154 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
23aa0d16
AD
2155 if ($cat_view) {
2156
2157 if ($feed > 0) {
2158 $cat_qpart = "cat_id = '$feed'";
2159 } else {
2160 $cat_qpart = "cat_id IS NULL";
2161 }
2162
571dad82 2163 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
23aa0d16
AD
2164 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2165
2166 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2167 $feed_url = $tmp_line["feed_url"];
571dad82 2168 $feed_id = $tmp_line["id"];
35bf080c 2169 update_rss_feed($link, $feed_url, $feed_id, $force_update);
23aa0d16
AD
2170 }
2171
2172 } else {
2173 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2174 WHERE id = '$feed'");
2175 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
35bf080c 2176 update_rss_feed($link, $feed_url, $feed, $force_update);
23aa0d16
AD
2177 }
2178 }
a9cb1f83 2179
4ffa126e 2180 function getAllCounters($link, $omode = "flc", $active_feed = false) {
cf4d339c 2181/* getLabelCounters($link);
a9cb1f83
AD
2182 getFeedCounters($link);
2183 getTagCounters($link);
2184 getGlobalCounters($link);
2185 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2186 getCategoryCounters($link);
cf4d339c
AD
2187 } */
2188
2bc2147f 2189 if (!$omode) $omode = "flc";
cf4d339c
AD
2190
2191 getGlobalCounters($link);
2192
2193 if (strchr($omode, "l")) getLabelCounters($link);
4ffa126e 2194 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
cf4d339c
AD
2195 if (strchr($omode, "t")) getTagCounters($link);
2196 if (strchr($omode, "c")) {
2197 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2198 getCategoryCounters($link);
2199 }
a9cb1f83
AD
2200 }
2201 }
2202
2203 function getCategoryCounters($link) {
bba7c4bf
AD
2204 # two special categories are -1 and -2 (all virtuals; all labels)
2205
2206 $ctr = getCategoryUnread($link, -1);
2207
2208 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2209
2210 $ctr = getCategoryUnread($link, -2);
2211
2212 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2213
14073c0a
AD
2214 $age_qpart = getMaxAgeSubquery();
2215
a9cb1f83 2216 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
14073c0a
AD
2217 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2218 AND id = ref_id AND $age_qpart
a9cb1f83
AD
2219 AND unread = true)) AS unread FROM ttrss_feeds
2220 WHERE
cfb02131 2221 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
a9cb1f83
AD
2222
2223 while ($line = db_fetch_assoc($result)) {
2224 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2225 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2226 $line["unread"]."\"/>";
2227 }
2228 }
2229
f295c368
AD
2230 function getCategoryUnread($link, $cat) {
2231
bba7c4bf 2232 if ($cat >= 0) {
18664970 2233
bba7c4bf
AD
2234 if ($cat != 0) {
2235 $cat_query = "cat_id = '$cat'";
2236 } else {
2237 $cat_query = "cat_id IS NULL";
2238 }
14073c0a
AD
2239
2240 $age_qpart = getMaxAgeSubquery();
2241
bba7c4bf
AD
2242 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2243 AND hidden = false
2244 AND owner_uid = " . $_SESSION["uid"]);
2245
2246 $cat_feeds = array();
2247 while ($line = db_fetch_assoc($result)) {
2248 array_push($cat_feeds, "feed_id = " . $line["id"]);
2249 }
2250
2251 if (count($cat_feeds) == 0) return 0;
2252
2253 $match_part = implode(" OR ", $cat_feeds);
2254
2255 $result = db_query($link, "SELECT COUNT(int_id) AS unread
14073c0a
AD
2256 FROM ttrss_user_entries,ttrss_entries
2257 WHERE unread = true AND ($match_part) AND id = ref_id
2258 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
bba7c4bf
AD
2259
2260 $unread = 0;
2261
2262 # this needs to be rewritten
2263 while ($line = db_fetch_assoc($result)) {
2264 $unread += $line["unread"];
2265 }
2266
2267 return $unread;
2268 } else if ($cat == -1) {
2d24f032 2269 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
bba7c4bf 2270 } else if ($cat == -2) {
f295c368 2271
bba7c4bf
AD
2272 $rv = getLabelCounters($link, false, true);
2273 $ctr = 0;
f295c368 2274
bba7c4bf
AD
2275 foreach (array_keys($rv) as $k) {
2276 if ($k < -10) {
2277 $ctr += $rv[$k]["counter"];
2278 }
2279 }
f295c368 2280
bba7c4bf 2281 return $ctr;
f295c368 2282 }
f295c368
AD
2283 }
2284
14073c0a
AD
2285 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2286 if (DB_TYPE == "pgsql") {
2287 return "ttrss_entries.date_entered >
2288 NOW() - INTERVAL '$days days'";
2289 } else {
2290 return "ttrss_entries.date_entered >
2291 DATE_SUB(NOW(), INTERVAL $days DAY)";
2292 }
2293 }
2294
f295c368 2295 function getFeedUnread($link, $feed, $is_cat = false) {
a9cb1f83 2296 $n_feed = sprintf("%d", $feed);
f295c368 2297
14073c0a
AD
2298 $age_qpart = getMaxAgeSubquery();
2299
f295c368 2300 if ($is_cat) {
831ff047 2301 return getCategoryUnread($link, $n_feed);
f295c368 2302 } else if ($n_feed == -1) {
a9cb1f83 2303 $match_part = "marked = true";
e4f4b46f
AD
2304 } else if ($n_feed == -2) {
2305 $match_part = "published = true";
2d24f032
AD
2306 } else if ($n_feed == -3) {
2307 $match_part = "unread = true";
2308
c1d7e6c3
AD
2309 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2310
2d24f032 2311 if (DB_TYPE == "pgsql") {
c1d7e6c3 2312 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 2313 } else {
c1d7e6c3 2314 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
2315 }
2316
4919fb42 2317 } else if ($n_feed > 0) {
831ff047 2318
e8b8485f
AD
2319 $result = db_query($link, "SELECT id FROM ttrss_feeds
2320 WHERE parent_feed = '$n_feed'
318260cc 2321 AND hidden = false
4919fb42 2322 AND owner_uid = " . $_SESSION["uid"]);
831ff047
AD
2323
2324 if (db_num_rows($result) > 0) {
4919fb42 2325
831ff047
AD
2326 $linked_feeds = array();
2327 while ($line = db_fetch_assoc($result)) {
2328 array_push($linked_feeds, "feed_id = " . $line["id"]);
2329 }
e8b8485f
AD
2330
2331 array_push($linked_feeds, "feed_id = $n_feed");
831ff047
AD
2332
2333 $match_part = implode(" OR ", $linked_feeds);
2334
4919fb42 2335 $result = db_query($link, "SELECT COUNT(int_id) AS unread
14073c0a
AD
2336 FROM ttrss_user_entries,ttrss_entries
2337 WHERE unread = true AND
2338 ttrss_user_entries.ref_id = ttrss_entries.id AND
2339 $age_qpart AND
2340 ($match_part) AND
2341 owner_uid = " . $_SESSION["uid"]);
4919fb42
AD
2342
2343 $unread = 0;
2344
2345 # this needs to be rewritten
2346 while ($line = db_fetch_assoc($result)) {
2347 $unread += $line["unread"];
2348 }
2349
2350 return $unread;
2351
831ff047
AD
2352 } else {
2353 $match_part = "feed_id = '$n_feed'";
2354 }
a9cb1f83 2355 } else if ($feed < -10) {
318260cc 2356
a9cb1f83
AD
2357 $label_id = -$feed - 11;
2358
2359 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2360 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2361
2362 $match_part = db_fetch_result($result, 0, "sql_exp");
2363 }
2364
2365 if ($match_part) {
2366
2367 $result = db_query($link, "SELECT count(int_id) AS unread
88040f57
AD
2368 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2369 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2370 ttrss_user_entries.ref_id = ttrss_entries.id AND
cfb02131 2371 ttrss_feeds.hidden = false AND
14073c0a 2372 $age_qpart AND
88040f57 2373 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
2374
2375 } else {
2376
2377 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
14073c0a 2378 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
828f22b7 2379 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
14073c0a 2380 AND unread = true AND $age_qpart AND
a9cb1f83
AD
2381 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2382 }
2383
2384 $unread = db_fetch_result($result, 0, "unread");
cfb02131 2385
a9cb1f83
AD
2386 return $unread;
2387 }
2388
2389 /* FIXME this needs reworking */
2390
f3acc32e
AD
2391 function getGlobalUnread($link, $user_id = false) {
2392
2393 if (!$user_id) {
2394 $user_id = $_SESSION["uid"];
2395 }
2396
14073c0a
AD
2397 $age_qpart = getMaxAgeSubquery();
2398
3831db41 2399 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
a9cb1f83 2400 WHERE unread = true AND
3831db41 2401 ttrss_user_entries.feed_id = ttrss_feeds.id AND
a9cb1f83 2402 ttrss_user_entries.ref_id = ttrss_entries.id AND
3831db41 2403 hidden = false AND
14073c0a 2404 $age_qpart AND
f3acc32e 2405 ttrss_user_entries.owner_uid = '$user_id'");
a9cb1f83
AD
2406 $c_id = db_fetch_result($result, 0, "c_id");
2407 return $c_id;
2408 }
2409
2410 function getGlobalCounters($link, $global_unread = -1) {
2411 if ($global_unread == -1) {
2412 $global_unread = getGlobalUnread($link);
2413 }
7bf7e4d3
AD
2414 print "<counter type=\"global\" id='global-unread'
2415 counter='$global_unread'/>";
2416
2417 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2418 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2419
2420 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2421
2422 print "<counter type=\"global\" id='subscribed-feeds'
2423 counter='$subscribed_feeds'/>";
2424
a9cb1f83
AD
2425 }
2426
2427 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
2428
2429 if ($smart_mode) {
2430 if (!$_SESSION["tctr_last_value"]) {
2431 $_SESSION["tctr_last_value"] = array();
2432 }
2433 }
2434
2435 $old_counters = $_SESSION["tctr_last_value"];
2436
2437 $tctrs_modified = false;
2438
2439/* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2440 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2441 ttrss_user_entries.ref_id = ttrss_entries.id AND
2442 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2443 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2444 UNION
2445 select tag_name,0 as count FROM ttrss_tags
2446 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2447
14073c0a
AD
2448 $age_qpart = getMaxAgeSubquery();
2449
a9cb1f83 2450 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
14073c0a
AD
2451 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2452 AND ref_id = id AND $age_qpart
a9cb1f83 2453 AND unread = true)) AS count FROM ttrss_tags
ef1ac7c7
AD
2454 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2455 ORDER BY count DESC LIMIT 55");
a9cb1f83
AD
2456
2457 $tags = array();
2458
2459 while ($line = db_fetch_assoc($result)) {
2460 $tags[$line["tag_name"]] += $line["count"];
2461 }
2462
2463 foreach (array_keys($tags) as $tag) {
2464 $unread = $tags[$tag];
2465
2466 $tag = htmlspecialchars($tag);
2467
2468 if (!$smart_mode || $old_counters[$tag] != $unread) {
2469 $old_counters[$tag] = $unread;
2470 $tctrs_modified = true;
2471 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2472 }
2473
2474 }
2475
2476 if ($smart_mode && $tctrs_modified) {
2477 $_SESSION["tctr_last_value"] = $old_counters;
2478 }
2479
2480 }
2481
ef393de7 2482 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
a9cb1f83 2483
14073c0a
AD
2484 $age_qpart = getMaxAgeSubquery();
2485
a9cb1f83
AD
2486 if ($smart_mode) {
2487 if (!$_SESSION["lctr_last_value"]) {
2488 $_SESSION["lctr_last_value"] = array();
2489 }
2490 }
2491
ef393de7
AD
2492 $ret_arr = array();
2493
a9cb1f83
AD
2494 $old_counters = $_SESSION["lctr_last_value"];
2495 $lctrs_modified = false;
2496
2d24f032 2497 $count = getFeedUnread($link, -1);
a9cb1f83 2498
ef393de7
AD
2499 if (!$ret_mode) {
2500 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2501 } else {
2502 $ret_arr["-1"]["counter"] = $count;
bba7c4bf 2503 $ret_arr["-1"]["description"] = __("Starred articles");
ef393de7 2504 }
a9cb1f83 2505
2d24f032 2506 $count = getFeedUnread($link, -2);
e4f4b46f
AD
2507
2508 if (!$ret_mode) {
2509 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2510 } else {
2511 $ret_arr["-2"]["counter"] = $count;
bba7c4bf 2512 $ret_arr["-2"]["description"] = __("Published articles");
e4f4b46f
AD
2513 }
2514
2d24f032
AD
2515 $count = getFeedUnread($link, -3);
2516
2517 if (!$ret_mode) {
2518 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2519 } else {
2520 $ret_arr["-3"]["counter"] = $count;
2521 $ret_arr["-3"]["description"] = __("Fresh articles");
2522 }
2523
e4f4b46f 2524
a9cb1f83
AD
2525 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2526 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2527
2528 while ($line = db_fetch_assoc($result)) {
2529
2530 $id = -$line["id"] - 11;
2531
ef393de7
AD
2532 $label_name = $line["description"];
2533
a9cb1f83
AD
2534 error_reporting (0);
2535
88040f57 2536 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
a9cb1f83 2537 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
cfb02131 2538 ttrss_feeds.hidden = false AND
14073c0a 2539 $age_qpart AND
88040f57 2540 ttrss_user_entries.feed_id = ttrss_feeds.id AND
a9cb1f83 2541 ttrss_user_entries.ref_id = ttrss_entries.id AND
88040f57 2542 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
a9cb1f83
AD
2543
2544 $count = db_fetch_result($tmp_result, 0, "count");
2545
2546 if (!$smart_mode || $old_counters[$id] != $count) {
2547 $old_counters[$id] = $count;
2548 $lctrs_modified = true;
ef393de7
AD
2549 if (!$ret_mode) {
2550 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2551 } else {
2552 $ret_arr[$id]["counter"] = $count;
2553 $ret_arr[$id]["description"] = $label_name;
2554 }
a9cb1f83
AD
2555 }
2556
2557 error_reporting (DEFAULT_ERROR_LEVEL);
2558 }
2559
2560 if ($smart_mode && $lctrs_modified) {
2561 $_SESSION["lctr_last_value"] = $old_counters;
2562 }
ef393de7
AD
2563
2564 return $ret_arr;
a9cb1f83
AD
2565 }
2566
2567/* function getFeedCounter($link, $id) {
2568
2569 $result = db_query($link, "SELECT
2570 count(id) as count,last_error
2571 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2572 WHERE feed_id = '$id' AND unread = true
2573 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2574 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2575
2576 $count = db_fetch_result($result, 0, "count");
2577 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2578
2579 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2580 } */
2581
4ffa126e 2582 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
a9cb1f83 2583
14073c0a
AD
2584 $age_qpart = getMaxAgeSubquery();
2585
a9cb1f83
AD
2586 if ($smart_mode) {
2587 if (!$_SESSION["fctr_last_value"]) {
2588 $_SESSION["fctr_last_value"] = array();
2589 }
2590 }
2591
2592 $old_counters = $_SESSION["fctr_last_value"];
2593
1b1b8a7b 2594/* $result = db_query($link, "SELECT id,last_error,parent_feed,
fb1fb4ab 2595 SUBSTRING(last_updated,1,19) AS last_updated,
a9cb1f83
AD
2596 (SELECT count(id)
2597 FROM ttrss_entries,ttrss_user_entries
2598 WHERE feed_id = ttrss_feeds.id AND
2599 ttrss_user_entries.ref_id = ttrss_entries.id
2600 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2601 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1b1b8a7b
AD
2602 AND parent_feed IS NULL"); */
2603
14073c0a
AD
2604 $query = "SELECT ttrss_feeds.id,
2605 ttrss_feeds.title,
1b1b8a7b
AD
2606 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2607 last_error,
bc60fda3 2608 COUNT(ttrss_entries.id) AS count
1b1b8a7b
AD
2609 FROM ttrss_feeds
2610 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2611 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2612 AND ttrss_user_entries.unread = true)
14073c0a
AD
2613 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2614 $age_qpart)
2615 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1b1b8a7b 2616 AND parent_feed IS NULL
14073c0a 2617 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
a9cb1f83 2618
14073c0a 2619 $result = db_query($link, $query);
a9cb1f83
AD
2620 $fctrs_modified = false;
2621
fb1fb4ab
AD
2622 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2623
a9cb1f83
AD
2624 while ($line = db_fetch_assoc($result)) {
2625
2626 $id = $line["id"];
2627 $count = $line["count"];
2628 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab
AD
2629
2630 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2631 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2632 } else {
2633 $last_updated = date($short_date, strtotime($line["last_updated"]));
2634 }
2635
588fb13b
AD
2636 $last_updated = htmlspecialchars($last_updated);
2637
a9cb1f83
AD
2638 $has_img = is_file(ICONS_DIR . "/$id.ico");
2639
2640 $tmp_result = db_query($link,
14073c0a 2641 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
a9cb1f83
AD
2642 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2643 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
14073c0a
AD
2644 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2645 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
a9cb1f83
AD
2646
2647 if (db_num_rows($tmp_result) > 0) {
2648 while ($l = db_fetch_assoc($tmp_result)) {
2649 $count += $l["unread"];
2650 }
2651 }
2652
2653 if (!$smart_mode || $old_counters[$id] != $count) {
2654 $old_counters[$id] = $count;
2655 $fctrs_modified = true;
2656
2657 if ($last_error) {
2658 $error_part = "error=\"$last_error\"";
2659 } else {
2660 $error_part = "";
2661 }
2662
2663 if ($has_img) {
2664 $has_img_part = "hi=\"$has_img\"";
2665 } else {
2666 $has_img_part = "";
2667 }
2668
4ffa126e
AD
2669 if ($active_feed && $id == $active_feed) {
2670 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2671 } else {
2672 $has_title_part = "";
2673 }
2674
2675 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
a9cb1f83
AD
2676 }
2677 }
2678
2679 if ($smart_mode && $fctrs_modified) {
2680 $_SESSION["fctr_last_value"] = $old_counters;
2681 }
2682 }
2683
1b758780 2684 function get_script_dt_add() {
34e420fb 2685 if (strpos(VERSION, ".99") === false) {
1b758780
AD
2686 return VERSION;
2687 } else {
2688 return time();
2689 }
2690 }
2691
6e7f8d26
AD
2692 function get_pgsql_version($link) {
2693 $result = db_query($link, "SELECT version() AS version");
2694 $version = split(" ", db_fetch_result($result, 0, "version"));
2695 return $version[1];
2696 }
2697
af106b0e
AD
2698 function print_error_xml($code, $add_msg = "") {
2699 global $ERRORS;
2700
2701 $error_msg = $ERRORS[$code];
2702
2703 if ($add_msg) {
2704 $error_msg = "$error_msg; $add_msg";
2705 }
2706
4c2abbc1 2707 print "<rpc-reply>";
af106b0e 2708 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
4c2abbc1 2709 print "</rpc-reply>";
af106b0e 2710 }
956c7629 2711
f27de515
AD
2712 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2713 $auth_login = '', $auth_pass = '') {
bb0f29a4 2714
b3dfe8ba 2715 # check for feed:http://url
c91c2249
AD
2716 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2717
b3dfe8ba 2718 # check for feed://URL
e2d84cdb 2719 if (strpos($feed_link, "//") === 0) {
b3dfe8ba
AD
2720 $feed_link = "http:$feed_link";
2721 }
2722
c91c2249 2723 if ($feed_link == "") return;
bb0f29a4 2724
956c7629
AD
2725 if ($cat_id == "0" || !$cat_id) {
2726 $cat_qpart = "NULL";
2727 } else {
2728 $cat_qpart = "'$cat_id'";
2729 }
2730
2731 $result = db_query($link,
2732 "SELECT id FROM ttrss_feeds
2733 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2734
2735 if (db_num_rows($result) == 0) {
2736
2737 $result = db_query($link,
f27de515
AD
2738 "INSERT INTO ttrss_feeds
2739 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
956c7629 2740 VALUES ('".$_SESSION["uid"]."', '$feed_link',
f27de515 2741 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
956c7629
AD
2742
2743 $result = db_query($link,
2744 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
f27de515 2745 AND owner_uid = " . $_SESSION["uid"]);
956c7629
AD
2746
2747 $feed_id = db_fetch_result($result, 0, "id");
2748
2749 if ($feed_id) {
2750 update_rss_feed($link, $feed_link, $feed_id, true);
2751 }
2752
2753 return true;
2754 } else {
2755 return false;
2756 }
2757 }
2758
673d54ca
AD
2759 function print_feed_select($link, $id, $default_id = "",
2760 $attributes = "", $include_all_feeds = true) {
2761
79f3553b 2762 print "<select id=\"$id\" name=\"$id\" $attributes>";
673d54ca 2763 if ($include_all_feeds) {
89cb787e 2764 print "<option value=\"0\">".__('All feeds')."</option>";
673d54ca
AD
2765 }
2766
2767 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2768 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2769
2770 if (db_num_rows($result) > 0 && $include_all_feeds) {
2771 print "<option disabled>--------</option>";
2772 }
2773
2774 while ($line = db_fetch_assoc($result)) {
2775 if ($line["id"] == $default_id) {
2776 $is_selected = "selected";
2777 } else {
2778 $is_selected = "";
2779 }
79f3553b 2780 printf("<option $is_selected value='%d'>%s</option>",
47439031 2781 $line["id"], htmlspecialchars($line["title"]));
673d54ca
AD
2782 }
2783
2784 print "</select>";
2785 }
2786
2787 function print_feed_cat_select($link, $id, $default_id = "",
2788 $attributes = "", $include_all_cats = true) {
2789
79f3553b 2790 print "<select id=\"$id\" name=\"$id\" $attributes>";
673d54ca
AD
2791
2792 if ($include_all_cats) {
d1db26aa 2793 print "<option value=\"0\">".__('Uncategorized')."</option>";
673d54ca
AD
2794 }
2795
2796 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2797 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2798
2799 if (db_num_rows($result) > 0 && $include_all_cats) {
2800 print "<option disabled>--------</option>";
2801 }
2802
2803 while ($line = db_fetch_assoc($result)) {
2804 if ($line["id"] == $default_id) {
2805 $is_selected = "selected";
2806 } else {
2807 $is_selected = "";
2808 }
14f69488 2809 printf("<option $is_selected value='%d'>%s</option>",
47439031 2810 $line["id"], htmlspecialchars($line["title"]));
673d54ca
AD
2811 }
2812
2813 print "</select>";
2814 }
2815
14f69488
AD
2816 function checkbox_to_sql_bool($val) {
2817 return ($val == "on") ? "true" : "false";
2818 }
86b682ce
AD
2819
2820 function getFeedCatTitle($link, $id) {
2821 if ($id == -1) {
d1db26aa 2822 return __("Special");
86b682ce 2823 } else if ($id < -10) {
d1db26aa 2824 return __("Labels");
86b682ce
AD
2825 } else if ($id > 0) {
2826 $result = db_query($link, "SELECT ttrss_feed_categories.title
2827 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2828 cat_id = ttrss_feed_categories.id");
2829 if (db_num_rows($result) == 1) {
2830 return db_fetch_result($result, 0, "title");
2831 } else {
d1db26aa 2832 return __("Uncategorized");
86b682ce
AD
2833 }
2834 } else {
2835 return "getFeedCatTitle($id) failed";
2836 }
2837
2838 }
2839
2840 function getFeedTitle($link, $id) {
2841 if ($id == -1) {
d1db26aa 2842 return __("Starred articles");
945c243e
AD
2843 } else if ($id == -2) {
2844 return __("Published articles");
2d24f032
AD
2845 } else if ($id == -3) {
2846 return __("Fresh articles");
86b682ce
AD
2847 } else if ($id < -10) {
2848 $label_id = -10 - $id;
2849 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2850 if (db_num_rows($result) == 1) {
2851 return db_fetch_result($result, 0, "description");
2852 } else {
2853 return "Unknown label ($label_id)";
2854 }
2855
2856 } else if ($id > 0) {
2857 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2858 if (db_num_rows($result) == 1) {
2859 return db_fetch_result($result, 0, "title");
2860 } else {
2861 return "Unknown feed ($id)";
2862 }
2863 } else {
2864 return "getFeedTitle($id) failed";
2865 }
2866
2867 }
3dd46f19
AD
2868
2869 function get_session_cookie_name() {
2870 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2871 }
3ac2b520
AD
2872
2873 function print_init_params($link) {
2874 print "<init-params>";
2875 if ($_SESSION["stored-params"]) {
2876 foreach (array_keys($_SESSION["stored-params"]) as $key) {
5f57b06d
AD
2877 if ($key) {
2878 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2879 print "<param key=\"$key\" value=\"$value\"/>";
2880 }
3ac2b520
AD
2881 }
2882 }
2883
20361063 2884 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
3ac2b520
AD
2885 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2886 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
17c0eeba 2887 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3ac2b520
AD
2888
2889 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2890 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2891
e8bd0da9 2892 print "<param key=\"hide_read_feeds\" value=\"" .
465ff90b 2893 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
e8bd0da9 2894
c9268ed5 2895 print "<param key=\"feeds_sort_by_unread\" value=\"" .
465ff90b 2896 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
c9268ed5 2897
f6d6e22f 2898 print "<param key=\"confirm_feed_catchup\" value=\"" .
465ff90b 2899 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
f6d6e22f 2900
ac7bcd71 2901 print "<param key=\"cdm_auto_catchup\" value=\"" .
465ff90b 2902 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
ac7bcd71 2903
8e9c121b
AD
2904 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2905
be0801a1
AD
2906 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2907
40496720
AD
2908 print "<param key=\"default_view_mode\" value=\"" .
2909 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2910
2911 print "<param key=\"default_view_limit\" value=\"" .
465ff90b 2912 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
40496720 2913
fe8d2059
AD
2914 print "<param key=\"prefs_active_tab\" value=\"" .
2915 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2916
465ff90b
AD
2917 print "<param key=\"infobox_disable_overlay\" value=\"" .
2918 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2919
527c3bf0
AD
2920 print "<param key=\"icons_location\" value=\"" .
2921 ICONS_URL . "\"/>";
2922
22f3e356
AD
2923 print "<param key=\"hide_read_shows_special\" value=\"" .
2924 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2925
3ac2b520
AD
2926 print "</init-params>";
2927 }
f54f515f
AD
2928
2929 function print_runtime_info($link) {
2930 print "<runtime-info>";
20361063 2931
71ad883b
AD
2932 if (ENABLE_UPDATE_DAEMON) {
2933 print "<param key=\"daemon_is_running\" value=\"".
2934 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
8e00ae9b 2935
9041f58b 2936 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b
AD
2937
2938 $stamp = (int)read_stampfile("update_daemon.stamp");
2939
fbae93d8
AD
2940// print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2941
8e00ae9b 2942 if ($stamp) {
9041f58b
AD
2943 $stamp_delta = time() - $stamp;
2944
2945 if ($stamp_delta > 1800) {
f6854e44 2946 $stamp_check = 0;
8e00ae9b 2947 } else {
f6854e44
AD
2948 $stamp_check = 1;
2949 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
2950 }
2951
f6854e44
AD
2952 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2953
8e00ae9b
AD
2954 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2955
2956 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2957 }
8e00ae9b 2958 }
71ad883b 2959 }
8e00ae9b 2960
d9fa39f1
AD
2961 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
2962
c04206e5 2963 if ($_SESSION["last_version_check"] + 7200 < time()) {
d9fa39f1
AD
2964 $new_version_details = check_for_update($link);
2965
2966 print "<param key=\"new_version_available\" value=\"".
2967 sprintf("%d", $new_version_details != ""). "\"/>";
2968
2969 $_SESSION["last_version_check"] = time();
2970 }
2971 }
2972
1c9df66e 2973// print "<param key=\"new_version_available\" value=\"1\"/>";
b4507bc2 2974
f54f515f
AD
2975 print "</runtime-info>";
2976 }
ef393de7 2977
88040f57 2978 function getSearchSql($search, $match_on) {
ef393de7 2979
88040f57 2980 $search_query_part = "";
e20c9d88 2981
88040f57
AD
2982 $keywords = split(" ", $search);
2983 $query_keywords = array();
e20c9d88 2984
88040f57 2985 if ($match_on == "both") {
e20c9d88 2986
88040f57
AD
2987 foreach ($keywords as $k) {
2988 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2989 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2990 }
e20c9d88 2991
88040f57 2992 $search_query_part = implode("AND", $query_keywords) . " AND ";
e20c9d88 2993
88040f57 2994 } else if ($match_on == "title") {
e20c9d88 2995
88040f57
AD
2996 foreach ($keywords as $k) {
2997 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2998 }
e20c9d88 2999
88040f57 3000 $search_query_part = implode("AND", $query_keywords) . " AND ";
e20c9d88 3001
88040f57
AD
3002 } else if ($match_on == "content") {
3003
3004 foreach ($keywords as $k) {
3005 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3006 }
3007 }
3008
3009 $search_query_part = implode("AND", $query_keywords);
3010
3011 return $search_query_part;
3012 }
3013
c36bf4d5
AD
3014 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3015
3016 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 3017
88040f57
AD
3018 if ($search) {
3019
3020 $search_query_part = getSearchSql($search, $match_on);
3021 $search_query_part .= " AND ";
e20c9d88 3022
ef393de7
AD
3023 } else {
3024 $search_query_part = "";
3025 }
3026
3027 $view_query_part = "";
3028
3029 if ($view_mode == "adaptive") {
3030 if ($search) {
3031 $view_query_part = " ";
3032 } else if ($feed != -1) {
f295c368 3033 $unread = getFeedUnread($link, $feed, $cat_view);
ef393de7
AD
3034 if ($unread > 0) {
3035 $view_query_part = " unread = true AND ";
3036 }
3037 }
3038 }
3039
3040 if ($view_mode == "marked") {
3041 $view_query_part = " marked = true AND ";
3042 }
3043
3044 if ($view_mode == "unread") {
3045 $view_query_part = " unread = true AND ";
3046 }
3047
3048 if ($limit > 0) {
3049 $limit_query_part = "LIMIT " . $limit;
3050 }
3051
3052 $vfeed_query_part = "";
3053
3054 // override query strategy and enable feed display when searching globally
3055 if ($search && $search_mode == "all_feeds") {
3056 $query_strategy_part = "ttrss_entries.id > 0";
3057 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3058 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3059 $query_strategy_part = "ttrss_entries.id > 0";
3060 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3061 id = feed_id) as feed_title,";
3062 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3063
3064 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846
AD
3065
3066 $tmp_result = false;
3067
3068 if ($cat_view) {
3069 $tmp_result = db_query($link, "SELECT id
3070 FROM ttrss_feeds WHERE cat_id = '$feed'");
3071 } else {
3072 $tmp_result = db_query($link, "SELECT id
3073 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3074 WHERE id = '$feed') AND id != '$feed'");
3075 }
ef393de7
AD
3076
3077 $cat_siblings = array();
3078
3079 if (db_num_rows($tmp_result) > 0) {
3080 while ($p = db_fetch_assoc($tmp_result)) {
3081 array_push($cat_siblings, "feed_id = " . $p["id"]);
3082 }
3083
3084 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3085 $feed, implode(" OR ", $cat_siblings));
3086
3087 } else {
3088 $query_strategy_part = "ttrss_entries.id > 0";
3089 }
3090
3091 } else if ($feed >= 0) {
3092
3093 if ($cat_view) {
5c365f60 3094
ef393de7
AD
3095 if ($feed > 0) {
3096 $query_strategy_part = "cat_id = '$feed'";
3097 } else {
3098 $query_strategy_part = "cat_id IS NULL";
3099 }
3100
3101 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 3102
ef393de7
AD
3103 } else {
3104 $tmp_result = db_query($link, "SELECT id
3105 FROM ttrss_feeds WHERE parent_feed = '$feed'
3106 ORDER BY cat_id,title");
3107
3108 $parent_ids = array();
3109
3110 if (db_num_rows($tmp_result) > 0) {
3111 while ($p = db_fetch_assoc($tmp_result)) {
3112 array_push($parent_ids, "feed_id = " . $p["id"]);
3113 }
3114
3115 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3116 $feed, implode(" OR ", $parent_ids));
3117
3118 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3119 } else {
3120 $query_strategy_part = "feed_id = '$feed'";
3121 }
3122 }
3123 } else if ($feed == -1) { // starred virtual feed
3124 $query_strategy_part = "marked = true";
3125 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
e4f4b46f
AD
3126 } else if ($feed == -2) { // published virtual feed
3127 $query_strategy_part = "published = true";
2d24f032
AD
3128 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3129 } else if ($feed == -3) { // fresh virtual feed
3130 $query_strategy_part = "unread = true";
3131
7a22dc2a 3132 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 3133
2d24f032 3134 if (DB_TYPE == "pgsql") {
c1d7e6c3 3135 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 3136 } else {
c1d7e6c3 3137 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
3138 }
3139
e4f4b46f 3140 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
3141 } else if ($feed <= -10) { // labels
3142 $label_id = -$feed - 11;
3143
3144 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3145 WHERE id = '$label_id'");
3146
3147 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
3de0261a
AD
3148
3149 if (!$query_strategy_part) {
3150 return false;
3151 }
3152
ef393de7
AD
3153 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3154 } else {
3155 $query_strategy_part = "id > 0"; // dumb
3156 }
d6e5706d 3157
7a22dc2a 3158 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
d6e5706d
AD
3159 $order_by = "updated";
3160 } else {
3161 $order_by = "updated DESC";
3162 }
e939722a
AD
3163
3164 if ($override_order) {
3165 $order_by = $override_order;
3166 }
ef393de7
AD
3167
3168 $feed_title = "";
3169
3170 if ($search && $search_mode == "all_feeds") {
b36e002f 3171 $feed_title = __("Search results")." ($search)";
ef393de7 3172 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
b36e002f 3173 $feed_title = __("Search results")." ($search, $feed)";
ef393de7
AD
3174 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3175 $feed_title = $feed;
3176 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3177
3178 if ($cat_view) {
5c365f60 3179
ef393de7
AD
3180 if ($feed != 0) {
3181 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
c36bf4d5 3182 WHERE id = '$feed' AND owner_uid = $owner_uid");
ef393de7
AD
3183 $feed_title = db_fetch_result($result, 0, "title");
3184 } else {
d1db26aa 3185 $feed_title = __("Uncategorized");
ef393de7 3186 }
e1eb2147
AD
3187
3188 if ($search) {
b36e002f 3189 $feed_title = __("Searched for")." $search ($feed_title)";
e1eb2147
AD
3190 }
3191
ef393de7
AD
3192 } else {
3193
3194 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
c36bf4d5 3195 WHERE id = '$feed' AND owner_uid = $owner_uid");
ef393de7
AD
3196
3197 $feed_title = db_fetch_result($result, 0, "title");
3198 $feed_site_url = db_fetch_result($result, 0, "site_url");
3199 $last_error = db_fetch_result($result, 0, "last_error");
e1eb2147
AD
3200
3201 if ($search) {
b36e002f 3202 $feed_title = __("Searched for") . " $search ($feed_title)";
e1eb2147 3203 }
ef393de7
AD
3204 }
3205
3206 } else if ($feed == -1) {
d1db26aa 3207 $feed_title = __("Starred articles");
e4f4b46f
AD
3208 } else if ($feed == -2) {
3209 $feed_title = __("Published articles");
2d24f032
AD
3210 } else if ($feed == -3) {
3211 $feed_title = __("Fresh articles");
ef393de7
AD
3212 } else if ($feed < -10) {
3213 $label_id = -$feed - 11;
3214 $result = db_query($link, "SELECT description FROM ttrss_labels
3215 WHERE id = '$label_id'");
3216 $feed_title = db_fetch_result($result, 0, "description");
88040f57
AD
3217
3218 if ($search) {
b36e002f 3219 $feed_title = __("Searched for") . " $search ($feed_title)";
88040f57 3220 }
ef393de7
AD
3221 } else {
3222 $feed_title = "?";
3223 }
3224
ef393de7
AD
3225 if ($feed < -10) error_reporting (0);
3226
62129e67
AD
3227 $content_query_part = "content as content_preview,";
3228
ef393de7
AD
3229 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3230
3231 if ($feed >= 0) {
3232 $feed_kind = "Feeds";
3233 } else {
3234 $feed_kind = "Labels";
3235 }
3236
95a82c08
AD
3237 if ($limit_query_part) {
3238 $offset_query_part = "OFFSET $offset";
3239 }
3240
ef393de7 3241 $query = "SELECT
1f64b1be 3242 guid,
ef393de7 3243 ttrss_entries.id,ttrss_entries.title,
46921916 3244 updated,
e4f4b46f 3245 unread,feed_id,marked,published,link,last_read,
ef393de7
AD
3246 SUBSTRING(last_read,1,19) as last_read_noms,
3247 $vfeed_query_part
3248 $content_query_part
d4b4b9de
AD
3249 SUBSTRING(updated,1,19) as updated_noms,
3250 author
ef393de7
AD
3251 FROM
3252 ttrss_entries,ttrss_user_entries,ttrss_feeds
3253 WHERE
cfb02131 3254 ttrss_feeds.hidden = false AND
ef393de7
AD
3255 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3256 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 3257 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7
AD
3258 $search_query_part
3259 $view_query_part
3260 $query_strategy_part ORDER BY $order_by
95a82c08 3261 $limit_query_part $offset_query_part";
ef393de7
AD
3262
3263 $result = db_query($link, $query);
3264
3265 if ($_GET["debug"]) print $query;
3266
3267 } else {
3268 // browsing by tag
3269
3270 $feed_kind = "Tags";
3271
3272 $result = db_query($link, "SELECT
1f64b1be 3273 guid,
ef393de7 3274 ttrss_entries.id as id,title,
46921916 3275 updated,
ef393de7
AD
3276 unread,feed_id,
3277 marked,link,last_read,
3278 SUBSTRING(last_read,1,19) as last_read_noms,
3279 $vfeed_query_part
3280 $content_query_part
3281 SUBSTRING(updated,1,19) as updated_noms
3282 FROM
3283 ttrss_entries,ttrss_user_entries,ttrss_tags
3284 WHERE
3285 ref_id = ttrss_entries.id AND
c36bf4d5 3286 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7
AD
3287 post_int_id = int_id AND tag_name = '$feed' AND
3288 $view_query_part
3289 $search_query_part
3290 $query_strategy_part ORDER BY $order_by
3291 $limit_query_part");
3292 }
3293
c7188969 3294 return array($result, $feed_title, $feed_site_url, $last_error);
ef393de7
AD
3295
3296 }
3297
c36bf4d5 3298 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3baeeeca 3299 $search, $search_mode, $match_on) {
18664970
AD
3300
3301 $qfh_ret = queryFeedHeadlines($link, $feed,
c36bf4d5
AD
3302 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3303 $owner_uid);
18664970
AD
3304
3305 $result = $qfh_ret[0];
59e2aab4 3306 $feed_title = htmlspecialchars($qfh_ret[1]);
18664970
AD
3307 $feed_site_url = $qfh_ret[2];
3308 $last_error = $qfh_ret[3];
3309
a5472764 3310// if (!$feed_site_url) $feed_site_url = "http://localhost/";
4bc64807 3311
a5472764
AD
3312 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3313 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3314 <rss version=\"2.0\">
3baeeeca
AD
3315 <channel>
3316 <title>$feed_title</title>
4bc64807
AD
3317 <link>$feed_site_url</link>
3318 <description>Feed generated by Tiny Tiny RSS</description>";
3baeeeca
AD
3319
3320 while ($line = db_fetch_assoc($result)) {
3321 print "<item>";
4bc64807 3322 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3baeeeca 3323 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
0c3d1c68 3324
bc976a8c 3325 $tags = get_article_tags($link, $line["id"], $owner_uid);
0c3d1c68
AD
3326
3327 foreach ($tags as $tag) {
3328 print "<category>" . htmlspecialchars($tag) . "</category>";
3329 }
3330
3baeeeca
AD
3331 $rfc822_date = date('r', strtotime($line["updated"]));
3332
3333 print "<pubDate>$rfc822_date</pubDate>";
3334
3335 print "<title>" .
3336 htmlspecialchars($line["title"]) . "</title>";
3337
0c3d1c68
AD
3338 print "<description><![CDATA[" .
3339 $line["content_preview"] . "]]></description>";
3baeeeca
AD
3340
3341 print "</item>";
3342 }
3343
3344 print "</channel></rss>";
18664970
AD
3345
3346 }
3347
0a6c4846
AD
3348 function getCategoryTitle($link, $cat_id) {
3349
bba7c4bf
AD
3350 if ($cat_id == -1) {
3351 return __("Special");
3352 } else if ($cat_id == -2) {
3353 return __("Labels");
0a6c4846 3354 } else {
bba7c4bf
AD
3355
3356 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3357 id = '$cat_id'");
3358
3359 if (db_num_rows($result) == 1) {
3360 return db_fetch_result($result, 0, "title");
3361 } else {
3362 return "Uncategorized";
3363 }
0a6c4846
AD
3364 }
3365 }
3366
f738aef1
AD
3367 // http://ru2.php.net/strip-tags
3368
3369 function strip_tags_long($textstring, $allowed){
3370 while($textstring != strip_tags($textstring, $allowed))
3371 {
3372 while (strlen($textstring) != 0)
3373 {
3374 if (strlen($textstring) > 1024) {
3375 $otherlen = 1024;
3376 } else {
3377 $otherlen = strlen($textstring);
3378 }
3379 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3380 $safetext .= $temptext;
3381 $textstring = substr_replace($textstring,'',0,$otherlen);
3382 }
3383 $textstring = $safetext;
3384 }
3385 return $textstring;
3386 }
3387
3388
1ac0baf4 3389 function sanitize_rss($link, $str, $force_strip_tags = false) {
60452879 3390 $res = $str;
183ad07b 3391
1ac0baf4 3392 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
f738aef1 3393
7e1265ed
AD
3394 $res = strip_tags_long($res,
3395 "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
f738aef1
AD
3396
3397// $res = preg_replace("/\r\n|\n|\r/", "", $res);
3398// $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
f826eee1
AD
3399 }
3400
183ad07b
AD
3401 return $res;
3402 }
b72c3ef8 3403
45004d43
AD
3404 /**
3405 * Send by mail a digest of last articles.
3406 *
3407 * @param mixed $link The database connection.
3408 * @param integer $limit The maximum number of articles by digest.
3409 * @return boolean Return false if digests are not enabled.
3410 */
9cd7c995
AD
3411 function send_headlines_digests($link, $limit = 100) {
3412
1ddba275
AD
3413 if (!DIGEST_ENABLE) return false;
3414
9cd7c995 3415 $user_limit = DIGEST_EMAIL_LIMIT;
5430c959 3416 $days = 1;
9cd7c995
AD
3417
3418 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3419
3420 if (DB_TYPE == "pgsql") {
3421 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3422 } else if (DB_TYPE == "mysql") {
3423 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3424 }
3425
3426 $result = db_query($link, "SELECT id,email FROM ttrss_users
3427 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3428
3429 while ($line = db_fetch_assoc($result)) {
dc85be2b 3430
9cd7c995
AD
3431 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3432 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3433
dc85be2b
AD
3434 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3435
9cd7c995
AD
3436 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3437 $digest = $tuple[0];
3438 $headlines_count = $tuple[1];
dc85be2b 3439 $affected_ids = $tuple[2];
c62a2c21 3440 $digest_text = $tuple[3];
9cd7c995
AD
3441
3442 if ($headlines_count > 0) {
a8931123 3443
c62a2c21 3444 $mail = new PHPMailer();
a8931123 3445
c62a2c21
AD
3446 $mail->PluginDir = "phpmailer/";
3447 $mail->SetLanguage("en", "phpmailer/language/");
a8931123 3448
c62a2c21 3449 $mail->CharSet = "UTF-8";
a8931123 3450
c62a2c21
AD
3451 $mail->From = DIGEST_FROM_ADDRESS;
3452 $mail->FromName = DIGEST_FROM_NAME;
3453 $mail->AddAddress($line["email"], $line["login"]);
c7ddac5c 3454
c62a2c21 3455 if (DIGEST_SMTP_HOST) {
a8931123
AD
3456 $mail->Host = DIGEST_SMTP_HOST;
3457 $mail->Mailer = "smtp";
a8931123
AD
3458 $mail->Username = DIGEST_SMTP_LOGIN;
3459 $mail->Password = DIGEST_SMTP_PASSWORD;
c62a2c21 3460 }
a8931123 3461
c62a2c21 3462 $mail->IsHTML(true);
163a295e 3463 $mail->Subject = DIGEST_SUBJECT;
c62a2c21
AD
3464 $mail->Body = $digest;
3465 $mail->AltBody = $digest_text;
a8931123 3466
c62a2c21 3467 $rc = $mail->Send();
a8931123 3468
c62a2c21 3469 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
a8931123 3470
9cd7c995 3471 print "RC=$rc\n";
a8931123 3472
c62a2c21 3473 if ($rc && $do_catchup) {
dc85be2b 3474 print "Marking affected articles as read...\n";
9968d46f 3475 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
dc85be2b
AD
3476 }
3477
9cd7c995
AD
3478 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3479 WHERE id = " . $line["id"]);
3480 } else {
3481 print "No headlines\n";
3482 }
3483 }
3484 }
3485
cedd3e89
AD
3486 print "All done.\n";
3487
9cd7c995
AD
3488 }
3489
7e3634d9 3490 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
c62a2c21
AD
3491
3492 require_once "MiniTemplator.class.php";
3493
3494 $tpl = new MiniTemplator;
3495 $tpl_t = new MiniTemplator;
3496
3497 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3498 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3499
3500 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3501 $tpl->setVariable('CUR_TIME', date('G:i'));
3502
3503 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3504 $tpl_t->setVariable('CUR_TIME', date('G:i'));
7e3634d9 3505
dc85be2b
AD
3506 $affected_ids = array();
3507
7e3634d9 3508 if (DB_TYPE == "pgsql") {
9cd7c995 3509 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
7e3634d9
AD
3510 } else if (DB_TYPE == "mysql") {
3511 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3512 }
3513
3514 $result = db_query($link, "SELECT ttrss_entries.title,
3515 ttrss_feeds.title AS feed_title,
3516 date_entered,
dc85be2b 3517 ttrss_user_entries.ref_id,
7e3634d9 3518 link,
c62a2c21 3519 SUBSTRING(content, 1, 120) AS excerpt,
7e3634d9
AD
3520 SUBSTRING(last_updated,1,19) AS last_updated
3521 FROM
3522 ttrss_user_entries,ttrss_entries,ttrss_feeds
3523 WHERE
3524 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3dd9183c 3525 AND include_in_digest = true
7e3634d9 3526 AND $interval_query
a8931123 3527 AND hidden = false
448b0abd 3528 AND ttrss_user_entries.owner_uid = $user_id
c62a2c21
AD
3529 AND unread = true
3530 ORDER BY ttrss_feeds.title, date_entered DESC
7e3634d9
AD
3531 LIMIT $limit");
3532
3533 $cur_feed_title = "";
3534
9cd7c995
AD
3535 $headlines_count = db_num_rows($result);
3536
c62a2c21
AD
3537 $headlines = array();
3538
7e3634d9 3539 while ($line = db_fetch_assoc($result)) {
c62a2c21
AD
3540 array_push($headlines, $line);
3541 }
3542
3543 for ($i = 0; $i < sizeof($headlines); $i++) {
3544
3545 $line = $headlines[$i];
dc85be2b
AD
3546
3547 array_push($affected_ids, $line["ref_id"]);
3548
7e3634d9 3549 $updated = smart_date_time(strtotime($line["last_updated"]));
7e3634d9 3550
c62a2c21
AD
3551 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3552 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3553 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3554 $tpl->setVariable('ARTICLE_UPDATED', $updated);
163a295e
AD
3555 $tpl->setVariable('ARTICLE_EXCERPT',
3556 truncate_string(strip_tags($line["excerpt"]), 100));
7e3634d9 3557
c62a2c21
AD
3558 $tpl->addBlock('article');
3559
3560 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3561 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3562 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3563 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3564// $tpl_t->setVariable('ARTICLE_EXCERPT',
3565// truncate_string(strip_tags($line["excerpt"]), 100));
3566
3567 $tpl_t->addBlock('article');
3568
3569 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3570 $tpl->addBlock('feed');
3571 $tpl_t->addBlock('feed');
7e3634d9
AD
3572 }
3573
7e3634d9
AD
3574 }
3575
c62a2c21
AD
3576 $tpl->addBlock('digest');
3577 $tpl->generateOutputToString($tmp);
3578
3579 $tpl_t->addBlock('digest');
3580 $tpl_t->generateOutputToString($tmp_t);
7e3634d9 3581
c62a2c21 3582 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
7e3634d9
AD
3583 }
3584
d9fa39f1 3585 function check_for_update($link, $brief_fmt = true) {
b72c3ef8
AD
3586 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3587
3588 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3589 return;
3590 }
3591
3592 error_reporting(0);
f67d9754
AD
3593 if (ENABLE_SIMPLEPIE) {
3594 $rss = new SimplePie();
3595 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
4148e809 3596// $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
f67d9754
AD
3597 $rss->set_feed_url($fetch_url);
3598 $rss->set_output_encoding('UTF-8');
3599 $rss->init();
3600 } else {
3601 $rss = fetch_rss($releases_feed);
3602 }
b72c3ef8
AD
3603 error_reporting (DEFAULT_ERROR_LEVEL);
3604
3605 if ($rss) {
3606
f67d9754
AD
3607 if (ENABLE_SIMPLEPIE) {
3608 $items = $rss->get_items();
3609 } else {
3610 $items = $rss->items;
b72c3ef8 3611
f67d9754
AD
3612 if (!$items || !is_array($items)) $items = $rss->entries;
3613 if (!$items || !is_array($items)) $items = $rss;
3614 }
b72c3ef8 3615
da412ad3 3616 if (!is_array($items) || count($items) == 0) {
b72c3ef8 3617 return;
da412ad3 3618 }
b72c3ef8 3619
a41d2c65 3620 $latest_item = $items[0];
b72c3ef8 3621
f67d9754
AD
3622 if (ENABLE_SIMPLEPIE) {
3623 $last_title = $latest_item->get_title();
3624 } else {
3625 $last_title = $latest_item["title"];
3626 }
b72c3ef8 3627
f67d9754
AD
3628 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3629
3630 if (ENABLE_SIMPLEPIE) {
dcf7fd08
AD
3631 $release_url = sanitize_rss($link, $latest_item->get_link());
3632 $content = sanitize_rss($link, $latest_item->get_description());
f67d9754
AD
3633 } else {
3634 $release_url = sanitize_rss($link, $latest_item["link"]);
3635 $content = sanitize_rss($link, $latest_item["description"]);
3636 }
48e1a342 3637
a41d2c65 3638 if (version_compare(VERSION, $latest_version) == -1) {
d9fa39f1 3639 if ($brief_fmt) {
0d32b41e 3640 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
d9fa39f1 3641 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
0d32b41e 3642 <div id=\"milestoneDetails\">$content</div>");
d9fa39f1 3643 } else {
92625568
AD
3644 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3645 <div class='milestoneDetails'>$content</div>
3646 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3647 download and update information.";
d9fa39f1
AD
3648 }
3649
da412ad3 3650 }
b72c3ef8
AD
3651 }
3652 }
472782e8 3653
18eddb2c
AD
3654 function markArticlesById($link, $ids, $cmode) {
3655
3656 $tmp_ids = array();
3657
3658 foreach ($ids as $id) {
3659 array_push($tmp_ids, "ref_id = '$id'");
3660 }
3661
3662 $ids_qpart = join(" OR ", $tmp_ids);
3663
3664 if ($cmode == 0) {
3665 db_query($link, "UPDATE ttrss_user_entries SET
3666 marked = false,last_read = NOW()
3667 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3668 } else if ($cmode == 1) {
3669 db_query($link, "UPDATE ttrss_user_entries SET
3670 marked = true
3671 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3672 } else {
3673 db_query($link, "UPDATE ttrss_user_entries SET
3674 marked = NOT marked,last_read = NOW()
3675 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3676 }
3677 }
3678
e4f4b46f
AD
3679 function publishArticlesById($link, $ids, $cmode) {
3680
3681 $tmp_ids = array();
3682
3683 foreach ($ids as $id) {
3684 array_push($tmp_ids, "ref_id = '$id'");
3685 }
3686
3687 $ids_qpart = join(" OR ", $tmp_ids);
3688
3689 if ($cmode == 0) {
3690 db_query($link, "UPDATE ttrss_user_entries SET
3691 published = false,last_read = NOW()
3692 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3693 } else if ($cmode == 1) {
3694 db_query($link, "UPDATE ttrss_user_entries SET
3695 published = true
3696 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3697 } else {
3698 db_query($link, "UPDATE ttrss_user_entries SET
3699 published = NOT published,last_read = NOW()
3700 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3701 }
3702 }
3703
9968d46f
AD
3704 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3705
3706 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
472782e8
AD
3707
3708 $tmp_ids = array();
3709
3710 foreach ($ids as $id) {
3711 array_push($tmp_ids, "ref_id = '$id'");
3712 }
3713
3714 $ids_qpart = join(" OR ", $tmp_ids);
3715
3716 if ($cmode == 0) {
3717 db_query($link, "UPDATE ttrss_user_entries SET
3718 unread = false,last_read = NOW()
9968d46f 3719 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8
AD
3720 } else if ($cmode == 1) {
3721 db_query($link, "UPDATE ttrss_user_entries SET
3722 unread = true
9968d46f 3723 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8
AD
3724 } else {
3725 db_query($link, "UPDATE ttrss_user_entries SET
3726 unread = NOT unread,last_read = NOW()
9968d46f 3727 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8
AD
3728 }
3729 }
3730
e097e8be
AD
3731 function catchupArticleById($link, $id, $cmode) {
3732
3733 if ($cmode == 0) {
3734 db_query($link, "UPDATE ttrss_user_entries SET
3735 unread = false,last_read = NOW()
3736 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3737 } else if ($cmode == 1) {
3738 db_query($link, "UPDATE ttrss_user_entries SET
3739 unread = true
3740 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3741 } else {
3742 db_query($link, "UPDATE ttrss_user_entries SET
3743 unread = NOT unread,last_read = NOW()
3744 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3745 }
3746 }
3747
1f64b1be
AD
3748 function make_guid_from_title($title) {
3749 return preg_replace("/[ \"\',.:;]/", "-",
fefef828 3750 mb_strtolower(strip_tags($title), 'utf-8'));
1f64b1be
AD
3751 }
3752
11befbb2
AD
3753 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3754 $bottom = false, $rtl_content = false, $feed_id = 0,
3755 $is_cat = false, $search = false, $match_on = false,
95a82c08 3756 $search_mode = false, $offset = 0, $limit = 0) {
11befbb2 3757
e6c115b2
AD
3758 $user_page_offset = $offset + 1;
3759
11befbb2
AD
3760 if (!$bottom) {
3761 $class = "headlinesSubToolbar";
3762 $tid = "headlineActionsTop";
3763 } else {
3764 $class = "headlinesSubToolbar";
3765 $tid = "headlineActionsBottom";
3766 }
3767
3768 print "<table class=\"$class\" id=\"$tid\"
3769 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3770
3771 if ($rtl_content) {
3772 $rtl_cpart = "RTL";
3773 } else {
3774 $rtl_cpart = "";
3775 }
3776
e6c115b2
AD
3777 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3778 $page_next_link = "javascript:viewFeedGoPage(1)";
3779 $page_first_link = "javascript:viewFeedGoPage(0)";
203de776 3780
eb28b131
AD
3781 $catchup_page_link = "javascript:catchupPage()";
3782 $catchup_feed_link = "javascript:catchupCurrentFeed()";
a5ae125a 3783 $catchup_sel_link = "javascript:catchupSelection()";
c6008b62 3784
11befbb2
AD
3785 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3786
c6008b62
AD
3787 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3788 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3789 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
11befbb2 3790
c6008b62
AD
3791 $tog_unread_link = "javascript:selectionToggleUnread()";
3792 $tog_marked_link = "javascript:selectionToggleMarked()";
e4f4b46f 3793 $tog_published_link = "javascript:selectionTogglePublished()";
11befbb2 3794
c6008b62 3795 } else {
11befbb2 3796
c6008b62
AD
3797 $sel_all_link = "javascript:cdmSelectArticles('all')";
3798 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3799 $sel_none_link = "javascript:cdmSelectArticles('none')";
3800
3801 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3802 $tog_marked_link = "javascript:selectionToggleMarked(true)";
e4f4b46f 3803 $tog_published_link = "javascript:selectionTogglePublished(true)";
c6008b62
AD
3804
3805 }
3806
d420f2ee 3807 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
c6008b62 3808
2dd2c13b
AD
3809 print "<td class=\"headlineActions$rtl_cpart\">
3810 <ul class=\"headlineDropdownMenu\">
3811 <li class=\"top2\">
3692e98f 3812 ".__('Select:')."
1025ad87
AD
3813 <a href=\"$sel_all_link\">".__('All')."</a>,
3814 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3815 <a href=\"$sel_none_link\">".__('None')."</a></li>
2dd2c13b 3816 <li class=\"vsep\">&nbsp;</li>
89cb787e 3817 <li class=\"top\">".__('Toggle')."<ul>
9cc600d1 3818 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
e4f4b46f
AD
3819 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3820 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3821 </ul></li>
2dd2c13b 3822 <li class=\"vsep\">&nbsp;</li>
77590c49 3823 <li class=\"top\">".__('Mark as read')."<ul>
a5ae125a 3824 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
e14a59be
AD
3825 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->";
3826
3827 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3828
3829 print "
8be83f42
AD
3830 <li><span class=\"insensitive\">--------</span></li>
3831 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3832 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
e14a59be
AD
3833 <li><span class=\"insensitive\">--------</span></li>";
3834 }
3835
3836 print "
1025ad87 3837 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
237ec2ad 3838 ";
95a82c08 3839
237ec2ad
AD
3840 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3841
3842 if ($limit != 0 && !$search && $enable_pagination) {
95a82c08 3843 print "
237ec2ad 3844 <li class=\"vsep\">&nbsp;</li>
1025ad87
AD
3845 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3846 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3847 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
95a82c08 3848 </ul>";
d420f2ee 3849 }
95a82c08 3850
d420f2ee 3851 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
237ec2ad
AD
3852 print "
3853 <li class=\"vsep\">&nbsp;</li>
3854 <li class=\"top3\">
d420f2ee
AD
3855 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3856 '$match_on', '$feed_id', '$is_cat');\">
b36e002f 3857 ".__('Convert to label')."</a></td>";
d420f2ee 3858 }
95a82c08 3859 print "
2dd2c13b
AD
3860 </td>";
3861
3862 } else {
e6c115b2
AD
3863 // old style subtoolbar:
3864
2dd2c13b 3865 print "<td class=\"headlineActions$rtl_cpart\">".
d1db26aa 3866 __('Select:')."
1025ad87
AD
3867 <a href=\"$sel_all_link\">".__('All')."</a>,
3868 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3869 <a href=\"$sel_none_link\">".__('None')."</a>
2dd2c13b 3870 &nbsp;&nbsp;".
1025ad87
AD
3871 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3872 <a href=\"$tog_marked_link\">".__('Starred')."</a>
2dd2c13b 3873 &nbsp;&nbsp;".
d1db26aa 3874 __('Mark as read:')."
1025ad87
AD
3875 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3876 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
d420f2ee
AD
3877
3878 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3879
3880 print "&nbsp;&nbsp;
3881 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3882 '$match_on', '$feed_id', '$is_cat');\">
b36e002f 3883 ".__('Convert to label')."</a>";
d420f2ee
AD
3884 }
3885
2dd2c13b
AD
3886 print "</td>";
3887
3888 }
c6008b62 3889
d420f2ee 3890/* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
c6008b62
AD
3891 print "<td class=\"headlineActions$rtl_cpart\">
3892 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3893 '$match_on', '$feed_id', '$is_cat');\">
d1db26aa 3894 ".__('Convert to Label')."</a></td>";
d420f2ee 3895} */
11befbb2
AD
3896
3897 print "<td class=\"headlineTitle$rtl_cpart\">";
11befbb2 3898
b27967ac 3899 print "<span class=\"headlineInnerTitle\">";
11befbb2 3900
b27967ac
AD
3901 if ($feed_site_url) {
3902 if (!$bottom) {
3903 $target = "target=\"_new\"";
20361063 3904 }
b27967ac
AD
3905 print "<a $target href=\"$feed_site_url\">".
3906 truncate_string($feed_title,30)."</a>";
3907 } else {
3908 print $feed_title;
3909 }
3910
3911 if ($search) {
3912 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
e6c115b2
AD
3913 }
3914
b27967ac
AD
3915 if ($user_page_offset > 1) {
3916 print " [$user_page_offset] ";
3917 }
3918
3919 print "</span>";
3920
11befbb2 3921 if (!$bottom) {
e6c115b2 3922 print "
11befbb2
AD
3923 <a target=\"_new\"
3924 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3925 <img class=\"noborder\"
1025ad87 3926 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
11befbb2
AD
3927 </a>";
3928 }
3929
3930 print "</td>";
3931 print "</tr></table>";
3932
3933 }
3934
bba7c4bf
AD
3935 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3936
3937 $tmp_category = getCategoryTitle($link, $cat_id);
3938 $cat_unread = getCategoryUnread($link, $cat_id);
3939
3940 if ($hidden) {
3941 $holder_style = "display:none;";
66a251f9 3942 $ellipsis = "…";
bba7c4bf
AD
3943 } else {
3944 $holder_style = "";
3945 $ellipsis = "";
3946 }
3947
3948 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3949
3950 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3951 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3952
3953 if ($can_browse) {
3954 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3955 } else {
3956 print "<span id=\"FCAP-$cat_id\">";
3957 }
3958
dda1396f 3959 print " <span id=\"FCATCTR-$cat_id\"
bba7c4bf
AD
3960 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
3961
3962 if ($can_browse) {
3963 print "</a>";
3964 } else {
3965 print "</span>";
3966 }
3967
3968 print "</li>";
3969
3970 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3971 }
3972
f407c086
AD
3973 function outputFeedList($link, $tags = false) {
3974
3bd9a780 3975 print "<ul class=\"feedList\" id=\"feedList\">";
f407c086
AD
3976
3977 $owner_uid = $_SESSION["uid"];
3978
cf4d339c 3979 /* virtual feeds */
f407c086 3980
cf4d339c 3981 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3b086176
AD
3982
3983 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
bba7c4bf 3984 $cat_hidden = true;
3b086176 3985 } else {
bba7c4bf 3986 $cat_hidden = false;
3b086176
AD
3987 }
3988
3989# print "<li class=\"feedCat\">".__('Special')."</li>";
3990# print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
bba7c4bf
AD
3991# print "<li class=\"feedCat\">".
3992# "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
3993# __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
3994#
3995# print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
3996# <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
3b086176 3997
bba7c4bf
AD
3998# $cat_unread = getCategoryUnread($link, -1);
3999# $tmp_category = __("Special");
4000# $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3b086176 4001
bba7c4bf 4002 printCategoryHeader($link, -1, $cat_hidden, false);
cf4d339c 4003 }
f407c086 4004
cf4d339c 4005 $num_starred = getFeedUnread($link, -1);
e4f4b46f 4006 $num_published = getFeedUnread($link, -2);
2d24f032
AD
4007 $num_fresh = getFeedUnread($link, -3);
4008
4009 $class = "virt";
4010
4011 if ($num_fresh > 0) $class .= "Unread";
4012
4013 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4014 "images/fresh.png", $link);
f407c086 4015
cf4d339c 4016 $class = "virt";
f407c086 4017
cf4d339c 4018 if ($num_starred > 0) $class .= "Unread";
f407c086 4019
abd8a516
AD
4020 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4021
4022 if ($is_ie) {
4023 $mark_img_ext = "gif";
4024 } else {
4025 $mark_img_ext = "png";
4026 }
4027
d1db26aa 4028 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
abd8a516 4029 "images/mark_set.$mark_img_ext", $link);
f407c086 4030
e4f4b46f
AD
4031 $class = "virt";
4032
4033 if ($num_published > 0) $class .= "Unread";
4034
4035 printFeedEntry(-2, $class, __("Published articles"), $num_published,
f5e0338d 4036 "images/pub_set.gif", $link);
e4f4b46f 4037
cf4d339c 4038 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3bd9a780 4039 print "</ul>";
cf4d339c 4040 }
f407c086 4041
cf4d339c 4042 if (!$tags) {
f407c086
AD
4043
4044 if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
4045
4046 $result = db_query($link, "SELECT id,sql_exp,description FROM
4047 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4048
4049 if (db_num_rows($result) > 0) {
4050 if (get_pref($link, 'ENABLE_FEED_CATS')) {
bd64489f
AD
4051
4052 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
bba7c4bf 4053 $cat_hidden = true;
bd64489f 4054 } else {
bba7c4bf 4055 $cat_hidden = false;
bd64489f
AD
4056 }
4057
bba7c4bf 4058 printCategoryHeader($link, -2, $cat_hidden, false);
bd64489f 4059
bba7c4bf
AD
4060# print "<li class=\"feedCat\">".
4061# "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
4062# __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
4063#
4064# print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
f407c086 4065 } else {
3bd9a780 4066 print "<li><hr></li>";
f407c086
AD
4067 }
4068 }
4069
4070 while ($line = db_fetch_assoc($result)) {
4071
4072 error_reporting (0);
4073
4074 $label_id = -$line['id'] - 11;
4075 $count = getFeedUnread($link, $label_id);
4076
4077 $class = "label";
4078
4079 if ($count > 0) {
4080 $class .= "Unread";
4081 }
4082
4083 error_reporting (DEFAULT_ERROR_LEVEL);
4084
4085 printFeedEntry($label_id,
47439031 4086 $class, $line["description"],
f407c086
AD
4087 $count, "images/label.png", $link);
4088
4089 }
4090
4091 if (db_num_rows($result) > 0) {
4092 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4093 print "</ul>";
4094 }
4095 }
4096
4097 }
4098
4099 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3bd9a780 4100 print "<li><hr></li>";
f407c086
AD
4101 }
4102
4103 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4104 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4105 $order_by_qpart = "category,unread DESC,title";
4106 } else {
4107 $order_by_qpart = "category,title";
4108 }
4109 } else {
4110 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4111 $order_by_qpart = "unread DESC,title";
4112 } else {
4113 $order_by_qpart = "title";
4114 }
4115 }
4116
14073c0a
AD
4117 $age_qpart = getMaxAgeSubquery();
4118
f407c086
AD
4119 $result = db_query($link, "SELECT ttrss_feeds.*,
4120 SUBSTRING(last_updated,1,19) AS last_updated_noms,
4121 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4122 WHERE feed_id = ttrss_feeds.id AND unread = true
14073c0a 4123 AND $age_qpart
f407c086
AD
4124 AND ttrss_user_entries.ref_id = ttrss_entries.id
4125 AND owner_uid = '$owner_uid') as unread,
4126 cat_id,last_error,
4127 ttrss_feed_categories.title AS category,
4128 ttrss_feed_categories.collapsed
4129 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4130 ON (ttrss_feed_categories.id = cat_id)
4131 WHERE
4132 ttrss_feeds.hidden = false AND
4133 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4134 ORDER BY $order_by_qpart");
4135
4136 $actid = $_GET["actid"];
4137
4138 /* real feeds */
4139
4140 $lnum = 0;
4141
4142 $total_unread = 0;
4143
4144 $category = "";
4145
4146 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4147
4148 while ($line = db_fetch_assoc($result)) {
4149
47439031 4150 $feed = trim($line["title"]);
0f39ae20
AD
4151
4152 if (!$feed) $feed = "[Untitled]";
4153
f407c086
AD
4154 $feed_id = $line["id"];
4155
4156 $subop = $_GET["subop"];
4157
4158 $unread = $line["unread"];
4159
4160 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4161 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4162 } else {
4163 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4164 }
4165
4166 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4167
4168 if ($rtl_content) {
4169 $rtl_tag = "dir=\"RTL\"";
4170 } else {
4171 $rtl_tag = "";
4172 }
4173
4174 $tmp_result = db_query($link,
4175 "SELECT id,COUNT(unread) AS unread
4176 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
4177 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
4178 WHERE parent_feed = '$feed_id' AND unread = true
4179 GROUP BY ttrss_feeds.id");
4180
4181 if (db_num_rows($tmp_result) > 0) {
4182 while ($l = db_fetch_assoc($tmp_result)) {
4183 $unread += $l["unread"];
4184 }
4185 }
4186
4187 $cat_id = $line["cat_id"];
4188
4189 $tmp_category = $line["category"];
4190
4191 if (!$tmp_category) {
d1db26aa 4192 $tmp_category = __("Uncategorized");
f407c086
AD
4193 }
4194
4195 // $class = ($lnum % 2) ? "even" : "odd";
4196
4197 if ($line["last_error"]) {
4198 $class = "error";
4199 } else {
4200 $class = "feed";
4201 }
4202
4203 if ($unread > 0) $class .= "Unread";
4204
4205 if ($actid == $feed_id) {
4206 $class .= "Selected";
4207 }
4208
4209 $total_unread += $unread;
4210
4211 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4212
4213 if ($category) {
4214 print "</ul></li>";
4215 }
4216
4217 $category = $tmp_category;
4218
4219 $collapsed = $line["collapsed"];
4220
4221 // workaround for NULL category
d1db26aa 4222 if ($category == __("Uncategorized")) {
f407c086
AD
4223 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4224 $collapsed = "t";
4225 }
4226 }
4227
4228 if ($collapsed == "t" || $collapsed == "1") {
225ec0d4
AD
4229 $holder_class = "feedCatHolder";
4230 $holder_style = "display:none;";
66a251f9 4231 $ellipsis = "…";
f407c086 4232 } else {
be5b75da 4233 $holder_class = "feedCatHolder";
225ec0d4 4234 $holder_style = "";
f407c086
AD
4235 $ellipsis = "";
4236 }
4237
4238 $cat_id = sprintf("%d", $cat_id);
4239
4240 $cat_unread = getCategoryUnread($link, $cat_id);
67dabe1a
AD
4241
4242 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4243
3bd9a780 4244 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
439bbe63 4245 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
7210613a 4246 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
dda1396f 4247 <span id=\"FCATCTR-$cat_id\"
67dabe1a 4248 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3bd9a780 4249 </a></li>";
f407c086 4250
225ec0d4 4251 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
f407c086
AD
4252 }
4253
4254 printFeedEntry($feed_id, $class, $feed, $unread,
68dcbd31 4255 ICONS_URL."/$feed_id.ico", $link, $rtl_content,
f407c086
AD
4256 $last_updated, $line["last_error"]);
4257
4258 ++$lnum;
4259 }
4260
4261 if (db_num_rows($result) == 0) {
3bd9a780 4262 print "<li>".__('No feeds to display.')."</li>";
f407c086
AD
4263 }
4264
4265 } else {
4266
4267 // tags
4268
4269/* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4270 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4271 post_int_id = ttrss_user_entries.int_id AND
4272 unread = true AND ref_id = ttrss_entries.id
4273 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4274 UNION
4275 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4276 ORDER BY tag_name"); */
4277
4278 if (get_pref($link, 'ENABLE_FEED_CATS')) {
d1db26aa 4279 print "<li class=\"feedCat\">".__('Tags')."</li>";
f407c086
AD
4280 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4281 }
4282
14073c0a
AD
4283 $age_qpart = getMaxAgeSubquery();
4284
f407c086 4285 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
14073c0a
AD
4286 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4287 AND ref_id = id AND $age_qpart
f407c086 4288 AND unread = true)) AS count FROM ttrss_tags
ef1ac7c7
AD
4289 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4290 ORDER BY count DESC LIMIT 50");
f407c086
AD
4291
4292 $tags = array();
4293
4294 while ($line = db_fetch_assoc($result)) {
4295 $tags[$line["tag_name"]] += $line["count"];
4296 }
4297
4298 foreach (array_keys($tags) as $tag) {
4299
4300 $unread = $tags[$tag];
4301
4302 $class = "tag";
4303
4304 if ($unread > 0) {
4305 $class .= "Unread";
4306 }
4307
4308 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4309
4310 }
4311
4312 if (db_num_rows($result) == 0) {
4313 print "<li>No tags to display.</li>";
4314 }
4315
4316 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3bd9a780 4317 print "</ul>";
f407c086
AD
4318 }
4319
4320 }
4321
4322 print "</ul>";
4323
4324 }
4325
bc976a8c 4326 function get_article_tags($link, $id, $owner_uid = 0) {
0b126ac2
AD
4327
4328 $a_id = db_escape_string($id);
4329
bc976a8c
AD
4330 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4331
0c3d1c68
AD
4332 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4333 owner_uid as owner FROM
0b126ac2 4334 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bc976a8c 4335 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
0b126ac2
AD
4336
4337 $tags = array();
4338
4339 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4340 array_push($tags, $tmp_line["tag_name"]);
4341 }
4342
4343 return $tags;
4344 }
4345
d62a3b63
AD
4346 function trim_value(&$value) {
4347 $value = trim($value);
4348 }
4349
4350 function trim_array($array) {
4351 $tmp = $array;
4352 array_walk($tmp, 'trim_value');
4353 return $tmp;
4354 }
4355
be832a1a 4356 function tag_is_valid($tag) {
ef063748
AD
4357 if ($tag == '') return false;
4358 if (preg_match("/^[0-9]*$/", $tag)) return false;
4359
4360 $tag = iconv("utf-8", "utf-8", $tag);
4361 if (!$tag) return false;
4362
4363 return true;
be832a1a
AD
4364 }
4365
793185a9
AD
4366 function render_login_form($link, $mobile = false) {
4367 if (!$mobile) {
4368 require_once "login_form.php";
4369 } else {
4370 require_once "mobile/login_form.php";
4371 }
01a87dff
AD
4372 }
4373
dc56b3b7
AD
4374 // from http://developer.apple.com/internet/safari/faq.html
4375 function no_cache_incantation() {
4376 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4377 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4378 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4379 header("Cache-Control: post-check=0, pre-check=0", false);
4380 header("Pragma: no-cache"); // HTTP/1.0
4381 }
4382
42395d28
AD
4383 function format_warning($msg, $id = "") {
4384 return "<div class=\"warning\" id=\"$id\">
e780d1d2 4385 <img src=\"images/sign_excl.gif\">$msg</div>";
0d32b41e
AD
4386 }
4387
4388 function format_notice($msg) {
4389 return "<div class=\"notice\">
e780d1d2 4390 <img src=\"images/sign_info.gif\">$msg</div>";
0d32b41e
AD
4391 }
4392
68d2f95e
AD
4393 function format_error($msg) {
4394 return "<div class=\"error\">
e780d1d2 4395 <img src=\"images/sign_excl.gif\">$msg</div>";
68d2f95e
AD
4396 }
4397
4dccf1ed
AD
4398 function print_notice($msg) {
4399 return print format_notice($msg);
4400 }
4401
4402 function print_warning($msg) {
4403 return print format_warning($msg);
4404 }
4405
68d2f95e
AD
4406 function print_error($msg) {
4407 return print format_error($msg);
4408 }
4409
4410
4dccf1ed
AD
4411 function T_sprintf() {
4412 $args = func_get_args();
4413 return vsprintf(__(array_shift($args)), $args);
4414 }
4415
3de0261a
AD
4416 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4417
10eb9da8
AD
4418 /* we can figure out feed_id from article id anyway, why do we
4419 * pass feed_id here? */
4420
4421 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4422 WHERE ref_id = '$id'");
4423
4424 $feed_id = db_fetch_result($result, 0, "feed_id");
4425
3de0261a
AD
4426 print "<article id='$id'><![CDATA[";
4427
4428 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4429 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4430
4431 if (db_num_rows($result) == 1) {
4432 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4433 } else {
4434 $rtl_content = false;
4435 }
4436
4437 if ($rtl_content) {
4438 $rtl_tag = "dir=\"RTL\"";
4439 $rtl_class = "RTL";
4440 } else {
4441 $rtl_tag = "";
4442 $rtl_class = "";
4443 }
4444
4445 if ($mark_as_read) {
4446 $result = db_query($link, "UPDATE ttrss_user_entries
4447 SET unread = false,last_read = NOW()
4448 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4449 }
4450
4451 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4452 SUBSTRING(updated,1,16) as updated,
4453 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4454 num_comments,
4455 author
4456 FROM ttrss_entries,ttrss_user_entries
4457 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4458
4459 if ($result) {
4460
4461 $link_target = "";
4462
4463 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4464 $link_target = "target=\"_new\"";
4465 }
4466
4467 $line = db_fetch_assoc($result);
4468
4469 if ($line["icon_url"]) {
4470 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4471 } else {
4472 $feed_icon = "&nbsp;";
4473 }
4474
4475/* if ($line["comments"] && $line["link"] != $line["comments"]) {
4476 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4477 } else {
4478 $entry_comments = "";
4479 } */
4480
4481 $num_comments = $line["num_comments"];
4482 $entry_comments = "";
4483
4484 if ($num_comments > 0) {
4485 if ($line["comments"]) {
4486 $comments_url = $line["comments"];
4487 } else {
4488 $comments_url = $line["link"];
4489 }
4490 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4491 } else {
4492 if ($line["comments"] && $line["link"] != $line["comments"]) {
4493 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4494 }
4495 }
4496
4497 print "<div class=\"postReply\">";
4498
4499 print "<div class=\"postHeader\">";
4500
4501 $entry_author = $line["author"];
4502
4503 if ($entry_author) {
60164936 4504 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
4505 }
4506
4507 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4508 strtotime($line["updated"]));
4509
4510 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4511
4512 if ($line["link"]) {
4513 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
06202d88 4514 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
3de0261a
AD
4515 } else {
4516 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4517 }
4518
9cfd409d 4519/* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3de0261a 4520 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
9cfd409d
AD
4521 ORDER BY tag_name"); */
4522
4523 $tags = get_article_tags($link, $id);
3de0261a
AD
4524
4525 $tags_str = "";
4526 $f_tags_str = "";
4527
4528 $num_tags = 0;
4529
20361063
AD
4530 if ($_SESSION["theme"] == "3pane") {
4531 $tag_limit = 3;
4532 } else {
4533 $tag_limit = 6;
4534 }
4535
9cfd409d 4536 foreach ($tags as $tag) {
3de0261a 4537 $num_tags++;
14b6c54b
AD
4538 $tag_escaped = str_replace("'", "\\'", $tag);
4539
4540 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
3de0261a 4541
20361063 4542 if ($num_tags == $tag_limit) {
66a251f9 4543 $tags_str .= "&hellip;";
e7544143 4544
20361063 4545 } else if ($num_tags < $tag_limit) {
3de0261a
AD
4546 $tags_str .= $tag_str;
4547 }
4548 $f_tags_str .= $tag_str;
4549 }
4550
4551 $tags_str = preg_replace("/, $/", "", $tags_str);
4552 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4553
66a251f9 4554 $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
e7544143
AD
4555 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4556
3de0261a
AD
4557 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4558
4559 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4560
5f014cf1
AD
4561 print "<div style='float : right'>
4562 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4563 $tags_str
3de0261a
AD
4564 <a title=\"Edit tags for this article\"
4565 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4566 <div clear='both'>$entry_comments</div>";
4567
4568 print "</div>";
4569
4570 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4571 print "<div class=\"postContent\">";
4572
e7544143 4573 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
3de0261a 4574
c41890b0
AD
4575 $line["content"] = sanitize_rss($link, $line["content"]);
4576
3de0261a
AD
4577 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4578 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4579 }
4580
ce53e200
AD
4581 print $line["content"];
4582
4583 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4584 post_id = '$id'");
4585
4586 if (db_num_rows($result) > 0) {
4587 print "<div class=\"postEnclosures\">";
4588
4589 if (db_num_rows($result) == 1) {
4590 print __("Attachment:") . " ";
4591 } else {
4592 print __("Attachments:") . " ";
4593 }
4594
4595 $entries = array();
4596
4597 while ($line = db_fetch_assoc($result)) {
4598
4599 $url = $line["content_url"];
4600
4601 $filename = substr($url, strrpos($url, "/")+1);
4602
46f73352 4603 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
ce53e200
AD
4604 $filename . " (" . $line["content_type"] . ")" . "</a>";
4605
4606 array_push($entries, $entry);
4607 }
4608
4609 print join(", ", $entries);
4610
4611 print "</div>";
4612 }
4613
4614 print "</div>";
3de0261a
AD
4615
4616 print "</div>";
4617
4618 }
4619
4620 print "]]></article>";
4621
4622 }
4623
4624 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4625 $next_unread_feed, $offset) {
4626
52d7e7da
AD
4627 $disable_cache = false;
4628
46921916
AD
4629 $timing_info = getmicrotime();
4630
961f4c73
AD
4631 $topmost_article_ids = array();
4632
ac541432
AD
4633 if (!$offset) {
4634 $offset = 0;
4635 }
3de0261a
AD
4636
4637 if ($subop == "undefined") $subop = "";
4638
4639 if ($subop == "CatchupSelected") {
4640 $ids = split(",", db_escape_string($_GET["ids"]));
4641 $cmode = sprintf("%d", $_GET["cmode"]);
4642
4643 catchupArticlesById($link, $ids, $cmode);
4644 }
4645
4646 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
35bf080c 4647 update_generic_feed($link, $feed, $cat_view, true);
3de0261a
AD
4648 }
4649
4650 if ($subop == "MarkAllRead") {
4651 catchup_feed($link, $feed, $cat_view);
4652
4653 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4654 if ($next_unread_feed) {
4655 $feed = $next_unread_feed;
4656 }
4657 }
4658 }
4659
4660 if ($feed_id > 0) {
4661 $result = db_query($link,
4662 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4663
4664 if (db_num_rows($result) == 0) {
4665 print "<div align='center'>".__('Feed not found.')."</div>";
4666 return;
4667 }
4668 }
4669
4670 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
10eb9da8 4671
3de0261a
AD
4672 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4673 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4674
4675 if (db_num_rows($result) == 1) {
4676 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4677 } else {
4678 $rtl_content = false;
4679 }
4680
4681 if ($rtl_content) {
4682 $rtl_tag = "dir=\"RTL\"";
4683 } else {
4684 $rtl_tag = "";
4685 }
4686 } else {
4687 $rtl_tag = "";
4688 $rtl_content = false;
4689 }
4690
4691 $script_dt_add = get_script_dt_add();
4692
4693 /// START /////////////////////////////////////////////////////////////////////////////////
4694
4695 $search = db_escape_string($_GET["query"]);
52d7e7da
AD
4696
4697 if ($search) {
4698 $disable_cache = true;
4699 }
4700
3de0261a
AD
4701 $search_mode = db_escape_string($_GET["search_mode"]);
4702 $match_on = db_escape_string($_GET["match_on"]);
4703
4704 if (!$match_on) {
4705 $match_on = "both";
4706 }
4707
4708 $real_offset = $offset * $limit;
4709
46921916
AD
4710 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4711
3de0261a
AD
4712 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4713 $search, $search_mode, $match_on, false, $real_offset);
4714
46921916
AD
4715 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4716
3de0261a
AD
4717 $result = $qfh_ret[0];
4718 $feed_title = $qfh_ret[1];
4719 $feed_site_url = $qfh_ret[2];
4720 $last_error = $qfh_ret[3];
f56e3080
AD
4721
4722 if ($feed == -2) {
4723 $feed_site_url = article_publish_url($link);
4724 }
4725
3de0261a
AD
4726 /// STOP //////////////////////////////////////////////////////////////////////////////////
4727
ac541432
AD
4728 if (!$offset) {
4729 print "<div id=\"headlinesContainer\" $rtl_tag>";
3de0261a 4730
ac541432
AD
4731 if (!$result) {
4732 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4733 return;
4734 }
3de0261a 4735
ac541432
AD
4736 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4737 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4738 $offset, $limit);
3de0261a 4739
ac541432
AD
4740 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4741 }
3de0261a 4742
29dfb258
AD
4743 $headlines_count = db_num_rows($result);
4744
3de0261a
AD
4745 if (db_num_rows($result) > 0) {
4746
4747# print "\{$offset}";
4748
ac541432 4749 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
3de0261a
AD
4750 print "<table class=\"headlinesList\" id=\"headlinesList\"
4751 cellspacing=\"0\">";
4752 }
4753
4ab4d364
AD
4754 $lnum = $limit*$offset;
4755
3de0261a
AD
4756 error_reporting (DEFAULT_ERROR_LEVEL);
4757
4758 $num_unread = 0;
4759
4760 while ($line = db_fetch_assoc($result)) {
4761
4762 $class = ($lnum % 2) ? "even" : "odd";
4763
4764 $id = $line["id"];
4765 $feed_id = $line["feed_id"];
961f4c73
AD
4766
4767 if (count($topmost_article_ids) < 5) {
4768 array_push($topmost_article_ids, $id);
4769 }
4770
3de0261a
AD
4771 if ($line["last_read"] == "" &&
4772 ($line["unread"] != "t" && $line["unread"] != "1")) {
4773
4774 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4775 alt=\"Updated\">";
4776 } else {
4777 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4778 alt=\"Updated\">";
4779 }
4780
4781 if ($line["unread"] == "t" || $line["unread"] == "1") {
4782 $class .= "Unread";
4783 ++$num_unread;
4784 $is_unread = true;
4785 } else {
4786 $is_unread = false;
4787 }
abd8a516
AD
4788
4789 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4790
4791 if ($is_ie) {
4792 $mark_img_ext = "gif";
4793 } else {
4794 $mark_img_ext = "png";
4795 }
4796
3de0261a 4797 if ($line["marked"] == "t" || $line["marked"] == "1") {
abd8a516 4798 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
3de0261a 4799 class=\"markedPic\"
f5e0338d 4800 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
3de0261a 4801 } else {
abd8a516 4802 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
3de0261a 4803 class=\"markedPic\"
f5e0338d 4804 alt=\"Star article\" onclick='javascript:tMark($id)'>";
3de0261a
AD
4805 }
4806
e4f4b46f 4807 if ($line["published"] == "t" || $line["published"] == "1") {
f5e0338d 4808 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
e4f4b46f 4809 class=\"markedPic\"
f5e0338d 4810 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
e4f4b46f 4811 } else {
f5e0338d 4812 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
e4f4b46f 4813 class=\"markedPic\"
f5e0338d 4814 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
e4f4b46f
AD
4815 }
4816
3de0261a
AD
4817# $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4818# $line["title"] . "</a>";
4819
4820 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4821 $line["title"] . "</a>";
4822
4823# $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4824# $line["title"] . "</a>";
4825
4826 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
46921916 4827 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
3de0261a
AD
4828 } else {
4829 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
46921916 4830 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
3de0261a
AD
4831 }
4832
4833 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4834 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4835 100);
4836 }
4837
4838 $entry_author = $line["author"];
4839
4840 if ($entry_author) {
60164936 4841 $entry_author = " - $entry_author";
3de0261a
AD
4842 }
4843
4844 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4845
4846 print "<tr class='$class' id='RROW-$id'>";
4847
67343d9f 4848 print "<td class='hlUpdPic'>$update_pic</td>";
3de0261a
AD
4849
4850 print "<td class='hlSelectRow'>
67343d9f
AD
4851 <input type=\"checkbox\" onclick=\"tSR(this)\"
4852 id=\"RCHK-$id\">
3de0261a
AD
4853 </td>";
4854
4855 print "<td class='hlMarkedPic'>$marked_pic</td>";
e4f4b46f 4856 print "<td class='hlMarkedPic'>$published_pic</td>";
3de0261a 4857
df456bb0
AD
4858# if ($line["feed_title"]) {
4859# print "<td class='hlContent'>$content_link</td>";
4860# print "<td class='hlFeed'>
4861# <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4862# truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
4863# } else {
4864
4865 print "<td class='hlContent' valign='middle'>";
4866
4867 print "<a href=\"javascript:view($id,$feed_id);\">" .
4868 $line["title"];
4869
4870 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4871 if ($content_preview) {
4872 print "<span class=\"contentPreview\"> - $content_preview</span>";
3de0261a 4873 }
3de0261a 4874 }
df456bb0
AD
4875
4876 print "</a>";
4877
4878# <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4879# $line["feed_title"]."</a>
4880
4881 if ($line["feed_title"]) {
4882 print "<span class=\"hlFeed\">
4883 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4884 $line["feed_title"]."</a>)
4885 </span>";
4886 }
4887
4888
4889 print "</td>";
4890
4891# }
3de0261a
AD
4892
4893 print "<td class=\"hlUpdated\"><nobr>$updated_fmt&nbsp;</nobr></td>";
4894
4895 print "</tr>";
4896
4897 } else {
4898
4899 if ($is_unread) {
4900 $add_class = "Unread";
4901 } else {
4902 $add_class = "";
4903 }
0cacc891
AD
4904
4905 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
4906
4907 if ($expand_cdm) {
4908 $cdm_cstyle = "";
4909 } else {
4910 $cdm_cstyle = "style=\"display : none\"";
4911 }
4912
e4914b62
AD
4913 print "<div class=\"cdmArticle$add_class\"
4914 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4915 onmouseout='cdmMouseOut(this)'>";
3de0261a
AD
4916
4917 print "<div class=\"cdmHeader\">";
4918
4919 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4920
4921 print "<a class=\"title\"
4922 onclick=\"javascript:toggleUnread($id, 0)\"
3fc2eed5 4923 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
3de0261a
AD
4924
4925 print $entry_author;
4926
0cacc891
AD
4927 if (!$expand_cdm) {
4928 print "&nbsp;<a id=\"CICH-$id\"
4929 href=\"javascript:cdmExpandArticle($id)\">
4930 (".__('Show article').")</a>";
4931 }
4932
4933
3de0261a
AD
4934 if ($line["feed_title"]) {
4935 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4936 }
4937
4938 print "</div>";
4939
3fc2eed5
AD
4940 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4941 $line["content_preview"] = preg_replace("/href=/i",
4942 "target=\"_new\" href=", $line["content_preview"]);
4943 }
4944
0cacc891 4945 print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
a04c8e8d 4946
0cacc891 4947// print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
a04c8e8d 4948 print $line["content_preview"];
3c66b582
AD
4949
4950 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4951 post_id = '$id'");
4952
4953 if (db_num_rows($e_result) > 0) {
4954 print "<div class=\"cdmEnclosures\">";
4955
4956 if (db_num_rows($e_result) == 1) {
4957 print __("Attachment:") . " ";
4958 } else {
4959 print __("Attachments:") . " ";
4960 }
4961
4962 $entries = array();
4963
4964 while ($e_line = db_fetch_assoc($e_result)) {
4965
4966 $url = $e_line["content_url"];
4967
4968 $filename = substr($url, strrpos($url, "/")+1);
4969
46f73352 4970 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3c66b582
AD
4971 $filename . " (" . $e_line["content_type"] . ")" . "</a>";
4972
4973 array_push($entries, $entry);
4974 }
4975
4976 print join(", ", $entries);
4977
4978 print "</div>";
4979 }
4980
0cacc891
AD
4981 print "<br clear='both'>";
4982// print "</div>";
a04c8e8d 4983
0cacc891 4984/* if (!$expand_cdm) {
12f5d8fe
AD
4985 print "<a id=\"CICH-$id\"
4986 href=\"javascript:cdmExpandArticle($id)\">
4987 Show article</a>";
0cacc891 4988 } */
a04c8e8d 4989
0cacc891 4990 print "</div>";
3de0261a 4991
e2ccbfab 4992 print "<div class=\"cdmFooter\"><span class='s0'>";
3de0261a 4993
e2ccbfab 4994 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
3de0261a 4995
e2ccbfab
AD
4996 print __("Select:").
4997 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
3de0261a
AD
4998 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
4999
e2ccbfab 5000 print "</span><span class='s1'>$marked_pic</span> ";
e4f4b46f 5001 print "<span class='s1'>$published_pic</span> ";
e2ccbfab 5002
3de0261a
AD
5003 $tags = get_article_tags($link, $id);
5004
5005 $tags_str = "";
22d1f3db 5006 $full_tags_str = "";
d735ebd2 5007 $num_tags = 0;
3de0261a
AD
5008
5009 foreach ($tags as $tag) {
5010 $num_tags++;
22d1f3db
AD
5011 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5012 if ($num_tags < 5) {
5013 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5014 } else if ($num_tags == 5) {
66a251f9 5015 $tags_str .= "&hellip;";
22d1f3db 5016 }
3de0261a
AD
5017 }
5018
5019 $tags_str = preg_replace("/, $/", "", $tags_str);
22d1f3db
AD
5020 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5021
66a251f9 5022 $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
22d1f3db
AD
5023
5024 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5025
3de0261a
AD
5026
5027 if ($tags_str == "") $tags_str = "no tags";
e2ccbfab
AD
5028
5029// print "<img src='images/tag.png' class='markedPic'>";
5030
5f014cf1
AD
5031 print "<span class='s1'>
5032 <img class='tagsPic' src='images/tag.png' alt='Tags'
5033 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
3de0261a
AD
5034 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5035
e2ccbfab 5036 print "</span>";
3de0261a 5037
e2ccbfab
AD
5038 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5039 href=\"javascript:toggleUnread($id)\">
5040 Unread</a></span>";
3de0261a 5041
e2ccbfab 5042 print "</div>";
3de0261a
AD
5043 print "</div>";
5044
5045 }
5046
5047 ++$lnum;
5048 }
5049
ac541432 5050 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
3de0261a
AD
5051 print "</table>";
5052 }
5053
5054// print_headline_subtoolbar($link,
5055// "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5056
5057
5058 } else {
ac541432 5059 if (!$offset) print "<div class='whiteBox'>".__('No articles found.')."</div>";
3de0261a
AD
5060 }
5061
ac541432
AD
5062 if (!$offset) {
5063 print "</div>";
5064 print "</div>";
5065 }
3de0261a 5066
52d7e7da 5067 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
3de0261a 5068 }
0979b696
AD
5069
5070// from here: http://www.roscripts.com/Create_tag_cloud-71.html
5071
5072 function printTagCloud($link) {
35a03bdd
AD
5073
5074 /* get first ref_id to count from */
5075
dcac082b
AD
5076 /*
5077
35a03bdd
AD
5078 $query = "";
5079
5080 if (DB_TYPE == "pgsql") {
5081 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5082 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5083 AND date_entered > NOW() - INTERVAL '30 days'";
5084 } else {
5085 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5086 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5087 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5088 }
5089
5090 $result = db_query($link, $query);
dcac082b 5091 $first_id = db_fetch_result($result, 0, "id"); */
35a03bdd 5092
dcac082b 5093 //AND post_int_id >= '$first_id'
0979b696
AD
5094 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5095 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
b31af972 5096 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
0979b696
AD
5097
5098 $result = db_query($link, $query);
5099
5100 $tags = array();
5101
5102 while ($line = db_fetch_assoc($result)) {
5103 $tags[$line["tag_name"]] = $line["count"];
5104 }
5105
5106 ksort($tags);
5107
5108 $max_size = 32; // max font size in pixels
4548a580 5109 $min_size = 11; // min font size in pixels
0979b696
AD
5110
5111 // largest and smallest array values
5112 $max_qty = max(array_values($tags));
5113 $min_qty = min(array_values($tags));
5114
5115 // find the range of values
5116 $spread = $max_qty - $min_qty;
5117 if ($spread == 0) { // we don't want to divide by zero
5118 $spread = 1;
5119 }
5120
5121 // set the font-size increment
5122 $step = ($max_size - $min_size) / ($spread);
5123
5124 // loop through the tag array
5125 foreach ($tags as $key => $value) {
5126 // calculate font-size
5127 // find the $value in excess of $min_qty
5128 // multiply by the font-size increment ($size)
5129 // and add the $min_size set above
5130 $size = round($min_size + (($value - $min_qty) * $step));
546ffab4
AD
5131
5132 $key_escaped = str_replace("'", "\\'", $key);
5133
5134 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
0979b696
AD
5135 $size . "px\" title=\"$value articles tagged with " .
5136 $key . '">' . $key . '</a> ';
5137 }
5138 }
46921916
AD
5139
5140 function print_checkpoint($n, $s) {
5141 $ts = getmicrotime();
5142 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5143 return $ts;
5144 }
14b6c54b
AD
5145
5146 function sanitize_tag($tag) {
5147 $tag = trim($tag);
5148
5149 $tag = mb_strtolower($tag, 'utf-8');
5150
0c3d1c68
AD
5151 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5152
5153// $tag = str_replace('"', "", $tag);
5154// $tag = str_replace("+", " ", $tag);
14b6c54b
AD
5155 $tag = str_replace("technorati tag: ", "", $tag);
5156
5157 return $tag;
5158 }
e4f4b46f
AD
5159
5160 function generate_publish_key() {
5161 return sha1(uniqid(rand(), true));
5162 }
5163
f56e3080
AD
5164 function article_publish_url($link) {
5165
17a756d1 5166 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
f56e3080
AD
5167
5168 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5169
5170 return $url_path;
5171 }
5172
45004d43
AD
5173 /**
5174 * Purge a feed contents, marked articles excepted.
5175 *
5176 * @param mixed $link The database connection.
5177 * @param integer $id The id of the feed to purge.
5178 * @return void
5179 */
d1f0c584
AD
5180 function clear_feed_articles($link, $id) {
5181 $result = db_query($link, "DELETE FROM ttrss_user_entries
a8ae1b9a 5182 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
d1f0c584
AD
5183
5184 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5185 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
45004d43
AD
5186 } // function clear_feed_articles
5187
5188 /**
5189 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5190 *
5191 * @return string The Mozilla Firefox feed adding URL.
5192 */
5193 function add_feed_url() {
755a43ee
AD
5194 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5195 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5196 return $url_path;
45004d43
AD
5197 } // function add_feed_url
5198
5199 /**
5200 * Encrypt a password in SHA1.
5201 *
5202 * @param string $pass The password to encrypt.
5203 * @param string $login A optionnal login.
5204 * @return string The encrypted password.
5205 */
1a9f4d3c
AD
5206 function encrypt_password($pass, $login = '') {
5207 if ($login) {
5208 return "SHA1X:" . sha1("$login:$pass");
5209 } else {
5210 return "SHA1:" . sha1($pass);
5211 }
45004d43
AD
5212 } // function encrypt_password
5213
5214 /**
5215 * Update a feed batch.
5216 * Used by daemons to update n feeds by run.
5217 * Only update feed needing a update, and not being processed
5218 * by another process.
5219 *
5220 * @param mixed $link Database link
5221 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5222 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5223 * @param boolean $debug Set to false to disable debug output. Default to true.
5224 * @return void
5225 */
5226 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5227 // Process all other feeds using last_updated and interval parameters
5228
5229 // Test if the user has loggued in recently. If not, it does not update its feeds.
5230 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5231 if (DB_TYPE == "pgsql") {
5232 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5233 } else {
5234 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5235 }
5236 } else {
5237 $login_thresh_qpart = "";
5238 }
5239
5240 // Test if the feed need a update (update interval exceded).
5241 if (DB_TYPE == "pgsql") {
5242 $update_limit_qpart = "AND ((
5243 ttrss_feeds.update_interval = 0
5244 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5245 ) OR (
5246 ttrss_feeds.update_interval > 0
5247 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
da4caf5d 5248 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5249 } else {
5250 $update_limit_qpart = "AND ((
5251 ttrss_feeds.update_interval = 0
5252 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5253 ) OR (
5254 ttrss_feeds.update_interval > 0
5255 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
da4caf5d 5256 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5257 }
5258
5259 // Test if feed is currently being updated by another process.
5260 if (DB_TYPE == "pgsql") {
5261 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5262 } else {
5263 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5264 }
5265
5266 // Test if there is a limit to number of updated feeds
5267 $query_limit = "";
5268 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5269
51b8c957
AD
5270 $random_qpart = sql_random_function();
5271
45004d43
AD
5272 // We search for feed needing update.
5273 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5274 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
5275 ttrss_feeds.update_interval
5276 FROM
5277 ttrss_feeds, ttrss_users, ttrss_user_prefs
5278 WHERE
5279 ttrss_feeds.owner_uid = ttrss_users.id
5280 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5281 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5282 $login_thresh_qpart $update_limit_qpart
51b8c957
AD
5283 $updstart_thresh_qpart
5284 ORDER BY $random_qpart $query_limit");
45004d43
AD
5285
5286 $user_prefs_cache = array();
5287
5288 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5289
5290 // Here is a little cache magic in order to minimize risk of double feed updates.
5291 $feeds_to_update = array();
5292 while ($line = db_fetch_assoc($result)) {
5293 $feeds_to_update[$line['id']] = $line;
5294 }
5295
5296 // We update the feed last update started date before anything else.
5297 // There is no lag due to feed contents downloads
5298 // It prevent an other process to update the same feed.
5299 $feed_ids = array_keys($feeds_to_update);
5300 if($feed_ids) {
5301 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5302 WHERE id IN (%s)", implode(',', $feed_ids)));
5303 }
5304
5305 // For each feed, we call the feed update function.
5306 while ($line = array_pop($feeds_to_update)) {
5307
5308 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5309
5310 // We setup a alarm to alert if the feed take more than 300s to update.
5311 // => HANG alarm.
5312 if(!$from_http) pcntl_alarm(300);
5313 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5314 // Cancel the alarm (the update went well)
5315 if(!$from_http) pcntl_alarm(0);
5316
5317 sleep(1); // prevent flood (FIXME make this an option?)
5318 }
5319
5320 // Send feed digests by email if needed.
5321 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5322
5323 } // function update_daemon_common
1a9f4d3c 5324
40d13c28 5325?>