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