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