]> git.wh0rd.org - tt-rss.git/blob - functions.php
offline: add workaround for stuck login screen when going back from offline mode
[tt-rss.git] / functions.php
1 <?php
2
3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
5 } else {
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
7 } */
8
9 require_once 'config.php';
10
11 if (DB_TYPE == "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
13 } else {
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
15 }
16
17 /**
18 * Return available translations names.
19 *
20 * @access public
21 * @return array A array of available translations.
22 */
23 function get_translations() {
24 $tr = array(
25 "auto" => "Detect automatically",
26 "en_US" => "English",
27 "de_DE" => "Deutsch",
28 "fr_FR" => "Français",
29 "hu_HU" => "Magyar (Hungarian)",
30 "it_IT" => "Italiano",
31 "ja_JP" => "日本語 (Japanese)",
32 "nb_NO" => "Norwegian bokmål",
33 "ru_RU" => "Русский",
34 "pt_BR" => "Portuguese/Brazil",
35 "zh_CN" => "Simplified Chinese");
36
37 return $tr;
38 }
39
40 if (ENABLE_TRANSLATIONS == true) { // If translations are enabled.
41 require_once "accept-to-gettext.php";
42 require_once "lib/gettext/gettext.inc";
43
44 function startup_gettext() {
45
46 # Get locale from Accept-Language header
47 $lang = al2gt(array_keys(get_translations()), "text/html");
48
49 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
50 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
51 }
52
53 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
54 $lang = $_COOKIE["ttrss_lang"];
55 }
56
57 /* In login action of mobile version */
58 if ($_POST["language"] && defined('MOBILE_VERSION')) {
59 $lang = $_POST["language"];
60 $_COOKIE["ttrss_lang"] = $lang;
61 }
62
63 if ($lang) {
64 if (defined('LC_MESSAGES')) {
65 _setlocale(LC_MESSAGES, $lang);
66 } else if (defined('LC_ALL')) {
67 _setlocale(LC_ALL, $lang);
68 } else {
69 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
70 }
71
72 if (defined('MOBILE_VERSION')) {
73 _bindtextdomain("messages", "../locale");
74 } else {
75 _bindtextdomain("messages", "locale");
76 }
77
78 _textdomain("messages");
79 _bind_textdomain_codeset("messages", "UTF-8");
80 }
81 }
82
83 startup_gettext();
84
85 } else { // If translations are enabled.
86 function __($msg) {
87 return $msg;
88 }
89 function startup_gettext() {
90 // no-op
91 return true;
92 }
93 } // If translations are enabled.
94
95 require_once 'db-prefs.php';
96 require_once 'compat.php';
97 require_once 'errors.php';
98 require_once 'version.php';
99
100 require_once 'lib/phpmailer/class.phpmailer.php';
101
102 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
103 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
104 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105
106 require_once "lib/simplepie/simplepie.inc";
107 require_once "lib/magpierss/rss_fetch.inc";
108 require_once 'lib/magpierss/rss_utils.inc';
109 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
110
111 /**
112 * Print a timestamped debug message.
113 *
114 * @param string $msg The debug message.
115 * @return void
116 */
117 function _debug($msg) {
118 $ts = strftime("%H:%M:%S", time());
119 if (function_exists('posix_getpid')) {
120 $ts = "$ts/" . posix_getpid();
121 }
122 print "[$ts] $msg\n";
123 } // function _debug
124
125 /**
126 * Purge a feed old posts.
127 *
128 * @param mixed $link A database connection.
129 * @param mixed $feed_id The id of the purged feed.
130 * @param mixed $purge_interval Olderness of purged posts.
131 * @param boolean $debug Set to True to enable the debug. False by default.
132 * @access public
133 * @return void
134 */
135 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
136
137 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
138
139 $rows = -1;
140
141 $result = db_query($link,
142 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
143
144 $owner_uid = false;
145
146 if (db_num_rows($result) == 1) {
147 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 }
149
150 if ($purge_interval == -1 || !$purge_interval) {
151 if ($owner_uid) {
152 ccache_update($link, $feed_id, $owner_uid);
153 }
154 return;
155 }
156
157 if (!$owner_uid) return;
158
159 if (FORCE_ARTICLE_PURGE == 0) {
160 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
161 $owner_uid, false);
162 } else {
163 $purge_unread = true;
164 $purge_interval = FORCE_ARTICLE_PURGE;
165 }
166
167 if (!$purge_unread) $query_limit = " unread = false AND ";
168
169 if (DB_TYPE == "pgsql") {
170 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
171 marked = false AND feed_id = '$feed_id' AND
172 (SELECT date_entered FROM ttrss_entries WHERE
173 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
174
175 $pg_version = get_pgsql_version($link);
176
177 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
178
179 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
180 ttrss_entries.id = ref_id AND
181 marked = false AND
182 feed_id = '$feed_id' AND
183 $query_limit
184 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
185
186 } else {
187
188 $result = db_query($link, "DELETE FROM ttrss_user_entries
189 USING ttrss_entries
190 WHERE ttrss_entries.id = ref_id AND
191 marked = false AND
192 feed_id = '$feed_id' AND
193 $query_limit
194 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
195 }
196
197 $rows = pg_affected_rows($result);
198
199 } else {
200
201 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
202 marked = false AND feed_id = '$feed_id' AND
203 (SELECT date_entered FROM ttrss_entries WHERE
204 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
205
206 $result = db_query($link, "DELETE FROM ttrss_user_entries
207 USING ttrss_user_entries, ttrss_entries
208 WHERE ttrss_entries.id = ref_id AND
209 marked = false AND
210 feed_id = '$feed_id' AND
211 $query_limit
212 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
213
214 $rows = mysql_affected_rows($link);
215
216 }
217
218 ccache_update($link, $feed_id, $owner_uid);
219
220 if ($debug) {
221 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
222 }
223 } // function purge_feed
224
225 /**
226 * Purge old posts from old feeds.
227 *
228 * @param mixed $link A database connection
229 * @param boolean $do_output Set to true to enable printed output, false by default.
230 * @param integer $limit The maximal number of removed posts.
231 * @access public
232 * @return void
233 */
234 function global_purge_old_posts($link, $do_output = false, $limit = false) {
235
236 $random_qpart = sql_random_function();
237
238 if ($limit) {
239 $limit_qpart = "LIMIT $limit";
240 } else {
241 $limit_qpart = "";
242 }
243
244 $result = db_query($link,
245 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
246 ORDER BY $random_qpart $limit_qpart");
247
248 while ($line = db_fetch_assoc($result)) {
249
250 $feed_id = $line["id"];
251 $purge_interval = $line["purge_interval"];
252 $owner_uid = $line["owner_uid"];
253
254 if ($purge_interval == 0) {
255
256 $tmp_result = db_query($link,
257 "SELECT value FROM ttrss_user_prefs WHERE
258 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
259
260 if (db_num_rows($tmp_result) != 0) {
261 $purge_interval = db_fetch_result($tmp_result, 0, "value");
262 }
263 }
264
265 if ($do_output) {
266 // print "Feed $feed_id: purge interval = $purge_interval\n";
267 }
268
269 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
270 purge_feed($link, $feed_id, $purge_interval, $do_output);
271 }
272 }
273
274 // purge orphaned posts in main content table
275 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
276 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
277
278 if ($do_output) {
279 $rows = db_affected_rows($link, $result);
280 _debug("Purged $rows orphaned posts.");
281 }
282
283 } // function global_purge_old_posts
284
285 function feed_purge_interval($link, $feed_id) {
286
287 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
288 WHERE id = '$feed_id'");
289
290 if (db_num_rows($result) == 1) {
291 $purge_interval = db_fetch_result($result, 0, "purge_interval");
292 $owner_uid = db_fetch_result($result, 0, "owner_uid");
293
294 if ($purge_interval == 0) $purge_interval = get_pref($link,
295 'PURGE_OLD_DAYS', $owner_uid);
296
297 return $purge_interval;
298
299 } else {
300 return -1;
301 }
302 }
303
304 function purge_old_posts($link) {
305
306 $user_id = $_SESSION["uid"];
307
308 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
309 WHERE owner_uid = '$user_id'");
310
311 while ($line = db_fetch_assoc($result)) {
312
313 $feed_id = $line["id"];
314 $purge_interval = $line["purge_interval"];
315
316 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
317
318 if ($purge_interval > 0) {
319 purge_feed($link, $feed_id, $purge_interval);
320 }
321 }
322
323 purge_orphans($link);
324 }
325
326 function purge_orphans($link) {
327 // purge orphaned posts in main content table
328 db_query($link, "DELETE FROM ttrss_entries WHERE
329 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
330 }
331
332 function get_feed_update_interval($link, $feed_id) {
333 $result = db_query($link, "SELECT owner_uid, update_interval FROM
334 ttrss_feeds WHERE id = '$feed_id'");
335
336 if (db_num_rows($result) == 1) {
337 $update_interval = db_fetch_result($result, 0, "update_interval");
338 $owner_uid = db_fetch_result($result, 0, "owner_uid");
339
340 if ($update_interval != 0) {
341 return $update_interval;
342 } else {
343 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
344 }
345
346 } else {
347 return -1;
348 }
349 }
350
351 function fetch_file_contents($url) {
352 if (USE_CURL_FOR_ICONS) {
353 $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
354
355 $ch = curl_init($url);
356 $fp = fopen($tmpfile, "w");
357
358 if ($fp) {
359 curl_setopt($ch, CURLOPT_FILE, $fp);
360 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
361 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
362 curl_exec($ch);
363 curl_close($ch);
364 fclose($fp);
365 }
366
367 $contents = file_get_contents($tmpfile);
368 unlink($tmpfile);
369
370 return $contents;
371
372 } else {
373 return file_get_contents($url);
374 }
375
376 }
377
378 /**
379 * Try to determine the favicon URL for a feed.
380 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
381 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
382 *
383 * @param string $url A feed or page URL
384 * @access public
385 * @return mixed The favicon URL, or false if none was found.
386 */
387 function get_favicon_url($url) {
388
389 if ($html = @fetch_file_contents($url)) {
390
391 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
392 // Attempt to grab a favicon link from their webpage url
393 $linkUrl = html_entity_decode($matches[1]);
394
395 if (substr($linkUrl, 0, 1) == '/') {
396 $urlParts = parse_url($url);
397 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
398 } else if (substr($linkUrl, 0, 7) == 'http://') {
399 $faviconURL = $linkUrl;
400 } else {
401 $pos = strrpos($url, "/");
402 // no "/" in url or "/" is part of "://"
403 if ($pos === false || $pos == (strpos($url, "://")+2)) {
404 $faviconURL = $url.'/'.$linkUrl;
405 } else {
406 $faviconURL = substr($url, 0, $pos+1).$linkUrl;
407 }
408 }
409
410 } else {
411 // If unsuccessful, attempt to "guess" the favicon location
412 $urlParts = parse_url($url);
413 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
414 }
415 }
416
417 // Run a test to see if what we have attempted to get actually exists.
418 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
419 return $faviconURL;
420 } else {
421 return false;
422 }
423 } // function get_favicon_url
424
425 /**
426 * Check if a link is a valid and working URL.
427 *
428 * @param mixed $link A URL to check
429 * @access public
430 * @return boolean True if the URL is valid, false otherwise.
431 */
432 function url_validate($link) {
433
434 $url_parts = @parse_url($link);
435
436 if ( empty( $url_parts["host"] ) )
437 return false;
438
439 if ( !empty( $url_parts["path"] ) ) {
440 $documentpath = $url_parts["path"];
441 } else {
442 $documentpath = "/";
443 }
444
445 if ( !empty( $url_parts["query"] ) )
446 $documentpath .= "?" . $url_parts["query"];
447
448 $host = $url_parts["host"];
449 $port = $url_parts["port"];
450
451 if ( empty($port) )
452 $port = "80";
453
454 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
455
456 if ( !$socket )
457 return false;
458
459 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
460
461 $http_response = fgets( $socket, 22 );
462
463 $responses = "/(200 OK)|(30[123])/";
464 if ( preg_match($responses, $http_response) ) {
465 fclose($socket);
466 return true;
467 } else {
468 return false;
469 }
470
471 } // function url_validate
472
473 function check_feed_favicon($site_url, $feed, $link) {
474 $favicon_url = get_favicon_url($site_url);
475
476 # print "FAVICON [$site_url]: $favicon_url\n";
477
478 error_reporting(0);
479
480 $icon_file = ICONS_DIR . "/$feed.ico";
481
482 if ($favicon_url && !file_exists($icon_file)) {
483 $contents = fetch_file_contents($favicon_url);
484
485 $fp = fopen($icon_file, "w");
486
487 if ($fp) {
488 fwrite($fp, $contents);
489 fclose($fp);
490 chmod($icon_file, 0644);
491 }
492 }
493
494 error_reporting(DEFAULT_ERROR_LEVEL);
495
496 }
497
498 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
499
500 if (!$_GET["daemon"] && !$ignore_daemon) {
501 return false;
502 }
503
504 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
505 _debug("update_rss_feed: start");
506 }
507
508 if (!$ignore_daemon) {
509
510 if (DB_TYPE == "pgsql") {
511 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
512 } else {
513 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
514 }
515
516 $result = db_query($link, "SELECT id,update_interval,auth_login,
517 auth_pass,cache_images,update_method
518 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
519
520 } else {
521
522 $result = db_query($link, "SELECT id,update_interval,auth_login,
523 auth_pass,cache_images,update_method,hidden,last_updated
524 FROM ttrss_feeds WHERE id = '$feed'");
525
526 }
527
528 if (db_num_rows($result) == 0) {
529 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
530 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
531 }
532 return false;
533 }
534
535 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
536 $update_method = db_fetch_result($result, 0, "update_method");
537 $last_updated = db_fetch_result($result, 0, "last_updated");
538
539 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
540 WHERE id = '$feed'");
541
542 $auth_login = db_fetch_result($result, 0, "auth_login");
543 $auth_pass = db_fetch_result($result, 0, "auth_pass");
544
545 if (ALLOW_SELECT_UPDATE_METHOD) {
546 if (ENABLE_SIMPLEPIE) {
547 $use_simplepie = $update_method != 1;
548 } else {
549 $use_simplepie = $update_method == 2;
550 }
551 } else {
552 $use_simplepie = ENABLE_SIMPLEPIE;
553 }
554
555 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
556 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
557 }
558
559 if (!$use_simplepie) {
560 $auth_login = urlencode($auth_login);
561 $auth_pass = urlencode($auth_pass);
562 }
563
564 $update_interval = db_fetch_result($result, 0, "update_interval");
565 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
566
567 if ($update_interval < 0) { return; }
568
569 $feed = db_escape_string($feed);
570
571 $fetch_url = $feed_url;
572
573 if ($auth_login && $auth_pass) {
574 $url_parts = array();
575 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
576
577 if ($url_parts[1] && $url_parts[2]) {
578 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
579 }
580
581 }
582
583 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
584 _debug("update_rss_feed: fetching [$fetch_url]...");
585 }
586
587 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
588 error_reporting(0);
589 }
590
591 if (!$use_simplepie) {
592 $rss = fetch_rss($fetch_url);
593 } else {
594 if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
595 mkdir(SIMPLEPIE_CACHE_DIR);
596 }
597
598 $rss = new SimplePie();
599 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
600 # $rss->set_timeout(10);
601 $rss->set_feed_url($fetch_url);
602 $rss->set_output_encoding('UTF-8');
603
604 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
605 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
606 _debug("enabling image cache");
607 }
608
609 $rss->set_image_handler('./image.php', 'i');
610 }
611
612 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
613 _debug("feed update interval (sec): " .
614 get_feed_update_interval($link, $feed)*60);
615 }
616
617 if (is_dir(SIMPLEPIE_CACHE_DIR)) {
618 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
619 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
620 }
621
622 $rss->init();
623 }
624
625 // print_r($rss);
626
627 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
628 _debug("update_rss_feed: fetch done, parsing...");
629 } else {
630 error_reporting (DEFAULT_ERROR_LEVEL);
631 }
632
633 $feed = db_escape_string($feed);
634
635 if ($use_simplepie) {
636 $fetch_ok = !$rss->error();
637 } else {
638 $fetch_ok = !!$rss;
639 }
640
641 if ($fetch_ok) {
642
643 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
644 _debug("update_rss_feed: processing feed data...");
645 }
646
647 // db_query($link, "BEGIN");
648
649 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
650 FROM ttrss_feeds WHERE id = '$feed'");
651
652 $registered_title = db_fetch_result($result, 0, "title");
653 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
654 $orig_site_url = db_fetch_result($result, 0, "site_url");
655
656 $owner_uid = db_fetch_result($result, 0, "owner_uid");
657
658 if ($use_simplepie) {
659 $site_url = $rss->get_link();
660 } else {
661 $site_url = $rss->channel["link"];
662 }
663
664 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
665 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
666 _debug("update_rss_feed: checking favicon...");
667 }
668
669 check_feed_favicon($site_url, $feed, $link);
670 }
671
672 if (!$registered_title || $registered_title == "[Unknown]") {
673
674 if ($use_simplepie) {
675 $feed_title = db_escape_string($rss->get_title());
676 } else {
677 $feed_title = db_escape_string($rss->channel["title"]);
678 }
679
680 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
681 _debug("update_rss_feed: registering title: $feed_title");
682 }
683
684 db_query($link, "UPDATE ttrss_feeds SET
685 title = '$feed_title' WHERE id = '$feed'");
686 }
687
688 // weird, weird Magpie
689 if (!$use_simplepie) {
690 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
691 }
692
693 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
694 db_query($link, "UPDATE ttrss_feeds SET
695 site_url = '$site_url' WHERE id = '$feed'");
696 }
697
698 // print "I: " . $rss->channel["image"]["url"];
699
700 if (!$use_simplepie) {
701 $icon_url = $rss->image["url"];
702 } else {
703 $icon_url = $rss->get_image_url();
704 }
705
706 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
707 $icon_url = db_escape_string($icon_url);
708 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
709 }
710
711 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
712 _debug("update_rss_feed: loading filters...");
713 }
714
715 $filters = load_filters($link, $feed, $owner_uid);
716
717 if ($use_simplepie) {
718 $iterator = $rss->get_items();
719 } else {
720 $iterator = $rss->items;
721 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
722 if (!$iterator || !is_array($iterator)) $iterator = $rss;
723 }
724
725 if (!is_array($iterator)) {
726 /* db_query($link, "UPDATE ttrss_feeds
727 SET last_error = 'Parse error: can\'t find any articles.'
728 WHERE id = '$feed'"); */
729
730 // clear any errors and mark feed as updated if fetched okay
731 // even if it's blank
732
733 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
734 _debug("update_rss_feed: entry iterator is not an array, no articles?");
735 }
736
737 db_query($link, "UPDATE ttrss_feeds
738 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
739
740 return; // no articles
741 }
742
743 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
744 _debug("update_rss_feed: processing articles...");
745 }
746
747 foreach ($iterator as $item) {
748
749 if ($_GET['xdebug']) {
750 print_r($item);
751
752 }
753
754 if ($use_simplepie) {
755 $entry_guid = $item->get_id();
756 if (!$entry_guid) $entry_guid = $item->get_link();
757 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
758
759 } else {
760
761 $entry_guid = $item["id"];
762
763 if (!$entry_guid) $entry_guid = $item["guid"];
764 if (!$entry_guid) $entry_guid = $item["link"];
765 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
766 }
767
768 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
769 _debug("update_rss_feed: guid $entry_guid");
770 }
771
772 if (!$entry_guid) continue;
773
774 $entry_timestamp = "";
775
776 if ($use_simplepie) {
777 $entry_timestamp = strtotime($item->get_date());
778 } else {
779 $rss_2_date = $item['pubdate'];
780 $rss_1_date = $item['dc']['date'];
781 $atom_date = $item['issued'];
782 if (!$atom_date) $atom_date = $item['updated'];
783
784 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
785 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
786 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
787 }
788
789 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
790 $entry_timestamp = time();
791 $no_orig_date = 'true';
792 } else {
793 $no_orig_date = 'false';
794 }
795
796 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
797
798 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
799 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
800 }
801
802 if ($use_simplepie) {
803 $entry_title = $item->get_title();
804 } else {
805 $entry_title = trim(strip_tags($item["title"]));
806 }
807
808 if ($use_simplepie) {
809 $entry_link = $item->get_link();
810 } else {
811 // strange Magpie workaround
812 $entry_link = $item["link_"];
813 if (!$entry_link) $entry_link = $item["link"];
814 }
815
816 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
817 _debug("update_rss_feed: title $entry_title");
818 }
819
820 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
821
822 $entry_link = strip_tags($entry_link);
823
824 if ($use_simplepie) {
825 $entry_content = $item->get_content();
826 if (!$entry_content) $entry_content = $item->get_description();
827 } else {
828 $entry_content = $item["content:escaped"];
829
830 if (!$entry_content) $entry_content = $item["content:encoded"];
831 if (!$entry_content) $entry_content = $item["content"]["encoded"];
832 if (!$entry_content) $entry_content = $item["content"];
833
834 // Magpie bugs are getting ridiculous
835 if (trim($entry_content) == "Array") $entry_content = false;
836
837 if (!$entry_content) $entry_content = $item["atom_content"];
838 if (!$entry_content) $entry_content = $item["summary"];
839
840 if (!$entry_content ||
841 strlen($entry_content) < strlen($item["description"])) {
842 $entry_content = $item["description"];
843 };
844
845 // WTF
846 if (is_array($entry_content)) {
847 $entry_content = $entry_content["encoded"];
848 if (!$entry_content) $entry_content = $entry_content["escaped"];
849 }
850 }
851
852 if ($_GET["xdebug"]) {
853 print "update_rss_feed: content: ";
854 print_r(htmlspecialchars($entry_content));
855 }
856
857 $entry_content_unescaped = $entry_content;
858
859 if ($use_simplepie) {
860 $entry_comments = strip_tags($item->data["comments"]);
861 if ($item->get_author()) {
862 $entry_author_item = $item->get_author();
863 $entry_author = $entry_author_item->get_name();
864 if (!$entry_author) $entry_author = $entry_author_item->get_email();
865
866 $entry_author = db_escape_string($entry_author);
867 }
868 } else {
869 $entry_comments = strip_tags($item["comments"]);
870
871 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
872
873 if ($item['author']) {
874
875 if (is_array($item['author'])) {
876
877 if (!$entry_author) {
878 $entry_author = db_escape_string(strip_tags($item['author']['name']));
879 }
880
881 if (!$entry_author) {
882 $entry_author = db_escape_string(strip_tags($item['author']['email']));
883 }
884 }
885
886 if (!$entry_author) {
887 $entry_author = db_escape_string(strip_tags($item['author']));
888 }
889 }
890 }
891
892 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
893
894 $entry_guid = db_escape_string(strip_tags($entry_guid));
895 $entry_guid = mb_substr($entry_guid, 0, 250);
896
897 $result = db_query($link, "SELECT id FROM ttrss_entries
898 WHERE guid = '$entry_guid'");
899
900 $entry_content = db_escape_string($entry_content);
901
902 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
903
904 $entry_title = db_escape_string($entry_title);
905 $entry_link = db_escape_string($entry_link);
906 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
907 $entry_author = mb_substr($entry_author, 0, 250);
908
909 if ($use_simplepie) {
910 $num_comments = 0; #FIXME#
911 } else {
912 $num_comments = db_escape_string($item["slash"]["comments"]);
913 }
914
915 if (!$num_comments) $num_comments = 0;
916
917 // parse <category> entries into tags
918
919 if ($use_simplepie) {
920
921 $additional_tags = array();
922 $additional_tags_src = $item->get_categories();
923
924 if (is_array($additional_tags_src)) {
925 foreach ($additional_tags_src as $tobj) {
926 array_push($additional_tags, $tobj->get_term());
927 }
928 }
929
930 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
931 _debug("update_rss_feed: category tags:");
932 print_r($additional_tags);
933 }
934
935 } else {
936
937 $t_ctr = $item['category#'];
938
939 $additional_tags = false;
940
941 if ($t_ctr == 0) {
942 $additional_tags = false;
943 } else if ($t_ctr > 0) {
944 $additional_tags = array($item['category']);
945
946 if ($item['category@term']) {
947 array_push($additional_tags, $item['category@term']);
948 }
949
950 for ($i = 0; $i <= $t_ctr; $i++ ) {
951 if ($item["category#$i"]) {
952 array_push($additional_tags, $item["category#$i"]);
953 }
954
955 if ($item["category#$i@term"]) {
956 array_push($additional_tags, $item["category#$i@term"]);
957 }
958 }
959 }
960
961 // parse <dc:subject> elements
962
963 $t_ctr = $item['dc']['subject#'];
964
965 if ($t_ctr > 0) {
966 $additional_tags = array($item['dc']['subject']);
967
968 for ($i = 0; $i <= $t_ctr; $i++ ) {
969 if ($item['dc']["subject#$i"]) {
970 array_push($additional_tags, $item['dc']["subject#$i"]);
971 }
972 }
973 }
974 }
975
976 // enclosures
977
978 $enclosures = array();
979
980 if ($use_simplepie) {
981 $encs = $item->get_enclosures();
982
983 if (is_array($encs)) {
984 foreach ($encs as $e) {
985 $e_item = array(
986 $e->link, $e->type, $e->length);
987
988 array_push($enclosures, $e_item);
989 }
990 }
991
992 } else {
993 // <enclosure>
994
995 $e_ctr = $item['enclosure#'];
996
997 if ($e_ctr > 0) {
998 $e_item = array($item['enclosure@url'],
999 $item['enclosure@type'],
1000 $item['enclosure@length']);
1001
1002 array_push($enclosures, $e_item);
1003
1004 for ($i = 0; $i <= $e_ctr; $i++ ) {
1005
1006 if ($item["enclosure#$i@url"]) {
1007 $e_item = array($item["enclosure#$i@url"],
1008 $item["enclosure#$i@type"],
1009 $item["enclosure#$i@length"]);
1010 array_push($enclosures, $e_item);
1011 }
1012 }
1013 }
1014
1015 // <media:content>
1016 // can there be many of those? yes -fox
1017
1018 $m_ctr = $item['media']['content#'];
1019
1020 if ($m_ctr > 0) {
1021 $e_item = array($item['media']['content@url'],
1022 $item['media']['content@medium'],
1023 $item['media']['content@length']);
1024
1025 array_push($enclosures, $e_item);
1026
1027 for ($i = 0; $i <= $m_ctr; $i++ ) {
1028
1029 if ($item["media"]["content#$i@url"]) {
1030 $e_item = array($item["media"]["content#$i@url"],
1031 $item["media"]["content#$i@medium"],
1032 $item["media"]["content#$i@length"]);
1033 array_push($enclosures, $e_item);
1034 }
1035 }
1036
1037 }
1038 }
1039
1040 # sanitize content
1041
1042 $entry_content = sanitize_article_content($entry_content);
1043 $entry_title = sanitize_article_content($entry_title);
1044
1045 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1046 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1047 }
1048
1049 db_query($link, "BEGIN");
1050
1051 if (db_num_rows($result) == 0) {
1052
1053 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1054 _debug("update_rss_feed: base guid not found");
1055 }
1056
1057 // base post entry does not exist, create it
1058
1059 $result = db_query($link,
1060 "INSERT INTO ttrss_entries
1061 (title,
1062 guid,
1063 link,
1064 updated,
1065 content,
1066 content_hash,
1067 no_orig_date,
1068 date_entered,
1069 comments,
1070 num_comments,
1071 author)
1072 VALUES
1073 ('$entry_title',
1074 '$entry_guid',
1075 '$entry_link',
1076 '$entry_timestamp_fmt',
1077 '$entry_content',
1078 '$content_hash',
1079 $no_orig_date,
1080 NOW(),
1081 '$entry_comments',
1082 '$num_comments',
1083 '$entry_author')");
1084 } else {
1085 // we keep encountering the entry in feeds, so we need to
1086 // update date_entered column so that we don't get horrible
1087 // dupes when the entry gets purged and reinserted again e.g.
1088 // in the case of SLOW SLOW OMG SLOW updating feeds
1089
1090 $base_entry_id = db_fetch_result($result, 0, "id");
1091
1092 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1093 WHERE id = '$base_entry_id'");
1094 }
1095
1096 // now it should exist, if not - bad luck then
1097
1098 $result = db_query($link, "SELECT
1099 id,content_hash,no_orig_date,title,
1100 ".SUBSTRING_FOR_DATE."(date_entered,1,19) as date_entered,
1101 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
1102 num_comments
1103 FROM
1104 ttrss_entries
1105 WHERE guid = '$entry_guid'");
1106
1107 $entry_ref_id = 0;
1108 $entry_int_id = 0;
1109
1110 if (db_num_rows($result) == 1) {
1111
1112 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1113 _debug("update_rss_feed: base guid found, checking for user record");
1114 }
1115
1116 // this will be used below in update handler
1117 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1118 $orig_title = db_fetch_result($result, 0, "title");
1119 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1120 $orig_date_entered = strtotime(db_fetch_result($result,
1121 0, "date_entered"));
1122
1123 $ref_id = db_fetch_result($result, 0, "id");
1124 $entry_ref_id = $ref_id;
1125
1126 // check for user post link to main table
1127
1128 // do we allow duplicate posts with same GUID in different feeds?
1129 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1130 $dupcheck_qpart = "AND feed_id = '$feed'";
1131 } else {
1132 $dupcheck_qpart = "";
1133 }
1134
1135 // error_reporting(0);
1136
1137 $article_filters = get_article_filters($filters, $entry_title,
1138 $entry_content, $entry_link, $entry_timestamp);
1139
1140 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1141 _debug("update_rss_feed: article filters: ");
1142 if (count($article_filters) != 0) {
1143 print_r($article_filters);
1144 }
1145 }
1146
1147 if (find_article_filter($article_filters, "filter")) {
1148 db_query($link, "COMMIT"); // close transaction in progress
1149 continue;
1150 }
1151
1152 // error_reporting (DEFAULT_ERROR_LEVEL);
1153
1154 $score = calculate_article_score($article_filters);
1155
1156 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1157 _debug("update_rss_feed: initial score: $score");
1158 }
1159
1160 $result = db_query($link,
1161 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1162 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1163 $dupcheck_qpart");
1164
1165 // okay it doesn't exist - create user entry
1166 if (db_num_rows($result) == 0) {
1167
1168 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1169 _debug("update_rss_feed: user record not found, creating...");
1170 }
1171
1172 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1173 $unread = 'true';
1174 $last_read_qpart = 'NULL';
1175 } else {
1176 $unread = 'false';
1177 $last_read_qpart = 'NOW()';
1178 }
1179
1180 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
1181 $marked = 'true';
1182 } else {
1183 $marked = 'false';
1184 }
1185
1186 if (find_article_filter($article_filters, 'publish')) {
1187 $published = 'true';
1188 } else {
1189 $published = 'false';
1190 }
1191
1192 $result = db_query($link,
1193 "INSERT INTO ttrss_user_entries
1194 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1195 published, score)
1196 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1197 $last_read_qpart, $marked, $published, '$score')");
1198
1199 $result = db_query($link,
1200 "SELECT int_id FROM ttrss_user_entries WHERE
1201 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1202 feed_id = '$feed' LIMIT 1");
1203
1204 if (db_num_rows($result) == 1) {
1205 $entry_int_id = db_fetch_result($result, 0, "int_id");
1206 }
1207 } else {
1208 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1209 $entry_int_id = db_fetch_result($result, 0, "int_id");
1210 }
1211
1212 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1213 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1214 }
1215
1216 $post_needs_update = false;
1217
1218 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1219 ($content_hash != $orig_content_hash)) {
1220 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1221 $post_needs_update = true;
1222 }
1223
1224 if (db_escape_string($orig_title) != $entry_title) {
1225 $post_needs_update = true;
1226 }
1227
1228 if ($orig_num_comments != $num_comments) {
1229 $post_needs_update = true;
1230 }
1231
1232 // this doesn't seem to be very reliable
1233 //
1234 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1235 // $post_needs_update = true;
1236 // }
1237
1238 // if post needs update, update it and mark all user entries
1239 // linking to this post as updated
1240 if ($post_needs_update) {
1241
1242 if (defined('DAEMON_EXTENDED_DEBUG')) {
1243 _debug("update_rss_feed: post $entry_guid needs update...");
1244 }
1245
1246 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1247
1248 db_query($link, "UPDATE ttrss_entries
1249 SET title = '$entry_title', content = '$entry_content',
1250 content_hash = '$content_hash',
1251 num_comments = '$num_comments'
1252 WHERE id = '$ref_id'");
1253
1254 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1255 db_query($link, "UPDATE ttrss_user_entries
1256 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1257 } else {
1258 db_query($link, "UPDATE ttrss_user_entries
1259 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1260 }
1261
1262 }
1263 }
1264
1265 db_query($link, "COMMIT");
1266
1267 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1268 _debug("update_rss_feed: assigning labels...");
1269 }
1270
1271 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1272 $owner_uid);
1273
1274 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1275 _debug("update_rss_feed: looking for enclosures...");
1276 }
1277
1278 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1279 print_r($enclosures);
1280 }
1281
1282 db_query($link, "BEGIN");
1283
1284 foreach ($enclosures as $enc) {
1285 $enc_url = db_escape_string($enc[0]);
1286 $enc_type = db_escape_string($enc[1]);
1287 $enc_dur = db_escape_string($enc[2]);
1288
1289 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1290 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1291
1292 if (db_num_rows($result) == 0) {
1293 db_query($link, "INSERT INTO ttrss_enclosures
1294 (content_url, content_type, title, duration, post_id) VALUES
1295 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1296 }
1297 }
1298
1299 db_query($link, "COMMIT");
1300
1301 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1302 _debug("update_rss_feed: looking for tags...");
1303 }
1304
1305 /* taaaags */
1306 // <a href="..." rel="tag">Xorg</a>, //
1307
1308 $entry_tags = null;
1309
1310 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1311 $entry_content_unescaped, $entry_tags);
1312
1313 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1314 print_r($entry_tags);
1315 print "<br/></p>"; */
1316
1317 $entry_tags = $entry_tags[1];
1318
1319 # check for manual tags
1320
1321 $tag_filter = find_article_filter($article_filters, "tag");
1322
1323 if ($tag_filter) {
1324
1325 $manual_tags = trim_array(split(",", $tag_filter[1]));
1326
1327 foreach ($manual_tags as $tag) {
1328 if (tag_is_valid($tag)) {
1329 array_push($entry_tags, $tag);
1330 }
1331 }
1332 }
1333
1334 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1335 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1336
1337 if ($additional_tags && is_array($additional_tags)) {
1338 foreach ($additional_tags as $tag) {
1339 if (tag_is_valid($tag) &&
1340 array_search($tag, $boring_tags) === FALSE) {
1341 array_push($entry_tags, $tag);
1342 }
1343 }
1344 }
1345
1346 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1347
1348 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1349 print_r($entry_tags);
1350 }
1351
1352 if (count($entry_tags) > 0) {
1353
1354 db_query($link, "BEGIN");
1355
1356 foreach ($entry_tags as $tag) {
1357
1358 $tag = sanitize_tag($tag);
1359 $tag = db_escape_string($tag);
1360
1361 if (!tag_is_valid($tag)) continue;
1362
1363 $result = db_query($link, "SELECT id FROM ttrss_tags
1364 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1365 owner_uid = '$owner_uid' LIMIT 1");
1366
1367 // print db_fetch_result($result, 0, "id");
1368
1369 if ($result && db_num_rows($result) == 0) {
1370
1371 db_query($link, "INSERT INTO ttrss_tags
1372 (owner_uid,tag_name,post_int_id)
1373 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1374 }
1375 }
1376
1377 db_query($link, "COMMIT");
1378 }
1379
1380 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1381 _debug("update_rss_feed: article processed");
1382 }
1383 }
1384
1385 if (!$last_updated) {
1386 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1387 _debug("update_rss_feed: new feed, catching it up...");
1388 }
1389 catchup_feed($link, $feed, false, $owner_uid);
1390 }
1391
1392 if (!$hidden) {
1393 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1394 _debug("update_rss_feed: updating counters cache...");
1395 }
1396
1397 // disabled, purge_feed() does that...
1398 //ccache_update($link, $feed, $owner_uid);
1399 }
1400
1401 purge_feed($link, $feed, 0);
1402
1403 db_query($link, "UPDATE ttrss_feeds
1404 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1405
1406 // db_query($link, "COMMIT");
1407
1408 } else {
1409
1410 if ($use_simplepie) {
1411 $error_msg = mb_substr($rss->error(), 0, 250);
1412 } else {
1413 $error_msg = mb_substr(magpie_error(), 0, 250);
1414 }
1415
1416 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1417 _debug("update_rss_feed: error fetching feed: $error_msg");
1418 }
1419
1420 $error_msg = db_escape_string($error_msg);
1421
1422 db_query($link,
1423 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1424 last_updated = NOW() WHERE id = '$feed'");
1425 }
1426
1427 if ($use_simplepie) {
1428 unset($rss);
1429 }
1430
1431 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1432 _debug("update_rss_feed: done");
1433 }
1434
1435 }
1436
1437 function print_select($id, $default, $values, $attributes = "") {
1438 print "<select name=\"$id\" id=\"$id\" $attributes>";
1439 foreach ($values as $v) {
1440 if ($v == $default)
1441 $sel = " selected";
1442 else
1443 $sel = "";
1444
1445 print "<option$sel>$v</option>";
1446 }
1447 print "</select>";
1448 }
1449
1450 function print_select_hash($id, $default, $values, $attributes = "") {
1451 print "<select name=\"$id\" id='$id' $attributes>";
1452 foreach (array_keys($values) as $v) {
1453 if ($v == $default)
1454 $sel = 'selected="selected"';
1455 else
1456 $sel = "";
1457
1458 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1459 }
1460
1461 print "</select>";
1462 }
1463
1464 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1465 $matches = array();
1466
1467 if ($filters["title"]) {
1468 foreach ($filters["title"] as $filter) {
1469 $reg_exp = $filter["reg_exp"];
1470 $inverse = $filter["inverse"];
1471 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1472 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1473
1474 array_push($matches, array($filter["action"], $filter["action_param"]));
1475 }
1476 }
1477 }
1478
1479 if ($filters["content"]) {
1480 foreach ($filters["content"] as $filter) {
1481 $reg_exp = $filter["reg_exp"];
1482 $inverse = $filter["inverse"];
1483
1484 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1485 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1486
1487 array_push($matches, array($filter["action"], $filter["action_param"]));
1488 }
1489 }
1490 }
1491
1492 if ($filters["both"]) {
1493 foreach ($filters["both"] as $filter) {
1494 $reg_exp = $filter["reg_exp"];
1495 $inverse = $filter["inverse"];
1496
1497 if ($inverse) {
1498 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1499 array_push($matches, array($filter["action"], $filter["action_param"]));
1500 }
1501 } else {
1502 if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1503 array_push($matches, array($filter["action"], $filter["action_param"]));
1504 }
1505 }
1506 }
1507 }
1508
1509 if ($filters["link"]) {
1510 $reg_exp = $filter["reg_exp"];
1511 foreach ($filters["link"] as $filter) {
1512 $reg_exp = $filter["reg_exp"];
1513 $inverse = $filter["inverse"];
1514
1515 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1516 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1517
1518 array_push($matches, array($filter["action"], $filter["action_param"]));
1519 }
1520 }
1521 }
1522
1523 if ($filters["date"]) {
1524 $reg_exp = $filter["reg_exp"];
1525 foreach ($filters["date"] as $filter) {
1526 $date_modifier = $filter["filter_param"];
1527 $inverse = $filter["inverse"];
1528 $check_timestamp = strtotime($filter["reg_exp"]);
1529
1530 # no-op when timestamp doesn't parse to prevent misfires
1531
1532 if ($check_timestamp) {
1533 $match_ok = false;
1534
1535 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1536 $date_modifier == "after" && $timestamp > $check_timestamp) {
1537 $match_ok = true;
1538 }
1539
1540 if ($inverse) $match_ok = !$match_ok;
1541
1542 if ($match_ok) {
1543 array_push($matches, array($filter["action"], $filter["action_param"]));
1544 }
1545 }
1546 }
1547 }
1548
1549 return $matches;
1550 }
1551
1552 function find_article_filter($filters, $filter_name) {
1553 foreach ($filters as $f) {
1554 if ($f[0] == $filter_name) {
1555 return $f;
1556 };
1557 }
1558 return false;
1559 }
1560
1561 function calculate_article_score($filters) {
1562 $score = 0;
1563
1564 foreach ($filters as $f) {
1565 if ($f[0] == "score") {
1566 $score += $f[1];
1567 };
1568 }
1569 return $score;
1570 }
1571
1572 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1573 foreach ($filters as $f) {
1574 if ($f[0] == "label") {
1575 label_add_article($link, $id, $f[1], $owner_uid);
1576 };
1577 }
1578 }
1579
1580 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1581 $rtl_content = false, $last_updated = false, $last_error = false,
1582 $fg_content = false, $bg_content = false) {
1583
1584 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1585 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1586 } else {
1587 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1588 }
1589
1590 if ($rtl_content) {
1591 $rtl_tag = "dir=\"rtl\"";
1592 } else {
1593 $rtl_tag = "dir=\"ltr\"";
1594 }
1595
1596 $error_notify_msg = "";
1597
1598 if ($last_error) {
1599 $link_title = "Error: $last_error ($last_updated)";
1600 $error_notify_msg = "(Error)";
1601 } else if ($last_updated) {
1602 $link_title = "Updated: $last_updated";
1603 }
1604
1605 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1606 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1607
1608 /* if ($feed_id < -10) {
1609 $bg_color = "#00ccff";
1610 $fg_color = "white";
1611 }
1612
1613 if ($fg_color || $bg_color) {
1614 $color_str = "<div class='labelColorIndicator'
1615 style='color : $fg_color; background-color : $bg_color'>l</div>";
1616 }
1617
1618 print $color_str; */
1619
1620 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1621 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1622 print "$feed_icon";
1623 }
1624
1625 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1626
1627 if ($unread != 0) {
1628 $fctr_class = "class=\"feedCtrHasUnread\"";
1629 } else {
1630 $fctr_class = "class=\"feedCtrNoUnread\"";
1631 }
1632
1633 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1634 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1635
1636 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1637 $total = getFeedArticles($link, $feed_id);
1638 print "<div class=\"feedExtInfo\">
1639 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1640 }
1641
1642 print "</li>";
1643
1644 }
1645
1646 function getmicrotime() {
1647 list($usec, $sec) = explode(" ",microtime());
1648 return ((float)$usec + (float)$sec);
1649 }
1650
1651 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1652 foreach ($values as $v) {
1653
1654 if ($v == $default)
1655 $sel = "checked";
1656 else
1657 $sel = "";
1658
1659 if ($v == $true_is) {
1660 $sel .= " value=\"1\"";
1661 } else {
1662 $sel .= " value=\"0\"";
1663 }
1664
1665 print "<input class=\"noborder\"
1666 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1667
1668 }
1669 }
1670
1671 function initialize_user_prefs($link, $uid) {
1672
1673 $uid = db_escape_string($uid);
1674
1675 db_query($link, "BEGIN");
1676
1677 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1678
1679 $u_result = db_query($link, "SELECT pref_name
1680 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1681
1682 $active_prefs = array();
1683
1684 while ($line = db_fetch_assoc($u_result)) {
1685 array_push($active_prefs, $line["pref_name"]);
1686 }
1687
1688 while ($line = db_fetch_assoc($result)) {
1689 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1690 // print "adding " . $line["pref_name"] . "<br>";
1691
1692 db_query($link, "INSERT INTO ttrss_user_prefs
1693 (owner_uid,pref_name,value) VALUES
1694 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1695
1696 }
1697 }
1698
1699 db_query($link, "COMMIT");
1700
1701 }
1702
1703 function lookup_user_id($link, $user) {
1704
1705 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1706 login = '$login'");
1707
1708 if (db_num_rows($result) == 1) {
1709 return db_fetch_result($result, 0, "id");
1710 } else {
1711 return false;
1712 }
1713 }
1714
1715 function http_authenticate_user($link) {
1716
1717 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1718
1719 if (!$_SERVER["PHP_AUTH_USER"]) {
1720
1721 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1722 header('HTTP/1.0 401 Unauthorized');
1723 exit;
1724
1725 } else {
1726 $auth_result = authenticate_user($link,
1727 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1728
1729 if (!$auth_result) {
1730 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1731 header('HTTP/1.0 401 Unauthorized');
1732 exit;
1733 }
1734 }
1735
1736 return true;
1737 }
1738
1739 function authenticate_user($link, $login, $password, $force_auth = false) {
1740
1741 if (!SINGLE_USER_MODE) {
1742
1743 $pwd_hash1 = encrypt_password($password);
1744 $pwd_hash2 = encrypt_password($password, $login);
1745 $login = db_escape_string($login);
1746
1747 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1748 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1749
1750 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1751
1752 $query = "SELECT id,login,access_level,pwd_hash
1753 FROM ttrss_users WHERE
1754 login = '$login'";
1755
1756 } else {
1757 $query = "SELECT id,login,access_level,pwd_hash
1758 FROM ttrss_users WHERE
1759 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1760 pwd_hash = '$pwd_hash2')";
1761 }
1762
1763 $result = db_query($link, $query);
1764
1765 if (db_num_rows($result) == 1) {
1766 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1767 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1768 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1769
1770 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1771 $_SESSION["uid"]);
1772
1773 $user_theme = get_user_theme_path($link);
1774
1775 $_SESSION["theme"] = $user_theme;
1776 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1777 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1778
1779 initialize_user_prefs($link, $_SESSION["uid"]);
1780
1781 return true;
1782 }
1783
1784 return false;
1785
1786 } else {
1787
1788 $_SESSION["uid"] = 1;
1789 $_SESSION["name"] = "admin";
1790
1791 $user_theme = get_user_theme_path($link);
1792
1793 $_SESSION["theme"] = $user_theme;
1794 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1795
1796 initialize_user_prefs($link, $_SESSION["uid"]);
1797
1798 return true;
1799 }
1800 }
1801
1802 function make_password($length = 8) {
1803
1804 $password = "";
1805 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1806
1807 $i = 0;
1808
1809 while ($i < $length) {
1810 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1811
1812 if (!strstr($password, $char)) {
1813 $password .= $char;
1814 $i++;
1815 }
1816 }
1817 return $password;
1818 }
1819
1820 // this is called after user is created to initialize default feeds, labels
1821 // or whatever else
1822
1823 // user preferences are checked on every login, not here
1824
1825 function initialize_user($link, $uid) {
1826
1827 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1828 VALUES ('$uid', 'All Articles')");
1829
1830 db_query($link, "INSERT INTO ttrss_filters
1831 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1832 action_id, action_param, filter_param)
1833 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1834
1835 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1836 values ('$uid', 'Tiny Tiny RSS: New Releases',
1837 'http://tt-rss.org/releases.rss')");
1838
1839 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1840 values ('$uid', 'Tiny Tiny RSS: Forum',
1841 'http://tt-rss.org/forum/rss.php')");
1842 }
1843
1844 function logout_user() {
1845 session_destroy();
1846 if (isset($_COOKIE[session_name()])) {
1847 setcookie(session_name(), '', time()-42000, '/');
1848 }
1849 }
1850
1851 function get_script_urlpath() {
1852 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1853 }
1854
1855 function validate_session($link) {
1856 if (SINGLE_USER_MODE) {
1857 return true;
1858 }
1859
1860 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1861 if ($_SESSION["ip_address"]) {
1862 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1863 $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1864 return false;
1865 }
1866 }
1867 }
1868
1869 if ($_SESSION["uid"]) {
1870
1871 $result = db_query($link,
1872 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1873
1874 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1875
1876 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1877 return false;
1878 }
1879 }
1880
1881 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1882
1883 //print_r($_SESSION);
1884
1885 if (time() > $_SESSION["cookie_lifetime"]) {
1886 return false;
1887 }
1888 } */
1889
1890 return true;
1891 }
1892
1893 function login_sequence($link, $mobile = false) {
1894 if (!SINGLE_USER_MODE) {
1895
1896 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1897 $swu = db_escape_string($_REQUEST["swu"]);
1898 if ($swu) {
1899 $_SESSION["prefs_cache"] = false;
1900 return authenticate_user($link, $swu, null, true);
1901 }
1902 }
1903
1904 $login_action = $_POST["login_action"];
1905
1906 # try to authenticate user if called from login form
1907 if ($login_action == "do_login") {
1908 $login = $_POST["login"];
1909 $password = $_POST["password"];
1910 $remember_me = $_POST["remember_me"];
1911
1912 if (authenticate_user($link, $login, $password)) {
1913 $_POST["password"] = "";
1914
1915 $_SESSION["language"] = $_POST["language"];
1916 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1917
1918 header("Location: " . $_SERVER["REQUEST_URI"]);
1919 exit;
1920
1921 return;
1922 } else {
1923 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1924 }
1925 }
1926
1927 if (!$_SESSION["uid"] || !validate_session($link)) {
1928 render_login_form($link, $mobile);
1929 //header("Location: login.php");
1930 exit;
1931 } else {
1932 /* bump login timestamp */
1933 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1934 $_SESSION["uid"]);
1935
1936 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
1937 setcookie("ttrss_lang", $_SESSION["language"],
1938 time() + SESSION_COOKIE_LIFETIME);
1939 }
1940
1941 /* bump counters stamp since we're getting reloaded anyway */
1942
1943 $_SESSION["get_all_counters_stamp"] = time();
1944 }
1945
1946 } else {
1947 return authenticate_user($link, "admin", null);
1948 }
1949 }
1950
1951 function truncate_string($str, $max_len) {
1952 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1953 return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
1954 } else {
1955 return $str;
1956 }
1957 }
1958
1959 function get_user_theme_path($link) {
1960 $result = db_query($link, "SELECT theme_path
1961 FROM
1962 ttrss_themes,ttrss_users
1963 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1964 if (db_num_rows($result) != 0) {
1965 return db_fetch_result($result, 0, "theme_path");
1966 } else {
1967 return null;
1968 }
1969 }
1970
1971 function smart_date_time($timestamp) {
1972 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1973 return date("G:i", $timestamp);
1974 } else if (date("Y", $timestamp) == date("Y")) {
1975 return date("M d, G:i", $timestamp);
1976 } else {
1977 return date("Y/m/d, G:i", $timestamp);
1978 }
1979 }
1980
1981 function smart_date($timestamp) {
1982 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1983 return "Today";
1984 } else if (date("Y", $timestamp) == date("Y")) {
1985 return date("D m", $timestamp);
1986 } else {
1987 return date("Y/m/d", $timestamp);
1988 }
1989 }
1990
1991 function sql_bool_to_string($s) {
1992 if ($s == "t" || $s == "1") {
1993 return "true";
1994 } else {
1995 return "false";
1996 }
1997 }
1998
1999 function sql_bool_to_bool($s) {
2000 if ($s == "t" || $s == "1") {
2001 return true;
2002 } else {
2003 return false;
2004 }
2005 }
2006
2007 function bool_to_sql_bool($s) {
2008 if ($s) {
2009 return "true";
2010 } else {
2011 return "false";
2012 }
2013 }
2014
2015 function toggleEvenOdd($a) {
2016 if ($a == "even")
2017 return "odd";
2018 else
2019 return "even";
2020 }
2021
2022 function sanity_check($link) {
2023
2024 error_reporting(0);
2025
2026 $error_code = 0;
2027 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2028 $schema_version = db_fetch_result($result, 0, "schema_version");
2029
2030 if ($schema_version != SCHEMA_VERSION) {
2031 $error_code = 5;
2032 }
2033
2034 if (DB_TYPE == "mysql") {
2035 $result = db_query($link, "SELECT true", false);
2036 if (db_num_rows($result) != 1) {
2037 $error_code = 10;
2038 }
2039 }
2040
2041 if (db_escape_string("testTEST") != "testTEST") {
2042 $error_code = 12;
2043 }
2044
2045 error_reporting (DEFAULT_ERROR_LEVEL);
2046
2047 if ($error_code != 0) {
2048 print_error_xml($error_code);
2049 return false;
2050 } else {
2051 return true;
2052 }
2053 }
2054
2055 function file_is_locked($filename) {
2056 if (function_exists('flock')) {
2057 error_reporting(0);
2058 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2059 error_reporting(DEFAULT_ERROR_LEVEL);
2060 if ($fp) {
2061 if (flock($fp, LOCK_EX | LOCK_NB)) {
2062 flock($fp, LOCK_UN);
2063 fclose($fp);
2064 return false;
2065 }
2066 fclose($fp);
2067 return true;
2068 } else {
2069 return false;
2070 }
2071 }
2072 return true; // consider the file always locked and skip the test
2073 }
2074
2075 function make_lockfile($filename) {
2076 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2077
2078 if (flock($fp, LOCK_EX | LOCK_NB)) {
2079 return $fp;
2080 } else {
2081 return false;
2082 }
2083 }
2084
2085 function make_stampfile($filename) {
2086 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2087
2088 if (flock($fp, LOCK_EX | LOCK_NB)) {
2089 fwrite($fp, time() . "\n");
2090 flock($fp, LOCK_UN);
2091 fclose($fp);
2092 return true;
2093 } else {
2094 return false;
2095 }
2096 }
2097
2098 function read_stampfile($filename) {
2099
2100 error_reporting(0);
2101 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2102 error_reporting (DEFAULT_ERROR_LEVEL);
2103
2104 if ($fp) {
2105 if (flock($fp, LOCK_EX)) {
2106 $stamp = fgets($fp);
2107 flock($fp, LOCK_UN);
2108 fclose($fp);
2109 return $stamp;
2110 } else {
2111 return false;
2112 }
2113 } else {
2114 return false;
2115 }
2116 }
2117
2118 function sql_random_function() {
2119 if (DB_TYPE == "mysql") {
2120 return "RAND()";
2121 } else {
2122 return "RANDOM()";
2123 }
2124 }
2125
2126 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2127
2128 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2129
2130 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2131
2132 if ($cat_view) {
2133
2134 if ($feed >= 0) {
2135
2136 if ($feed > 0) {
2137 $cat_qpart = "cat_id = '$feed'";
2138 } else {
2139 $cat_qpart = "cat_id IS NULL";
2140 }
2141
2142 $tmp_result = db_query($link, "SELECT id
2143 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2144
2145 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2146
2147 $tmp_feed = $tmp_line["id"];
2148
2149 db_query($link, "UPDATE ttrss_user_entries
2150 SET unread = false,last_read = NOW()
2151 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2152 }
2153 } else if ($feed == -2) {
2154
2155
2156 db_query($link, "UPDATE ttrss_user_entries
2157 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2158 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2159 AND unread = true AND owner_uid = $owner_uid");
2160 }
2161
2162 } else if ($feed > 0) {
2163
2164 $tmp_result = db_query($link, "SELECT id
2165 FROM ttrss_feeds WHERE parent_feed = '$feed'
2166 ORDER BY cat_id,title");
2167
2168 $parent_ids = array();
2169
2170 if (db_num_rows($tmp_result) > 0) {
2171 while ($p = db_fetch_assoc($tmp_result)) {
2172 array_push($parent_ids, "feed_id = " . $p["id"]);
2173 }
2174
2175 $children_qpart = implode(" OR ", $parent_ids);
2176
2177 db_query($link, "UPDATE ttrss_user_entries
2178 SET unread = false,last_read = NOW()
2179 WHERE (feed_id = '$feed' OR $children_qpart)
2180 AND owner_uid = $owner_uid");
2181
2182 } else {
2183 db_query($link, "UPDATE ttrss_user_entries
2184 SET unread = false,last_read = NOW()
2185 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2186 }
2187
2188 } else if ($feed < 0 && $feed > -10) { // special, like starred
2189
2190 if ($feed == -1) {
2191 db_query($link, "UPDATE ttrss_user_entries
2192 SET unread = false,last_read = NOW()
2193 WHERE marked = true AND owner_uid = $owner_uid");
2194 }
2195
2196 if ($feed == -2) {
2197 db_query($link, "UPDATE ttrss_user_entries
2198 SET unread = false,last_read = NOW()
2199 WHERE published = true AND owner_uid = $owner_uid");
2200 }
2201
2202 if ($feed == -3) {
2203
2204 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2205
2206 if (DB_TYPE == "pgsql") {
2207 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2208 } else {
2209 $match_part = "updated > DATE_SUB(NOW(),
2210 INTERVAL $intl HOUR) ";
2211 }
2212
2213 $result = db_query($link, "SELECT id FROM ttrss_entries,
2214 ttrss_user_entries WHERE $match_part AND
2215 unread = true AND
2216 ttrss_user_entries.ref_id = ttrss_entries.id AND
2217 owner_uid = $owner_uid");
2218
2219 $affected_ids = array();
2220
2221 while ($line = db_fetch_assoc($result)) {
2222 array_push($affected_ids, $line["id"]);
2223 }
2224
2225 catchupArticlesById($link, $affected_ids, 0);
2226 }
2227
2228 if ($feed == -4) {
2229 db_query($link, "UPDATE ttrss_user_entries
2230 SET unread = false,last_read = NOW()
2231 WHERE owner_uid = $owner_uid");
2232 }
2233
2234 } else if ($feed < -10) { // label
2235
2236 $label_id = -$feed - 11;
2237
2238 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2239 SET unread = false, last_read = NOW()
2240 WHERE label_id = '$label_id' AND unread = true
2241 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2242
2243 }
2244
2245 ccache_update($link, $feed, $owner_uid, $cat_view);
2246
2247 } else { // tag
2248 db_query($link, "BEGIN");
2249
2250 $tag_name = db_escape_string($feed);
2251
2252 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2253 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2254
2255 while ($line = db_fetch_assoc($result)) {
2256 db_query($link, "UPDATE ttrss_user_entries SET
2257 unread = false, last_read = NOW()
2258 WHERE int_id = " . $line["post_int_id"]);
2259 }
2260 db_query($link, "COMMIT");
2261 }
2262 }
2263
2264 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2265 if ($cat_view) {
2266
2267 if ($feed > 0) {
2268 $cat_qpart = "cat_id = '$feed'";
2269 } else {
2270 $cat_qpart = "cat_id IS NULL";
2271 }
2272
2273 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2274 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2275
2276 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2277 $feed_url = $tmp_line["feed_url"];
2278 $feed_id = $tmp_line["id"];
2279 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2280 }
2281
2282 } else {
2283 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2284 WHERE id = '$feed'");
2285 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2286 update_rss_feed($link, $feed_url, $feed, $force_update);
2287 }
2288 }
2289
2290 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2291
2292 if (!$omode) $omode = "flc";
2293
2294 getGlobalCounters($link);
2295
2296 if (strchr($omode, "l")) getLabelCounters($link);
2297 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
2298 if (strchr($omode, "t")) getTagCounters($link);
2299 if (strchr($omode, "c")) {
2300 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2301 getCategoryCounters($link);
2302 }
2303 }
2304 }
2305
2306 function getCategoryCounters($link) {
2307 # two special categories are -1 and -2 (all virtuals; all labels)
2308
2309 /* $ctr = getCategoryUnread($link, -1);
2310
2311 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2312
2313 $ctr = getCategoryUnread($link, -2);
2314
2315 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2316
2317 $age_qpart = getMaxAgeSubquery();
2318
2319 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2320 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2321 WHERE ttrss_cat_counters_cache.feed_id = id AND
2322 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2323
2324 while ($line = db_fetch_assoc($result)) {
2325 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2326
2327 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2328 $line["unread"]."\"/>";
2329 }
2330
2331 /* Special case: NULL category doesn't actually exist in the DB */
2332
2333 print "<counter type=\"category\" id=\"0\" counter=\"".
2334 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2335
2336 }
2337
2338 function getCategoryUnread($link, $cat, $owner_uid = false) {
2339
2340 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2341
2342 if ($cat >= 0) {
2343
2344 if ($cat != 0) {
2345 $cat_query = "cat_id = '$cat'";
2346 } else {
2347 $cat_query = "cat_id IS NULL";
2348 }
2349
2350 $age_qpart = getMaxAgeSubquery();
2351
2352 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2353 AND hidden = false
2354 AND owner_uid = " . $owner_uid);
2355
2356 $cat_feeds = array();
2357 while ($line = db_fetch_assoc($result)) {
2358 array_push($cat_feeds, "feed_id = " . $line["id"]);
2359 }
2360
2361 if (count($cat_feeds) == 0) return 0;
2362
2363 $match_part = implode(" OR ", $cat_feeds);
2364
2365 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2366 FROM ttrss_user_entries,ttrss_entries
2367 WHERE unread = true AND ($match_part) AND id = ref_id
2368 AND $age_qpart AND owner_uid = " . $owner_uid);
2369
2370 $unread = 0;
2371
2372 # this needs to be rewritten
2373 while ($line = db_fetch_assoc($result)) {
2374 $unread += $line["unread"];
2375 }
2376
2377 return $unread;
2378 } else if ($cat == -1) {
2379 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
2380 } else if ($cat == -2) {
2381
2382 $result = db_query($link, "
2383 SELECT COUNT(unread) AS unread FROM
2384 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2385 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2386 ttrss_labels2.owner_uid = '$owner_uid'
2387 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2388 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2389
2390 $unread = db_fetch_result($result, 0, "unread");
2391
2392 return $unread;
2393
2394 }
2395 }
2396
2397 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2398 if (DB_TYPE == "pgsql") {
2399 return "ttrss_entries.date_entered >
2400 NOW() - INTERVAL '$days days'";
2401 } else {
2402 return "ttrss_entries.date_entered >
2403 DATE_SUB(NOW(), INTERVAL $days DAY)";
2404 }
2405 }
2406
2407 function getFeedUnread($link, $feed, $is_cat = false) {
2408 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2409 }
2410
2411 function getLabelUnread($link, $label_id, $owner_uid = false) {
2412 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2413
2414 $result = db_query($link, "
2415 SELECT COUNT(unread) AS unread FROM
2416 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2417 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2418 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2419 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2420 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2421
2422 if (db_num_rows($result) != 0) {
2423 return db_fetch_result($result, 0, "unread");
2424 } else {
2425 return 0;
2426 }
2427 }
2428
2429 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2430 $owner_uid = false) {
2431
2432 $n_feed = sprintf("%d", $feed);
2433
2434 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2435
2436 if ($unread_only) {
2437 $unread_qpart = "unread = true";
2438 } else {
2439 $unread_qpart = "true";
2440 }
2441
2442 $age_qpart = getMaxAgeSubquery();
2443
2444 if ($is_cat) {
2445 return getCategoryUnread($link, $n_feed, $owner_uid);
2446 } else if ($n_feed == -1) {
2447 $match_part = "marked = true";
2448 } else if ($n_feed == -2) {
2449 $match_part = "published = true";
2450 } else if ($n_feed == -3) {
2451 $match_part = "unread = true";
2452
2453 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2454
2455 if (DB_TYPE == "pgsql") {
2456 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2457 } else {
2458 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2459 }
2460 } else if ($n_feed == -4) {
2461 $match_part = "true";
2462 } else if ($n_feed > 0) {
2463
2464 $result = db_query($link, "SELECT id FROM ttrss_feeds
2465 WHERE parent_feed = '$n_feed'
2466 AND hidden = false
2467 AND owner_uid = " . $owner_uid);
2468
2469 if (db_num_rows($result) > 0) {
2470
2471 $linked_feeds = array();
2472 while ($line = db_fetch_assoc($result)) {
2473 array_push($linked_feeds, "feed_id = " . $line["id"]);
2474 }
2475
2476 array_push($linked_feeds, "feed_id = $n_feed");
2477
2478 $match_part = implode(" OR ", $linked_feeds);
2479
2480 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2481 FROM ttrss_user_entries,ttrss_entries
2482 WHERE $unread_qpart AND
2483 ttrss_user_entries.ref_id = ttrss_entries.id AND
2484 $age_qpart AND
2485 ($match_part) AND
2486 owner_uid = " . $owner_uid);
2487
2488 $unread = 0;
2489
2490 # this needs to be rewritten
2491 while ($line = db_fetch_assoc($result)) {
2492 $unread += $line["unread"];
2493 }
2494
2495 return $unread;
2496
2497 } else {
2498 $match_part = "feed_id = '$n_feed'";
2499 }
2500 } else if ($feed < -10) {
2501
2502 $label_id = -$feed - 11;
2503
2504 return getLabelUnread($link, $label_id, $owner_uid);
2505
2506 }
2507
2508 if ($match_part) {
2509
2510 $result = db_query($link, "SELECT count(int_id) AS unread
2511 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2512 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2513 ttrss_user_entries.ref_id = ttrss_entries.id AND
2514 ttrss_feeds.hidden = false AND
2515 $age_qpart AND
2516 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2517
2518 } else {
2519
2520 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2521 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2522 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2523 AND $unread_qpart AND $age_qpart AND
2524 ttrss_tags.owner_uid = " . $owner_uid);
2525 }
2526
2527 $unread = db_fetch_result($result, 0, "unread");
2528
2529 return $unread;
2530 }
2531
2532 function getGlobalUnread($link, $user_id = false) {
2533
2534 if (!$user_id) {
2535 $user_id = $_SESSION["uid"];
2536 }
2537
2538 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2539 WHERE owner_uid = '$user_id' AND feed_id > 0");
2540
2541 $c_id = db_fetch_result($result, 0, "c_id");
2542
2543 return $c_id;
2544 }
2545
2546 function getGlobalCounters($link, $global_unread = -1) {
2547 if ($global_unread == -1) {
2548 $global_unread = getGlobalUnread($link);
2549 }
2550 print "<counter type=\"global\" id='global-unread'
2551 counter='$global_unread'/>";
2552
2553 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2554 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2555
2556 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2557
2558 print "<counter type=\"global\" id='subscribed-feeds'
2559 counter='$subscribed_feeds'/>";
2560
2561 }
2562
2563 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
2564
2565 if ($smart_mode) {
2566 if (!$_SESSION["tctr_last_value"]) {
2567 $_SESSION["tctr_last_value"] = array();
2568 }
2569 }
2570
2571 $old_counters = $_SESSION["tctr_last_value"];
2572
2573 $tctrs_modified = false;
2574
2575 $age_qpart = getMaxAgeSubquery();
2576
2577 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2578 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2579 AND ref_id = id AND $age_qpart
2580 AND unread = true)) AS count FROM ttrss_tags
2581 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2582 ORDER BY count DESC LIMIT 55");
2583
2584 $tags = array();
2585
2586 while ($line = db_fetch_assoc($result)) {
2587 $tags[$line["tag_name"]] += $line["count"];
2588 }
2589
2590 foreach (array_keys($tags) as $tag) {
2591 $unread = $tags[$tag];
2592
2593 $tag = htmlspecialchars($tag);
2594
2595 if (!$smart_mode || $old_counters[$tag] != $unread) {
2596 $old_counters[$tag] = $unread;
2597 $tctrs_modified = true;
2598 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2599 }
2600
2601 }
2602
2603 if ($smart_mode && $tctrs_modified) {
2604 $_SESSION["tctr_last_value"] = $old_counters;
2605 }
2606
2607 }
2608
2609 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
2610
2611 $age_qpart = getMaxAgeSubquery();
2612
2613 if ($smart_mode) {
2614 if (!$_SESSION["lctr_last_value"]) {
2615 $_SESSION["lctr_last_value"] = array();
2616 }
2617 }
2618
2619 $ret_arr = array();
2620
2621 for ($i = -1; $i >= -4; $i--) {
2622
2623 $count = getFeedUnread($link, $i);
2624
2625 if (!$ret_mode) {
2626
2627 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2628 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2629 } else {
2630 $xmsg_part = "";
2631 }
2632
2633 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2634 } else {
2635 $ret_arr[$i]["counter"] = $count;
2636 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2637 }
2638
2639 }
2640
2641 $old_counters = $_SESSION["lctr_last_value"];
2642 $lctrs_modified = false;
2643
2644
2645 $owner_uid = $_SESSION["uid"];
2646
2647 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2648 WHERE owner_uid = '$owner_uid'");
2649
2650 while ($line = db_fetch_assoc($result)) {
2651
2652 $id = -$line["id"] - 11;
2653
2654 $label_name = $line["caption"];
2655 $count = getFeedUnread($link, $id);
2656
2657 if (!$smart_mode || $old_counters[$id] != $count) {
2658 $old_counters[$id] = $count;
2659 $lctrs_modified = true;
2660 if (!$ret_mode) {
2661
2662 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2663 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2664 } else {
2665 $xmsg_part = "";
2666 }
2667
2668 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2669 } else {
2670 $ret_arr[$id]["counter"] = $count;
2671 $ret_arr[$id]["description"] = $label_name;
2672 }
2673 }
2674
2675 error_reporting (DEFAULT_ERROR_LEVEL);
2676 }
2677
2678 if ($smart_mode && $lctrs_modified) {
2679 $_SESSION["lctr_last_value"] = $old_counters;
2680 }
2681
2682 return $ret_arr;
2683 }
2684
2685 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
2686
2687 $age_qpart = getMaxAgeSubquery();
2688
2689 if ($smart_mode) {
2690 if (!$_SESSION["fctr_last_value"]) {
2691 $_SESSION["fctr_last_value"] = array();
2692 }
2693 }
2694
2695 $old_counters = $_SESSION["fctr_last_value"];
2696
2697 $query = "SELECT ttrss_feeds.id,
2698 ttrss_feeds.title,
2699 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2700 last_error, value AS count
2701 FROM ttrss_feeds, ttrss_counters_cache
2702 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2703 AND parent_feed IS NULL
2704 AND ttrss_counters_cache.feed_id = id";
2705
2706 $result = db_query($link, $query);
2707 $fctrs_modified = false;
2708
2709 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2710
2711 while ($line = db_fetch_assoc($result)) {
2712
2713 $id = $line["id"];
2714 $count = $line["count"];
2715 $last_error = htmlspecialchars($line["last_error"]);
2716
2717 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2718 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2719 } else {
2720 $last_updated = date($short_date, strtotime($line["last_updated"]));
2721 }
2722
2723 $last_updated = htmlspecialchars($last_updated);
2724
2725 $has_img = feed_has_icon($id);
2726
2727 $tmp_result = db_query($link,
2728 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2729 WHERE parent_feed = '$id' AND feed_id = id");
2730
2731 $count += db_fetch_result($tmp_result, 0, "unread");
2732
2733 if (!$smart_mode || $old_counters[$id] != $count) {
2734 $old_counters[$id] = $count;
2735 $fctrs_modified = true;
2736
2737 if ($last_error) {
2738 $error_part = "error=\"$last_error\"";
2739 } else {
2740 $error_part = "";
2741 }
2742
2743 if ($has_img) {
2744 $has_img_part = "hi=\"$has_img\"";
2745 } else {
2746 $has_img_part = "";
2747 }
2748
2749 if ($active_feed && $id == $active_feed) {
2750 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2751 } else {
2752 $has_title_part = "";
2753 }
2754
2755 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2756 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2757 }
2758
2759 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2760 }
2761 }
2762
2763 if ($smart_mode && $fctrs_modified) {
2764 $_SESSION["fctr_last_value"] = $old_counters;
2765 }
2766 }
2767
2768 function get_script_dt_add() {
2769 /* if (strpos(VERSION, ".99") === false) {
2770 return VERSION;
2771 } else {
2772 return time();
2773 } */
2774 return time();
2775 }
2776
2777 function get_pgsql_version($link) {
2778 $result = db_query($link, "SELECT version() AS version");
2779 $version = split(" ", db_fetch_result($result, 0, "version"));
2780 return $version[1];
2781 }
2782
2783 function print_error_xml($code, $add_msg = "") {
2784 global $ERRORS;
2785
2786 $error_msg = $ERRORS[$code];
2787
2788 if ($add_msg) {
2789 $error_msg = "$error_msg; $add_msg";
2790 }
2791
2792 print "<rpc-reply>";
2793 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2794 print "</rpc-reply>";
2795 }
2796
2797 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2798 $auth_login = '', $auth_pass = '') {
2799
2800 # check for feed:http://url
2801 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2802
2803 # check for feed://URL
2804 if (strpos($feed_link, "//") === 0) {
2805 $feed_link = "http:$feed_link";
2806 }
2807
2808 if ($feed_link == "") return;
2809
2810 if ($cat_id == "0" || !$cat_id) {
2811 $cat_qpart = "NULL";
2812 } else {
2813 $cat_qpart = "'$cat_id'";
2814 }
2815
2816 $result = db_query($link,
2817 "SELECT id FROM ttrss_feeds
2818 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2819
2820 if (db_num_rows($result) == 0) {
2821
2822 $result = db_query($link,
2823 "INSERT INTO ttrss_feeds
2824 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2825 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2826 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2827
2828 $result = db_query($link,
2829 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2830 AND owner_uid = " . $_SESSION["uid"]);
2831
2832 $feed_id = db_fetch_result($result, 0, "id");
2833
2834 if ($feed_id) {
2835 update_rss_feed($link, $feed_link, $feed_id, true);
2836 }
2837
2838 return true;
2839 } else {
2840 return false;
2841 }
2842 }
2843
2844 function print_feed_select($link, $id, $default_id = "",
2845 $attributes = "", $include_all_feeds = true) {
2846
2847 print "<select id=\"$id\" name=\"$id\" $attributes>";
2848 if ($include_all_feeds) {
2849 print "<option value=\"0\">".__('All feeds')."</option>";
2850 }
2851
2852 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2853 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2854
2855 if (db_num_rows($result) > 0 && $include_all_feeds) {
2856 print "<option disabled>--------</option>";
2857 }
2858
2859 while ($line = db_fetch_assoc($result)) {
2860 if ($line["id"] == $default_id) {
2861 $is_selected = "selected";
2862 } else {
2863 $is_selected = "";
2864 }
2865
2866 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2867
2868 printf("<option $is_selected value='%d'>%s</option>",
2869 $line["id"], $title);
2870 }
2871
2872 print "</select>";
2873 }
2874
2875 function print_feed_cat_select($link, $id, $default_id = "",
2876 $attributes = "", $include_all_cats = true) {
2877
2878 print "<select id=\"$id\" name=\"$id\" $attributes>";
2879
2880 if ($include_all_cats) {
2881 print "<option value=\"0\">".__('Uncategorized')."</option>";
2882 }
2883
2884 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2885 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2886
2887 if (db_num_rows($result) > 0 && $include_all_cats) {
2888 print "<option disabled>--------</option>";
2889 }
2890
2891 while ($line = db_fetch_assoc($result)) {
2892 if ($line["id"] == $default_id) {
2893 $is_selected = "selected";
2894 } else {
2895 $is_selected = "";
2896 }
2897 printf("<option $is_selected value='%d'>%s</option>",
2898 $line["id"], htmlspecialchars($line["title"]));
2899 }
2900
2901 print "</select>";
2902 }
2903
2904 function checkbox_to_sql_bool($val) {
2905 return ($val == "on") ? "true" : "false";
2906 }
2907
2908 function getFeedCatTitle($link, $id) {
2909 if ($id == -1) {
2910 return __("Special");
2911 } else if ($id < -10) {
2912 return __("Labels");
2913 } else if ($id > 0) {
2914 $result = db_query($link, "SELECT ttrss_feed_categories.title
2915 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2916 cat_id = ttrss_feed_categories.id");
2917 if (db_num_rows($result) == 1) {
2918 return db_fetch_result($result, 0, "title");
2919 } else {
2920 return __("Uncategorized");
2921 }
2922 } else {
2923 return "getFeedCatTitle($id) failed";
2924 }
2925
2926 }
2927
2928 function getFeedTitle($link, $id) {
2929 if ($id == -1) {
2930 return __("Starred articles");
2931 } else if ($id == -2) {
2932 return __("Published articles");
2933 } else if ($id == -3) {
2934 return __("Fresh articles");
2935 } else if ($id == -4) {
2936 return __("All articles");
2937 } else if ($id < -10) {
2938 $label_id = -$id - 11;
2939 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2940 if (db_num_rows($result) == 1) {
2941 return db_fetch_result($result, 0, "caption");
2942 } else {
2943 return "Unknown label ($label_id)";
2944 }
2945
2946 } else if ($id > 0) {
2947 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2948 if (db_num_rows($result) == 1) {
2949 return db_fetch_result($result, 0, "title");
2950 } else {
2951 return "Unknown feed ($id)";
2952 }
2953 } else {
2954 if (preg_match("/^-?[0-9][0-9]*$/", $id)) {
2955 return "getFeedTitle($id) failed";
2956 } else {
2957 return $id;
2958 }
2959 }
2960
2961 }
2962
2963 function get_session_cookie_name() {
2964 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2965 }
2966
2967 function print_init_params($link) {
2968 print "<init-params>";
2969 if ($_SESSION["stored-params"]) {
2970 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2971 if ($key) {
2972 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2973 print "<param key=\"$key\" value=\"$value\"/>";
2974 }
2975 }
2976 }
2977
2978 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2979 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2980 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2981 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2982
2983 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2984 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2985
2986 print "<param key=\"hide_read_feeds\" value=\"" .
2987 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2988
2989 print "<param key=\"enable_feed_cats\" value=\"" .
2990 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2991
2992 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2993 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2994
2995 print "<param key=\"confirm_feed_catchup\" value=\"" .
2996 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2997
2998 print "<param key=\"cdm_auto_catchup\" value=\"" .
2999 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3000
3001 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
3002
3003 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
3004
3005 print "<param key=\"default_view_mode\" value=\"" .
3006 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3007
3008 print "<param key=\"default_view_limit\" value=\"" .
3009 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3010
3011 print "<param key=\"default_view_order_by\" value=\"" .
3012 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3013
3014 print "<param key=\"prefs_active_tab\" value=\"" .
3015 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3016
3017 print "<param key=\"infobox_disable_overlay\" value=\"" .
3018 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3019
3020 print "<param key=\"icons_location\" value=\"" .
3021 ICONS_URL . "\"/>";
3022
3023 print "<param key=\"hide_read_shows_special\" value=\"" .
3024 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3025
3026 print "<param key=\"hide_feedlist\" value=\"" .
3027 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3028
3029 print "<param key=\"bw_limit\" value=\"".
3030 (int) $_SESSION["bw_limit"]."\"/>";
3031
3032 // print "<param key=\"sync_counters\" value=\"" .
3033 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3034
3035 print "<param key=\"sync_counters\" value=\"1\"/>";
3036
3037 print "<param key=\"offline_enabled\" value=\"".
3038 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3039
3040 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3041 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3042
3043 $num_feeds = db_fetch_result($result, 0, "cf");
3044
3045 print "<param key=\"num_feeds\" value=\"".
3046 (int)$num_feeds. "\"/>";
3047
3048 print "</init-params>";
3049 }
3050
3051 function print_runtime_info($link) {
3052 print "<runtime-info>";
3053
3054 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3055 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3056
3057 $num_feeds = db_fetch_result($result, 0, "cf");
3058
3059 print "<param key=\"num_feeds\" value=\"".
3060 (int)$num_feeds. "\"/>";
3061
3062 if (ENABLE_UPDATE_DAEMON) {
3063 print "<param key=\"daemon_is_running\" value=\"".
3064 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3065
3066 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3067
3068 $stamp = (int)read_stampfile("update_daemon.stamp");
3069
3070 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3071
3072 if ($stamp) {
3073 $stamp_delta = time() - $stamp;
3074
3075 if ($stamp_delta > 1800) {
3076 $stamp_check = 0;
3077 } else {
3078 $stamp_check = 1;
3079 $_SESSION["daemon_stamp_check"] = time();
3080 }
3081
3082 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3083
3084 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3085
3086 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3087 }
3088 }
3089 }
3090
3091 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
3092
3093 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
3094 $new_version_details = check_for_update($link);
3095
3096 print "<param key=\"new_version_available\" value=\"".
3097 sprintf("%d", $new_version_details != ""). "\"/>";
3098
3099 $_SESSION["last_version_check"] = time();
3100 }
3101 }
3102
3103 // print "<param key=\"new_version_available\" value=\"1\"/>";
3104
3105 print "</runtime-info>";
3106 }
3107
3108 function getSearchSql($search, $match_on) {
3109
3110 $search_query_part = "";
3111
3112 $keywords = split(" ", $search);
3113 $query_keywords = array();
3114
3115 if ($match_on == "both") {
3116
3117 foreach ($keywords as $k) {
3118 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3119 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3120 }
3121
3122 $search_query_part = implode("AND", $query_keywords) . " AND ";
3123
3124 } else if ($match_on == "title") {
3125
3126 foreach ($keywords as $k) {
3127 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3128 }
3129
3130 $search_query_part = implode("AND", $query_keywords) . " AND ";
3131
3132 } else if ($match_on == "content") {
3133
3134 foreach ($keywords as $k) {
3135 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3136 }
3137 }
3138
3139 $search_query_part = implode("AND", $query_keywords);
3140
3141 return $search_query_part;
3142 }
3143
3144 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3145
3146 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3147
3148 if ($search) {
3149
3150 $search_query_part = getSearchSql($search, $match_on);
3151 $search_query_part .= " AND ";
3152
3153 } else {
3154 $search_query_part = "";
3155 }
3156
3157 $view_query_part = "";
3158
3159 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3160 if ($search) {
3161 $view_query_part = " ";
3162 } else if ($feed != -1) {
3163 $unread = getFeedUnread($link, $feed, $cat_view);
3164 if ($unread > 0) {
3165 $view_query_part = " unread = true AND ";
3166 }
3167 }
3168 }
3169
3170 if ($view_mode == "marked") {
3171 $view_query_part = " marked = true AND ";
3172 }
3173
3174 if ($view_mode == "unread") {
3175 $view_query_part = " unread = true AND ";
3176 }
3177
3178 if ($view_mode == "updated") {
3179 $view_query_part = " (last_read is null and unread = false) AND ";
3180 }
3181
3182 if ($limit > 0) {
3183 $limit_query_part = "LIMIT " . $limit;
3184 }
3185
3186 $vfeed_query_part = "";
3187
3188 // override query strategy and enable feed display when searching globally
3189 if ($search && $search_mode == "all_feeds") {
3190 $query_strategy_part = "ttrss_entries.id > 0";
3191 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3192 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3193 $query_strategy_part = "ttrss_entries.id > 0";
3194 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3195 id = feed_id) as feed_title,";
3196 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3197
3198 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3199
3200 $tmp_result = false;
3201
3202 if ($cat_view) {
3203 $tmp_result = db_query($link, "SELECT id
3204 FROM ttrss_feeds WHERE cat_id = '$feed'");
3205 } else {
3206 $tmp_result = db_query($link, "SELECT id
3207 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3208 WHERE id = '$feed') AND id != '$feed'");
3209 }
3210
3211 $cat_siblings = array();
3212
3213 if (db_num_rows($tmp_result) > 0) {
3214 while ($p = db_fetch_assoc($tmp_result)) {
3215 array_push($cat_siblings, "feed_id = " . $p["id"]);
3216 }
3217
3218 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3219 $feed, implode(" OR ", $cat_siblings));
3220
3221 } else {
3222 $query_strategy_part = "ttrss_entries.id > 0";
3223 }
3224
3225 } else if ($feed >= 0) {
3226
3227 if ($cat_view) {
3228
3229 if ($feed > 0) {
3230 $query_strategy_part = "cat_id = '$feed'";
3231 } else {
3232 $query_strategy_part = "cat_id IS NULL";
3233 }
3234
3235 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3236
3237 } else {
3238 $tmp_result = db_query($link, "SELECT id
3239 FROM ttrss_feeds WHERE parent_feed = '$feed'
3240 ORDER BY cat_id,title");
3241
3242 $parent_ids = array();
3243
3244 if (db_num_rows($tmp_result) > 0) {
3245 while ($p = db_fetch_assoc($tmp_result)) {
3246 array_push($parent_ids, "feed_id = " . $p["id"]);
3247 }
3248
3249 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3250 $feed, implode(" OR ", $parent_ids));
3251
3252 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3253 } else {
3254 $query_strategy_part = "feed_id = '$feed'";
3255 }
3256 }
3257 } else if ($feed == -1) { // starred virtual feed
3258 $query_strategy_part = "marked = true";
3259 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3260 } else if ($feed == -2) { // published virtual feed OR labels category
3261
3262 if (!$cat_view) {
3263 $query_strategy_part = "published = true";
3264 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3265 } else {
3266 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3267
3268 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3269
3270 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3271 ttrss_user_labels2.article_id = ref_id";
3272
3273 }
3274
3275 } else if ($feed == -3) { // fresh virtual feed
3276 $query_strategy_part = "unread = true";
3277
3278 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3279
3280 if (DB_TYPE == "pgsql") {
3281 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3282 } else {
3283 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3284 }
3285
3286 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3287 } else if ($feed == -4) { // all articles virtual feed
3288 $query_strategy_part = "true";
3289 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3290 } else if ($feed <= -10) { // labels
3291 $label_id = -$feed - 11;
3292
3293 $query_strategy_part = "label_id = '$label_id' AND
3294 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3295 ttrss_user_labels2.article_id = ref_id";
3296
3297 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3298 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3299
3300 } else {
3301 $query_strategy_part = "id > 0"; // dumb
3302 }
3303
3304 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3305 $order_by = "updated";
3306 } else {
3307 $order_by = "updated DESC";
3308 }
3309
3310 if ($view_mode != "noscores") {
3311 $order_by = "score DESC, $order_by";
3312 }
3313
3314 if ($override_order) {
3315 $order_by = $override_order;
3316 }
3317
3318 $feed_title = "";
3319
3320 if ($search && $search_mode == "all_feeds") {
3321 $feed_title = __("Search results")." ($search)";
3322 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3323 $feed_title = __("Search results")." ($search, $feed)";
3324 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3325 $feed_title = $feed;
3326 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3327
3328 if ($cat_view) {
3329
3330 if ($feed != 0) {
3331 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3332 WHERE id = '$feed' AND owner_uid = $owner_uid");
3333 $feed_title = db_fetch_result($result, 0, "title");
3334 } else {
3335 $feed_title = __("Uncategorized");
3336 }
3337
3338 if ($search) {
3339 $feed_title = __("Searched for")." $search ($feed_title)";
3340 }
3341
3342 } else {
3343
3344 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3345 WHERE id = '$feed' AND owner_uid = $owner_uid");
3346
3347 $feed_title = db_fetch_result($result, 0, "title");
3348 $feed_site_url = db_fetch_result($result, 0, "site_url");
3349 $last_error = db_fetch_result($result, 0, "last_error");
3350
3351 if ($search) {
3352 $feed_title = __("Searched for") . " $search ($feed_title)";
3353 }
3354 }
3355
3356 } else if ($feed == -1) {
3357 $feed_title = __("Starred articles");
3358 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3359 } else if ($feed == -2) {
3360 if (!$cat_view) {
3361 $feed_title = __("Published articles");
3362 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3363 } else {
3364 $feed_title = __("Labels");
3365 }
3366 } else if ($feed == -3) {
3367 $feed_title = __("Fresh articles");
3368 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3369 } else if ($feed == -4) {
3370 $feed_title = __("All articles");
3371 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3372 } else if ($feed < -10) {
3373 $label_id = -$feed - 11;
3374 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3375 WHERE id = '$label_id'");
3376 $feed_title = db_fetch_result($result, 0, "caption");
3377
3378 if ($search) {
3379 $feed_title = __("Searched for") . " $search ($feed_title)";
3380 }
3381 } else {
3382 $feed_title = "?";
3383 }
3384
3385 $content_query_part = "content as content_preview,";
3386
3387 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3388
3389 if ($feed >= 0) {
3390 $feed_kind = "Feeds";
3391 } else {
3392 $feed_kind = "Labels";
3393 }
3394
3395 if ($limit_query_part) {
3396 $offset_query_part = "OFFSET $offset";
3397 }
3398
3399 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3400 if (!$override_order) {
3401 $order_by = "ttrss_feeds.title, $order_by";
3402 }
3403
3404 // Special output for Fresh feed
3405
3406 /* if ($feed == -3) {
3407 $group_limit_part = "(select count(*) from
3408 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3409 t1.ref_id = t2.id and t1.owner_uid = 2 and
3410 t1.feed_id = ttrss_user_entries.feed_id and
3411 t2.updated > ttrss_entries.updated) <= 5 AND";
3412 } */
3413 }
3414
3415 $query = "SELECT DISTINCT
3416 guid,
3417 ttrss_entries.id,ttrss_entries.title,
3418 updated,
3419 note,
3420 unread,feed_id,marked,published,link,last_read,
3421 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3422 $vfeed_query_part
3423 $content_query_part
3424 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3425 author,score
3426 FROM
3427 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3428 WHERE
3429 $group_limit_part
3430 ttrss_feeds.hidden = false AND
3431 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3432 ttrss_user_entries.ref_id = ttrss_entries.id AND
3433 ttrss_user_entries.owner_uid = '$owner_uid' AND
3434 $search_query_part
3435 $view_query_part
3436 $query_strategy_part ORDER BY $order_by
3437 $limit_query_part $offset_query_part";
3438
3439 if ($_GET["debug"]) print $query;
3440
3441 $result = db_query($link, $query);
3442
3443 } else {
3444 // browsing by tag
3445
3446 $feed_kind = "Tags";
3447
3448 $result = db_query($link, "SELECT
3449 guid,
3450 note,
3451 ttrss_entries.id as id,title,
3452 updated,
3453 unread,feed_id,
3454 marked,link,last_read,
3455 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3456 $vfeed_query_part
3457 $content_query_part
3458 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3459 score
3460 FROM
3461 ttrss_entries,ttrss_user_entries,ttrss_tags
3462 WHERE
3463 ref_id = ttrss_entries.id AND
3464 ttrss_user_entries.owner_uid = '$owner_uid' AND
3465 post_int_id = int_id AND tag_name = '$feed' AND
3466 $view_query_part
3467 $search_query_part
3468 $query_strategy_part ORDER BY $order_by
3469 $limit_query_part");
3470 }
3471
3472 return array($result, $feed_title, $feed_site_url, $last_error);
3473
3474 }
3475
3476 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3477 $limit, $search, $search_mode, $match_on) {
3478
3479 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3480 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3481 "margin-bottom : 1em; color : #9a8c59;";
3482
3483 if (!$limit) $limit = 30;
3484
3485 $qfh_ret = queryFeedHeadlines($link, $feed,
3486 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3487 $owner_uid);
3488
3489 $result = $qfh_ret[0];
3490 $feed_title = htmlspecialchars($qfh_ret[1]);
3491 $feed_site_url = $qfh_ret[2];
3492 $last_error = $qfh_ret[3];
3493
3494 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3495
3496 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3497 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3498 <rss version=\"2.0\">
3499 <channel>
3500 <title>$feed_title</title>
3501 <link>$feed_site_url</link>
3502 <description>Feed generated by Tiny Tiny RSS</description>";
3503
3504 while ($line = db_fetch_assoc($result)) {
3505 print "<item>";
3506 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3507 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3508
3509 $tags = get_article_tags($link, $line["id"], $owner_uid);
3510
3511 foreach ($tags as $tag) {
3512 print "<category>" . htmlspecialchars($tag) . "</category>";
3513 }
3514
3515 $rfc822_date = date('r', strtotime($line["updated"]));
3516
3517 print "<pubDate>$rfc822_date</pubDate>";
3518
3519 print "<title>" .
3520 htmlspecialchars($line["title"]) . "</title>";
3521
3522 print "<description><![CDATA[";
3523
3524 if ($line["note"]) {
3525 print "<div style='$note_style'>";
3526 print $line["note"];
3527 print "</div>";
3528 }
3529
3530 print sanitize_rss($link, $line["content_preview"]);
3531 print "]]></description>";
3532
3533 print "</item>";
3534 }
3535
3536 print "</channel></rss>";
3537
3538 }
3539
3540 function getCategoryTitle($link, $cat_id) {
3541
3542 if ($cat_id == -1) {
3543 return __("Special");
3544 } else if ($cat_id == -2) {
3545 return __("Labels");
3546 } else {
3547
3548 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3549 id = '$cat_id'");
3550
3551 if (db_num_rows($result) == 1) {
3552 return db_fetch_result($result, 0, "title");
3553 } else {
3554 return "Uncategorized";
3555 }
3556 }
3557 }
3558
3559 function strip_tags_long($string, $allowed) {
3560
3561 $config = HTMLPurifier_Config::createDefault();
3562
3563 $config->set('HTML', 'Allowed', $allowed);
3564 $purifier = new HTMLPurifier($config);
3565
3566 return $purifier->purify($string);
3567
3568 }
3569
3570 // http://ru2.php.net/strip-tags
3571
3572 /* function strip_tags_long($textstring, $allowed){
3573 while($textstring != strip_tags($textstring, $allowed))
3574 {
3575 while (strlen($textstring) != 0)
3576 {
3577 if (strlen($textstring) > 1024) {
3578 $otherlen = 1024;
3579 } else {
3580 $otherlen = strlen($textstring);
3581 }
3582 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3583 $safetext .= $temptext;
3584 $textstring = substr_replace($textstring,'',0,$otherlen);
3585 }
3586 $textstring = $safetext;
3587 }
3588 return $textstring;
3589 } */
3590
3591
3592 function sanitize_rss($link, $str, $force_strip_tags = false) {
3593 $res = $str;
3594
3595 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
3596
3597 // $res = strip_tags_long($res,
3598 // "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3599
3600 $res = strip_tags_long($res,
3601 "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4");
3602
3603 }
3604
3605 if (get_pref($link, "STRIP_IMAGES")) {
3606
3607 $res = preg_replace('/<img[^>]+>/is', '', $res);
3608
3609 }
3610
3611 return $res;
3612 }
3613
3614 /**
3615 * Send by mail a digest of last articles.
3616 *
3617 * @param mixed $link The database connection.
3618 * @param integer $limit The maximum number of articles by digest.
3619 * @return boolean Return false if digests are not enabled.
3620 */
3621 function send_headlines_digests($link, $limit = 100) {
3622
3623 if (!DIGEST_ENABLE) return false;
3624
3625 $user_limit = DIGEST_EMAIL_LIMIT;
3626 $days = 1;
3627
3628 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3629
3630 if (DB_TYPE == "pgsql") {
3631 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3632 } else if (DB_TYPE == "mysql") {
3633 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3634 }
3635
3636 $result = db_query($link, "SELECT id,email FROM ttrss_users
3637 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3638
3639 while ($line = db_fetch_assoc($result)) {
3640
3641 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3642 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3643
3644 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3645
3646 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3647 $digest = $tuple[0];
3648 $headlines_count = $tuple[1];
3649 $affected_ids = $tuple[2];
3650 $digest_text = $tuple[3];
3651
3652 if ($headlines_count > 0) {
3653
3654 $mail = new PHPMailer();
3655
3656 $mail->PluginDir = "lib/phpmailer/";
3657 $mail->SetLanguage("en", "lib/phpmailer/language/");
3658
3659 $mail->CharSet = "UTF-8";
3660
3661 $mail->From = DIGEST_FROM_ADDRESS;
3662 $mail->FromName = DIGEST_FROM_NAME;
3663 $mail->AddAddress($line["email"], $line["login"]);
3664
3665 if (DIGEST_SMTP_HOST) {
3666 $mail->Host = DIGEST_SMTP_HOST;
3667 $mail->Mailer = "smtp";
3668 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
3669 $mail->Username = DIGEST_SMTP_LOGIN;
3670 $mail->Password = DIGEST_SMTP_PASSWORD;
3671 }
3672
3673 $mail->IsHTML(true);
3674 $mail->Subject = DIGEST_SUBJECT;
3675 $mail->Body = $digest;
3676 $mail->AltBody = $digest_text;
3677
3678 $rc = $mail->Send();
3679
3680 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3681
3682 print "RC=$rc\n";
3683
3684 if ($rc && $do_catchup) {
3685 print "Marking affected articles as read...\n";
3686 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3687 }
3688
3689 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3690 WHERE id = " . $line["id"]);
3691 } else {
3692 print "No headlines\n";
3693 }
3694 }
3695 }
3696
3697 print "All done.\n";
3698
3699 }
3700
3701 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3702
3703 require_once "lib/MiniTemplator.class.php";
3704
3705 $tpl = new MiniTemplator;
3706 $tpl_t = new MiniTemplator;
3707
3708 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3709 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3710
3711 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3712 $tpl->setVariable('CUR_TIME', date('G:i'));
3713
3714 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3715 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3716
3717 $affected_ids = array();
3718
3719 if (DB_TYPE == "pgsql") {
3720 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3721 } else if (DB_TYPE == "mysql") {
3722 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3723 }
3724
3725 $result = db_query($link, "SELECT ttrss_entries.title,
3726 ttrss_feeds.title AS feed_title,
3727 date_entered,
3728 ttrss_user_entries.ref_id,
3729 link,
3730 SUBSTRING(content, 1, 120) AS excerpt,
3731 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
3732 FROM
3733 ttrss_user_entries,ttrss_entries,ttrss_feeds
3734 WHERE
3735 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3736 AND include_in_digest = true
3737 AND $interval_query
3738 AND hidden = false
3739 AND ttrss_user_entries.owner_uid = $user_id
3740 AND unread = true
3741 ORDER BY ttrss_feeds.title, date_entered DESC
3742 LIMIT $limit");
3743
3744 $cur_feed_title = "";
3745
3746 $headlines_count = db_num_rows($result);
3747
3748 $headlines = array();
3749
3750 while ($line = db_fetch_assoc($result)) {
3751 array_push($headlines, $line);
3752 }
3753
3754 for ($i = 0; $i < sizeof($headlines); $i++) {
3755
3756 $line = $headlines[$i];
3757
3758 array_push($affected_ids, $line["ref_id"]);
3759
3760 $updated = smart_date_time(strtotime($line["last_updated"]));
3761
3762 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3763 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3764 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3765 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3766 $tpl->setVariable('ARTICLE_EXCERPT',
3767 truncate_string(strip_tags($line["excerpt"]), 100));
3768
3769 $tpl->addBlock('article');
3770
3771 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3772 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3773 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3774 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3775 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3776 // truncate_string(strip_tags($line["excerpt"]), 100));
3777
3778 $tpl_t->addBlock('article');
3779
3780 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3781 $tpl->addBlock('feed');
3782 $tpl_t->addBlock('feed');
3783 }
3784
3785 }
3786
3787 $tpl->addBlock('digest');
3788 $tpl->generateOutputToString($tmp);
3789
3790 $tpl_t->addBlock('digest');
3791 $tpl_t->generateOutputToString($tmp_t);
3792
3793 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3794 }
3795
3796 function check_for_update($link) {
3797 $releases_feed = "http://tt-rss.org/releases.rss";
3798
3799 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3800 return;
3801 }
3802
3803 error_reporting(0);
3804 if (ENABLE_SIMPLEPIE) {
3805 $rss = new SimplePie();
3806 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
3807 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3808 $rss->set_feed_url($fetch_url);
3809 $rss->set_output_encoding('UTF-8');
3810 $rss->init();
3811 } else {
3812 $rss = fetch_rss($releases_feed);
3813 }
3814 error_reporting (DEFAULT_ERROR_LEVEL);
3815
3816 if ($rss) {
3817
3818 if (ENABLE_SIMPLEPIE) {
3819 $items = $rss->get_items();
3820 } else {
3821 $items = $rss->items;
3822
3823 if (!$items || !is_array($items)) $items = $rss->entries;
3824 if (!$items || !is_array($items)) $items = $rss;
3825 }
3826
3827 if (!is_array($items) || count($items) == 0) {
3828 return;
3829 }
3830
3831 $latest_item = $items[0];
3832
3833 if (ENABLE_SIMPLEPIE) {
3834 $last_title = $latest_item->get_title();
3835 } else {
3836 $last_title = $latest_item["title"];
3837 }
3838
3839 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3840
3841 if (ENABLE_SIMPLEPIE) {
3842 $release_url = sanitize_rss($link, $latest_item->get_link());
3843 $content = sanitize_rss($link, $latest_item->get_description());
3844 } else {
3845 $release_url = sanitize_rss($link, $latest_item["link"]);
3846 $content = sanitize_rss($link, $latest_item["description"]);
3847 }
3848
3849 if (version_compare(VERSION, $latest_version) == -1) {
3850 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3851 $latest_version)."<div class='milestoneDetails'>$content</div>";
3852 } else {
3853 return false;
3854 }
3855 }
3856 }
3857
3858 function markArticlesById($link, $ids, $cmode) {
3859
3860 $tmp_ids = array();
3861
3862 foreach ($ids as $id) {
3863 array_push($tmp_ids, "ref_id = '$id'");
3864 }
3865
3866 $ids_qpart = join(" OR ", $tmp_ids);
3867
3868 if ($cmode == 0) {
3869 db_query($link, "UPDATE ttrss_user_entries SET
3870 marked = false,last_read = NOW()
3871 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3872 } else if ($cmode == 1) {
3873 db_query($link, "UPDATE ttrss_user_entries SET
3874 marked = true
3875 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3876 } else {
3877 db_query($link, "UPDATE ttrss_user_entries SET
3878 marked = NOT marked,last_read = NOW()
3879 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3880 }
3881 }
3882
3883 function publishArticlesById($link, $ids, $cmode) {
3884
3885 $tmp_ids = array();
3886
3887 foreach ($ids as $id) {
3888 array_push($tmp_ids, "ref_id = '$id'");
3889 }
3890
3891 $ids_qpart = join(" OR ", $tmp_ids);
3892
3893 if ($cmode == 0) {
3894 db_query($link, "UPDATE ttrss_user_entries SET
3895 published = false,last_read = NOW()
3896 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3897 } else if ($cmode == 1) {
3898 db_query($link, "UPDATE ttrss_user_entries SET
3899 published = true
3900 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3901 } else {
3902 db_query($link, "UPDATE ttrss_user_entries SET
3903 published = NOT published,last_read = NOW()
3904 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3905 }
3906 }
3907
3908 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3909
3910 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3911
3912 $tmp_ids = array();
3913
3914 foreach ($ids as $id) {
3915 array_push($tmp_ids, "ref_id = '$id'");
3916 }
3917
3918 $ids_qpart = join(" OR ", $tmp_ids);
3919
3920 if ($cmode == 0) {
3921 db_query($link, "UPDATE ttrss_user_entries SET
3922 unread = false,last_read = NOW()
3923 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3924 } else if ($cmode == 1) {
3925 db_query($link, "UPDATE ttrss_user_entries SET
3926 unread = true
3927 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3928 } else {
3929 db_query($link, "UPDATE ttrss_user_entries SET
3930 unread = NOT unread,last_read = NOW()
3931 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3932 }
3933
3934 /* update ccache */
3935
3936 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3937 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3938
3939 while ($line = db_fetch_assoc($result)) {
3940 ccache_update($link, $line["feed_id"], $owner_uid);
3941 }
3942 }
3943
3944 function catchupArticleById($link, $id, $cmode) {
3945
3946 if ($cmode == 0) {
3947 db_query($link, "UPDATE ttrss_user_entries SET
3948 unread = false,last_read = NOW()
3949 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3950 } else if ($cmode == 1) {
3951 db_query($link, "UPDATE ttrss_user_entries SET
3952 unread = true
3953 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3954 } else {
3955 db_query($link, "UPDATE ttrss_user_entries SET
3956 unread = NOT unread,last_read = NOW()
3957 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3958 }
3959 }
3960
3961 function make_guid_from_title($title) {
3962 return preg_replace("/[ \"\',.:;]/", "-",
3963 mb_strtolower(strip_tags($title), 'utf-8'));
3964 }
3965
3966 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3967 $feed_id, $is_cat, $search, $match_on,
3968 $search_mode) {
3969
3970 print "<div class=\"headlinesSubToolbar\">";
3971
3972 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3973 $page_next_link = "javascript:viewFeedGoPage(1)";
3974 $page_first_link = "javascript:viewFeedGoPage(0)";
3975
3976 $catchup_page_link = "javascript:catchupPage()";
3977 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3978 $catchup_sel_link = "javascript:catchupSelection()";
3979
3980 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3981
3982 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3983 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3984 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3985 $sel_inv_link = "javascript:invertHeadlineSelection()";
3986
3987 $tog_unread_link = "javascript:selectionToggleUnread()";
3988 $tog_marked_link = "javascript:selectionToggleMarked()";
3989 $tog_published_link = "javascript:selectionTogglePublished()";
3990
3991 } else {
3992
3993 $sel_all_link = "javascript:cdmSelectArticles('all')";
3994 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3995 $sel_none_link = "javascript:cdmSelectArticles('none')";
3996
3997 $sel_inv_link = "javascript:invertHeadlineSelection()";
3998
3999 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4000 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4001 $tog_published_link = "javascript:selectionTogglePublished(true)";
4002
4003 }
4004
4005 print "<div id=\"subtoolbar_ftitle\">";
4006
4007 if ($feed_site_url) {
4008 if (!$bottom) {
4009 $target = "target=\"_blank\"";
4010 }
4011 print "<a $target href=\"$feed_site_url\">".
4012 truncate_string($feed_title,30)."</a>";
4013 } else {
4014 print $feed_title;
4015 }
4016
4017 if ($search) {
4018 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4019 }
4020
4021 print "
4022 <a target=\"_blank\"
4023 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4024 <img class=\"noborder\"
4025 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4026 </a>";
4027
4028 print "</div>";
4029
4030 print __('Select:')."
4031 <a href=\"$sel_all_link\">".__('All')."</a>,
4032 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4033 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4034 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4035
4036 print "&nbsp;&nbsp;";
4037
4038 print "<span
4039 onmouseover=\"enable_selection(false)\"
4040 onmouseout=\"enable_selection(true)\"
4041 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4042 __("Actions...") . "&nbsp;&nbsp;<img width='11' height'7'
4043 src=\"images/down_arrow.png\">
4044 </span>";
4045
4046 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4047
4048 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4049 <li onclick=\"$tog_unread_link\">&nbsp;&nbsp;".__('Unread')."</li>
4050 <li onclick=\"$tog_marked_link\">&nbsp;&nbsp;".__('Starred')."</li>
4051 <li onclick=\"$tog_published_link\">&nbsp;&nbsp;".__('Published')."</li>
4052 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4053 <li class=\"insensitive\">".__('Mark as read:')."</li>
4054 <li onclick=\"$catchup_sel_link\">&nbsp;&nbsp;".__('Selection')."</li>";
4055
4056 print "<li onclick=\"$catchup_feed_link\">&nbsp;&nbsp;".__('Entire feed').
4057 "</li>";
4058
4059 //print "<li><span class=\"insensitive\">--------</span></li>";
4060 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4061
4062 print_labels_headlines_dropdown($link, $feed_id);
4063
4064 print "</ul>";
4065
4066 print "</div>";
4067 }
4068
4069 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4070
4071 $tmp_category = getCategoryTitle($link, $cat_id);
4072
4073 if ($cat_id > 0) {
4074 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4075 } else if ($cat_id == 0 || $cat_id == -2) {
4076 $cat_unread = getCategoryUnread($link, $cat_id);
4077 }
4078
4079 if ($hidden) {
4080 $holder_style = "display:none;";
4081 $ellipsis = "…";
4082 } else {
4083 $holder_style = "";
4084 $ellipsis = "";
4085 }
4086
4087 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4088
4089 if ($can_browse) {
4090 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4091 $inner_title_class = "catTitle";
4092 } else {
4093 $browse_cat_link = "";
4094 $inner_title_class = "catTitleNL";
4095 }
4096
4097 $cat_class = "feedCat";
4098
4099 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4100 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4101 title=\"".__('Click to collapse category')."\"
4102 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4103 id=\"FCATN-$cat_id\" $browse_cat_link
4104 \">$tmp_category</span>";
4105
4106 print "<span id=\"FCAP-$cat_id\">";
4107
4108 print " <span id=\"FCATCTR-$cat_id\"
4109 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4110
4111 print "</span>";
4112
4113 //print "</li>";
4114
4115 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4116
4117 }
4118
4119 function outputFeedList($link, $tags = false) {
4120
4121 print "<ul class=\"feedList\" id=\"feedList\">";
4122
4123 $owner_uid = $_SESSION["uid"];
4124
4125 /* virtual feeds */
4126
4127 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4128
4129 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4130 $cat_hidden = true;
4131 } else {
4132 $cat_hidden = false;
4133 }
4134
4135 printCategoryHeader($link, -1, $cat_hidden, false);
4136 }
4137
4138 $num_starred = getFeedUnread($link, -1);
4139 $num_published = getFeedUnread($link, -2);
4140 $num_fresh = getFeedUnread($link, -3);
4141 $num_total = getFeedUnread($link, -4);
4142
4143 $class = "virt";
4144
4145 if ($num_total > 0) $class .= "Unread";
4146
4147 printFeedEntry(-4, $class, __("All articles"), $num_total,
4148 "images/tag.png", $link);
4149
4150 $class = "virt";
4151
4152 if ($num_fresh > 0) $class .= "Unread";
4153
4154 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4155 "images/fresh.png", $link);
4156
4157 $class = "virt";
4158
4159 if ($num_starred > 0) $class .= "Unread";
4160
4161 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4162
4163 if ($is_ie) {
4164 $mark_img_ext = "gif";
4165 } else {
4166 $mark_img_ext = "png";
4167 }
4168
4169 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4170 "images/mark_set.$mark_img_ext", $link);
4171
4172 $class = "virt";
4173
4174 if ($num_published > 0) $class .= "Unread";
4175
4176 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4177 "images/pub_set.gif", $link);
4178
4179 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4180 print "</ul></li>";
4181 }
4182
4183 if (!$tags) {
4184
4185
4186 $result = db_query($link, "SELECT * FROM
4187 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4188
4189 if (db_num_rows($result) > 0) {
4190 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4191
4192 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4193 $cat_hidden = true;
4194 } else {
4195 $cat_hidden = false;
4196 }
4197
4198 printCategoryHeader($link, -2, $cat_hidden, true);
4199
4200 } else {
4201 print "<li><hr></li>";
4202 }
4203 }
4204
4205 while ($line = db_fetch_assoc($result)) {
4206
4207 $label_id = -$line['id'] - 11;
4208 $count = getFeedUnread($link, $label_id);
4209
4210 $class = "label";
4211
4212 if ($count > 0) {
4213 $class .= "Unread";
4214 }
4215
4216 printFeedEntry($label_id,
4217 $class, $line["caption"],
4218 $count, "images/label.png", $link,
4219 false, false, false,
4220 $line['fg_color'], $line['bg_color']);
4221
4222 }
4223
4224 if (db_num_rows($result) > 0) {
4225 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4226 print "</ul>";
4227 }
4228 }
4229
4230
4231 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4232 print "<li><hr></li>";
4233 }
4234
4235 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4236 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4237 $order_by_qpart = "order_id,category,unread DESC,title";
4238 } else {
4239 $order_by_qpart = "order_id,category,title";
4240 }
4241 } else {
4242 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4243 $order_by_qpart = "unread DESC,title";
4244 } else {
4245 $order_by_qpart = "title";
4246 }
4247 }
4248
4249 $age_qpart = getMaxAgeSubquery();
4250
4251 $query = "SELECT ttrss_feeds.*,
4252 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4253 cat_id,last_error,
4254 ttrss_feed_categories.title AS category,
4255 ttrss_feed_categories.collapsed,
4256 value AS unread
4257 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4258 ON (ttrss_feed_categories.id = cat_id)
4259 LEFT JOIN ttrss_counters_cache
4260 ON
4261 (ttrss_feeds.id = feed_id)
4262 WHERE
4263 ttrss_feeds.hidden = false AND
4264 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4265 ORDER BY $order_by_qpart";
4266
4267 $result = db_query($link, $query);
4268
4269 $actid = $_GET["actid"];
4270
4271 /* real feeds */
4272
4273 $lnum = 0;
4274
4275 $total_unread = 0;
4276
4277 $category = "";
4278
4279 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4280
4281 while ($line = db_fetch_assoc($result)) {
4282
4283 $feed = htmlspecialchars(trim($line["title"]));
4284
4285 if (!$feed) $feed = "[Untitled]";
4286
4287 $feed_id = $line["id"];
4288 $unread = $line["unread"];
4289
4290 $subop = $_GET["subop"];
4291
4292 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4293 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4294 } else {
4295 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4296 }
4297
4298 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4299
4300 if ($rtl_content) {
4301 $rtl_tag = "dir=\"RTL\"";
4302 } else {
4303 $rtl_tag = "";
4304 }
4305
4306 $tmp_result = db_query($link,
4307 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4308 WHERE parent_feed = '$feed_id' AND feed_id = id");
4309
4310 $unread += db_fetch_result($tmp_result, 0, "unread");
4311
4312 $cat_id = $line["cat_id"];
4313
4314 $tmp_category = $line["category"];
4315
4316 if (!$tmp_category) {
4317 $tmp_category = __("Uncategorized");
4318 }
4319
4320 // $class = ($lnum % 2) ? "even" : "odd";
4321
4322 if ($line["last_error"]) {
4323 $class = "error";
4324 } else {
4325 $class = "feed";
4326 }
4327
4328 if ($unread > 0) $class .= "Unread";
4329
4330 if ($actid == $feed_id) {
4331 $class .= "Selected";
4332 }
4333
4334 $total_unread += $unread;
4335
4336 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4337
4338 if ($category) {
4339 print "</ul></li>";
4340 }
4341
4342 $category = $tmp_category;
4343
4344 $collapsed = sql_bool_to_bool($line["collapsed"]);
4345
4346 // workaround for NULL category
4347 if ($category == __("Uncategorized")) {
4348 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4349 $collapsed = "t";
4350 }
4351 }
4352
4353 $cat_id = sprintf("%d", $cat_id);
4354
4355 printCategoryHeader($link, $cat_id, $collapsed, true);
4356
4357 }
4358
4359 printFeedEntry($feed_id, $class, $feed, $unread,
4360 ICONS_URL."/$feed_id.ico", $link, $rtl_content,
4361 $last_updated, $line["last_error"]);
4362
4363 ++$lnum;
4364 }
4365
4366 if (db_num_rows($result) == 0) {
4367 print "<li>".__('No feeds to display.')."</li>";
4368 }
4369
4370 } else {
4371
4372 // tags
4373
4374 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4375 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4376 post_int_id = ttrss_user_entries.int_id AND
4377 unread = true AND ref_id = ttrss_entries.id
4378 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4379 UNION
4380 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4381 ORDER BY tag_name"); */
4382
4383 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4384 print "<li class=\"feedCat\">".__('Tags')."</li>";
4385 print "<ul class=\"feedCatList\">";
4386 }
4387
4388 $age_qpart = getMaxAgeSubquery();
4389
4390 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4391 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4392 AND ref_id = id AND $age_qpart
4393 AND unread = true)) AS count FROM ttrss_tags
4394 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4395 ORDER BY count DESC LIMIT 50");
4396
4397 $tags = array();
4398
4399 while ($line = db_fetch_assoc($result)) {
4400 $tags[$line["tag_name"]] += $line["count"];
4401 }
4402
4403 foreach (array_keys($tags) as $tag) {
4404
4405 $unread = $tags[$tag];
4406
4407 $class = "tag";
4408
4409 if ($unread > 0) {
4410 $class .= "Unread";
4411 }
4412
4413 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4414
4415 }
4416
4417 if (db_num_rows($result) == 0) {
4418 print "<li>No tags to display.</li>";
4419 }
4420
4421 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4422 print "</ul>";
4423 }
4424
4425 }
4426
4427 print "</ul>";
4428
4429 }
4430
4431 function get_article_tags($link, $id, $owner_uid = 0) {
4432
4433 $a_id = db_escape_string($id);
4434
4435 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4436
4437 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4438 owner_uid as owner FROM
4439 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4440 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4441
4442 $tags = array();
4443
4444 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4445 array_push($tags, $tmp_line["tag_name"]);
4446 }
4447
4448 return $tags;
4449 }
4450
4451 function trim_value(&$value) {
4452 $value = trim($value);
4453 }
4454
4455 function trim_array($array) {
4456 $tmp = $array;
4457 array_walk($tmp, 'trim_value');
4458 return $tmp;
4459 }
4460
4461 function tag_is_valid($tag) {
4462 if ($tag == '') return false;
4463 if (preg_match("/^[0-9]*$/", $tag)) return false;
4464 if (mb_strlen($tag) > 250) return false;
4465
4466 if (function_exists('iconv')) {
4467 $tag = iconv("utf-8", "utf-8", $tag);
4468 }
4469
4470 if (!$tag) return false;
4471
4472 return true;
4473 }
4474
4475 function render_login_form($link, $mobile = false) {
4476 if (!$mobile) {
4477 require_once "login_form.php";
4478 } else {
4479 require_once "mobile/login_form.php";
4480 }
4481 }
4482
4483 // from http://developer.apple.com/internet/safari/faq.html
4484 function no_cache_incantation() {
4485 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4486 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4487 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4488 header("Cache-Control: post-check=0, pre-check=0", false);
4489 header("Pragma: no-cache"); // HTTP/1.0
4490 }
4491
4492 function format_warning($msg, $id = "") {
4493 return "<div class=\"warning\" id=\"$id\">
4494 <img src=\"images/sign_excl.gif\">$msg</div>";
4495 }
4496
4497 function format_notice($msg) {
4498 return "<div class=\"notice\">
4499 <img src=\"images/sign_info.gif\">$msg</div>";
4500 }
4501
4502 function format_error($msg) {
4503 return "<div class=\"error\">
4504 <img src=\"images/sign_excl.gif\">$msg</div>";
4505 }
4506
4507 function print_notice($msg) {
4508 return print format_notice($msg);
4509 }
4510
4511 function print_warning($msg) {
4512 return print format_warning($msg);
4513 }
4514
4515 function print_error($msg) {
4516 return print format_error($msg);
4517 }
4518
4519
4520 function T_sprintf() {
4521 $args = func_get_args();
4522 return vsprintf(__(array_shift($args)), $args);
4523 }
4524
4525 function format_inline_player($link, $url, $ctype) {
4526
4527 $entry = "";
4528
4529 if (($ctype == __("audio/mpeg")) && (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4530
4531 $entry .= "<object type=\"application/x-shockwave-flash\"
4532 data=\"extras/button/musicplayer.swf?song_url=$url\"
4533 width=\"17\" height=\"17\">
4534 <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object>";
4535 }
4536
4537 /*
4538
4539 if (substr($ctype,0,6)=="audio/" || $ctype=="application/ogg" || $ctype=="application/x-ogg") {
4540 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4541 if (($ctype == __("audio/mpeg")) &&
4542 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4543 $entry .= "<span><object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object></span>";
4544 }
4545 $entry .= "</audio> ";
4546 if (($ctype == __("audio/mpeg")) &&
4547 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4548 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a>";
4549 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
4550 }
4551 } elseif (substr($ctype,0,6)=="video/") {
4552 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4553 $entry .= "</video>";
4554 } */
4555
4556
4557
4558 return $entry;
4559 }
4560
4561 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4562 $zoom_mode = false) {
4563
4564 /* we can figure out feed_id from article id anyway, why do we
4565 * pass feed_id here? */
4566
4567 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4568 WHERE ref_id = '$id'");
4569
4570 $feed_id = db_fetch_result($result, 0, "feed_id");
4571
4572 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4573
4574 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4575 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4576
4577 if (db_num_rows($result) == 1) {
4578 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4579 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4580 } else {
4581 $rtl_content = false;
4582 $always_display_enclosures = false;
4583 }
4584
4585 if ($rtl_content) {
4586 $rtl_tag = "dir=\"RTL\"";
4587 $rtl_class = "RTL";
4588 } else {
4589 $rtl_tag = "";
4590 $rtl_class = "";
4591 }
4592
4593 if ($mark_as_read) {
4594 $result = db_query($link, "UPDATE ttrss_user_entries
4595 SET unread = false,last_read = NOW()
4596 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4597
4598 ccache_update($link, $feed_id, $_SESSION["uid"]);
4599 }
4600
4601 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4602 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4603 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4604 num_comments,
4605 author,
4606 note
4607 FROM ttrss_entries,ttrss_user_entries
4608 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4609
4610 if ($result) {
4611
4612 $link_target = "";
4613
4614 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4615 $link_target = "target=\"_blank\"";
4616 }
4617
4618 $line = db_fetch_assoc($result);
4619
4620 if ($line["icon_url"]) {
4621 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4622 } else {
4623 $feed_icon = "&nbsp;";
4624 }
4625
4626 $num_comments = $line["num_comments"];
4627 $entry_comments = "";
4628
4629 if ($num_comments > 0) {
4630 if ($line["comments"]) {
4631 $comments_url = $line["comments"];
4632 } else {
4633 $comments_url = $line["link"];
4634 }
4635 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4636 } else {
4637 if ($line["comments"] && $line["link"] != $line["comments"]) {
4638 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4639 }
4640 }
4641
4642 if ($zoom_mode) {
4643 header("Content-Type: text/html");
4644 print "<html><head>
4645 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4646 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4647 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4648 </head><body>";
4649 }
4650
4651
4652 print "<div class=\"postReply\">";
4653
4654 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4655 onmouseout=\"enable_resize(false)\">";
4656
4657 $entry_author = $line["author"];
4658
4659 if ($entry_author) {
4660 $entry_author = __(" - ") . $entry_author;
4661 }
4662
4663 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4664 strtotime($line["updated"]));
4665
4666 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4667
4668 if ($line["link"]) {
4669 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4670 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4671 } else {
4672 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4673 }
4674
4675 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4676
4677 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4678
4679 print "<div style='float : right'>
4680 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
4681
4682 if (!$zoom_mode) {
4683 print "<span id=\"ATSTR-$id\">$tags_str</span>
4684 <a title=\"".__('Edit tags for this article')."\"
4685 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4686
4687 if (defined('_ENABLE_INLINE_VIEW')) {
4688
4689 print "<img src=\"images/art-inline.png\" class='tagsPic'
4690 style=\"cursor : pointer\" style=\"cursor : pointer\"
4691 onclick=\"showOriginalArticleInline($id)\"
4692 alt='Inline' title='".__('Display original article content')."'>";
4693
4694 }
4695
4696 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4697 style=\"cursor : pointer\" style=\"cursor : pointer\"
4698 onclick=\"zoomToArticle($id)\"
4699 alt='Zoom' title='".__('Show article summary in new window')."'>";
4700
4701 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4702
4703 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4704 style=\"cursor : pointer\" style=\"cursor : pointer\"
4705 onclick=\"publishWithNote($id, '$note_escaped')\"
4706 alt='PubNote' title='".__('Publish article with a note')."'>";
4707
4708 }
4709 print "</div>";
4710 print "<div clear='both'>$entry_comments</div>";
4711
4712 print "</div>";
4713
4714 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4715
4716 print "<div class=\"postContent\">";
4717
4718 $article_content = sanitize_rss($link, $line["content"]);
4719
4720 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4721 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4722 $article_content);
4723 }
4724
4725 print "<div id=\"POSTNOTE-$id\">";
4726 if ($line['note']) {
4727 print format_article_note($id, $line['note']);
4728 }
4729 print "</div>";
4730
4731 print $article_content;
4732
4733 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4734 post_id = '$id' AND content_url != ''");
4735
4736 if (db_num_rows($result) > 0) {
4737
4738 $entries_html = array();
4739 $entries = array();
4740
4741 while ($line = db_fetch_assoc($result)) {
4742
4743 $url = $line["content_url"];
4744 $ctype = $line["content_type"];
4745
4746 if (!$ctype) $ctype = __("unknown type");
4747
4748 $filename = substr($url, strrpos($url, "/")+1);
4749
4750 $entry = format_inline_player($link, $url, $ctype);
4751
4752 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4753 $filename . " (" . $ctype . ")" . "</a>";
4754
4755 array_push($entries_html, $entry);
4756
4757 $entry = array();
4758
4759 $entry["type"] = $ctype;
4760 $entry["filename"] = $filename;
4761 $entry["url"] = $url;
4762
4763 array_push($entries, $entry);
4764 }
4765
4766 print "<div class=\"postEnclosures\">";
4767
4768 if ($always_display_enclosures || !preg_match("/<img/i", $article_content)) {
4769 foreach ($entries as $entry) {
4770 if (preg_match("/image/", $entry["type"])) {
4771 print "<p><img
4772 alt=\"".htmlspecialchars($entry["filename"])."\"
4773 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4774 }
4775 }
4776 }
4777
4778 print "<div class=\"postEnclosures\">";
4779
4780 if (db_num_rows($result) == 1) {
4781 print __("Attachment:") . " ";
4782 } else {
4783 print __("Attachments:") . " ";
4784 }
4785
4786 print join(", ", $entries_html);
4787
4788 print "</div>";
4789 }
4790
4791 print "</div>";
4792
4793 print "</div>";
4794
4795 }
4796
4797 if (!$zoom_mode) {
4798 print "]]></article>";
4799 } else {
4800 print "
4801 <div style=\"text-align : center\">
4802 <input type=\"submit\" onclick=\"return window.close()\"
4803 value=\"".__("Close this window")."\"></div>";
4804 print "</body></html>";
4805
4806 }
4807
4808 }
4809
4810 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4811 $next_unread_feed, $offset, $vgr_last_feed = false,
4812 $override_order = false) {
4813
4814 $disable_cache = false;
4815
4816 $timing_info = getmicrotime();
4817
4818 $topmost_article_ids = array();
4819
4820 if (!$offset) {
4821 $offset = 0;
4822 }
4823
4824 if ($subop == "undefined") $subop = "";
4825
4826 $subop_split = split(":", $subop);
4827
4828 if ($subop == "CatchupSelected") {
4829 $ids = split(",", db_escape_string($_GET["ids"]));
4830 $cmode = sprintf("%d", $_GET["cmode"]);
4831
4832 catchupArticlesById($link, $ids, $cmode);
4833 }
4834
4835 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4836 update_generic_feed($link, $feed, $cat_view, true);
4837 }
4838
4839 if ($subop == "MarkAllRead") {
4840 catchup_feed($link, $feed, $cat_view);
4841
4842 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4843 if ($next_unread_feed) {
4844 $feed = $next_unread_feed;
4845 }
4846 }
4847 }
4848
4849 if ($subop_split[0] == "MarkAllReadGR") {
4850 catchup_feed($link, $subop_split[1], false);
4851 }
4852
4853
4854 if ($feed_id > 0) {
4855 $result = db_query($link,
4856 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4857
4858 if (db_num_rows($result) == 0) {
4859 print "<div align='center'>".__('Feed not found.')."</div>";
4860 return;
4861 }
4862 }
4863
4864 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4865
4866 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4867 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4868
4869 if (db_num_rows($result) == 1) {
4870 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4871 } else {
4872 $rtl_content = false;
4873 }
4874
4875 if ($rtl_content) {
4876 $rtl_tag = "dir=\"RTL\"";
4877 } else {
4878 $rtl_tag = "";
4879 }
4880 } else {
4881 $rtl_tag = "";
4882 $rtl_content = false;
4883 }
4884
4885 $script_dt_add = get_script_dt_add();
4886
4887 /// START /////////////////////////////////////////////////////////////////////////////////
4888
4889 $search = db_escape_string($_GET["query"]);
4890
4891 if ($search) {
4892 $disable_cache = true;
4893 }
4894
4895 $search_mode = db_escape_string($_GET["search_mode"]);
4896 $match_on = db_escape_string($_GET["match_on"]);
4897
4898 if (!$match_on) {
4899 $match_on = "both";
4900 }
4901
4902 $real_offset = $offset * $limit;
4903
4904 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4905
4906 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4907 $search, $search_mode, $match_on, $override_order, $real_offset);
4908
4909 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4910
4911 $result = $qfh_ret[0];
4912 $feed_title = $qfh_ret[1];
4913 $feed_site_url = $qfh_ret[2];
4914 $last_error = $qfh_ret[3];
4915
4916 $vgroup_last_feed = $vgr_last_feed;
4917
4918 if ($feed == -2) {
4919 $feed_site_url = article_publish_url($link);
4920 }
4921
4922 /// STOP //////////////////////////////////////////////////////////////////////////////////
4923
4924 if (!$offset) {
4925 print "<div id=\"headlinesContainer\" $rtl_tag>";
4926
4927 if (!$result) {
4928 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4929 return;
4930 }
4931
4932 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4933 $feed, $cat_view, $search, $match_on, $search_mode);
4934
4935 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4936 }
4937
4938 $headlines_count = db_num_rows($result);
4939
4940 if (db_num_rows($result) > 0) {
4941
4942 # print "\{$offset}";
4943
4944 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4945 print "<table class=\"headlinesList\" id=\"headlinesList\"
4946 cellspacing=\"0\">";
4947 }
4948
4949 $lnum = $limit*$offset;
4950
4951 error_reporting (DEFAULT_ERROR_LEVEL);
4952
4953 $num_unread = 0;
4954 $cur_feed_title = '';
4955
4956 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4957
4958 while ($line = db_fetch_assoc($result)) {
4959
4960 $class = ($lnum % 2) ? "even" : "odd";
4961
4962 $id = $line["id"];
4963 $feed_id = $line["feed_id"];
4964
4965 $labels = get_article_labels($link, $id);
4966
4967 $labels_str = "<span id=\"HLLCTR-$id\">";
4968 $labels_str .= format_article_labels($labels, $id);
4969 $labels_str .= "</span>";
4970
4971 if (count($topmost_article_ids) < 5) {
4972 array_push($topmost_article_ids, $id);
4973 }
4974
4975 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4976
4977 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4978 alt=\"Updated\">";
4979 } else {
4980 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4981 alt=\"Updated\">";
4982 }
4983
4984 if (sql_bool_to_bool($line["unread"]) &&
4985 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4986
4987 $update_pic = "<img id='FUPDPIC-$id' src=\"images/fresh_sign.png\"
4988 alt=\"Fresh\">";
4989 }
4990
4991 if ($line["unread"] == "t" || $line["unread"] == "1") {
4992 $class .= "Unread";
4993 ++$num_unread;
4994 $is_unread = true;
4995 } else {
4996 $is_unread = false;
4997 }
4998
4999 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5000
5001 if ($is_ie) {
5002 $mark_img_ext = "gif";
5003 } else {
5004 $mark_img_ext = "png";
5005 }
5006
5007 if ($line["marked"] == "t" || $line["marked"] == "1") {
5008 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5009 class=\"markedPic\"
5010 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5011 } else {
5012 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5013 class=\"markedPic\"
5014 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5015 }
5016
5017 if ($line["published"] == "t" || $line["published"] == "1") {
5018 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5019 class=\"markedPic\"
5020 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5021 } else {
5022 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5023 class=\"markedPic\"
5024 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5025 }
5026
5027 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5028 # $line["title"] . "</a>";
5029
5030 # $content_link = "<a
5031 # href=\"" . htmlspecialchars($line["link"]) . "\"
5032 # onclick=\"view($id,$feed_id);\">" .
5033 # $line["title"] . "</a>";
5034
5035 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5036 # $line["title"] . "</a>";
5037
5038 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5039 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5040 } else {
5041 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5042 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5043 }
5044
5045 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5046 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5047 100);
5048 }
5049
5050 $score = $line["score"];
5051
5052 $score_pic = get_score_pic($score);
5053
5054 /* $score_title = __("(Click to change)");
5055 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5056 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5057
5058 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5059 title=\"$score\">";
5060
5061 if ($score > 500) {
5062 $hlc_suffix = "H";
5063 } else if ($score < -100) {
5064 $hlc_suffix = "L";
5065 } else {
5066 $hlc_suffix = "";
5067 }
5068
5069 $entry_author = $line["author"];
5070
5071 if ($entry_author) {
5072 $entry_author = " - $entry_author";
5073 }
5074
5075 $has_feed_icon = feed_has_icon($feed_id);
5076
5077 if ($has_feed_icon) {
5078 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5079 } else {
5080 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5081 $feed_icon_img = "";
5082 }
5083
5084 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5085
5086 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5087 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5088
5089 $cur_feed_title = $line["feed_title"];
5090 $vgroup_last_feed = $feed_id;
5091
5092 $cur_feed_title = htmlspecialchars($cur_feed_title);
5093
5094 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5095
5096 print "<tr class='feedTitle'><td colspan='7'>".
5097 "<div style=\"float : right\">$feed_icon_img</div>".
5098 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5099 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5100 }
5101 }
5102
5103 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5104 onmouseout='postMouseOut($id)'";
5105
5106 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5107
5108 print "<td class='hlUpdPic'>$update_pic</td>";
5109
5110 print "<td class='hlSelectRow'>
5111 <input type=\"checkbox\" onclick=\"tSR(this)\"
5112 id=\"RCHK-$id\">
5113 </td>";
5114
5115 print "<td class='hlMarkedPic'>$marked_pic</td>";
5116 print "<td class='hlMarkedPic'>$published_pic</td>";
5117
5118 # if ($line["feed_title"]) {
5119 # print "<td class='hlContent'>$content_link</td>";
5120 # print "<td class='hlFeed'>
5121 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5122 # truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
5123 # } else {
5124
5125 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle' id='HLC-$id'>";
5126
5127 print "<a id=\"RTITLE-$id\"
5128 href=\"" . htmlspecialchars($line["link"]) . "\"
5129 onclick=\"return false\">" .
5130 $line["title"];
5131
5132 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5133 if ($content_preview) {
5134 print "<span class=\"contentPreview\"> - $content_preview</span>";
5135 }
5136 }
5137
5138 print "</a>";
5139
5140 print $labels_str;
5141
5142 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5143 # $line["feed_title"]."</a>
5144
5145 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5146 if ($line["feed_title"]) {
5147 print "<span class=\"hlFeed\">
5148 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5149 $line["feed_title"]."</a>)
5150 </span>";
5151 }
5152 }
5153
5154 // print "<img id='HLL-$id' class='hlLoading'
5155 // src='images/indicator_tiny.gif' style='display : none'>";
5156
5157 print "</td>";
5158
5159 # }
5160
5161 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt&nbsp;</nobr></td>";
5162
5163 print "<td class='hlMarkedPic'>$score_pic</td>";
5164
5165 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5166 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5167 }
5168
5169 print "</tr>";
5170
5171 } else {
5172
5173 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5174 if ($feed_id != $vgroup_last_feed) {
5175
5176 $cur_feed_title = $line["feed_title"];
5177 $vgroup_last_feed = $feed_id;
5178
5179 $cur_feed_title = htmlspecialchars($cur_feed_title);
5180
5181 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5182
5183 $has_feed_icon = feed_has_icon($feed_id);
5184
5185 if ($has_feed_icon) {
5186 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5187 } else {
5188 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5189 }
5190
5191 print "<div class='cdmFeedTitle'>".
5192 "<div style=\"float : right\">$feed_icon_img</div>".
5193 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5194 $line["feed_title"]."</a> $vf_catchup_link</div>";
5195 }
5196 }
5197
5198 if ($is_unread) {
5199 $add_class = "Unread";
5200 } else {
5201 $add_class = "";
5202 }
5203
5204 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5205 $show_excerpt = false;
5206
5207 if ($expand_cdm && $score >= -100) {
5208 $cdm_cstyle = "";
5209 $show_excerpt = false;
5210 } else {
5211 $cdm_cstyle = "style=\"display : none\"";
5212 $show_excerpt = true;
5213 }
5214
5215 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5216 onmouseout='postMouseOut($id)'";
5217
5218 print "<div class=\"cdmArticle$add_class\"
5219 id=\"RROW-$id\"
5220 $mouseover_attrs'>";
5221
5222 print "<div class=\"cdmHeader\">";
5223
5224 if (!get_pref($link, "VFEED_GROUP_BY_FEED") || !$line["feed_title"]) {
5225 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5226 }
5227
5228 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5229 </div>";
5230
5231 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5232 onclick=\"javascript:toggleUnread($id, 0)\"
5233 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5234 ";
5235
5236 print $entry_author;
5237
5238 /* if (!$expand_cdm || $score < -100) {
5239 print "&nbsp;<a id=\"CICH-$id\"
5240 href=\"javascript:cdmExpandArticle($id)\">
5241 (".__('Show article').")</a>";
5242 } */
5243
5244 print $labels_str;
5245
5246 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5247 if ($line["feed_title"]) {
5248 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5249 }
5250 }
5251
5252 print "</span></div>";
5253
5254 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5255 $line["content_preview"] = preg_replace("/href=/i",
5256 "target=\"_blank\" href=", $line["content_preview"]);
5257 }
5258
5259 if ($show_excerpt) {
5260 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5261 onclick=\"cdmExpandArticle($id)\"
5262 title=\"".__('Click to expand article')."\">";
5263
5264 $content_preview = trim(truncate_string(strip_tags($line["content_preview"]), 100));
5265
5266 if (strlen($content_preview) != 0) {
5267 print $content_preview;
5268 } else {
5269 print __('Click to expand article');
5270 }
5271 print "</div>";
5272 }
5273
5274 print "<div class=\"cdmContent\"
5275 onclick=\"cdmClicked($id)\"
5276 id=\"CICD-$id\" $cdm_cstyle>";
5277
5278 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5279
5280 print "<div id=\"POSTNOTE-$id\">";
5281 if ($line['note']) {
5282 print format_article_note($id, $line['note']);
5283 }
5284 print "</div>";
5285
5286 print sanitize_rss($link, $line["content_preview"]);
5287
5288 $article_content = $line["content_preview"];
5289
5290 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5291 post_id = '$id' AND content_url != ''");
5292
5293 if (db_num_rows($e_result) > 0) {
5294
5295 $entries_html = array();
5296 $entries = array();
5297
5298 while ($e_line = db_fetch_assoc($e_result)) {
5299
5300 $url = $e_line["content_url"];
5301 $ctype = $e_line["content_type"];
5302 if (!$ctype) $ctype = __("unknown type");
5303
5304 $filename = substr($url, strrpos($url, "/")+1);
5305
5306 $entry = format_inline_player($link, $url, $ctype);
5307
5308 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5309 $filename . " (" . $ctype . ")" . "</a>";
5310
5311 array_push($entries_html, $entry);
5312
5313 $entry = array();
5314
5315 $entry["type"] = $ctype;
5316 $entry["filename"] = $filename;
5317 $entry["url"] = $url;
5318
5319 array_push($entries, $entry);
5320 }
5321
5322 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5323 ttrss_feeds WHERE id = ".$line['feed_id']." AND owner_uid = ".$_SESSION["uid"]);
5324
5325 $always_display_enclosures = db_fetch_result($tmp_result, 0, "always_display_enclosures");
5326
5327 if ($always_display_enclosures || !preg_match("/img/i", $article_content)) {
5328 foreach ($entries as $entry) {
5329 if (preg_match("/image/", $entry["type"])) {
5330 print "<p><img
5331 alt=\"".htmlspecialchars($entry["filename"])."\"
5332 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5333 }
5334 }
5335 }
5336
5337 print "<div class=\"cdmEnclosures\">";
5338
5339 if (db_num_rows($e_result) == 1) {
5340 print __("Attachment:") . " ";
5341 } else {
5342 print __("Attachments:") . " ";
5343 }
5344
5345 print join(", ", $entries_html);
5346
5347 print "</div>";
5348 }
5349
5350
5351 print "<br clear='both'>";
5352 // print "</div>";
5353
5354 /* if (!$expand_cdm) {
5355 print "<a id=\"CICH-$id\"
5356 href=\"javascript:cdmExpandArticle($id)\">
5357 Show article</a>";
5358 } */
5359
5360 print "</div>";
5361
5362 print "<div class=\"cdmFooter\"><span class='s0'>";
5363
5364 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5365
5366 print __("Select:").
5367 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5368 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5369
5370 print "</span><span class='s1'>$marked_pic&nbsp;";
5371 print "$published_pic&nbsp;";
5372 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5373 onclick=\"zoomToArticle($id)\"
5374 style=\"cursor : pointer\"
5375 alt='Zoom'
5376 title='".__('Show article summary in new window')."'>&nbsp;";
5377
5378 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5379
5380 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5381 style=\"cursor : pointer\" style=\"cursor : pointer\"
5382 onclick=\"publishWithNote($id, '$note_escaped')\"
5383 alt='PubNote' title='".__('Publish article with a note')."'>";
5384
5385 print "</span>";
5386
5387 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5388
5389 // print "<img src='images/tag.png' class='markedPic'>";
5390
5391 print "<span class='s1'>
5392 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5393 <span id=\"ATSTR-$id\">$tags_str</span>
5394 <a title=\"".__('Edit tags for this article')."\"
5395 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5396
5397 print "</span>";
5398
5399 print "<span class='s2'><a class=\"cdmToggleLink\"
5400 href=\"javascript:toggleUnread($id)\">
5401 ".__('toggle unread')."</a></span>";
5402
5403 print "</div>";
5404 print "</div>";
5405
5406 }
5407
5408 ++$lnum;
5409 }
5410
5411 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5412 print "</table>";
5413 }
5414
5415 } else {
5416 $message = "";
5417
5418 switch ($view_mode) {
5419 case "unread":
5420 $message = __("No unread articles found to display.");
5421 break;
5422 case "updated":
5423 $message = __("No updated articles found to display.");
5424 break;
5425 case "marked":
5426 $message = __("No starred articles found to display.");
5427 break;
5428 default:
5429 if ($feed < -10) {
5430 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5431 } else {
5432 $message = __("No articles found to display.");
5433 }
5434 }
5435
5436 if (!$offset) print "<div class='whiteBox'>$message</div>";
5437 }
5438
5439 if (!$offset) {
5440 print "</div>";
5441 print "</div>";
5442 }
5443
5444 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5445 }
5446
5447 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5448
5449 function printTagCloud($link) {
5450
5451 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5452 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5453 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5454
5455 $result = db_query($link, $query);
5456
5457 $tags = array();
5458
5459 while ($line = db_fetch_assoc($result)) {
5460 $tags[$line["tag_name"]] = $line["count"];
5461 }
5462
5463 ksort($tags);
5464
5465 $max_size = 32; // max font size in pixels
5466 $min_size = 11; // min font size in pixels
5467
5468 // largest and smallest array values
5469 $max_qty = max(array_values($tags));
5470 $min_qty = min(array_values($tags));
5471
5472 // find the range of values
5473 $spread = $max_qty - $min_qty;
5474 if ($spread == 0) { // we don't want to divide by zero
5475 $spread = 1;
5476 }
5477
5478 // set the font-size increment
5479 $step = ($max_size - $min_size) / ($spread);
5480
5481 // loop through the tag array
5482 foreach ($tags as $key => $value) {
5483 // calculate font-size
5484 // find the $value in excess of $min_qty
5485 // multiply by the font-size increment ($size)
5486 // and add the $min_size set above
5487 $size = round($min_size + (($value - $min_qty) * $step));
5488
5489 $key_escaped = str_replace("'", "\\'", $key);
5490
5491 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5492 $size . "px\" title=\"$value articles tagged with " .
5493 $key . '">' . $key . '</a> ';
5494 }
5495 }
5496
5497 function print_checkpoint($n, $s) {
5498 $ts = getmicrotime();
5499 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5500 return $ts;
5501 }
5502
5503 function sanitize_tag($tag) {
5504 $tag = trim($tag);
5505
5506 $tag = mb_strtolower($tag, 'utf-8');
5507
5508 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5509
5510 // $tag = str_replace('"', "", $tag);
5511 // $tag = str_replace("+", " ", $tag);
5512 $tag = str_replace("technorati tag: ", "", $tag);
5513
5514 return $tag;
5515 }
5516
5517 function generate_publish_key() {
5518 return sha1(uniqid(rand(), true));
5519 }
5520
5521 function article_publish_url($link) {
5522
5523 $url_path = "";
5524
5525
5526 if ($_SERVER['HTTPS'] != "on") {
5527 $url_path = "http://";
5528 } else {
5529 $url_path = "https://";
5530 }
5531
5532 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5533 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5534
5535 return $url_path;
5536 }
5537
5538 /**
5539 * Purge a feed contents, marked articles excepted.
5540 *
5541 * @param mixed $link The database connection.
5542 * @param integer $id The id of the feed to purge.
5543 * @return void
5544 */
5545 function clear_feed_articles($link, $id) {
5546 $result = db_query($link, "DELETE FROM ttrss_user_entries
5547 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5548
5549 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5550 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5551
5552 ccache_update($link, $id, $_SESSION['uid']);
5553 } // function clear_feed_articles
5554
5555 /**
5556 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5557 *
5558 * @return string The Mozilla Firefox feed adding URL.
5559 */
5560 function add_feed_url() {
5561 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5562 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5563 return $url_path;
5564 } // function add_feed_url
5565
5566 /**
5567 * Encrypt a password in SHA1.
5568 *
5569 * @param string $pass The password to encrypt.
5570 * @param string $login A optionnal login.
5571 * @return string The encrypted password.
5572 */
5573 function encrypt_password($pass, $login = '') {
5574 if ($login) {
5575 return "SHA1X:" . sha1("$login:$pass");
5576 } else {
5577 return "SHA1:" . sha1($pass);
5578 }
5579 } // function encrypt_password
5580
5581 /**
5582 * Update a feed batch.
5583 * Used by daemons to update n feeds by run.
5584 * Only update feed needing a update, and not being processed
5585 * by another process.
5586 *
5587 * @param mixed $link Database link
5588 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5589 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5590 * @param boolean $debug Set to false to disable debug output. Default to true.
5591 * @return void
5592 */
5593 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5594 // Process all other feeds using last_updated and interval parameters
5595
5596 // Test if the user has loggued in recently. If not, it does not update its feeds.
5597 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5598 if (DB_TYPE == "pgsql") {
5599 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5600 } else {
5601 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5602 }
5603 } else {
5604 $login_thresh_qpart = "";
5605 }
5606
5607 // Test if the feed need a update (update interval exceded).
5608 if (DB_TYPE == "pgsql") {
5609 $update_limit_qpart = "AND ((
5610 ttrss_feeds.update_interval = 0
5611 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5612 ) OR (
5613 ttrss_feeds.update_interval > 0
5614 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5615 ) OR ttrss_feeds.last_updated IS NULL)";
5616 } else {
5617 $update_limit_qpart = "AND ((
5618 ttrss_feeds.update_interval = 0
5619 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5620 ) OR (
5621 ttrss_feeds.update_interval > 0
5622 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5623 ) OR ttrss_feeds.last_updated IS NULL)";
5624 }
5625
5626 // Test if feed is currently being updated by another process.
5627 if (DB_TYPE == "pgsql") {
5628 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5629 } else {
5630 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5631 }
5632
5633 // Test if there is a limit to number of updated feeds
5634 $query_limit = "";
5635 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5636
5637 $random_qpart = sql_random_function();
5638
5639 // We search for feed needing update.
5640 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5641 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5642 ttrss_feeds.update_interval
5643 FROM
5644 ttrss_feeds, ttrss_users, ttrss_user_prefs
5645 WHERE
5646 ttrss_feeds.owner_uid = ttrss_users.id
5647 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5648 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5649 $login_thresh_qpart $update_limit_qpart
5650 $updstart_thresh_qpart
5651 ORDER BY $random_qpart $query_limit");
5652
5653 $user_prefs_cache = array();
5654
5655 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5656
5657 // Here is a little cache magic in order to minimize risk of double feed updates.
5658 $feeds_to_update = array();
5659 while ($line = db_fetch_assoc($result)) {
5660 $feeds_to_update[$line['id']] = $line;
5661 }
5662
5663 // We update the feed last update started date before anything else.
5664 // There is no lag due to feed contents downloads
5665 // It prevent an other process to update the same feed.
5666 $feed_ids = array_keys($feeds_to_update);
5667 if($feed_ids) {
5668 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5669 WHERE id IN (%s)", implode(',', $feed_ids)));
5670 }
5671
5672 // For each feed, we call the feed update function.
5673 while ($line = array_pop($feeds_to_update)) {
5674
5675 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5676
5677 // We setup a alarm to alert if the feed take more than 300s to update.
5678 // => HANG alarm.
5679 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5680 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5681 // Cancel the alarm (the update went well)
5682 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5683
5684 sleep(1); // prevent flood (FIXME make this an option?)
5685 }
5686
5687 // Send feed digests by email if needed.
5688 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5689
5690 purge_orphans($link);
5691
5692 } // function update_daemon_common
5693
5694 function sanitize_article_content($text) {
5695 # we don't support CDATA sections in articles, they break our own escaping
5696 $text = preg_replace("/\[\[CDATA/", "", $text);
5697 $text = preg_replace("/\]\]\>/", "", $text);
5698 return $text;
5699 }
5700
5701 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5702 $filters = array();
5703
5704 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5705
5706 $result = db_query($link, "SELECT reg_exp,
5707 ttrss_filter_types.name AS name,
5708 ttrss_filter_actions.name AS action,
5709 inverse,
5710 action_param,
5711 filter_param
5712 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5713 enabled = true AND
5714 $ftype_query_part
5715 owner_uid = $owner_uid AND
5716 ttrss_filter_types.id = filter_type AND
5717 ttrss_filter_actions.id = action_id AND
5718 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5719
5720 while ($line = db_fetch_assoc($result)) {
5721 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5722 $filter["reg_exp"] = $line["reg_exp"];
5723 $filter["action"] = $line["action"];
5724 $filter["action_param"] = $line["action_param"];
5725 $filter["filter_param"] = $line["filter_param"];
5726 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5727
5728 array_push($filters[$line["name"]], $filter);
5729 }
5730
5731 return $filters;
5732 }
5733
5734 function get_score_pic($score) {
5735 if ($score > 100) {
5736 return "score_high.png";
5737 } else if ($score > 0) {
5738 return "score_half_high.png";
5739 } else if ($score < -100) {
5740 return "score_low.png";
5741 } else if ($score < 0) {
5742 return "score_half_low.png";
5743 } else {
5744 return "score_neutral.png";
5745 }
5746 }
5747
5748 function rounded_table_start($classname, $header = "&nbsp;") {
5749 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5750 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5751 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5752 }
5753
5754 function rounded_table_end($footer = "&nbsp;") {
5755 print "</td><td class='right'>&nbsp;</td></tr>";
5756 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5757 print "</table>";
5758 }
5759
5760 function feed_has_icon($id) {
5761 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5762 }
5763
5764 function init_connection($link) {
5765 if (DB_TYPE == "pgsql") {
5766 pg_query($link, "set client_encoding = 'UTF-8'");
5767 pg_set_client_encoding("UNICODE");
5768 pg_query($link, "set datestyle = 'ISO, european'");
5769 } else {
5770 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5771 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5772 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5773 }
5774 }
5775 }
5776
5777 function update_feedbrowser_cache($link) {
5778
5779 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5780 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5781 WHERE tf.feed_url = ttrss_feeds.feed_url
5782 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5783 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5784
5785 db_query($link, "BEGIN");
5786
5787 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5788
5789 $count = 0;
5790
5791 while ($line = db_fetch_assoc($result)) {
5792 $subscribers = db_escape_string($line["subscribers"]);
5793 $feed_url = db_escape_string($line["feed_url"]);
5794 $title = db_escape_string($line["title"]);
5795
5796 $tmp_result = db_query($link, "SELECT subscribers FROM
5797 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5798
5799 if (db_num_rows($tmp_result) == 0) {
5800
5801 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5802 (feed_url, title, subscribers) VALUES ('$feed_url',
5803 '$title', '$subscribers')");
5804
5805 ++$count;
5806
5807 }
5808
5809 }
5810
5811 db_query($link, "COMMIT");
5812
5813 return $count;
5814
5815 }
5816
5817 function ccache_zero($link, $feed_id, $owner_uid) {
5818 db_query($link, "UPDATE ttrss_counters_cache SET
5819 value = 0, updated = NOW() WHERE
5820 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5821 }
5822
5823 function ccache_zero_all($link, $owner_uid) {
5824 db_query($link, "UPDATE ttrss_counters_cache SET
5825 value = 0 WHERE owner_uid = '$owner_uid'");
5826
5827 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5828 value = 0 WHERE owner_uid = '$owner_uid'");
5829 }
5830
5831 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5832
5833 if (!$is_cat) {
5834 $table = "ttrss_counters_cache";
5835 } else {
5836 $table = "ttrss_cat_counters_cache";
5837 }
5838
5839 db_query($link, "DELETE FROM $table WHERE
5840 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5841
5842 }
5843
5844 function ccache_update_all($link, $owner_uid) {
5845
5846 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5847
5848 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5849 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5850
5851 while ($line = db_fetch_assoc($result)) {
5852 ccache_update($link, $line["feed_id"], $owner_uid, true);
5853 }
5854
5855 /* We have to manually include category 0 */
5856
5857 ccache_update($link, 0, $owner_uid, true);
5858
5859 } else {
5860 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5861 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5862
5863 while ($line = db_fetch_assoc($result)) {
5864 print ccache_update($link, $line["feed_id"], $owner_uid);
5865
5866 }
5867
5868 }
5869 }
5870
5871 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5872 $no_update = false) {
5873
5874 if (!is_numeric($feed_id)) return;
5875
5876 if (!$is_cat) {
5877 $table = "ttrss_counters_cache";
5878 if ($feed_id > 0) {
5879 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5880 WHERE id = '$feed_id'");
5881 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5882 }
5883 } else {
5884 $table = "ttrss_cat_counters_cache";
5885 }
5886
5887 if (DB_TYPE == "pgsql") {
5888 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5889 } else if (DB_TYPE == "mysql") {
5890 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5891 }
5892
5893 $result = db_query($link, "SELECT value FROM $table
5894 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5895 LIMIT 1");
5896
5897 if (db_num_rows($result) == 1) {
5898 return db_fetch_result($result, 0, "value");
5899 } else {
5900 if ($no_update) {
5901 return -1;
5902 } else {
5903 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5904 }
5905 }
5906
5907 }
5908
5909 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5910 $update_pcat = true) {
5911
5912 if (!is_numeric($feed_id)) return;
5913
5914 if (!$is_cat && $feed_id > 0) {
5915 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5916 WHERE id = '$feed_id'");
5917 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5918 }
5919
5920 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5921
5922 /* When updating a label, all we need to do is recalculate feed counters
5923 * because labels are not cached */
5924
5925 if ($feed_id < 0) {
5926 ccache_update_all($link, $owner_uid);
5927 return;
5928 }
5929
5930 if (!$is_cat) {
5931 $table = "ttrss_counters_cache";
5932 } else {
5933 $table = "ttrss_cat_counters_cache";
5934 }
5935
5936 if ($is_cat && $feed_id >= 0) {
5937 if ($feed_id != 0) {
5938 $cat_qpart = "cat_id = '$feed_id'";
5939 } else {
5940 $cat_qpart = "cat_id IS NULL";
5941 }
5942
5943 /* Recalculate counters for child feeds */
5944
5945 $result = db_query($link, "SELECT id FROM ttrss_feeds
5946 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5947
5948 while ($line = db_fetch_assoc($result)) {
5949 ccache_update($link, $line["id"], $owner_uid, false, false);
5950 }
5951
5952 $result = db_query($link, "SELECT SUM(value) AS sv
5953 FROM ttrss_counters_cache, ttrss_feeds
5954 WHERE id = feed_id AND $cat_qpart AND
5955 ttrss_feeds.owner_uid = '$owner_uid'");
5956
5957 $unread = (int) db_fetch_result($result, 0, "sv");
5958
5959 } else {
5960 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5961 }
5962
5963 db_query($link, "BEGIN");
5964
5965 $result = db_query($link, "SELECT feed_id FROM $table
5966 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5967
5968 if (db_num_rows($result) == 1) {
5969 db_query($link, "UPDATE $table SET
5970 value = '$unread', updated = NOW() WHERE
5971 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5972
5973 } else {
5974 db_query($link, "INSERT INTO $table
5975 (feed_id, value, owner_uid, updated)
5976 VALUES
5977 ($feed_id, $unread, $owner_uid, NOW())");
5978 }
5979
5980 db_query($link, "COMMIT");
5981
5982 if ($feed_id > 0 && $prev_unread != $unread) {
5983
5984 if (!$is_cat) {
5985
5986 /* Update parent category */
5987
5988 if ($update_pcat) {
5989
5990 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5991 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5992
5993 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5994
5995 ccache_update($link, $cat_id, $owner_uid, true);
5996
5997 }
5998 }
5999 } else if ($feed_id < 0) {
6000 ccache_update_all($link, $owner_uid);
6001 }
6002
6003 return $unread;
6004 }
6005
6006 function label_find_id($link, $label, $owner_uid) {
6007 $result = db_query($link,
6008 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6009 AND owner_uid = '$owner_uid' LIMIT 1");
6010
6011 if (db_num_rows($result) == 1) {
6012 return db_fetch_result($result, 0, "id");
6013 } else {
6014 return 0;
6015 }
6016 }
6017
6018 function get_article_labels($link, $id) {
6019 $result = db_query($link,
6020 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6021 FROM ttrss_labels2, ttrss_user_labels2
6022 WHERE id = label_id
6023 AND article_id = '$id'
6024 AND owner_uid = ".$_SESSION["uid"] . "
6025 ORDER BY caption");
6026
6027 $rv = array();
6028
6029 while ($line = db_fetch_assoc($result)) {
6030 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6031 $line["bg_color"]);
6032 array_push($rv, $rk);
6033 }
6034
6035 return $rv;
6036 }
6037
6038
6039 function label_find_caption($link, $label, $owner_uid) {
6040 $result = db_query($link,
6041 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6042 AND owner_uid = '$owner_uid' LIMIT 1");
6043
6044 if (db_num_rows($result) == 1) {
6045 return db_fetch_result($result, 0, "caption");
6046 } else {
6047 return "";
6048 }
6049 }
6050
6051 function label_remove_article($link, $id, $label, $owner_uid) {
6052
6053 $label_id = label_find_id($link, $label, $owner_uid);
6054
6055 if (!$label_id) return;
6056
6057 $result = db_query($link,
6058 "DELETE FROM ttrss_user_labels2
6059 WHERE
6060 label_id = '$label_id' AND
6061 article_id = '$id'");
6062 }
6063
6064 function label_add_article($link, $id, $label, $owner_uid) {
6065
6066 $label_id = label_find_id($link, $label, $owner_uid);
6067
6068 if (!$label_id) return;
6069
6070 $result = db_query($link,
6071 "SELECT
6072 article_id FROM ttrss_labels2, ttrss_user_labels2
6073 WHERE
6074 label_id = id AND
6075 label_id = '$label_id' AND
6076 article_id = '$id' AND owner_uid = '$owner_uid'
6077 LIMIT 1");
6078
6079 if (db_num_rows($result) == 0) {
6080 db_query($link, "INSERT INTO ttrss_user_labels2
6081 (label_id, article_id) VALUES ('$label_id', '$id')");
6082 }
6083 }
6084
6085 function label_remove($link, $id, $owner_uid) {
6086
6087 db_query($link, "BEGIN");
6088
6089 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6090 WHERE id = '$id'");
6091
6092 $caption = db_fetch_result($result, 0, "caption");
6093
6094 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6095 AND owner_uid = " . $_SESSION["uid"]);
6096
6097 if (db_affected_rows($link, $result) != 0 && $caption) {
6098
6099 /* Disable filters that reference label being removed */
6100
6101 db_query($link, "UPDATE ttrss_filters SET
6102 enabled = false WHERE action_param = '$caption'
6103 AND action_id = 7
6104 AND owner_uid = " . $_SESSION["uid"]);
6105 }
6106
6107 db_query($link, "COMMIT");
6108 }
6109
6110 function label_create($link, $caption) {
6111
6112 db_query($link, "BEGIN");
6113
6114 $result = false;
6115
6116 $result = db_query($link, "SELECT id FROM ttrss_labels2
6117 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6118
6119 if (db_num_rows($result) == 0) {
6120 $result = db_query($link,
6121 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6122 VALUES ('$caption', '".$_SESSION["uid"]."')");
6123
6124 $result = db_affected_rows($link, $result) != 0;
6125 }
6126
6127 db_query($link, "COMMIT");
6128
6129 return $result;
6130 }
6131
6132 function print_labels_headlines_dropdown($link, $feed_id) {
6133 print "<li onclick=\"javascript:addLabel()\">
6134 &nbsp;&nbsp;".__("Create label...")."</li>";
6135
6136 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6137 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6138
6139 while ($line = db_fetch_assoc($result)) {
6140
6141 $label_id = $line["id"];
6142 $label_caption = $line["caption"];
6143
6144 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6145 print "<li id=\"LHDL-$id\"
6146 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6147 &nbsp;&nbsp;$label_caption ".__('(remove)')."</li>";
6148 } else {
6149 print "<li id=\"LHDL-$id\"
6150 onclick=\"javascript:selectionAssignLabel($label_id)\">
6151 &nbsp;&nbsp;$label_caption</li>";
6152 }
6153 }
6154 }
6155
6156 function format_tags_string($tags, $id) {
6157
6158 $tags_str = "";
6159 $tags_nolinks_str = "";
6160
6161 $num_tags = 0;
6162
6163 if ($_SESSION["theme"] == "3pane") {
6164 $tag_limit = 3;
6165 } else {
6166 $tag_limit = 6;
6167 }
6168
6169 $formatted_tags = array();
6170
6171 foreach ($tags as $tag) {
6172 $num_tags++;
6173 $tag_escaped = str_replace("'", "\\'", $tag);
6174
6175 if (mb_strlen($tag) > 30) {
6176 $tag = truncate_string($tag, 30);
6177 }
6178
6179 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6180
6181 array_push($formatted_tags, $tag_str);
6182
6183 $tmp_tags_str = implode(", ", $formatted_tags);
6184
6185 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
6186 break;
6187 }
6188 }
6189
6190 $tags_str = implode(", ", $formatted_tags);
6191
6192 if ($num_tags < count($tags)) {
6193 $tags_str .= ", &hellip;";
6194 }
6195
6196 if ($num_tags == 0) {
6197 $tags_str = __("no tags");
6198 }
6199
6200 return $tags_str;
6201
6202 }
6203
6204 function format_article_labels($labels, $id) {
6205
6206 $labels_str = "";
6207
6208 foreach ($labels as $l) {
6209 $labels_str .= sprintf("<span class='hlLabelRef'
6210 style='color : %s; background-color : %s'>%s</span>",
6211 $l[2], $l[3], $l[1]);
6212 }
6213
6214 return $labels_str;
6215
6216 }
6217
6218 function format_article_note($id, $note) {
6219
6220 $note_escaped = htmlspecialchars($note, ENT_QUOTES);
6221
6222 $str = "<div class='articleNote'>";
6223 $str .= $note;
6224 $str .= "<div class='articleNoteOps'>";
6225 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6226 __('edit note')."</a>";
6227 $str .= "</div>";
6228 $str .= "</div>";
6229
6230 return $str;
6231 }
6232 ?>