]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
f6783ff94d16d153f37d8bde27fd3b87fa3ba280
[tt-rss.git] / functions.php
1 <?php
2
3 /*      if ($_GET["debug"]) {
4                 define('DEFAULT_ERROR_LEVEL', E_ALL);
5         } else {
6                 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
7         } */
8
9         require_once 'config.php';
10
11         if (ENABLE_TRANSLATIONS == true) { 
12                 require_once "accept-to-gettext.php";
13                 require_once "gettext/gettext.inc";
14
15                 function startup_gettext() {
16         
17                         # Get locale from Accept-Language header
18                         $lang = al2gt(array("en_US", "ru_RU"), "text/html");
19         
20                         if ($lang) {
21                                 _setlocale(LC_MESSAGES, $lang);
22                                 _bindtextdomain("messages", "locale");
23                                 _textdomain("messages");
24                                 _bind_textdomain_codeset("messages", "UTF-8");
25                         }
26                 }
27
28                 startup_gettext();
29
30         } else {
31                 function __($msg) {
32                         return $msg;
33                 }
34                 function startup_gettext() {
35                         // no-op
36                         return true;
37                 }
38         }
39
40         require_once 'db-prefs.php';
41         require_once 'compat.php';
42         require_once 'errors.php';
43         require_once 'version.php';
44
45         define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
46         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
47
48         require_once "magpierss/rss_fetch.inc";
49         require_once 'magpierss/rss_utils.inc';
50
51         include_once "tw/tw-config.php";
52         include_once "tw/tw.php";
53         include_once TW_SETUP . "paranoya.php";
54
55         $tw_parser = new twParser();
56
57         function _debug($msg) {
58                 $ts = strftime("%H:%M:%S", time());
59                 print "[$ts] $msg\n";
60         }
61
62         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
63
64                 $rows = -1;
65
66                 if (DB_TYPE == "pgsql") {
67 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
68                                 marked = false AND feed_id = '$feed_id' AND
69                                 (SELECT date_entered FROM ttrss_entries WHERE
70                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
71
72                         $pg_version = get_pgsql_version($link);
73
74                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
75
76                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
77                                         ttrss_entries.id = ref_id AND 
78                                         marked = false AND 
79                                         feed_id = '$feed_id' AND 
80                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
81
82                         } else {
83
84                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
85                                         USING ttrss_entries 
86                                         WHERE ttrss_entries.id = ref_id AND 
87                                         marked = false AND 
88                                         feed_id = '$feed_id' AND 
89                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
90                         }
91
92                         $rows = pg_affected_rows($result);
93                         
94                 } else {
95                 
96 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
97                                 marked = false AND feed_id = '$feed_id' AND
98                                 (SELECT date_entered FROM ttrss_entries WHERE 
99                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
100
101                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
102                                 USING ttrss_user_entries, ttrss_entries 
103                                 WHERE ttrss_entries.id = ref_id AND 
104                                 marked = false AND 
105                                 feed_id = '$feed_id' AND 
106                                 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
107                                         
108                         $rows = mysql_affected_rows($link);
109
110                 }
111
112                 if ($debug) {
113                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
114                 }
115         }
116
117         function global_purge_old_posts($link, $do_output = false, $limit = false) {
118
119                 $random_qpart = sql_random_function();
120
121                 if ($limit) {
122                         $limit_qpart = "LIMIT $limit";
123                 } else {
124                         $limit_qpart = "";
125                 }
126                 
127                 $result = db_query($link, 
128                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
129                                 ORDER BY $random_qpart $limit_qpart");
130
131                 while ($line = db_fetch_assoc($result)) {
132
133                         $feed_id = $line["id"];
134                         $purge_interval = $line["purge_interval"];
135                         $owner_uid = $line["owner_uid"];
136
137                         if ($purge_interval == 0) {
138                         
139                                 $tmp_result = db_query($link, 
140                                         "SELECT value FROM ttrss_user_prefs WHERE
141                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
142
143                                 if (db_num_rows($tmp_result) != 0) {                    
144                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
145                                 }
146                         }
147
148                         if ($do_output) {
149 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
150                         }
151
152                         if ($purge_interval > 0) {
153                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
154                         }
155                 }       
156
157                 // purge orphaned posts in main content table
158                 db_query($link, "DELETE FROM ttrss_entries WHERE 
159                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
160
161         }
162
163         function purge_old_posts($link) {
164
165                 $user_id = $_SESSION["uid"];
166         
167                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
168                         WHERE owner_uid = '$user_id'");
169
170                 while ($line = db_fetch_assoc($result)) {
171
172                         $feed_id = $line["id"];
173                         $purge_interval = $line["purge_interval"];
174
175                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
176
177                         if ($purge_interval > 0) {
178                                 purge_feed($link, $feed_id, $purge_interval);
179                         }
180                 }       
181
182                 // purge orphaned posts in main content table
183                 db_query($link, "DELETE FROM ttrss_entries WHERE 
184                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
185         }
186
187         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
188
189                 if (WEB_DEMO_MODE) return;
190
191                 if (!$user_id) {
192                         $user_id = $_SESSION["uid"];
193                         purge_old_posts($link);
194                 }
195
196 //              db_query($link, "BEGIN");
197
198                 if (MAX_UPDATE_TIME > 0) {
199                         if (DB_TYPE == "mysql") {
200                                 $q_order = "RAND()";
201                         } else {
202                                 $q_order = "RANDOM()";
203                         }
204                 } else {
205                         $q_order = "last_updated DESC";
206                 }
207
208                 $result = db_query($link, "SELECT feed_url,id,
209                         SUBSTRING(last_updated,1,19) AS last_updated,
210                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
211                         ORDER BY $q_order");
212
213                 $upd_start = time();
214
215                 while ($line = db_fetch_assoc($result)) {
216                         $upd_intl = $line["update_interval"];
217
218                         if (!$upd_intl || $upd_intl == 0) {
219                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
220                         }
221
222                         if ($upd_intl < 0) { 
223                                 // Updates for this feed are disabled
224                                 continue; 
225                         }
226
227                         if ($fetch || (!$line["last_updated"] || 
228                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
229
230 //                              print "<!-- feed: ".$line["feed_url"]." -->";
231
232                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
233
234                                 $upd_elapsed = time() - $upd_start;
235
236                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
237                                         return;
238                                 }
239                         }
240                 }
241
242 //              db_query($link, "COMMIT");
243
244         }
245
246         function fetch_file_contents($url) {
247                 if (USE_CURL_FOR_ICONS) {
248                         $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
249
250                         $ch = curl_init($url);
251                         $fp = fopen($tmpfile, "w");
252
253                         if ($fp) {
254                                 curl_setopt($ch, CURLOPT_FILE, $fp);
255                                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
256                                 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
257                                 curl_exec($ch);
258                                 curl_close($ch);
259                                 fclose($fp);                                    
260                         }
261
262                         $contents =  file_get_contents($tmpfile);
263                         unlink($tmpfile);
264
265                         return $contents;
266
267                 } else {
268                         return file_get_contents($url);
269                 }
270
271         }
272
273         // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
274         // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
275
276         function get_favicon_url($url) {
277
278                 if ($html = @fetch_file_contents($url)) {
279
280                         if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
281                                 // Attempt to grab a favicon link from their webpage url
282                                 $linkUrl = html_entity_decode($matches[1]);
283
284                                 if (substr($linkUrl, 0, 1) == '/') {
285                                         $urlParts = parse_url($url);
286                                         $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
287                                 } else if (substr($linkUrl, 0, 7) == 'http://') {
288                                         $faviconURL = $linkUrl;
289                                 } else if (substr($url, -1, 1) == '/') {
290                                         $faviconURL = $url.$linkUrl;
291                                 } else {
292                                         $faviconURL = $url.'/'.$linkUrl;
293                                 }
294
295                         } else {
296                                 // If unsuccessful, attempt to "guess" the favicon location
297                                 $urlParts = parse_url($url);
298                                 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
299                         }
300                 }
301
302                 // Run a test to see if what we have attempted to get actually exists.
303                 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
304                         return $faviconURL;
305                 } else {
306                         return false;
307                 }
308         }
309
310         function url_validate($link) {
311                 
312                 $url_parts = @parse_url($link);
313
314                 if ( empty( $url_parts["host"] ) )
315                                 return false;
316
317                 if ( !empty( $url_parts["path"] ) ) {
318                                 $documentpath = $url_parts["path"];
319                 } else {
320                                 $documentpath = "/";
321                 }
322
323                 if ( !empty( $url_parts["query"] ) )
324                                 $documentpath .= "?" . $url_parts["query"];
325
326                 $host = $url_parts["host"];
327                 $port = $url_parts["port"];
328                 
329                 if ( empty($port) )
330                                 $port = "80";
331
332                 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
333                 
334                 if ( !$socket )
335                                 return false;
336                                 
337                 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
338
339                 $http_response = fgets( $socket, 22 );
340
341                 $responses = "/(200 OK)|(30[0-9] Moved)/";
342                 if ( preg_match($responses, $http_response) ) {
343                                 fclose($socket);
344                                 return true;
345                 } else {
346                                 return false;
347                 }
348
349         } 
350
351         function check_feed_favicon($site_url, $feed, $link) {
352                 $favicon_url = get_favicon_url($site_url);
353
354 #               print "FAVICON [$site_url]: $favicon_url\n";
355
356                 error_reporting(0);
357
358                 $icon_file = ICONS_DIR . "/$feed.ico";
359
360                 if ($favicon_url && !file_exists($icon_file)) {
361                         $contents = fetch_file_contents($favicon_url);
362
363                         $fp = fopen($icon_file, "w");
364
365                         if ($fp) {
366                                 fwrite($fp, $contents);
367                                 fclose($fp);
368                                 chmod($icon_file, 0644);
369                         }
370                 }
371
372                 error_reporting(DEFAULT_ERROR_LEVEL);
373
374         }
375
376         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
377
378                 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
379                         return;                 
380                 }
381
382                 if (defined('DAEMON_EXTENDED_DEBUG')) {
383                         _debug("update_rss_feed: start");
384                 }
385
386                 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
387                         FROM ttrss_feeds WHERE id = '$feed'");
388
389                 $auth_login = db_unescape_string(db_fetch_result($result, 0, "auth_login"));
390                 $auth_pass = db_unescape_string(db_fetch_result($result, 0, "auth_pass"));
391
392                 $update_interval = db_fetch_result($result, 0, "update_interval");
393
394                 if ($update_interval < 0) { return; }
395
396                 $feed = db_escape_string($feed);
397
398                 $fetch_url = $feed_url;
399
400                 if ($auth_login && $auth_pass) {
401                         $url_parts = array();
402                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
403
404                         if ($url_parts[1] && $url_parts[2]) {
405                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
406                         }
407
408                 }
409
410                 if (defined('DAEMON_EXTENDED_DEBUG')) {
411                         _debug("update_rss_feed: fetching...");
412                 }
413
414                 if (!defined('DAEMON_EXTENDED_DEBUG')) {
415                         error_reporting(0);
416                 }
417
418                 $rss = fetch_rss($fetch_url);
419
420                 if (defined('DAEMON_EXTENDED_DEBUG')) {
421                         _debug("update_rss_feed: fetch done, parsing...");
422                 } else {
423                         error_reporting (DEFAULT_ERROR_LEVEL);
424                 }
425
426                 $feed = db_escape_string($feed);
427
428                 if ($rss) {
429
430                         if (defined('DAEMON_EXTENDED_DEBUG')) {
431                                 _debug("update_rss_feed: processing feed data...");
432                         }
433
434 //                      db_query($link, "BEGIN");
435
436                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
437                                 FROM ttrss_feeds WHERE id = '$feed'");
438
439                         $registered_title = db_fetch_result($result, 0, "title");
440                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
441                         $orig_site_url = db_fetch_result($result, 0, "site_url");
442
443                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
444
445                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
446                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
447                                         _debug("update_rss_feed: checking favicon...");
448                                 }
449                                 check_feed_favicon($rss->channel["link"], $feed, $link);
450                         }
451
452                         if (!$registered_title || $registered_title == "[Unknown]") {
453                         
454                                 $feed_title = db_escape_string($rss->channel["title"]);
455                                 
456                                 db_query($link, "UPDATE ttrss_feeds SET 
457                                         title = '$feed_title' WHERE id = '$feed'");
458                         }
459
460                         $site_url = $rss->channel["link"];
461                         // weird, weird Magpie
462                         if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
463
464                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
465                                 db_query($link, "UPDATE ttrss_feeds SET 
466                                         site_url = '$site_url' WHERE id = '$feed'");
467                         }
468
469 //                      print "I: " . $rss->channel["image"]["url"];
470
471                         $icon_url = $rss->image["url"];
472
473                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
474                                 $icon_url = db_escape_string($icon_url);
475                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
476                         }
477
478                         if (defined('DAEMON_EXTENDED_DEBUG')) {
479                                 _debug("update_rss_feed: loading filters...");
480                         }
481
482                         $filters = array();
483
484                         $result = db_query($link, "SELECT reg_exp,
485                                 ttrss_filter_types.name AS name,
486                                 ttrss_filter_actions.name AS action,
487                                 inverse,
488                                 action_param
489                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
490                                         enabled = true AND
491                                         owner_uid = $owner_uid AND
492                                         ttrss_filter_types.id = filter_type AND
493                                         ttrss_filter_actions.id = action_id AND
494                                 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
495
496                         while ($line = db_fetch_assoc($result)) {
497                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
498
499                                 $filter["reg_exp"] = $line["reg_exp"];
500                                 $filter["action"] = $line["action"];
501                                 $filter["action_param"] = $line["action_param"];
502                                 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
503                         
504                                 array_push($filters[$line["name"]], $filter);
505                         }
506
507                         $iterator = $rss->items;
508
509                         if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
510                         if (!$iterator || !is_array($iterator)) $iterator = $rss;
511
512                         if (!is_array($iterator)) {
513                                 /* db_query($link, "UPDATE ttrss_feeds 
514                                         SET last_error = 'Parse error: can\'t find any articles.'
515                                         WHERE id = '$feed'"); */
516
517                                 // clear any errors and mark feed as updated if fetched okay
518                                 // even if it's blank
519
520                                 db_query($link, "UPDATE ttrss_feeds 
521                                         SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
522
523                                 return; // no articles
524                         }
525
526                         if (defined('DAEMON_EXTENDED_DEBUG')) {
527                                 _debug("update_rss_feed: processing articles...");
528                         }
529
530                         foreach ($iterator as $item) {
531
532                                 $entry_guid = $item["id"];
533
534                                 if (!$entry_guid) $entry_guid = $item["guid"];
535                                 if (!$entry_guid) $entry_guid = $item["link"];
536                                 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
537
538                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
539                                         _debug("update_rss_feed: guid $entry_guid");
540                                 }
541
542                                 if (!$entry_guid) continue;
543
544                                 $entry_timestamp = "";
545
546                                 $rss_2_date = $item['pubdate'];
547                                 $rss_1_date = $item['dc']['date'];
548                                 $atom_date = $item['issued'];
549                                 if (!$atom_date) $atom_date = $item['updated'];
550                         
551                                 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
552                                 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
553                                 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
554                                 
555                                 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
556                                         $entry_timestamp = time();
557                                         $no_orig_date = 'true';
558                                 } else {
559                                         $no_orig_date = 'false';
560                                 }
561
562                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
563
564                                 $entry_title = trim(strip_tags($item["title"]));
565
566                                 // strange Magpie workaround
567                                 $entry_link = $item["link_"];
568                                 if (!$entry_link) $entry_link = $item["link"];
569
570                                 if (!$entry_title) continue;
571 #                                       if (!$entry_link) continue;
572
573                                 $entry_link = strip_tags($entry_link);
574
575                                 $entry_content = $item["content:escaped"];
576
577                                 if (!$entry_content) $entry_content = $item["content:encoded"];
578                                 if (!$entry_content) $entry_content = $item["content"];
579                                 if (!$entry_content) $entry_content = $item["atom_content"];
580                                 if (!$entry_content) $entry_content = $item["summary"];
581                                 if (!$entry_content) $entry_content = $item["description"];
582
583 //                              if (!$entry_content) continue;
584
585                                 // WTF
586                                 if (is_array($entry_content)) {
587                                         $entry_content = $entry_content["encoded"];
588                                         if (!$entry_content) $entry_content = $entry_content["escaped"];
589                                 }
590
591 //                              print_r($item);
592 //                              print_r(htmlspecialchars($entry_content));
593 //                              print "<br>";
594
595                                 $entry_content_unescaped = $entry_content;
596
597                                 $entry_comments = strip_tags($item["comments"]);
598
599                                 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
600
601                                 if ($item['author']) {
602
603                                         if (is_array($item['author'])) {
604
605                                                 if (!$entry_author) {
606                                                         $entry_author = db_escape_string(strip_tags($item['author']['name']));
607                                                 }
608
609                                                 if (!$entry_author) {
610                                                         $entry_author = db_escape_string(strip_tags($item['author']['email']));
611                                                 }
612                                         }
613
614                                         if (!$entry_author) {
615                                                 $entry_author = db_escape_string(strip_tags($item['author']));
616                                         }
617                                 }
618
619                                 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
620
621                                 $entry_guid = db_escape_string(strip_tags($entry_guid));
622
623                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
624                                         WHERE guid = '$entry_guid'");
625
626                                 $entry_content = db_escape_string($entry_content);
627
628                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
629
630                                 $entry_title = db_escape_string($entry_title);
631                                 $entry_link = db_escape_string($entry_link);
632                                 $entry_comments = db_escape_string($entry_comments);
633
634                                 $num_comments = db_escape_string($item["slash"]["comments"]);
635
636                                 if (!$num_comments) $num_comments = 0;
637
638                                 // parse <category> entries into tags
639
640                                 $t_ctr = $item['category#'];
641
642                                 $additional_tags = false;
643
644                                 if ($t_ctr == 0) {
645                                         $additional_tags = false;
646                                 } else if ($t_ctr == 1) {
647                                         $additional_tags = array($item['category']);
648                                 } else {
649                                         $additional_tags = array();
650                                         for ($i = 0; $i <= $t_ctr; $i++ ) {
651                                                 if ($item["category#$i"]) {
652                                                         array_push($additional_tags, $item["category#$i"]);
653                                                 }
654                                         }
655                                 }
656
657                                 // parse <dc:subject> elements
658
659                                 $t_ctr = $item['dc']['subject#'];
660
661                                 if ($t_ctr == 1) {
662                                         $additional_tags = array($item['dc']['subject']);
663                                 } else if ($t_ctr > 1) {
664                                         $additional_tags = array();
665                                         for ($i = 0; $i <= $t_ctr; $i++ ) {
666                                                 if ($item['dc']["subject#$i"]) {
667                                                         array_push($additional_tags, $item['dc']["subject#$i"]);
668                                                 }
669                                         }
670                                 }
671
672                                 # sanitize content
673                                 
674 //                              $entry_content = sanitize_rss($entry_content);
675
676                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
677                                         _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
678                                 }
679
680                                 db_query($link, "BEGIN");
681
682                                 if (db_num_rows($result) == 0) {
683
684                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
685                                                 _debug("update_rss_feed: base guid not found");
686                                         }
687
688                                         // base post entry does not exist, create it
689
690                                         $result = db_query($link,
691                                                 "INSERT INTO ttrss_entries 
692                                                         (title,
693                                                         guid,
694                                                         link,
695                                                         updated,
696                                                         content,
697                                                         content_hash,
698                                                         no_orig_date,
699                                                         date_entered,
700                                                         comments,
701                                                         num_comments,
702                                                         author)
703                                                 VALUES
704                                                         ('$entry_title', 
705                                                         '$entry_guid', 
706                                                         '$entry_link',
707                                                         '$entry_timestamp_fmt', 
708                                                         '$entry_content', 
709                                                         '$content_hash',
710                                                         $no_orig_date, 
711                                                         NOW(), 
712                                                         '$entry_comments',
713                                                         '$num_comments',
714                                                         '$entry_author')");
715                                 } else {
716                                         // we keep encountering the entry in feeds, so we need to
717                                         // update date_entered column so that we don't get horrible
718                                         // dupes when the entry gets purged and reinserted again e.g.
719                                         // in the case of SLOW SLOW OMG SLOW updating feeds
720
721                                         $base_entry_id = db_fetch_result($result, 0, "id");
722
723                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
724                                                 WHERE id = '$base_entry_id'");
725                                 }
726
727                                 // now it should exist, if not - bad luck then
728
729                                 $result = db_query($link, "SELECT 
730                                                 id,content_hash,no_orig_date,title,
731                                                 substring(date_entered,1,19) as date_entered,
732                                                 substring(updated,1,19) as updated,
733                                                 num_comments
734                                         FROM 
735                                                 ttrss_entries 
736                                         WHERE guid = '$entry_guid'");
737
738                                 if (db_num_rows($result) == 1) {
739
740                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
741                                                 _debug("update_rss_feed: base guid found, checking for user record");
742                                         }
743
744                                         // this will be used below in update handler
745                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
746                                         $orig_title = db_fetch_result($result, 0, "title");
747                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
748                                         $orig_date_entered = strtotime(db_fetch_result($result, 
749                                                 0, "date_entered"));
750
751                                         $ref_id = db_fetch_result($result, 0, "id");
752
753                                         // check for user post link to main table
754
755                                         // do we allow duplicate posts with same GUID in different feeds?
756                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
757                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
758                                         } else { 
759                                                 $dupcheck_qpart = "";
760                                         }
761
762 //                                      error_reporting(0);
763
764                                         $article_filters = get_article_filters($filters, $entry_title, 
765                                                         $entry_content, $entry_link);
766
767                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
768                                                 _debug("update_rss_feed: article filters: ");
769                                                 if (count($article_filters) != 0) {
770                                                         print_r($article_filters);
771                                                 }
772                                         }
773
774                                         if (find_article_filter($article_filters, "filter")) {
775                                                 continue;
776                                         }
777
778 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
779
780                                         $result = db_query($link,
781                                                 "SELECT ref_id FROM ttrss_user_entries WHERE
782                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
783                                                         $dupcheck_qpart");
784
785                                         // okay it doesn't exist - create user entry
786                                         if (db_num_rows($result) == 0) {
787
788                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
789                                                         _debug("update_rss_feed: user record not found, creating...");
790                                                 }
791
792                                                 if (!find_article_filter($article_filters, 'catchup')) {
793                                                         $unread = 'true';
794                                                         $last_read_qpart = 'NULL';
795                                                 } else {
796                                                         $unread = 'false';
797                                                         $last_read_qpart = 'NOW()';
798                                                 }                                               
799
800                                                 if (find_article_filter($article_filters, 'mark')) {
801                                                         $marked = 'true';
802                                                 } else {
803                                                         $marked = 'false';
804                                                 }
805                                                 
806                                                 $result = db_query($link,
807                                                         "INSERT INTO ttrss_user_entries 
808                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked) 
809                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
810                                                                 $last_read_qpart, $marked)");
811                                         }
812                                         
813                                         $post_needs_update = false;
814
815                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
816                                                 ($content_hash != $orig_content_hash)) {
817 //                                              print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
818                                                 $post_needs_update = true;
819                                         }
820
821                                         if (db_escape_string($orig_title) != $entry_title) {
822                                                 $post_needs_update = true;
823                                         }
824
825                                         if ($orig_num_comments != $num_comments) {
826                                                 $post_needs_update = true;
827                                         }
828
829 //                                      this doesn't seem to be very reliable
830 //
831 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
832 //                                              $post_needs_update = true;
833 //                                      }
834
835                                         // if post needs update, update it and mark all user entries 
836                                         // linking to this post as updated                                      
837                                         if ($post_needs_update) {
838
839                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
840                                                         _debug("update_rss_feed: post $entry_guid needs update...");
841                                                 }
842
843 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
844
845                                                 db_query($link, "UPDATE ttrss_entries 
846                                                         SET title = '$entry_title', content = '$entry_content',
847                                                                 content_hash = '$content_hash',
848                                                                 num_comments = '$num_comments'
849                                                         WHERE id = '$ref_id'");
850
851                                                 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
852                                                         db_query($link, "UPDATE ttrss_user_entries 
853                                                                 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
854                                                 } else {
855                                                         db_query($link, "UPDATE ttrss_user_entries 
856                                                                 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
857                                                 }
858
859                                         }
860                                 }
861
862                                 db_query($link, "COMMIT");
863
864                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
865                                         _debug("update_rss_feed: looking for tags...");
866                                 }
867
868                                 /* taaaags */
869                                 // <a href="..." rel="tag">Xorg</a>, //
870
871                                 $entry_tags = null;
872
873                                 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i", 
874                                         $entry_content_unescaped, $entry_tags);
875
876 /*                              print "<p><br/>$entry_title : $entry_content_unescaped<br>";
877                                 print_r($entry_tags);
878                                 print "<br/></p>"; */
879
880                                 $entry_tags = $entry_tags[1];
881
882                                 # check for manual tags
883
884                                 $tag_filter = find_article_filter($article_filters, "tag"); 
885
886                                 if ($tag_filter) {
887
888                                         $manual_tags = trim_array(split(",", $tag_filter[1]));
889
890                                         foreach ($manual_tags as $tag) {
891                                                 if (tag_is_valid($tag)) {
892                                                         array_push($entry_tags, $tag);
893                                                 }
894                                         }
895                                 }
896
897                                 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link, 
898                                         'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
899
900                                 if ($additional_tags && is_array($additional_tags)) {
901                                         foreach ($additional_tags as $tag) {
902                                                 if (tag_is_valid($tag) && 
903                                                                 array_search($tag, $boring_tags) === FALSE) {
904                                                         array_push($entry_tags, $tag);
905                                                 }
906                                         }
907                                 } 
908
909 //                              print "<p>TAGS: "; print_r($entry_tags); print "</p>";
910
911                                 if (count($entry_tags) > 0) {
912                                 
913                                         db_query($link, "BEGIN");
914                         
915                                         $result = db_query($link, "SELECT id,int_id 
916                                                 FROM ttrss_entries,ttrss_user_entries 
917                                                 WHERE guid = '$entry_guid' 
918                                                 AND feed_id = '$feed' AND ref_id = id
919                                                 AND owner_uid = '$owner_uid'");
920
921                                         if (db_num_rows($result) == 1) {
922
923                                                 $entry_id = db_fetch_result($result, 0, "id");
924                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
925                                                 
926                                                 foreach ($entry_tags as $tag) {
927
928                                                         $tag = sanitize_tag($tag);
929                                                         $tag = db_escape_string($tag);
930
931                                                         if (!tag_is_valid($tag)) continue;
932                                                         
933                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
934                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
935                                                                 owner_uid = '$owner_uid' LIMIT 1");
936         
937         //                                              print db_fetch_result($result, 0, "id");
938         
939                                                         if ($result && db_num_rows($result) == 0) {
940                                                                 
941                                                                 db_query($link, "INSERT INTO ttrss_tags 
942                                                                         (owner_uid,tag_name,post_int_id)
943                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
944                                                         }                                                       
945                                                 }
946                                         }
947                                         db_query($link, "COMMIT");
948                                 } 
949                         } 
950
951                         db_query($link, "UPDATE ttrss_feeds 
952                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
953
954 //                      db_query($link, "COMMIT");
955
956                 } else {
957                         $error_msg = db_escape_string(magpie_error());
958                         db_query($link, 
959                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
960                                         last_updated = NOW() WHERE id = '$feed'");
961                 }
962
963                 if (defined('DAEMON_EXTENDED_DEBUG')) {
964                         _debug("update_rss_feed: done");
965                 }
966
967         }
968
969         function print_select($id, $default, $values, $attributes = "") {
970                 print "<select name=\"$id\" id=\"$id\" $attributes>";
971                 foreach ($values as $v) {
972                         if ($v == $default)
973                                 $sel = " selected";
974                          else
975                                 $sel = "";
976                         
977                         print "<option$sel>$v</option>";
978                 }
979                 print "</select>";
980         }
981
982         function print_select_hash($id, $default, $values, $attributes = "") {
983                 print "<select name=\"$id\" id='$id' $attributes>";
984                 foreach (array_keys($values) as $v) {
985                         if ($v == $default)
986                                 $sel = "selected";
987                          else
988                                 $sel = "";
989                         
990                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
991                 }
992
993                 print "</select>";
994         }
995
996         function get_article_filters($filters, $title, $content, $link) {
997                 $matches = array();
998
999                 if ($filters["title"]) {
1000                         foreach ($filters["title"] as $filter) {
1001                                 $reg_exp = $filter["reg_exp"];          
1002                                 $inverse = $filter["inverse"];  
1003                                 if ((!$inverse && preg_match("/$reg_exp/i", $title)) || 
1004                                                 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1005
1006                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1007                                 }
1008                         }
1009                 }
1010
1011                 if ($filters["content"]) {
1012                         foreach ($filters["content"] as $filter) {
1013                                 $reg_exp = $filter["reg_exp"];
1014                                 $inverse = $filter["inverse"];
1015
1016                                 if ((!$inverse && preg_match("/$reg_exp/i", $content)) || 
1017                                                 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1018
1019                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1020                                 }               
1021                         }
1022                 }
1023
1024                 if ($filters["both"]) {
1025                         foreach ($filters["both"] as $filter) {                 
1026                                 $reg_exp = $filter["reg_exp"];          
1027                                 $inverse = $filter["inverse"];
1028
1029                                 if ($inverse) {
1030                                         if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
1031                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1032                                         }
1033                                 } else {
1034                                         if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1035                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1036                                         }
1037                                 }
1038                         }
1039                 }
1040
1041                 if ($filters["link"]) {
1042                         $reg_exp = $filter["reg_exp"];
1043                         foreach ($filters["link"] as $filter) {
1044                                 $reg_exp = $filter["reg_exp"];
1045                                 $inverse = $filter["inverse"];
1046
1047                                 if ((!$inverse && preg_match("/$reg_exp/i", $link)) || 
1048                                                 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1049                                                 
1050                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1051                                 }
1052                         }
1053                 }
1054
1055                 return $matches;
1056         }
1057
1058         function find_article_filter($filters, $filter_name) {
1059                 foreach ($filters as $f) {
1060                         if ($f[0] == $filter_name) {
1061                                 return $f;
1062                         };
1063                 }
1064                 return false;
1065         }
1066
1067         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1068                 $rtl_content = false, $last_updated = false, $last_error = false) {
1069
1070                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1071                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1072                 } else {
1073                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1074                 }
1075
1076                 if ($rtl_content) {
1077                         $rtl_tag = "dir=\"rtl\"";
1078                 } else {
1079                         $rtl_tag = "dir=\"ltr\"";
1080                 }
1081
1082                 $error_notify_msg = "";
1083                 
1084                 if ($last_error) {
1085                         $link_title = "Error: $last_error ($last_updated)";
1086                         $error_notify_msg = "(Error)";
1087                 } else if ($last_updated) {
1088                         $link_title = "Updated: $last_updated";
1089                 }
1090
1091                 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" 
1092                         href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1093
1094                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1095                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1096                         print "$feed_icon";
1097                 }
1098
1099                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1100
1101                 if ($unread != 0) {
1102                         $fctr_class = "";
1103                 } else {
1104                         $fctr_class = "class=\"invisible\"";
1105                 }
1106
1107                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1108                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1109
1110                 if (get_pref($link, "EXTENDED_FEEDLIST")) {                      
1111                         print "<div class=\"feedExtInfo\">
1112                                 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1113                 }
1114                          
1115                 print "</li>";
1116
1117         }
1118
1119         function getmicrotime() {
1120                 list($usec, $sec) = explode(" ",microtime());
1121                 return ((float)$usec + (float)$sec);
1122         }
1123
1124         function print_radio($id, $default, $values, $attributes = "") {
1125                 foreach ($values as $v) {
1126                 
1127                         if ($v == $default)
1128                                 $sel = "checked";
1129                          else
1130                                 $sel = "";
1131
1132                         if ($v == "Yes") {
1133                                 $sel .= " value=\"1\"";
1134                         } else {
1135                                 $sel .= " value=\"0\"";
1136                         }
1137                         
1138                         print "<input class=\"noborder\" 
1139                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1140
1141                 }
1142         }
1143
1144         function initialize_user_prefs($link, $uid) {
1145
1146                 $uid = db_escape_string($uid);
1147
1148                 db_query($link, "BEGIN");
1149
1150                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1151                 
1152                 $u_result = db_query($link, "SELECT pref_name 
1153                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1154
1155                 $active_prefs = array();
1156
1157                 while ($line = db_fetch_assoc($u_result)) {
1158                         array_push($active_prefs, $line["pref_name"]);                  
1159                 }
1160
1161                 while ($line = db_fetch_assoc($result)) {
1162                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1163 //                              print "adding " . $line["pref_name"] . "<br>";
1164
1165                                 db_query($link, "INSERT INTO ttrss_user_prefs
1166                                         (owner_uid,pref_name,value) VALUES 
1167                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1168
1169                         }
1170                 }
1171
1172                 db_query($link, "COMMIT");
1173
1174         }
1175
1176         function lookup_user_id($link, $user) {
1177
1178                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
1179                         login = '$login'");
1180
1181                 if (db_num_rows($result) == 1) {
1182                         return db_fetch_result($result, 0, "id");
1183                 } else {
1184                         return false;
1185                 }
1186         }
1187
1188         function http_authenticate_user($link) {
1189
1190                 if (!$_SERVER["PHP_AUTH_USER"]) {
1191
1192                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1193                         header('HTTP/1.0 401 Unauthorized');
1194                         exit;
1195                                         
1196                 } else {
1197                         $auth_result = authenticate_user($link, 
1198                                 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1199
1200                         if (!$auth_result) {
1201                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1202                                 header('HTTP/1.0 401 Unauthorized');
1203                                 exit;
1204                         }
1205                 }
1206
1207                 return true;
1208         }
1209
1210         function authenticate_user($link, $login, $password, $force_auth = false) {
1211
1212                 if (!SINGLE_USER_MODE) {
1213
1214                         $pwd_hash = 'SHA1:' . sha1($password);
1215
1216                         if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1217                                 $query = "SELECT id,login,access_level
1218                     FROM ttrss_users WHERE
1219                          login = '$login'";
1220                         } else {
1221                                 $query = "SELECT id,login,access_level
1222                     FROM ttrss_users WHERE
1223                          login = '$login' AND pwd_hash = '$pwd_hash'";
1224                         }
1225
1226                         $result = db_query($link, $query);
1227         
1228                         if (db_num_rows($result) == 1) {
1229                                 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1230                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1231                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1232         
1233                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1234                                         $_SESSION["uid"]);
1235         
1236                                 $user_theme = get_user_theme_path($link);
1237         
1238                                 $_SESSION["theme"] = $user_theme;
1239                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1240         
1241                                 initialize_user_prefs($link, $_SESSION["uid"]);
1242         
1243                                 return true;
1244                         }
1245         
1246                         return false;
1247
1248                 } else {
1249
1250                         $_SESSION["uid"] = 1;
1251                         $_SESSION["name"] = "admin";
1252
1253                         $user_theme = get_user_theme_path($link);
1254         
1255                         $_SESSION["theme"] = $user_theme;
1256                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1257         
1258                         initialize_user_prefs($link, $_SESSION["uid"]);
1259         
1260                         return true;
1261                 }
1262         }
1263
1264         function make_password($length = 8) {
1265
1266                 $password = "";
1267                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
1268                 
1269         $i = 0; 
1270     
1271                 while ($i < $length) { 
1272                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1273         
1274                         if (!strstr($password, $char)) { 
1275                                 $password .= $char;
1276                                 $i++;
1277                         }
1278                 }
1279                 return $password;
1280         }
1281
1282         // this is called after user is created to initialize default feeds, labels
1283         // or whatever else
1284         
1285         // user preferences are checked on every login, not here
1286
1287         function initialize_user($link, $uid) {
1288
1289                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1290                         values ('$uid','unread = true', 'Unread articles')");
1291
1292                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1293                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
1294                 
1295                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1296                         values ('$uid', 'Tiny Tiny RSS: New Releases',
1297                         'http://tt-rss.spb.ru/releases.rss')");
1298
1299                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1300                         values ('$uid', 'Tiny Tiny RSS: Forum',
1301                         'http://tt-rss.spb.ru/forum/rss.php')");
1302         }
1303
1304         function logout_user() {
1305                 session_destroy();
1306                 if (isset($_COOKIE[session_name()])) {
1307                    setcookie(session_name(), '', time()-42000, '/');
1308                 }
1309         }
1310
1311         function get_script_urlpath() {
1312                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1313         }
1314
1315         function validate_session($link) {
1316                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1317                         if ($_SESSION["ip_address"]) {
1318                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1319                                         $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1320                                         return false;
1321                                 }
1322                         }
1323                 }
1324
1325 /*              if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1326
1327                         //print_r($_SESSION);
1328
1329                         if (time() > $_SESSION["cookie_lifetime"]) {
1330                                 return false;
1331                         }
1332                 } */
1333
1334                 return true;
1335         }
1336
1337         function login_sequence($link, $mobile = false) {
1338                 if (!SINGLE_USER_MODE) {
1339
1340                         if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1341                                 $swu = db_escape_string($_REQUEST["swu"]);
1342                                 if ($swu) {
1343                                         $_SESSION["prefs_cache"] = false;
1344                                         return authenticate_user($link, $swu, null, true);
1345                                 }
1346                         }
1347
1348                         $login_action = $_POST["login_action"];
1349
1350                         # try to authenticate user if called from login form                    
1351                         if ($login_action == "do_login") {
1352                                 $login = $_POST["login"];
1353                                 $password = $_POST["password"];
1354                                 $remember_me = $_POST["remember_me"];
1355
1356                                 if (authenticate_user($link, $login, $password)) {
1357                                         $_POST["password"] = "";
1358
1359                                         header("Location: " . $_SERVER["REQUEST_URI"]);
1360                                         exit;
1361
1362                                         return;
1363                                 } else {
1364                                         $_SESSION["login_error_msg"] = "Incorrect username or password";
1365                                 }
1366                         }
1367
1368 //                      print session_id();
1369 //                      print_r($_SESSION);
1370
1371                         if (!$_SESSION["uid"] || !validate_session($link)) {
1372                                 render_login_form($link, $mobile);
1373                                 exit;
1374                         } else {
1375                                 /* bump login timestamp */
1376                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1377                                         $_SESSION["uid"]);
1378                         }
1379
1380                 } else {
1381                         return authenticate_user($link, "admin", null);
1382                 }
1383         }
1384
1385         function truncate_string($str, $max_len) {
1386                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1387                         return mb_substr($str, 0, $max_len, "utf-8") . "...";
1388                 } else {
1389                         return $str;
1390                 }
1391         }
1392
1393         function get_user_theme_path($link) {
1394                 $result = db_query($link, "SELECT theme_path 
1395                         FROM 
1396                                 ttrss_themes,ttrss_users
1397                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1398                 if (db_num_rows($result) != 0) {
1399                         return db_fetch_result($result, 0, "theme_path");
1400                 } else {
1401                         return null;
1402                 }
1403         }
1404
1405         function smart_date_time($timestamp) {
1406                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1407                         return date("G:i", $timestamp);
1408                 } else if (date("Y", $timestamp) == date("Y")) {
1409                         return date("M d, G:i", $timestamp);
1410                 } else {
1411                         return date("Y/m/d, G:i", $timestamp);
1412                 }
1413         }
1414
1415         function smart_date($timestamp) {
1416                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1417                         return "Today";
1418                 } else if (date("Y", $timestamp) == date("Y")) {
1419                         return date("D m", $timestamp);
1420                 } else {
1421                         return date("Y/m/d", $timestamp);
1422                 }
1423         }
1424
1425         function sql_bool_to_string($s) {
1426                 if ($s == "t" || $s == "1") {
1427                         return "true";
1428                 } else {
1429                         return "false";
1430                 }
1431         }
1432
1433         function sql_bool_to_bool($s) {
1434                 if ($s == "t" || $s == "1") {
1435                         return true;
1436                 } else {
1437                         return false;
1438                 }
1439         }
1440         
1441
1442         function toggleEvenOdd($a) {
1443                 if ($a == "even") 
1444                         return "odd";
1445                 else
1446                         return "even";
1447         }
1448
1449         function sanity_check($link) {
1450
1451                 error_reporting(0);
1452
1453                 $error_code = 0;
1454                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1455                 $schema_version = db_fetch_result($result, 0, "schema_version");
1456
1457                 if ($schema_version != SCHEMA_VERSION) {
1458                         $error_code = 5;
1459                 }
1460
1461                 if (DB_TYPE == "mysql") {
1462                         $result = db_query($link, "SELECT true", false);
1463                         if (db_num_rows($result) != 1) {
1464                                 $error_code = 10;
1465                         }
1466                 }
1467
1468                 error_reporting (DEFAULT_ERROR_LEVEL);
1469
1470                 if ($error_code != 0) {
1471                         print_error_xml($error_code);
1472                         return false;
1473                 } else {
1474                         return true;
1475                 }
1476         }
1477
1478         function file_is_locked($filename) {
1479                 error_reporting(0);
1480                 $fp = fopen($filename, "r");
1481                 error_reporting(DEFAULT_ERROR_LEVEL);
1482                 if ($fp) {
1483                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1484                                 flock($fp, LOCK_UN);
1485                                 fclose($fp);
1486                                 return false;
1487                         }
1488                         fclose($fp);
1489                         return true;
1490                 }
1491                 return false;
1492         }
1493
1494         function make_lockfile($filename) {
1495                 $fp = fopen($filename, "w");
1496
1497                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
1498                         return $fp;
1499                 } else {
1500                         return false;
1501                 }
1502         }
1503
1504         function sql_random_function() {
1505                 if (DB_TYPE == "mysql") {
1506                         return "RAND()";
1507                 } else {
1508                         return "RANDOM()";
1509                 }
1510         }
1511
1512         function catchup_feed($link, $feed, $cat_view) {
1513
1514                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1515                         
1516                                 if ($cat_view) {
1517
1518                                         if ($feed > 0) {
1519                                                 $cat_qpart = "cat_id = '$feed'";
1520                                         } else {
1521                                                 $cat_qpart = "cat_id IS NULL";
1522                                         }
1523                                         
1524                                         $tmp_result = db_query($link, "SELECT id 
1525                                                 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " . 
1526                                                 $_SESSION["uid"]);
1527
1528                                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
1529
1530                                                 $tmp_feed = $tmp_line["id"];
1531
1532                                                 db_query($link, "UPDATE ttrss_user_entries 
1533                                                         SET unread = false,last_read = NOW() 
1534                                                         WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1535                                         }
1536
1537                                 } else if ($feed > 0) {
1538
1539                                         $tmp_result = db_query($link, "SELECT id 
1540                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
1541                                                 ORDER BY cat_id,title");
1542
1543                                         $parent_ids = array();
1544
1545                                         if (db_num_rows($tmp_result) > 0) {
1546                                                 while ($p = db_fetch_assoc($tmp_result)) {
1547                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
1548                                                 }
1549
1550                                                 $children_qpart = implode(" OR ", $parent_ids);
1551                                                 
1552                                                 db_query($link, "UPDATE ttrss_user_entries 
1553                                                         SET unread = false,last_read = NOW() 
1554                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
1555                                                         AND owner_uid = " . $_SESSION["uid"]);
1556
1557                                         } else {                                                
1558                                                 db_query($link, "UPDATE ttrss_user_entries 
1559                                                         SET unread = false,last_read = NOW() 
1560                                                         WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1561                                         }
1562                                                 
1563                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
1564
1565                                         if ($feed == -1) {
1566                                                 db_query($link, "UPDATE ttrss_user_entries 
1567                                                         SET unread = false,last_read = NOW()
1568                                                         WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1569                                         }
1570                         
1571                                 } else if ($feed < -10) { // label
1572
1573                                         // TODO make this more efficient
1574
1575                                         $label_id = -$feed - 11;
1576
1577                                         $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1578                                                 WHERE id = '$label_id'");                                       
1579
1580                                         if ($tmp_result) {
1581                                                 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1582
1583                                                 db_query($link, "BEGIN");
1584
1585                                                 $tmp2_result = db_query($link,
1586                                                         "SELECT 
1587                                                                 int_id 
1588                                                         FROM 
1589                                                                 ttrss_user_entries,ttrss_entries,ttrss_feeds
1590                                                         WHERE
1591                                                                 ref_id = ttrss_entries.id AND 
1592                                                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1593                                                                 $sql_exp AND
1594                                                                 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1595
1596                                                 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1597                                                         db_query($link, "UPDATE 
1598                                                                 ttrss_user_entries 
1599                                                         SET 
1600                                                                 unread = false, last_read = NOW()
1601                                                         WHERE
1602                                                                 int_id = " . $tmp_line["int_id"]);
1603                                                 }
1604                                                                 
1605                                                 db_query($link, "COMMIT");
1606
1607 /*                                              db_query($link, "UPDATE ttrss_user_entries,ttrss_entries 
1608                                                         SET unread = false,last_read = NOW()
1609                                                         WHERE $sql_exp
1610                                                         AND ref_id = id
1611                                                         AND owner_uid = ".$_SESSION["uid"]); */
1612                                         }
1613                                 }
1614                         } else { // tag
1615                                 db_query($link, "BEGIN");
1616
1617                                 $tag_name = db_escape_string($feed);
1618
1619                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1620                                         WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1621
1622                                 while ($line = db_fetch_assoc($result)) {
1623                                         db_query($link, "UPDATE ttrss_user_entries SET
1624                                                 unread = false, last_read = NOW() 
1625                                                 WHERE int_id = " . $line["post_int_id"]);
1626                                 }
1627                                 db_query($link, "COMMIT");
1628                         }
1629         }
1630
1631         function update_generic_feed($link, $feed, $cat_view) {
1632                         if ($cat_view) {
1633
1634                                 if ($feed > 0) {
1635                                         $cat_qpart = "cat_id = '$feed'";
1636                                 } else {
1637                                         $cat_qpart = "cat_id IS NULL";
1638                                 }
1639                                 
1640                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1641                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1642
1643                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
1644                                         $feed_url = $tmp_line["feed_url"];
1645                                         update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1646                                 }
1647
1648                         } else {
1649                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1650                                         WHERE id = '$feed'");
1651                                 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
1652                                 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1653                         }
1654         }
1655
1656         function getAllCounters($link, $omode = "tflc") {
1657 /*              getLabelCounters($link);
1658                 getFeedCounters($link);
1659                 getTagCounters($link);
1660                 getGlobalCounters($link);
1661                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1662                         getCategoryCounters($link);
1663                 } */
1664
1665                 if (!$omode) $omode = "tflc";
1666
1667                 getGlobalCounters($link);
1668
1669                 if (strchr($omode, "l")) getLabelCounters($link);
1670                 if (strchr($omode, "f")) getFeedCounters($link);
1671                 if (strchr($omode, "t")) getTagCounters($link);
1672                 if (strchr($omode, "c")) {                      
1673                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
1674                                 getCategoryCounters($link);
1675                         }
1676                 }
1677         }       
1678
1679         function getCategoryCounters($link) {
1680                 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
1681                                 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id 
1682                                         AND unread = true)) AS unread FROM ttrss_feeds 
1683                         WHERE 
1684                                 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1685
1686                 while ($line = db_fetch_assoc($result)) {
1687                         $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1688                         print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1689                                 $line["unread"]."\"/>";
1690                 }
1691         }
1692
1693         function getCategoryUnread($link, $cat) {
1694
1695                 if ($cat != 0) {
1696                         $cat_query = "cat_id = '$cat'";
1697                 } else {
1698                         $cat_query = "cat_id IS NULL";
1699                 }
1700
1701                 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
1702                                 AND hidden = false
1703                                 AND owner_uid = " . $_SESSION["uid"]);
1704
1705                 $cat_feeds = array();
1706                 while ($line = db_fetch_assoc($result)) {
1707                         array_push($cat_feeds, "feed_id = " . $line["id"]);
1708                 }
1709
1710                 if (count($cat_feeds) == 0) return 0;
1711
1712                 $match_part = implode(" OR ", $cat_feeds);
1713
1714                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1715                         FROM ttrss_user_entries 
1716                         WHERE   unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1717
1718                 $unread = 0;
1719
1720                 # this needs to be rewritten
1721                 while ($line = db_fetch_assoc($result)) {
1722                         $unread += $line["unread"];
1723                 }
1724
1725                 return $unread;
1726
1727         }
1728
1729         function getFeedUnread($link, $feed, $is_cat = false) {
1730                 $n_feed = sprintf("%d", $feed);
1731
1732                 if ($is_cat) {
1733                         return getCategoryUnread($link, $n_feed);               
1734                 } else if ($n_feed == -1) {
1735                         $match_part = "marked = true";
1736                 } else if ($n_feed > 0) {
1737
1738                         $result = db_query($link, "SELECT id FROM ttrss_feeds 
1739                                         WHERE parent_feed = '$n_feed'
1740                                         AND hidden = false
1741                                         AND owner_uid = " . $_SESSION["uid"]);
1742
1743                         if (db_num_rows($result) > 0) {
1744
1745                                 $linked_feeds = array();
1746                                 while ($line = db_fetch_assoc($result)) {
1747                                         array_push($linked_feeds, "feed_id = " . $line["id"]);
1748                                 }
1749
1750                                 array_push($linked_feeds, "feed_id = $n_feed");
1751                                 
1752                                 $match_part = implode(" OR ", $linked_feeds);
1753
1754                                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1755                                         FROM ttrss_user_entries
1756                                         WHERE   unread = true AND ($match_part) 
1757                                         AND owner_uid = " . $_SESSION["uid"]);
1758
1759                                 $unread = 0;
1760
1761                                 # this needs to be rewritten
1762                                 while ($line = db_fetch_assoc($result)) {
1763                                         $unread += $line["unread"];
1764                                 }
1765
1766                                 return $unread;
1767
1768                         } else {
1769                                 $match_part = "feed_id = '$n_feed'";
1770                         }
1771                 } else if ($feed < -10) {
1772
1773                         $label_id = -$feed - 11;
1774
1775                         $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1776                                 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1777
1778                         $match_part = db_fetch_result($result, 0, "sql_exp");
1779                 }
1780
1781                 if ($match_part) {
1782                 
1783                         $result = db_query($link, "SELECT count(int_id) AS unread 
1784                                 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1785                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1786                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1787                                 ttrss_feeds.hidden = false AND
1788                                 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1789                                 
1790                 } else {
1791                 
1792                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1793                                 FROM ttrss_tags,ttrss_user_entries 
1794                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1795                                         ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1796                 }
1797                 
1798                 $unread = db_fetch_result($result, 0, "unread");
1799
1800                 return $unread;
1801         }
1802
1803         /* FIXME this needs reworking */
1804
1805         function getGlobalUnread($link, $user_id = false) {
1806
1807                 if (!$user_id) {
1808                         $user_id = $_SESSION["uid"];
1809                 }
1810
1811                 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1812                         WHERE unread = true AND 
1813                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1814                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1815                         hidden = false AND
1816                         ttrss_user_entries.owner_uid = '$user_id'");
1817                 $c_id = db_fetch_result($result, 0, "c_id");
1818                 return $c_id;
1819         }
1820
1821         function getGlobalCounters($link, $global_unread = -1) {
1822                 if ($global_unread == -1) {     
1823                         $global_unread = getGlobalUnread($link);
1824                 }
1825                 print "<counter type=\"global\" id='global-unread' 
1826                         counter='$global_unread'/>";
1827
1828                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
1829                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1830
1831                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1832
1833                 print "<counter type=\"global\" id='subscribed-feeds' 
1834                         counter='$subscribed_feeds'/>";
1835
1836         }
1837
1838         function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1839
1840                 if ($smart_mode) {
1841                         if (!$_SESSION["tctr_last_value"]) {
1842                                 $_SESSION["tctr_last_value"] = array();
1843                         }
1844                 }
1845
1846                 $old_counters = $_SESSION["tctr_last_value"];
1847
1848                 $tctrs_modified = false;
1849
1850 /*              $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1851                         FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1852                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1853                         ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1854                         post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name 
1855                 UNION
1856                         select tag_name,0 as count FROM ttrss_tags
1857                         WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1858
1859                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
1860                         FROM ttrss_user_entries WHERE int_id = post_int_id 
1861                                 AND unread = true)) AS count FROM ttrss_tags 
1862                         WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1863                         
1864                 $tags = array();
1865
1866                 while ($line = db_fetch_assoc($result)) {
1867                         $tags[$line["tag_name"]] += $line["count"];
1868                 }
1869
1870                 foreach (array_keys($tags) as $tag) {
1871                         $unread = $tags[$tag];                  
1872
1873                         $tag = htmlspecialchars($tag);
1874
1875                         if (!$smart_mode || $old_counters[$tag] != $unread) {                   
1876                                 $old_counters[$tag] = $unread;
1877                                 $tctrs_modified = true;
1878                                 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1879                         }
1880
1881                 } 
1882
1883                 if ($smart_mode && $tctrs_modified) {
1884                         $_SESSION["tctr_last_value"] = $old_counters;
1885                 }
1886
1887         }
1888
1889         function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
1890
1891                 if ($smart_mode) {
1892                         if (!$_SESSION["lctr_last_value"]) {
1893                                 $_SESSION["lctr_last_value"] = array();
1894                         }
1895                 }
1896
1897                 $ret_arr = array();
1898                 
1899                 $old_counters = $_SESSION["lctr_last_value"];
1900                 $lctrs_modified = false;
1901
1902                 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1903                         WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
1904                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1905                         unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1906
1907                 $count = db_fetch_result($result, 0, "count");
1908
1909                 if (!$ret_mode) {
1910                         print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1911                 } else {
1912                         $ret_arr["-1"]["counter"] = $count;
1913                         $ret_arr["-1"]["description"] = "Starred";
1914                 }
1915
1916                 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1917                         ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1918         
1919                 while ($line = db_fetch_assoc($result)) {
1920
1921                         $id = -$line["id"] - 11;
1922
1923                         $label_name = $line["description"];
1924
1925                         error_reporting (0);
1926
1927                         $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1928                                 WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
1929                                 ttrss_feeds.hidden = false AND
1930                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1931                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1932                                 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1933
1934                         $count = db_fetch_result($tmp_result, 0, "count");
1935
1936                         if (!$smart_mode || $old_counters[$id] != $count) {     
1937                                 $old_counters[$id] = $count;
1938                                 $lctrs_modified = true;
1939                                 if (!$ret_mode) {
1940                                         print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1941                                 } else {
1942                                         $ret_arr[$id]["counter"] = $count;
1943                                         $ret_arr[$id]["description"] = $label_name;
1944                                 }
1945                         }
1946
1947                         error_reporting (DEFAULT_ERROR_LEVEL);
1948                 }
1949
1950                 if ($smart_mode && $lctrs_modified) {
1951                         $_SESSION["lctr_last_value"] = $old_counters;
1952                 }
1953
1954                 return $ret_arr;
1955         }
1956
1957 /*      function getFeedCounter($link, $id) {
1958         
1959                 $result = db_query($link, "SELECT 
1960                                 count(id) as count,last_error
1961                         FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1962                         WHERE feed_id = '$id' AND unread = true
1963                         AND ttrss_user_entries.feed_id = ttrss_feeds.id
1964                         AND ttrss_user_entries.ref_id = ttrss_entries.id");
1965         
1966                         $count = db_fetch_result($result, 0, "count");
1967                         $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1968                         
1969                         print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
1970         } */
1971
1972         function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1973
1974                 if ($smart_mode) {
1975                         if (!$_SESSION["fctr_last_value"]) {
1976                                 $_SESSION["fctr_last_value"] = array();
1977                         }
1978                 }
1979
1980                 $old_counters = $_SESSION["fctr_last_value"];
1981
1982                 $result = db_query($link, "SELECT id,last_error,parent_feed,
1983                         SUBSTRING(last_updated,1,19) AS last_updated,
1984                         (SELECT count(id) 
1985                                 FROM ttrss_entries,ttrss_user_entries 
1986                                 WHERE feed_id = ttrss_feeds.id AND 
1987                                         ttrss_user_entries.ref_id = ttrss_entries.id
1988                                 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1989                         FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1990                                 AND parent_feed IS NULL");
1991
1992                 $fctrs_modified = false;
1993
1994                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1995
1996                 while ($line = db_fetch_assoc($result)) {
1997                 
1998                         $id = $line["id"];
1999                         $count = $line["count"];
2000                         $last_error = htmlspecialchars($line["last_error"]);
2001
2002                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2003                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2004                         } else {
2005                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
2006                         }                               
2007
2008                         $has_img = is_file(ICONS_DIR . "/$id.ico");
2009
2010                         $tmp_result = db_query($link,
2011                                 "SELECT id,COUNT(unread) AS unread
2012                                 FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
2013                                         ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
2014                                 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
2015                         
2016                         if (db_num_rows($tmp_result) > 0) {                             
2017                                 while ($l = db_fetch_assoc($tmp_result)) {
2018                                         $count += $l["unread"];
2019                                 }
2020                         }
2021
2022                         if (!$smart_mode || $old_counters[$id] != $count) {
2023                                 $old_counters[$id] = $count;
2024                                 $fctrs_modified = true;
2025
2026                                 if ($last_error) {
2027                                         $error_part = "error=\"$last_error\"";
2028                                 } else {
2029                                         $error_part = "";
2030                                 }
2031
2032                                 if ($has_img) {
2033                                         $has_img_part = "hi=\"$has_img\"";
2034                                 } else {
2035                                         $has_img_part = "";
2036                                 }                               
2037
2038                                 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
2039                         }
2040                 }
2041
2042                 if ($smart_mode && $fctrs_modified) {
2043                         $_SESSION["fctr_last_value"] = $old_counters;
2044                 }
2045         }
2046
2047         function get_script_dt_add() {
2048                 if (strpos(VERSION, ".99") === false) {
2049                         return VERSION;
2050                 } else {
2051                         return time();
2052                 }
2053         }
2054
2055         function get_pgsql_version($link) {
2056                 $result = db_query($link, "SELECT version() AS version");
2057                 $version = split(" ", db_fetch_result($result, 0, "version"));
2058                 return $version[1];
2059         }
2060
2061         function print_error_xml($code, $add_msg = "") {
2062                 global $ERRORS;
2063
2064                 $error_msg = $ERRORS[$code];
2065                 
2066                 if ($add_msg) {
2067                         $error_msg = "$error_msg; $add_msg";
2068                 }
2069                 
2070                 print "<rpc-reply>";
2071                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2072                 print "</rpc-reply>";
2073         }
2074
2075         function subscribe_to_feed($link, $feed_link, $cat_id = 0, 
2076                         $auth_login = '', $auth_pass = '') {
2077
2078                 # check for feed:http://url
2079                 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2080
2081                 # check for feed://URL
2082                 if (strpos($feed_link, "//") === 0) {
2083                         $feed_link = "http:$feed_link";
2084                 }
2085
2086                 if ($feed_link == "") return;
2087
2088                 if ($cat_id == "0" || !$cat_id) {
2089                         $cat_qpart = "NULL";
2090                 } else {
2091                         $cat_qpart = "'$cat_id'";
2092                 }
2093         
2094                 $result = db_query($link,
2095                         "SELECT id FROM ttrss_feeds 
2096                         WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2097         
2098                 if (db_num_rows($result) == 0) {
2099                         
2100                         $result = db_query($link,
2101                                 "INSERT INTO ttrss_feeds 
2102                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass) 
2103                                 VALUES ('".$_SESSION["uid"]."', '$feed_link', 
2104                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2105         
2106                         $result = db_query($link,
2107                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link' 
2108                                         AND owner_uid = " . $_SESSION["uid"]);
2109         
2110                         $feed_id = db_fetch_result($result, 0, "id");
2111         
2112                         if ($feed_id) {
2113                                 update_rss_feed($link, $feed_link, $feed_id, true);
2114                         }
2115
2116                         return true;
2117                 } else {
2118                         return false;
2119                 }
2120         }
2121
2122         function print_feed_select($link, $id, $default_id = "", 
2123                 $attributes = "", $include_all_feeds = true) {
2124
2125                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2126                 if ($include_all_feeds) { 
2127                         print "<option value=\"0\">All feeds</option>";
2128                 }
2129         
2130                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2131                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2132
2133                 if (db_num_rows($result) > 0 && $include_all_feeds) {
2134                         print "<option disabled>--------</option>";
2135                 }
2136
2137                 while ($line = db_fetch_assoc($result)) {
2138                         if ($line["id"] == $default_id) {
2139                                 $is_selected = "selected";
2140                         } else {
2141                                 $is_selected = "";
2142                         }
2143                         printf("<option $is_selected value='%d'>%s</option>", 
2144                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2145                 }
2146         
2147                 print "</select>";
2148         }
2149
2150         function print_feed_cat_select($link, $id, $default_id = "", 
2151                 $attributes = "", $include_all_cats = true) {
2152                 
2153                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2154
2155                 if ($include_all_cats) {
2156                         print "<option value=\"0\">".__('Uncategorized')."</option>";
2157                 }
2158
2159                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2160                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2161
2162                 if (db_num_rows($result) > 0 && $include_all_cats) {
2163                         print "<option disabled>--------</option>";
2164                 }
2165
2166                 while ($line = db_fetch_assoc($result)) {
2167                         if ($line["id"] == $default_id) {
2168                                 $is_selected = "selected";
2169                         } else {
2170                                 $is_selected = "";
2171                         }
2172                         printf("<option $is_selected value='%d'>%s</option>", 
2173                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2174                 }
2175
2176                 print "</select>";
2177         }
2178         
2179         function checkbox_to_sql_bool($val) {
2180                 return ($val == "on") ? "true" : "false";
2181         }
2182
2183         function getFeedCatTitle($link, $id) {
2184                 if ($id == -1) {
2185                         return __("Special");
2186                 } else if ($id < -10) {
2187                         return __("Labels");
2188                 } else if ($id > 0) {
2189                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
2190                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2191                                         cat_id = ttrss_feed_categories.id");
2192                         if (db_num_rows($result) == 1) {
2193                                 return db_fetch_result($result, 0, "title");
2194                         } else {
2195                                 return __("Uncategorized");
2196                         }
2197                 } else {
2198                         return "getFeedCatTitle($id) failed";
2199                 }
2200
2201         }
2202
2203         function getFeedTitle($link, $id) {
2204                 if ($id == -1) {
2205                         return __("Starred articles");
2206                 } else if ($id < -10) {
2207                         $label_id = -10 - $id;
2208                         $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2209                         if (db_num_rows($result) == 1) {
2210                                 return db_fetch_result($result, 0, "description");
2211                         } else {
2212                                 return "Unknown label ($label_id)";
2213                         }
2214
2215                 } else if ($id > 0) {
2216                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2217                         if (db_num_rows($result) == 1) {
2218                                 return db_fetch_result($result, 0, "title");
2219                         } else {
2220                                 return "Unknown feed ($id)";
2221                         }
2222                 } else {
2223                         return "getFeedTitle($id) failed";
2224                 }
2225
2226         }
2227
2228         function get_session_cookie_name() {
2229                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2230         }
2231
2232         function print_init_params($link) {
2233                 print "<init-params>";
2234                 if ($_SESSION["stored-params"]) {
2235                         foreach (array_keys($_SESSION["stored-params"]) as $key) {
2236                                 if ($key) {
2237                                         $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2238                                         print "<param key=\"$key\" value=\"$value\"/>";
2239                                 }
2240                         }
2241                 }
2242
2243                 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2244                 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2245                 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY . "\"/>";
2246
2247                 print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
2248                         get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2249
2250                 print "<param key=\"hide_read_feeds\" value=\"" . 
2251                         (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2252
2253                 print "<param key=\"feeds_sort_by_unread\" value=\"" . 
2254                         (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2255
2256                 print "<param key=\"confirm_feed_catchup\" value=\"" . 
2257                         (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2258
2259                 print "<param key=\"cdm_auto_catchup\" value=\"" . 
2260                         (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2261
2262                 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2263
2264                 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2265
2266                 print "<param key=\"default_view_mode\" value=\"" . 
2267                         get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2268
2269                 print "<param key=\"default_view_limit\" value=\"" . 
2270                         (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2271
2272                 print "<param key=\"prefs_active_tab\" value=\"" . 
2273                         get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2274
2275                 print "<param key=\"infobox_disable_overlay\" value=\"" . 
2276                         get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2277
2278                 print "</init-params>";
2279         }
2280
2281         function print_runtime_info($link) {
2282                 print "<runtime-info>";
2283                 if (ENABLE_UPDATE_DAEMON) {
2284                         print "<param key=\"daemon_is_running\" value=\"".
2285                                 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2286                 }
2287                 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
2288                         
2289                         if ($_SESSION["last_version_check"] + 600 < time()) {
2290                                 $new_version_details = check_for_update($link);
2291
2292                                 print "<param key=\"new_version_available\" value=\"".
2293                                         sprintf("%d", $new_version_details != ""). "\"/>";
2294
2295                                 $_SESSION["last_version_check"] = time();
2296                         }
2297                 }
2298
2299                 print "</runtime-info>";
2300         }
2301
2302         function getSearchSql($search, $match_on) {
2303
2304                 $search_query_part = "";
2305
2306                 $keywords = split(" ", $search);
2307                 $query_keywords = array();
2308
2309                 if ($match_on == "both") {
2310
2311                         foreach ($keywords as $k) {
2312                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2313                                         OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2314                         }
2315
2316                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2317
2318                 } else if ($match_on == "title") {
2319
2320                         foreach ($keywords as $k) {
2321                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2322                         }
2323
2324                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2325
2326                 } else if ($match_on == "content") {
2327
2328                         foreach ($keywords as $k) {
2329                                 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2330                         }
2331                 }
2332
2333                 $search_query_part = implode("AND", $query_keywords);
2334
2335                 return $search_query_part;
2336         }
2337
2338         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2339
2340                         if ($search) {
2341                         
2342                                 $search_query_part = getSearchSql($search, $match_on);
2343                                 $search_query_part .= " AND ";
2344
2345                         } else {
2346                                 $search_query_part = "";
2347                         }
2348
2349                         $view_query_part = "";
2350         
2351                         if ($view_mode == "adaptive") {
2352                                 if ($search) {
2353                                         $view_query_part = " ";
2354                                 } else if ($feed != -1) {
2355                                         $unread = getFeedUnread($link, $feed, $cat_view);
2356                                         if ($unread > 0) {
2357                                                 $view_query_part = " unread = true AND ";
2358                                         }
2359                                 }
2360                         }
2361         
2362                         if ($view_mode == "marked") {
2363                                 $view_query_part = " marked = true AND ";
2364                         }
2365         
2366                         if ($view_mode == "unread") {
2367                                 $view_query_part = " unread = true AND ";
2368                         }
2369         
2370                         if ($limit > 0) {
2371                                 $limit_query_part = "LIMIT " . $limit;
2372                         } 
2373
2374                         $vfeed_query_part = "";
2375         
2376                         // override query strategy and enable feed display when searching globally
2377                         if ($search && $search_mode == "all_feeds") {
2378                                 $query_strategy_part = "ttrss_entries.id > 0";
2379                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2380                         } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2381                                 $query_strategy_part = "ttrss_entries.id > 0";
2382                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2383                                         id = feed_id) as feed_title,";
2384                         } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2385         
2386                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2387
2388                                 $tmp_result = false;
2389
2390                                 if ($cat_view) {
2391                                         $tmp_result = db_query($link, "SELECT id 
2392                                                 FROM ttrss_feeds WHERE cat_id = '$feed'");
2393                                 } else {
2394                                         $tmp_result = db_query($link, "SELECT id
2395                                                 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds 
2396                                                         WHERE id = '$feed') AND id != '$feed'");
2397                                 }
2398         
2399                                 $cat_siblings = array();
2400         
2401                                 if (db_num_rows($tmp_result) > 0) {
2402                                         while ($p = db_fetch_assoc($tmp_result)) {
2403                                                 array_push($cat_siblings, "feed_id = " . $p["id"]);
2404                                         }
2405         
2406                                         $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2407                                                 $feed, implode(" OR ", $cat_siblings));
2408         
2409                                 } else {
2410                                         $query_strategy_part = "ttrss_entries.id > 0";
2411                                 }
2412                                 
2413                         } else if ($feed >= 0) {
2414         
2415                                 if ($cat_view) {
2416
2417                                         if ($feed > 0) {
2418                                                 $query_strategy_part = "cat_id = '$feed'";
2419                                         } else {
2420                                                 $query_strategy_part = "cat_id IS NULL";
2421                                         }
2422         
2423                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2424
2425                                 } else {                
2426                                         $tmp_result = db_query($link, "SELECT id 
2427                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
2428                                                 ORDER BY cat_id,title");
2429                 
2430                                         $parent_ids = array();
2431                 
2432                                         if (db_num_rows($tmp_result) > 0) {
2433                                                 while ($p = db_fetch_assoc($tmp_result)) {
2434                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
2435                                                 }
2436                 
2437                                                 $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2438                                                         $feed, implode(" OR ", $parent_ids));
2439                 
2440                                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2441                                         } else {
2442                                                 $query_strategy_part = "feed_id = '$feed'";
2443                                         }
2444                                 }
2445                         } else if ($feed == -1) { // starred virtual feed
2446                                 $query_strategy_part = "marked = true";
2447                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2448                         } else if ($feed <= -10) { // labels
2449                                 $label_id = -$feed - 11;
2450         
2451                                 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2452                                         WHERE id = '$label_id'");
2453                         
2454                                 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2455
2456                                 if (!$query_strategy_part) {
2457                                         return false;
2458                                 }
2459
2460                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2461                         } else {
2462                                 $query_strategy_part = "id > 0"; // dumb
2463                         }
2464
2465                         if (get_pref($link, 'REVERSE_HEADLINES')) {
2466                                 $order_by = "updated";
2467                         } else {        
2468                                 $order_by = "updated DESC";
2469                         }
2470
2471                         if ($override_order) {
2472                                 $order_by = $override_order;
2473                         }
2474         
2475                         $feed_title = "";
2476
2477                         if ($search && $search_mode == "all_feeds") {
2478                                 $feed_title = __("Search results")." ($search)";
2479                         } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2480                                 $feed_title = __("Search results")." ($search, $feed)";
2481                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2482                                 $feed_title = $feed;
2483                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2484         
2485                                 if ($cat_view) {
2486
2487                                         if ($feed != 0) {                       
2488                                                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2489                                                         WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2490                                                 $feed_title = db_fetch_result($result, 0, "title");
2491                                         } else {
2492                                                 $feed_title = __("Uncategorized");
2493                                         }
2494
2495                                         if ($search) {
2496                                                 $feed_title = __("Searched for")." $search ($feed_title)";
2497                                         }
2498
2499                                 } else {
2500                                         
2501                                         $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds 
2502                                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2503                 
2504                                         $feed_title = db_fetch_result($result, 0, "title");
2505                                         $feed_site_url = db_fetch_result($result, 0, "site_url");
2506                                         $last_error = db_fetch_result($result, 0, "last_error");
2507
2508                                         if ($search) {
2509                                                 $feed_title = __("Searched for") . " $search ($feed_title)";
2510                                         }
2511                                 }
2512         
2513                         } else if ($feed == -1) {
2514                                 $feed_title = __("Starred articles");
2515                         } else if ($feed < -10) {
2516                                 $label_id = -$feed - 11;
2517                                 $result = db_query($link, "SELECT description FROM ttrss_labels
2518                                         WHERE id = '$label_id'");
2519                                 $feed_title = db_fetch_result($result, 0, "description");
2520
2521                                 if ($search) {
2522                                         $feed_title = __("Searched for") . " $search ($feed_title)";
2523                                 }
2524                         } else {
2525                                 $feed_title = "?";
2526                         }
2527
2528                         $feed_title = db_unescape_string($feed_title);
2529
2530                         if ($feed < -10) error_reporting (0);
2531
2532                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2533         
2534                                 if ($feed >= 0) {
2535                                         $feed_kind = "Feeds";
2536                                 } else {
2537                                         $feed_kind = "Labels";
2538                                 }
2539         
2540                                 $content_query_part = "content as content_preview,";
2541
2542                                 if ($limit_query_part) {
2543                                         $offset_query_part = "OFFSET $offset";
2544                                 }
2545
2546                                 $query = "SELECT 
2547                                                 guid,
2548                                                 ttrss_entries.id,ttrss_entries.title,
2549                                                 updated,
2550                                                 unread,feed_id,marked,link,last_read,
2551                                                 SUBSTRING(last_read,1,19) as last_read_noms,
2552                                                 $vfeed_query_part
2553                                                 $content_query_part
2554                                                 SUBSTRING(updated,1,19) as updated_noms,
2555                                                 author
2556                                         FROM
2557                                                 ttrss_entries,ttrss_user_entries,ttrss_feeds
2558                                         WHERE
2559                                         ttrss_feeds.hidden = false AND
2560                                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
2561                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2562                                         ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2563                                         $search_query_part
2564                                         $view_query_part
2565                                         $query_strategy_part ORDER BY $order_by
2566                                         $limit_query_part $offset_query_part";
2567                                         
2568                                 $result = db_query($link, $query);
2569         
2570                                 if ($_GET["debug"]) print $query;
2571         
2572                         } else {
2573                                 // browsing by tag
2574         
2575                                 $feed_kind = "Tags";
2576         
2577                                 $result = db_query($link, "SELECT
2578                                         guid,
2579                                         ttrss_entries.id as id,title,
2580                                         updated,
2581                                         unread,feed_id,
2582                                         marked,link,last_read,                          
2583                                         SUBSTRING(last_read,1,19) as last_read_noms,
2584                                         $vfeed_query_part
2585                                         $content_query_part
2586                                         SUBSTRING(updated,1,19) as updated_noms
2587                                         FROM
2588                                                 ttrss_entries,ttrss_user_entries,ttrss_tags
2589                                         WHERE
2590                                                 ref_id = ttrss_entries.id AND
2591                                                 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2592                                                 post_int_id = int_id AND tag_name = '$feed' AND
2593                                                 $view_query_part
2594                                                 $search_query_part
2595                                                 $query_strategy_part ORDER BY $order_by
2596                                         $limit_query_part");    
2597                         }
2598
2599                         return array($result, $feed_title, $feed_site_url, $last_error);
2600                         
2601         }
2602
2603         function generate_syndicated_feed($link, $feed, $is_cat,
2604                 $search, $search_mode, $match_on) {
2605
2606                 $qfh_ret = queryFeedHeadlines($link, $feed, 
2607                                 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2608
2609                 $result = $qfh_ret[0];
2610                 $feed_title = htmlspecialchars($qfh_ret[1]);
2611                 $feed_site_url = $qfh_ret[2];
2612                 $last_error = $qfh_ret[3];
2613
2614                 print "<rss version=\"2.0\">
2615                         <channel>
2616                         <title>$feed_title</title>
2617                         <link>$feed_site_url</link>
2618                         <generator>Tiny Tiny RSS v".VERSION."</generator>";
2619  
2620                 while ($line = db_fetch_assoc($result)) {
2621                         print "<item>";
2622                         print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2623                         print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2624   
2625                         $rfc822_date = date('r', strtotime($line["updated"]));
2626   
2627                         print "<pubDate>$rfc822_date</pubDate>";
2628  
2629                         print "<title>" . 
2630                                 htmlspecialchars($line["title"]) . "</title>";
2631   
2632                         print "<description>" . 
2633                                 htmlspecialchars($line["content_preview"]) . "</description>";
2634   
2635                         print "</item>";
2636                 }
2637   
2638                 print "</channel></rss>";
2639
2640         }
2641
2642         function getCategoryTitle($link, $cat_id) {
2643
2644                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2645                         id = '$cat_id'");
2646
2647                 if (db_num_rows($result) == 1) {
2648                         return db_fetch_result($result, 0, "title");
2649                 } else {
2650                         return "Uncategorized";
2651                 }
2652         }
2653
2654         // http://ru2.php.net/strip-tags
2655
2656         function strip_tags_long($textstring, $allowed){
2657         while($textstring != strip_tags($textstring, $allowed))
2658     {
2659     while (strlen($textstring) != 0)
2660          {
2661          if (strlen($textstring) > 1024) {
2662               $otherlen = 1024;
2663          } else {
2664               $otherlen = strlen($textstring);
2665          }
2666          $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
2667          $safetext .= $temptext;
2668          $textstring = substr_replace($textstring,'',0,$otherlen);
2669          }  
2670     $textstring = $safetext;
2671     }
2672         return $textstring;
2673         }
2674
2675
2676         function sanitize_rss($link, $str, $force_strip_tags = false) {
2677                 $res = $str;
2678
2679                 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
2680                         global $tw_parser;
2681                         global $tw_paranoya_setup;
2682
2683                         $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
2684
2685 //                      $res = preg_replace("/\r\n|\n|\r/", "", $res);
2686 //                      $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");                       
2687                 }
2688
2689                 return $res;
2690         }
2691
2692         function send_headlines_digests($link, $limit = 100) {
2693
2694                 if (!DIGEST_ENABLE) return false;
2695
2696                 $user_limit = DIGEST_EMAIL_LIMIT;
2697                 $days = 1;
2698
2699                 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2700
2701                 if (DB_TYPE == "pgsql") {
2702                         $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2703                 } else if (DB_TYPE == "mysql") {
2704                         $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2705                 }
2706
2707                 $result = db_query($link, "SELECT id,email FROM ttrss_users 
2708                                 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2709
2710                 while ($line = db_fetch_assoc($result)) {
2711                         if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2712                                 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2713
2714                                 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2715                                 $digest = $tuple[0];
2716                                 $headlines_count = $tuple[1];
2717
2718                                 if ($headlines_count > 0) {
2719                                         $rc = mail($line["login"] . " <" . $line["email"] . ">",
2720                                                 "[tt-rss] New headlines for last 24 hours", $digest,
2721                                                 "From: " . MAIL_FROM . "\n".
2722                                                 "Content-Type: text/plain; charset=\"utf-8\"\n".
2723                                                 "Content-Transfer-Encoding: 8bit\n");
2724                                         print "RC=$rc\n";
2725                                         db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
2726                                                         WHERE id = " . $line["id"]);
2727                                 } else {
2728                                         print "No headlines\n";
2729                                 }
2730                         }
2731                 }
2732
2733 //              $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2734
2735         }
2736
2737         function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2738                 $tmp =  __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";       
2739                 $tmp .= "=======================================================\n\n";
2740
2741                 if (DB_TYPE == "pgsql") {
2742                         $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2743                 } else if (DB_TYPE == "mysql") {
2744                         $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2745                 }
2746
2747                 $result = db_query($link, "SELECT ttrss_entries.title,
2748                                 ttrss_feeds.title AS feed_title,
2749                                 date_entered,
2750                                 link,
2751                                 SUBSTRING(last_updated,1,19) AS last_updated
2752                         FROM 
2753                                 ttrss_user_entries,ttrss_entries,ttrss_feeds 
2754                         WHERE 
2755                                 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
2756                                 AND include_in_digest = true
2757                                 AND $interval_query
2758                                 AND ttrss_user_entries.owner_uid = $user_id
2759                                 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2760                         LIMIT $limit");
2761
2762                 $cur_feed_title = "";
2763
2764                 $headlines_count = db_num_rows($result);
2765
2766                 while ($line = db_fetch_assoc($result)) {
2767                         $updated = smart_date_time(strtotime($line["last_updated"]));
2768                         $feed_title = $line["feed_title"];
2769
2770                         if ($cur_feed_title != $feed_title) {
2771                                 $cur_feed_title = $feed_title;
2772
2773                                 $tmp .= "$feed_title\n\n";
2774                         }
2775
2776                         $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2777                         $tmp .= "   " . trim($line["link"]) . "\n";
2778                         $tmp .= "\n";
2779                 }
2780
2781                 $tmp .= "--- \n";
2782                 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") . 
2783                         DIGEST_HOSTNAME . "\n".
2784                         __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2785                         
2786
2787                 return array($tmp, $headlines_count);
2788         }
2789
2790         function check_for_update($link, $brief_fmt = true) {
2791                 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2792
2793                 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
2794                         return;
2795                 }
2796
2797                 error_reporting(0);
2798                 $rss = fetch_rss($releases_feed);
2799                 error_reporting (DEFAULT_ERROR_LEVEL);
2800
2801                 if ($rss) {
2802
2803                         $items = $rss->items;
2804
2805                         if (!$items || !is_array($items)) $items = $rss->entries;
2806                         if (!$items || !is_array($items)) $items = $rss;
2807
2808                         if (!is_array($items) || count($items) == 0) {
2809                                 return;
2810                         }                       
2811
2812                         $latest_item = $items[0];
2813
2814                         $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2815
2816                         $release_url = sanitize_rss($link, $latest_item["link"]);
2817                         $content = sanitize_rss($link, $latest_item["description"]);
2818
2819                         if (version_compare(VERSION, $latest_version) == -1) {
2820                                 if ($brief_fmt) {
2821                                         return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">      
2822                                                 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2823                                                 <div id=\"milestoneDetails\">$content</div>");
2824                                 } else {
2825                                         return "New version of Tiny-Tiny RSS ($latest_version) is available:
2826                                                 <div class='milestoneDetails'>$content</div>
2827                                                 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2828                                                 download and update information.";      
2829                                 }
2830
2831                         }                       
2832                 }
2833         }
2834
2835         function markArticlesById($link, $ids, $cmode) {
2836
2837                 $tmp_ids = array();
2838
2839                 foreach ($ids as $id) {
2840                         array_push($tmp_ids, "ref_id = '$id'");
2841                 }
2842
2843                 $ids_qpart = join(" OR ", $tmp_ids);
2844
2845                 if ($cmode == 0) {
2846                         db_query($link, "UPDATE ttrss_user_entries SET 
2847                         marked = false,last_read = NOW()
2848                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2849                 } else if ($cmode == 1) {
2850                         db_query($link, "UPDATE ttrss_user_entries SET 
2851                         marked = true
2852                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2853                 } else {
2854                         db_query($link, "UPDATE ttrss_user_entries SET 
2855                         marked = NOT marked,last_read = NOW()
2856                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2857                 }
2858         }
2859
2860         function catchupArticlesById($link, $ids, $cmode) {
2861
2862                 $tmp_ids = array();
2863
2864                 foreach ($ids as $id) {
2865                         array_push($tmp_ids, "ref_id = '$id'");
2866                 }
2867
2868                 $ids_qpart = join(" OR ", $tmp_ids);
2869
2870                 if ($cmode == 0) {
2871                         db_query($link, "UPDATE ttrss_user_entries SET 
2872                         unread = false,last_read = NOW()
2873                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2874                 } else if ($cmode == 1) {
2875                         db_query($link, "UPDATE ttrss_user_entries SET 
2876                         unread = true
2877                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2878                 } else {
2879                         db_query($link, "UPDATE ttrss_user_entries SET 
2880                         unread = NOT unread,last_read = NOW()
2881                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2882                 }
2883         }
2884
2885         function catchupArticleById($link, $id, $cmode) {
2886
2887                 if ($cmode == 0) {
2888                         db_query($link, "UPDATE ttrss_user_entries SET 
2889                         unread = false,last_read = NOW()
2890                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2891                 } else if ($cmode == 1) {
2892                         db_query($link, "UPDATE ttrss_user_entries SET 
2893                         unread = true
2894                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2895                 } else {
2896                         db_query($link, "UPDATE ttrss_user_entries SET 
2897                         unread = NOT unread,last_read = NOW()
2898                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2899                 }
2900         }
2901
2902         function escape_for_form($s) {
2903                 return htmlspecialchars(db_unescape_string($s));
2904         }
2905
2906         function make_guid_from_title($title) {
2907                 return preg_replace("/[ \"\',.:;]/", "-", 
2908                         mb_strtolower(strip_tags($title), 'utf-8'));
2909         }
2910
2911         function print_headline_subtoolbar($link, $feed_site_url, $feed_title, 
2912                         $bottom = false, $rtl_content = false, $feed_id = 0,
2913                         $is_cat = false, $search = false, $match_on = false,
2914                         $search_mode = false, $offset = 0, $limit = 0) {
2915
2916                         $user_page_offset = $offset + 1;
2917
2918                         if (!$bottom) {
2919                                 $class = "headlinesSubToolbar";
2920                                 $tid = "headlineActionsTop";
2921                         } else {
2922                                 $class = "headlinesSubToolbar";
2923                                 $tid = "headlineActionsBottom";
2924                         }
2925
2926                         print "<table class=\"$class\" id=\"$tid\"
2927                                 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2928
2929                         if ($rtl_content) {
2930                                 $rtl_cpart = "RTL";
2931                         } else {
2932                                 $rtl_cpart = "";
2933                         }
2934
2935                         $page_prev_link = "javascript:viewFeedGoPage(-1)";
2936                         $page_next_link = "javascript:viewFeedGoPage(1)";
2937                         $page_first_link = "javascript:viewFeedGoPage(0)";
2938
2939                         $catchup_page_link = "javascript:catchupPage()";
2940                         $catchup_feed_link = "javascript:catchupCurrentFeed()";
2941
2942                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2943
2944                                 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2945                                 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2946                                 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2947
2948                                 $tog_unread_link = "javascript:selectionToggleUnread()";
2949                                 $tog_marked_link = "javascript:selectionToggleMarked()";
2950
2951                         } else {
2952
2953                                 $sel_all_link = "javascript:cdmSelectArticles('all')";
2954                                 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2955                                 $sel_none_link = "javascript:cdmSelectArticles('none')";
2956
2957                                 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2958                                 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2959
2960                         }
2961
2962                         if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
2963
2964                                 print "<td class=\"headlineActions$rtl_cpart\">
2965                                         <ul class=\"headlineDropdownMenu\">
2966                                         <li class=\"top2\">
2967                                         ".__('Select:')."
2968                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
2969                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2970                                                 <a href=\"$sel_none_link\">".__('None')."</a></li>
2971                                         <li class=\"vsep\">&nbsp;</li>
2972                                         <li class=\"top\">Toggle<ul>
2973                                                 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
2974                                                 <li onclick=\"$tog_marked_link\">".__('Starred')."</li></ul></li>
2975                                         <li class=\"vsep\">&nbsp;</li>
2976                                         <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
2977                                                 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
2978                                                 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
2979                                         <li class=\"vsep\">&nbsp;</li>";
2980
2981                                         if ($limit != 0 && !$search) {
2982                                                 print "
2983                                                 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
2984                                                         <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
2985                                                         <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
2986                                                         </ul>";
2987                                                 }
2988
2989                                         if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
2990                                                 print "<li class=\"top3\">
2991                                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2992                                                                 '$match_on', '$feed_id', '$is_cat');\">
2993                                                                 ".__('Convert to label')."</a></td>";
2994                                         }
2995                                         print " 
2996                                         </td>"; 
2997
2998                         } else {
2999                         // old style subtoolbar:
3000
3001                                 print "<td class=\"headlineActions$rtl_cpart\">".
3002                                         __('Select:')."
3003                                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
3004                                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3005                                                                 <a href=\"$sel_none_link\">".__('None')."</a>
3006                                                 &nbsp;&nbsp;".
3007                                                 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3008                                                         <a href=\"$tog_marked_link\">".__('Starred')."</a>
3009                                                 &nbsp;&nbsp;".
3010                                                 __('Mark as read:')."
3011                                                         <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3012                                                         <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3013
3014                                 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3015
3016                                         print "&nbsp;&nbsp;
3017                                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3018                                                                 '$match_on', '$feed_id', '$is_cat');\">
3019                                                         ".__('Convert to label')."</a>";
3020                                 }
3021
3022                                 print "</td>";  
3023
3024                         }
3025
3026 /*                      if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3027                                 print "<td class=\"headlineActions$rtl_cpart\">
3028                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3029                                                         '$match_on', '$feed_id', '$is_cat');\">
3030                                                 ".__('Convert to Label')."</a></td>";
3031 } */
3032
3033                         print "<td class=\"headlineTitle$rtl_cpart\">";
3034                 
3035                         if ($feed_site_url) {
3036                                 if (!$bottom) {
3037                                         $target = "target=\"_blank\"";
3038                                 }
3039                                 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
3040                         } else {
3041                                 print $feed_title;
3042                         }
3043
3044                         if ($search) {
3045                                 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3046                         }
3047
3048                         if ($user_page_offset > 1) {
3049                                 print " [$user_page_offset] ";
3050                         }
3051
3052                         if (!$bottom) {
3053                                 print "
3054                                         <a target=\"_new\" 
3055                                                 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3056                                                 <img class=\"noborder\" 
3057                                                         alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3058                                         </a>";
3059                         }
3060                                 
3061                         print "</td>";
3062                         print "</tr></table>";
3063
3064                 }
3065
3066         function outputFeedList($link, $tags = false) {
3067
3068                 print "<ul class=\"feedList\" id=\"feedList\">";
3069
3070                 $owner_uid = $_SESSION["uid"];
3071
3072                 /* virtual feeds */
3073
3074                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3075                         print "<li class=\"feedCat\">".__('Special')."</li>";
3076                         print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3077                 }
3078
3079                 $num_starred = getFeedUnread($link, -1);
3080
3081                 $class = "virt";
3082
3083                 if ($num_starred > 0) $class .= "Unread";
3084
3085                 printFeedEntry(-1, $class, __("Starred articles"), $num_starred, 
3086                         "images/mark_set.png", $link);
3087
3088                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3089                         print "</ul>";
3090                 }
3091
3092                 if (!$tags) {
3093
3094                         if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
3095         
3096                                 $result = db_query($link, "SELECT id,sql_exp,description FROM
3097                                         ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3098                 
3099                                 if (db_num_rows($result) > 0) {
3100                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3101                                                 print "<li class=\"feedCat\">".__('Labels')."</li>";
3102                                                 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3103                                         } else {
3104                                                 print "<li><hr></li>";
3105                                         }
3106                                 }
3107                 
3108                                 while ($line = db_fetch_assoc($result)) {
3109         
3110                                         error_reporting (0);
3111
3112                                         $label_id = -$line['id'] - 11;
3113                                         $count = getFeedUnread($link, $label_id);
3114
3115                                         $class = "label";
3116         
3117                                         if ($count > 0) {
3118                                                 $class .= "Unread";
3119                                         }
3120                                         
3121                                         error_reporting (DEFAULT_ERROR_LEVEL);
3122         
3123                                         printFeedEntry($label_id, 
3124                                                 $class, db_unescape_string($line["description"]), 
3125                                                 $count, "images/label.png", $link);
3126                 
3127                                 }
3128
3129                                 if (db_num_rows($result) > 0) {
3130                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3131                                                 print "</ul>";
3132                                         }
3133                                 }
3134
3135                         }
3136
3137                         if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3138                                 print "<li><hr></li>";
3139                         }
3140
3141                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3142                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3143                                         $order_by_qpart = "category,unread DESC,title";
3144                                 } else {
3145                                         $order_by_qpart = "category,title";
3146                                 }
3147                         } else {
3148                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3149                                         $order_by_qpart = "unread DESC,title";
3150                                 } else {                
3151                                         $order_by_qpart = "title";
3152                                 }
3153                         }
3154
3155                         $result = db_query($link, "SELECT ttrss_feeds.*,
3156                                 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3157                                 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3158                                         WHERE feed_id = ttrss_feeds.id AND unread = true
3159                                                 AND ttrss_user_entries.ref_id = ttrss_entries.id
3160                                                 AND owner_uid = '$owner_uid') as unread,
3161                                 cat_id,last_error,
3162                                 ttrss_feed_categories.title AS category,
3163                                 ttrss_feed_categories.collapsed 
3164                                 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories 
3165                                         ON (ttrss_feed_categories.id = cat_id)                          
3166                                 WHERE 
3167                                         ttrss_feeds.hidden = false AND
3168                                         ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3169                                 ORDER BY $order_by_qpart"); 
3170
3171                         $actid = $_GET["actid"];
3172         
3173                         /* real feeds */
3174         
3175                         $lnum = 0;
3176         
3177                         $total_unread = 0;
3178
3179                         $category = "";
3180
3181                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3182         
3183                         while ($line = db_fetch_assoc($result)) {
3184                         
3185                                 $feed = trim(db_unescape_string($line["title"]));
3186
3187                                 if (!$feed) $feed = "[Untitled]";
3188
3189                                 $feed_id = $line["id"];   
3190         
3191                                 $subop = $_GET["subop"];
3192                                 
3193                                 $unread = $line["unread"];
3194
3195                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3196                                         $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3197                                 } else {
3198                                         $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3199                                 }
3200
3201                                 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3202
3203                                 if ($rtl_content) {
3204                                         $rtl_tag = "dir=\"RTL\"";
3205                                 } else {
3206                                         $rtl_tag = "";
3207                                 }
3208
3209                                 $tmp_result = db_query($link,
3210                                         "SELECT id,COUNT(unread) AS unread
3211                                         FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
3212                                                 ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
3213                                         WHERE parent_feed = '$feed_id' AND unread = true 
3214                                         GROUP BY ttrss_feeds.id");
3215                         
3216                                 if (db_num_rows($tmp_result) > 0) {                             
3217                                         while ($l = db_fetch_assoc($tmp_result)) {
3218                                                 $unread += $l["unread"];
3219                                         }
3220                                 }
3221
3222                                 $cat_id = $line["cat_id"];
3223
3224                                 $tmp_category = $line["category"];
3225
3226                                 if (!$tmp_category) {
3227                                         $tmp_category = __("Uncategorized");
3228                                 }
3229                                 
3230         //                      $class = ($lnum % 2) ? "even" : "odd";
3231
3232                                 if ($line["last_error"]) {
3233                                         $class = "error";
3234                                 } else {
3235                                         $class = "feed";
3236                                 }
3237         
3238                                 if ($unread > 0) $class .= "Unread";
3239         
3240                                 if ($actid == $feed_id) {
3241                                         $class .= "Selected";
3242                                 }
3243         
3244                                 $total_unread += $unread;
3245
3246                                 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3247                                 
3248                                         if ($category) {
3249                                                 print "</ul></li>";
3250                                         }
3251                                 
3252                                         $category = $tmp_category;
3253
3254                                         $collapsed = $line["collapsed"];
3255
3256                                         // workaround for NULL category
3257                                         if ($category == __("Uncategorized")) {
3258                                                 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3259                                                         $collapsed = "t";
3260                                                 }
3261                                         }
3262
3263                                         if ($collapsed == "t" || $collapsed == "1") {
3264                                                 $holder_class = "invisible";
3265                                                 $ellipsis = "...";
3266                                         } else {
3267                                                 $holder_class = "feedCatHolder";
3268                                                 $ellipsis = "";
3269                                         }
3270
3271                                         $cat_id = sprintf("%d", $cat_id);
3272
3273                                         $cat_unread = getCategoryUnread($link, $cat_id);
3274
3275                                         $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3276
3277                                         print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3278                                                 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3279                                                         <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3280                                                         <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\" 
3281                                                         class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3282                                                         </a></li>";
3283
3284                                         // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3285                                         // -> keyboard navigation, etc.
3286                                         print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3287                                 }
3288         
3289                                 printFeedEntry($feed_id, $class, $feed, $unread, 
3290                                         ICONS_DIR."/$feed_id.ico", $link, $rtl_content, 
3291                                         $last_updated, $line["last_error"]);
3292         
3293                                 ++$lnum;
3294                         }
3295
3296                         if (db_num_rows($result) == 0) {
3297                                 print "<li>".__('No feeds to display.')."</li>";
3298                         }
3299
3300                 } else {
3301
3302                         // tags
3303
3304 /*                      $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3305                                 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3306                                 post_int_id = ttrss_user_entries.int_id AND 
3307                                 unread = true AND ref_id = ttrss_entries.id
3308                                 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name       
3309                         UNION
3310                                 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3311                         ORDER BY tag_name"); */
3312
3313                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3314                                 print "<li class=\"feedCat\">".__('Tags')."</li>";
3315                                 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3316                         }
3317
3318                         $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
3319                                 FROM ttrss_user_entries WHERE int_id = post_int_id 
3320                                         AND unread = true)) AS count FROM ttrss_tags 
3321                                 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3322
3323                         $tags = array();
3324         
3325                         while ($line = db_fetch_assoc($result)) {
3326                                 $tags[$line["tag_name"]] += $line["count"];
3327                         }
3328         
3329                         foreach (array_keys($tags) as $tag) {
3330         
3331                                 $unread = $tags[$tag];
3332         
3333                                 $class = "tag";
3334         
3335                                 if ($unread > 0) {
3336                                         $class .= "Unread";
3337                                 }
3338         
3339                                 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3340         
3341                         } 
3342
3343                         if (db_num_rows($result) == 0) {
3344                                 print "<li>No tags to display.</li>";
3345                         }
3346
3347                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3348                                 print "</ul>";
3349                         }
3350
3351                 }
3352
3353                 print "</ul>";
3354
3355         }
3356
3357         function get_article_tags($link, $id) {
3358
3359                 $a_id = db_escape_string($id);
3360
3361                 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3362                         ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3363                                 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3364
3365                 $tags = array();        
3366         
3367                 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3368                         array_push($tags, $tmp_line["tag_name"]);                               
3369                 }
3370
3371                 return $tags;
3372         }
3373
3374         function trim_value(&$value) {
3375                 $value = trim($value);
3376         }       
3377
3378         function trim_array($array) {
3379                 $tmp = $array;
3380                 array_walk($tmp, 'trim_value');
3381                 return $tmp;
3382         }
3383
3384         function tag_is_valid($tag) {
3385                 if ($tag == '') return false;
3386                 if (preg_match("/^[0-9]*$/", $tag)) return false;
3387
3388                 $tag = iconv("utf-8", "utf-8", $tag);
3389                 if (!$tag) return false;
3390
3391                 return true;
3392         }
3393
3394         function render_login_form($link, $mobile = false) {
3395                 if (!$mobile) {
3396                         require_once "login_form.php";
3397                 } else {
3398                         require_once "mobile/login_form.php";
3399                 }
3400         }
3401
3402         // from http://developer.apple.com/internet/safari/faq.html
3403         function no_cache_incantation() {
3404                 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3405                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3406                 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3407                 header("Cache-Control: post-check=0, pre-check=0", false);
3408                 header("Pragma: no-cache"); // HTTP/1.0
3409         }
3410
3411         function format_warning($msg, $id = "") {
3412                 return "<div class=\"warning\" id=\"$id\"> 
3413                         <img src=\"images/sign_excl.png\">$msg</div>";
3414         }
3415
3416         function format_notice($msg) {
3417                 return "<div class=\"notice\"> 
3418                         <img src=\"images/sign_info.png\">$msg</div>";
3419         }
3420
3421         function format_error($msg) {
3422                 return "<div class=\"error\"> 
3423                         <img src=\"images/sign_excl.png\">$msg</div>";
3424         }
3425
3426         function print_notice($msg) {
3427                 return print format_notice($msg);
3428         }
3429
3430         function print_warning($msg) {
3431                 return print format_warning($msg);
3432         }
3433
3434         function print_error($msg) {
3435                 return print format_error($msg);
3436         }
3437
3438
3439         function T_sprintf() {
3440                 $args = func_get_args();
3441                 return vsprintf(__(array_shift($args)), $args);
3442         }
3443
3444         function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
3445
3446                 /* we can figure out feed_id from article id anyway, why do we
3447                  * pass feed_id here? */
3448
3449                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3450                         WHERE ref_id = '$id'");
3451
3452                 $feed_id = db_fetch_result($result, 0, "feed_id");
3453
3454                 print "<article id='$id'><![CDATA[";
3455
3456                 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3457                         WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3458
3459                 if (db_num_rows($result) == 1) {
3460                         $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3461                 } else {
3462                         $rtl_content = false;
3463                 }
3464
3465                 if ($rtl_content) {
3466                         $rtl_tag = "dir=\"RTL\"";
3467                         $rtl_class = "RTL";
3468                 } else {
3469                         $rtl_tag = "";
3470                         $rtl_class = "";
3471                 }
3472
3473                 if ($mark_as_read) {
3474                         $result = db_query($link, "UPDATE ttrss_user_entries 
3475                                 SET unread = false,last_read = NOW() 
3476                                 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3477                 }
3478
3479                 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3480                         SUBSTRING(updated,1,16) as updated,
3481                         (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3482                         num_comments,
3483                         author
3484                         FROM ttrss_entries,ttrss_user_entries
3485                         WHERE   id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3486
3487                 if ($result) {
3488
3489                         $link_target = "";
3490
3491                         if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3492                                 $link_target = "target=\"_new\"";
3493                         }
3494
3495                         $line = db_fetch_assoc($result);
3496
3497                         if ($line["icon_url"]) {
3498                                 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
3499                         } else {
3500                                 $feed_icon = "&nbsp;";
3501                         }
3502
3503 /*                      if ($line["comments"] && $line["link"] != $line["comments"]) {
3504                                 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
3505                         } else {
3506                                 $entry_comments = "";
3507                         } */
3508
3509                         $num_comments = $line["num_comments"];
3510                         $entry_comments = "";
3511
3512                         if ($num_comments > 0) {
3513                                 if ($line["comments"]) {
3514                                         $comments_url = $line["comments"];
3515                                 } else {
3516                                         $comments_url = $line["link"];
3517                                 }
3518                                 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
3519                         } else {
3520                                 if ($line["comments"] && $line["link"] != $line["comments"]) {
3521                                         $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
3522                                 }                               
3523                         }
3524
3525                         print "<div class=\"postReply\">";
3526
3527                         print "<div class=\"postHeader\">";
3528
3529                         $entry_author = $line["author"];
3530
3531                         if ($entry_author) {
3532                                 $entry_author = __(" - by ") . $entry_author;
3533                         }
3534
3535                         $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'), 
3536                                 strtotime($line["updated"]));
3537                 
3538                         print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3539
3540                         if ($line["link"]) {
3541                                 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" . 
3542                                         $line["title"] . "</a>$entry_author</div>";
3543                         } else {
3544                                 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3545                         }
3546
3547                         $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3548                                 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
3549                                 ORDER BY tag_name");
3550         
3551                         $tags_str = "";
3552                         $f_tags_str = "";
3553
3554                         $num_tags = 0;
3555
3556                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
3557                                 $num_tags++;
3558                                 $tag = $tmp_line["tag_name"];
3559                                 $tag_escaped = str_replace("'", "\\'", $tag);
3560
3561                                 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
3562                                 
3563                                 if ($num_tags == 6) {
3564                                         $tags_str .= "<a href=\"javascript:showBlockElement('allEntryTags')\">...</a>";
3565                                 } else if ($num_tags < 6) {
3566                                         $tags_str .= $tag_str;
3567                                 }
3568                                 $f_tags_str .= $tag_str;
3569                         }
3570
3571                         $tags_str = preg_replace("/, $/", "", $tags_str);
3572                         $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
3573
3574                         if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3575
3576                         if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
3577
3578                         print "<div style='float : right'>$tags_str 
3579                                 <a title=\"Edit tags for this article\" 
3580                                         href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
3581                                 <div clear='both'>$entry_comments</div>";
3582
3583                         print "</div>";
3584
3585                         print "<div class=\"postIcon\">" . $feed_icon . "</div>";
3586                         print "<div class=\"postContent\">";
3587                         
3588                         if (db_num_rows($tmp_result) > 0) {
3589                                 print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
3590                         }
3591
3592                         if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3593                                 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
3594                         }
3595
3596                         $line["content"] = sanitize_rss($link, $line["content"]);
3597
3598                         print $line["content"] . "</div>";
3599                         
3600                         print "</div>";
3601
3602                 }
3603
3604                 print "]]></article>";
3605
3606         }
3607
3608         function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
3609                                         $next_unread_feed, $offset) {
3610
3611                 $timing_info = getmicrotime();
3612
3613                 $topmost_article_ids = array();
3614
3615                 if (!$offset) $offset = 0;
3616
3617                 if ($subop == "undefined") $subop = "";
3618
3619                 if ($subop == "CatchupSelected") {
3620                         $ids = split(",", db_escape_string($_GET["ids"]));
3621                         $cmode = sprintf("%d", $_GET["cmode"]);
3622
3623                         catchupArticlesById($link, $ids, $cmode);
3624                 }
3625
3626                 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
3627                         update_generic_feed($link, $feed, $cat_view);
3628                 }
3629
3630                 if ($subop == "MarkAllRead")  {
3631                         catchup_feed($link, $feed, $cat_view);
3632
3633                         if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
3634                                 if ($next_unread_feed) {
3635                                         $feed = $next_unread_feed;
3636                                 }
3637                         }
3638                 }
3639
3640                 if ($feed_id > 0) {             
3641                         $result = db_query($link,
3642                                 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
3643                 
3644                         if (db_num_rows($result) == 0) {
3645                                 print "<div align='center'>".__('Feed not found.')."</div>";                            
3646                                 return;
3647                         }
3648                 }
3649
3650                 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3651
3652                         $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3653                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
3654
3655                         if (db_num_rows($result) == 1) {
3656                                 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3657                         } else {
3658                                 $rtl_content = false;
3659                         }
3660         
3661                         if ($rtl_content) {
3662                                 $rtl_tag = "dir=\"RTL\"";
3663                         } else {
3664                                 $rtl_tag = "";
3665                         }
3666                 } else {
3667                         $rtl_tag = "";
3668                         $rtl_content = false;
3669                 }
3670
3671                 $script_dt_add = get_script_dt_add();
3672
3673                 /// START /////////////////////////////////////////////////////////////////////////////////
3674
3675                 $search = db_escape_string($_GET["query"]);
3676                 $search_mode = db_escape_string($_GET["search_mode"]);
3677                 $match_on = db_escape_string($_GET["match_on"]);
3678
3679                 if (!$match_on) {
3680                         $match_on = "both";
3681                 }
3682
3683                 $real_offset = $offset * $limit;
3684
3685                 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
3686
3687                 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, 
3688                         $search, $search_mode, $match_on, false, $real_offset);
3689
3690                 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
3691
3692                 $result = $qfh_ret[0];
3693                 $feed_title = $qfh_ret[1];
3694                 $feed_site_url = $qfh_ret[2];
3695                 $last_error = $qfh_ret[3];
3696                 
3697                 /// STOP //////////////////////////////////////////////////////////////////////////////////
3698
3699                 print "<div id=\"headlinesContainer\" $rtl_tag>";
3700
3701                 if (!$result) {
3702                         print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
3703                         return;
3704                 }
3705
3706                 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false, 
3707                         $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode, 
3708                         $offset, $limit);
3709
3710                 print "<div id=\"headlinesInnerContainer\">";
3711
3712                 if (db_num_rows($result) > 0) {
3713
3714 #                       print "\{$offset}";
3715
3716                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3717                                 print "<table class=\"headlinesList\" id=\"headlinesList\" 
3718                                         cellspacing=\"0\">";
3719                         }
3720
3721                         $lnum = 0;
3722         
3723                         error_reporting (DEFAULT_ERROR_LEVEL);
3724         
3725                         $num_unread = 0;
3726         
3727                         while ($line = db_fetch_assoc($result)) {
3728
3729                                 $class = ($lnum % 2) ? "even" : "odd";
3730         
3731                                 $id = $line["id"];
3732                                 $feed_id = $line["feed_id"];
3733
3734                                 if (count($topmost_article_ids) < 5) {
3735                                         array_push($topmost_article_ids, $id);
3736                                 }
3737
3738                                 if ($line["last_read"] == "" && 
3739                                                 ($line["unread"] != "t" && $line["unread"] != "1")) {
3740         
3741                                         $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\" 
3742                                                 alt=\"Updated\">";
3743                                 } else {
3744                                         $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\" 
3745                                                 alt=\"Updated\">";
3746                                 }
3747         
3748                                 if ($line["unread"] == "t" || $line["unread"] == "1") {
3749                                         $class .= "Unread";
3750                                         ++$num_unread;
3751                                         $is_unread = true;
3752                                 } else {
3753                                         $is_unread = false;
3754                                 }
3755         
3756                                 if ($line["marked"] == "t" || $line["marked"] == "1") {
3757                                         $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.png\" 
3758                                                 class=\"markedPic\"
3759                                                 alt=\"Reset mark\" onclick='javascript:tMark($id)'>";
3760                                 } else {
3761                                         $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.png\" 
3762                                                 class=\"markedPic\"
3763                                                 alt=\"Set mark\" onclick='javascript:tMark($id)'>";
3764                                 }
3765
3766 #                               $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
3767 #                                       $line["title"] . "</a>";
3768
3769                                 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
3770                                         $line["title"] . "</a>";
3771
3772 #                               $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
3773 #                                       $line["title"] . "</a>";
3774
3775                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3776                                         $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
3777                                 } else {
3778                                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3779                                         $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
3780                                 }                               
3781
3782                                 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3783                                         $content_preview = truncate_string(strip_tags($line["content_preview"]), 
3784                                                 100);
3785                                 }
3786
3787                                 $entry_author = $line["author"];
3788
3789                                 if ($entry_author) {
3790                                         $entry_author = " - by $entry_author";
3791                                 }
3792
3793                                 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3794                                         
3795                                         print "<tr class='$class' id='RROW-$id'>";
3796                 
3797                                         print "<td class='hlUpdPic'>$update_pic</td>";
3798                 
3799                                         print "<td class='hlSelectRow'>
3800                                                 <input type=\"checkbox\" onclick=\"tSR(this)\"
3801                                                         id=\"RCHK-$id\">
3802                                                 </td>";
3803                 
3804                                         print "<td class='hlMarkedPic'>$marked_pic</td>";
3805
3806                                         if ($line["feed_title"]) {                      
3807                                                 print "<td class='hlContent'>$content_link</td>";
3808                                                 print "<td class='hlFeed'>
3809                                                         <a href=\"javascript:viewfeed($feed_id, '', false)\">".
3810                                                                 $line["feed_title"]."</a>&nbsp;</td>";
3811                                         } else {                        
3812                                                 print "<td class='hlContent' valign='middle'>";
3813
3814                                                 print "<a href=\"javascript:view($id,$feed_id);\">" .
3815                                                         $line["title"];
3816
3817                                                 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3818                                                         if ($content_preview) {
3819                                                                 print "<span class=\"contentPreview\"> - $content_preview</span>";
3820                                                         }
3821                                                 }
3822                 
3823                                                 print "</a>";
3824                                                 print "</td>";
3825                                         }
3826                                         
3827                                         print "<td class=\"hlUpdated\"><nobr>$updated_fmt&nbsp;</nobr></td>";
3828                 
3829                                         print "</tr>";
3830
3831                                 } else {
3832                                         
3833                                         if ($is_unread) {
3834                                                 $add_class = "Unread";
3835                                         } else {
3836                                                 $add_class = "";
3837                                         }       
3838                                         
3839                                         print "<div class=\"cdmArticle$add_class\" id=\"RROW-$id\">";
3840
3841                                         print "<div class=\"cdmHeader\">";
3842
3843                                         print "<div class=\"articleUpdated\">$updated_fmt</div>";
3844                                         
3845                                         print "<a class=\"title\" 
3846                                                 onclick=\"javascript:toggleUnread($id, 0)\"
3847                                                 target=\"new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
3848
3849                                         print $entry_author;
3850
3851                                         if ($line["feed_title"]) {      
3852                                                 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
3853                                         }
3854
3855                                         print "</div>";
3856
3857                                         print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
3858
3859                                         print "<div class=\"cdmFooter\">";
3860
3861                                         print "$marked_pic";
3862
3863                                         print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this, 
3864                                                         'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
3865
3866                                         $tags = get_article_tags($link, $id);
3867
3868                                         $tags_str = "";
3869
3870                                         foreach ($tags as $tag) {
3871                                                 $num_tags++;
3872                                                 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, "; 
3873                                         }
3874
3875                                         $tags_str = preg_replace("/, $/", "", $tags_str);
3876
3877                                         if ($tags_str == "") $tags_str = "no tags";
3878         
3879                                         print " $tags_str <a title=\"Edit tags for this article\" 
3880                                                         href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
3881
3882                                         print "</div>";
3883
3884 #                                       print "<div align=\"center\"><a class=\"cdmToggleLink\"
3885 #                                                       href=\"javascript:toggleUnread($id)\">
3886 #                                                       Toggle unread</a></div>";
3887
3888                                         print "</div>"; 
3889
3890                                 }                               
3891         
3892                                 ++$lnum;
3893                         }
3894
3895                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {                        
3896                                 print "</table>";
3897                         }
3898
3899 //                      print_headline_subtoolbar($link, 
3900 //                              "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
3901
3902
3903                 } else {
3904                         print "<div class='whiteBox'>".__('No articles found.')."</div>";
3905                 }
3906
3907                 print "</div>";
3908
3909                 print "</div>";
3910
3911                 return $topmost_article_ids;
3912         }
3913
3914 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
3915
3916         function printTagCloud($link) {
3917
3918                 /* get first ref_id to count from */
3919
3920                 /*
3921
3922                 $query = "";
3923
3924                 if (DB_TYPE == "pgsql") {
3925                         $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries 
3926                                 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3927                                 AND date_entered > NOW() - INTERVAL '30 days'";
3928                 } else {
3929                         $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries 
3930                                 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]." 
3931                                 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
3932                 }
3933
3934                 $result = db_query($link, $query);
3935                 $first_id = db_fetch_result($result, 0, "id"); */
3936
3937                 //AND post_int_id >= '$first_id'
3938                 $query = "SELECT tag_name, COUNT(post_int_id) AS count 
3939                         FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]." 
3940                         GROUP BY tag_name ORDER BY count DESC LIMIT 50";
3941
3942                 $result = db_query($link, $query);
3943
3944                 $tags = array();
3945
3946                 while ($line = db_fetch_assoc($result)) {
3947                         $tags[$line["tag_name"]] = $line["count"];
3948                 }
3949
3950                 ksort($tags);
3951
3952                 $max_size = 32; // max font size in pixels
3953                 $min_size = 11; // min font size in pixels
3954                    
3955                 // largest and smallest array values
3956                 $max_qty = max(array_values($tags));
3957                 $min_qty = min(array_values($tags));
3958                    
3959                 // find the range of values
3960                 $spread = $max_qty - $min_qty;
3961                 if ($spread == 0) { // we don't want to divide by zero
3962                                 $spread = 1;
3963                 }
3964                    
3965                 // set the font-size increment
3966                 $step = ($max_size - $min_size) / ($spread);
3967                    
3968                 // loop through the tag array
3969                 foreach ($tags as $key => $value) {
3970                         // calculate font-size
3971                         // find the $value in excess of $min_qty
3972                         // multiply by the font-size increment ($size)
3973                         // and add the $min_size set above
3974                         $size = round($min_size + (($value - $min_qty) * $step));
3975                    
3976                         echo "<a href=\"javascript:viewfeed('$key') \" style=\"font-size: " . 
3977                                 $size . "px\" title=\"$value articles tagged with " . 
3978                                 $key . '">' . $key . '</a> ';
3979                 }
3980         }
3981
3982         function print_checkpoint($n, $s) {
3983                 $ts = getmicrotime();   
3984                 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3985                 return $ts;
3986         }
3987
3988         function sanitize_tag($tag) {
3989                 $tag = trim($tag);
3990
3991                 $tag = mb_strtolower($tag, 'utf-8');
3992
3993                 $tag = str_replace('\"', "", $tag);     
3994                 $tag = str_replace('"', "", $tag);      
3995                 $tag = str_replace("+", " ", $tag);     
3996                 $tag = str_replace("technorati tag: ", "", $tag);
3997
3998                 return $tag;
3999         }
4000 ?>