]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
implement preferred time for sending out digests
[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 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
705 $pwd_hash = encrypt_password($password, $salt, true);
706
707 $query2 = "INSERT INTO ttrss_users
708 (login,access_level,last_login,created,pwd_hash,salt)
709 VALUES ('$login', 0, null, NOW(), '$pwd_hash','$salt')";
710 db_query($link, $query2);
711 }
712 }
713
714 } else if (get_schema_version($link) > 87) {
715 $result = db_query($link, "SELECT salt FROM ttrss_users WHERE
716 login = '$login'");
717
718 if (db_num_rows($result) != 1) {
719 return false;
720 }
721
722 $salt = db_fetch_result($result, 0, "salt");
723
724 if ($salt == "") {
725
726 $query = "SELECT id,login,access_level,pwd_hash
727 FROM ttrss_users WHERE
728 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
729 pwd_hash = '$pwd_hash2')";
730
731 // verify and upgrade password to new salt base
732
733 $result = db_query($link, $query);
734
735 if (db_num_rows($result) == 1) {
736 // upgrade password to MODE2
737
738 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
739 $pwd_hash = encrypt_password($password, $salt, true);
740
741 db_query($link, "UPDATE ttrss_users SET
742 pwd_hash = '$pwd_hash', salt = '$salt' WHERE login = '$login'");
743
744 $query = "SELECT id,login,access_level,pwd_hash
745 FROM ttrss_users WHERE
746 login = '$login' AND pwd_hash = '$pwd_hash'";
747
748 } else {
749 return false;
750 }
751
752 } else {
753
754 $pwd_hash = encrypt_password($password, $salt, true);
755
756 $query = "SELECT id,login,access_level,pwd_hash
757 FROM ttrss_users WHERE
758 login = '$login' AND pwd_hash = '$pwd_hash'";
759
760 }
761 } else {
762 $query = "SELECT id,login,access_level,pwd_hash
763 FROM ttrss_users WHERE
764 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
765 pwd_hash = '$pwd_hash2')";
766 }
767
768 $result = db_query($link, $query);
769
770 if (db_num_rows($result) == 1) {
771 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
772 $_SESSION["name"] = db_fetch_result($result, 0, "login");
773 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
774 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
775
776 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
777 $_SESSION["uid"]);
778
779
780 // LemonLDAP can send user informations via HTTP HEADER
781 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER){
782 // update user name
783 $fullname = $_SERVER['HTTP_USER_NAME'] ? $_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
784 if ($fullname){
785 $fullname = db_escape_string($fullname);
786 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
787 $_SESSION["uid"]);
788 }
789 // update user mail
790 $email = $_SERVER['HTTP_USER_MAIL'] ? $_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
791 if ($email){
792 $email = db_escape_string($email);
793 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
794 $_SESSION["uid"]);
795 }
796 }
797
798 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
799 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
800
801 $_SESSION["last_version_check"] = time();
802
803 initialize_user_prefs($link, $_SESSION["uid"]);
804
805 return true;
806 }
807
808 return false;
809
810 } else {
811
812 $_SESSION["uid"] = 1;
813 $_SESSION["name"] = "admin";
814
815 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
816
817 initialize_user_prefs($link, $_SESSION["uid"]);
818
819 return true;
820 }
821 }
822
823 function make_password($length = 8) {
824
825 $password = "";
826 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
827
828 $i = 0;
829
830 while ($i < $length) {
831 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
832
833 if (!strstr($password, $char)) {
834 $password .= $char;
835 $i++;
836 }
837 }
838 return $password;
839 }
840
841 // this is called after user is created to initialize default feeds, labels
842 // or whatever else
843
844 // user preferences are checked on every login, not here
845
846 function initialize_user($link, $uid) {
847
848 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
849 values ('$uid', 'Tiny Tiny RSS: New Releases',
850 'http://tt-rss.org/releases.rss')");
851
852 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
853 values ('$uid', 'Tiny Tiny RSS: Forum',
854 'http://tt-rss.org/forum/rss.php')");
855 }
856
857 function logout_user() {
858 session_destroy();
859 if (isset($_COOKIE[session_name()])) {
860 setcookie(session_name(), '', time()-42000, '/');
861 }
862 }
863
864 function validate_csrf($csrf_token) {
865 return $csrf_token == $_SESSION['csrf_token'];
866 }
867
868 function validate_session($link) {
869 if (SINGLE_USER_MODE) return true;
870
871 $check_ip = $_SESSION['ip_address'];
872
873 switch (SESSION_CHECK_ADDRESS) {
874 case 0:
875 $check_ip = '';
876 break;
877 case 1:
878 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
879 break;
880 case 2:
881 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
882 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
883 break;
884 };
885
886 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
887 $_SESSION["login_error_msg"] =
888 __("Session failed to validate (incorrect IP)");
889 return false;
890 }
891
892 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
893 return false;
894
895 if ($_SESSION["uid"]) {
896
897 $result = db_query($link,
898 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
899
900 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
901
902 if ($pwd_hash != $_SESSION["pwd_hash"]) {
903 return false;
904 }
905 }
906
907 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
908
909 //print_r($_SESSION);
910
911 if (time() > $_SESSION["cookie_lifetime"]) {
912 return false;
913 }
914 } */
915
916 return true;
917 }
918
919 function login_sequence($link, $mobile = false) {
920 $_SESSION["prefs_cache"] = array();
921
922 if (!SINGLE_USER_MODE) {
923
924 $login_action = $_POST["login_action"];
925
926 # try to authenticate user if called from login form
927 if ($login_action == "do_login") {
928 $login = db_escape_string($_POST["login"]);
929 $password = $_POST["password"];
930 $remember_me = $_POST["remember_me"];
931
932 if (authenticate_user($link, $login, $password)) {
933 $_POST["password"] = "";
934
935 $_SESSION["language"] = $_POST["language"];
936 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
937 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
938
939 if ($_POST["profile"]) {
940
941 $profile = db_escape_string($_POST["profile"]);
942
943 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
944 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
945
946 if (db_num_rows($result) != 0) {
947 $_SESSION["profile"] = $profile;
948 $_SESSION["prefs_cache"] = array();
949 }
950 }
951
952 if ($_REQUEST['return']) {
953 header("Location: " . $_REQUEST['return']);
954 } else {
955 header("Location: " . $_SERVER["REQUEST_URI"]);
956 }
957
958 exit;
959
960 return;
961 } else {
962 $_SESSION["login_error_msg"] = __("Incorrect username or password");
963 }
964 }
965
966 if (!$_SESSION["uid"] || !validate_session($link)) {
967
968 if (get_remote_user($link) && AUTO_LOGIN) {
969 authenticate_user($link, get_remote_user($link), null);
970 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
971 } else {
972 render_login_form($link, $mobile);
973 //header("Location: login.php");
974 exit;
975 }
976 } else {
977 /* bump login timestamp */
978 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
979 $_SESSION["uid"]);
980
981 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
982 setcookie("ttrss_lang", $_SESSION["language"],
983 time() + SESSION_COOKIE_LIFETIME);
984 }
985
986 // try to remove possible duplicates from feed counter cache
987 // ccache_cleanup($link, $_SESSION["uid"]);
988 }
989
990 } else {
991 return authenticate_user($link, "admin", null);
992 }
993 }
994
995 function truncate_string($str, $max_len, $suffix = '&hellip;') {
996 if (mb_strlen($str, "utf-8") > $max_len - 3) {
997 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
998 } else {
999 return $str;
1000 }
1001 }
1002
1003 function theme_image($link, $filename) {
1004 if ($link) {
1005 $theme_path = get_user_theme_path($link);
1006
1007 if ($theme_path && is_file($theme_path.$filename)) {
1008 return $theme_path.$filename;
1009 } else {
1010 return $filename;
1011 }
1012 } else {
1013 return $filename;
1014 }
1015 }
1016
1017 function get_user_theme($link) {
1018
1019 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1020 $theme_name = get_pref($link, "_THEME_ID");
1021 if (is_dir("themes/$theme_name")) {
1022 return $theme_name;
1023 } else {
1024 return '';
1025 }
1026 } else {
1027 return '';
1028 }
1029
1030 }
1031
1032 function get_user_theme_path($link) {
1033 $theme_path = '';
1034
1035 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1036 $theme_name = get_pref($link, "_THEME_ID");
1037
1038 if ($theme_name && is_dir("themes/$theme_name")) {
1039 $theme_path = "themes/$theme_name/";
1040 } else {
1041 $theme_name = '';
1042 }
1043 } else {
1044 $theme_path = '';
1045 }
1046
1047 if ($theme_path) {
1048 if (is_file("$theme_path/theme.ini")) {
1049 $ini = parse_ini_file("$theme_path/theme.ini", true);
1050 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
1051 return $theme_path;
1052 }
1053 }
1054 }
1055 return '';
1056 }
1057
1058 function get_user_theme_options($link) {
1059 $t = get_user_theme_path($link);
1060
1061 if ($t) {
1062 if (is_file("$t/theme.ini")) {
1063 $ini = parse_ini_file("$t/theme.ini", true);
1064 if ($ini['theme']['version']) {
1065 return $ini['theme']['options'];
1066 }
1067 }
1068 }
1069 return '';
1070 }
1071
1072 function print_theme_includes($link) {
1073
1074 $t = get_user_theme_path($link);
1075 $time = time();
1076
1077 if ($t) {
1078 print "<link rel=\"stylesheet\" type=\"text/css\"
1079 href=\"$t/theme.css?$time \">";
1080 if (file_exists("$t/theme.js")) {
1081 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
1082 </script>";
1083 }
1084 }
1085 }
1086
1087 function get_all_themes() {
1088 $themes = glob("themes/*");
1089
1090 asort($themes);
1091
1092 $rv = array();
1093
1094 foreach ($themes as $t) {
1095 if (is_file("$t/theme.ini")) {
1096 $ini = parse_ini_file("$t/theme.ini", true);
1097 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
1098 !$ini['theme']['disabled']) {
1099 $entry = array();
1100 $entry["path"] = $t;
1101 $entry["base"] = basename($t);
1102 $entry["name"] = $ini['theme']['name'];
1103 $entry["version"] = $ini['theme']['version'];
1104 $entry["author"] = $ini['theme']['author'];
1105 $entry["options"] = $ini['theme']['options'];
1106 array_push($rv, $entry);
1107 }
1108 }
1109 }
1110
1111 return $rv;
1112 }
1113
1114 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
1115
1116 try {
1117 $source_tz = new DateTimeZone($source_tz);
1118 } catch (Exception $e) {
1119 $source_tz = new DateTimeZone('UTC');
1120 }
1121
1122 try {
1123 $dest_tz = new DateTimeZone($dest_tz);
1124 } catch (Exception $e) {
1125 $dest_tz = new DateTimeZone('UTC');
1126 }
1127
1128 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
1129 return $dt->format('U') + $dest_tz->getOffset($dt);
1130 }
1131
1132 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
1133 $no_smart_dt = false) {
1134
1135 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1136 if (!$timestamp) $timestamp = '1970-01-01 0:00';
1137
1138 global $utc_tz;
1139 global $tz_offset;
1140
1141 # We store date in UTC internally
1142 $dt = new DateTime($timestamp, $utc_tz);
1143
1144 if ($tz_offset == -1) {
1145
1146 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
1147
1148 try {
1149 $user_tz = new DateTimeZone($user_tz_string);
1150 } catch (Exception $e) {
1151 $user_tz = $utc_tz;
1152 }
1153
1154 $tz_offset = $user_tz->getOffset($dt);
1155 }
1156
1157 $user_timestamp = $dt->format('U') + $tz_offset;
1158
1159 if (!$no_smart_dt) {
1160 return smart_date_time($link, $user_timestamp,
1161 $tz_offset, $owner_uid);
1162 } else {
1163 if ($long)
1164 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1165 else
1166 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1167
1168 return date($format, $user_timestamp);
1169 }
1170 }
1171
1172 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
1173 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1174
1175 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
1176 return date("G:i", $timestamp);
1177 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
1178 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1179 return date($format, $timestamp);
1180 } else {
1181 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1182 return date($format, $timestamp);
1183 }
1184 }
1185
1186 function sql_bool_to_bool($s) {
1187 if ($s == "t" || $s == "1" || $s == "true") {
1188 return true;
1189 } else {
1190 return false;
1191 }
1192 }
1193
1194 function bool_to_sql_bool($s) {
1195 if ($s) {
1196 return "true";
1197 } else {
1198 return "false";
1199 }
1200 }
1201
1202 // Session caching removed due to causing wrong redirects to upgrade
1203 // script when get_schema_version() is called on an obsolete session
1204 // created on a previous schema version.
1205 function get_schema_version($link, $nocache = false) {
1206 global $schema_version;
1207
1208 if (!$schema_version) {
1209 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1210 $version = db_fetch_result($result, 0, "schema_version");
1211 $schema_version = $version;
1212 return $version;
1213 } else {
1214 return $schema_version;
1215 }
1216 }
1217
1218 function sanity_check($link) {
1219 require_once 'errors.php';
1220
1221 $error_code = 0;
1222 $schema_version = get_schema_version($link, true);
1223
1224 if ($schema_version != SCHEMA_VERSION) {
1225 $error_code = 5;
1226 }
1227
1228 if (DB_TYPE == "mysql") {
1229 $result = db_query($link, "SELECT true", false);
1230 if (db_num_rows($result) != 1) {
1231 $error_code = 10;
1232 }
1233 }
1234
1235 if (db_escape_string("testTEST") != "testTEST") {
1236 $error_code = 12;
1237 }
1238
1239 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1240 }
1241
1242 function file_is_locked($filename) {
1243 if (function_exists('flock')) {
1244 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1245 if ($fp) {
1246 if (flock($fp, LOCK_EX | LOCK_NB)) {
1247 flock($fp, LOCK_UN);
1248 fclose($fp);
1249 return false;
1250 }
1251 fclose($fp);
1252 return true;
1253 } else {
1254 return false;
1255 }
1256 }
1257 return true; // consider the file always locked and skip the test
1258 }
1259
1260 function make_lockfile($filename) {
1261 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1262
1263 if (flock($fp, LOCK_EX | LOCK_NB)) {
1264 if (function_exists('posix_getpid')) {
1265 fwrite($fp, posix_getpid() . "\n");
1266 }
1267 return $fp;
1268 } else {
1269 return false;
1270 }
1271 }
1272
1273 function make_stampfile($filename) {
1274 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1275
1276 if (flock($fp, LOCK_EX | LOCK_NB)) {
1277 fwrite($fp, time() . "\n");
1278 flock($fp, LOCK_UN);
1279 fclose($fp);
1280 return true;
1281 } else {
1282 return false;
1283 }
1284 }
1285
1286 function sql_random_function() {
1287 if (DB_TYPE == "mysql") {
1288 return "RAND()";
1289 } else {
1290 return "RANDOM()";
1291 }
1292 }
1293
1294 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
1295
1296 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1297
1298 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1299
1300 if (is_numeric($feed)) {
1301 if ($cat_view) {
1302
1303 if ($feed >= 0) {
1304
1305 if ($feed > 0) {
1306 $cat_qpart = "cat_id = '$feed'";
1307 } else {
1308 $cat_qpart = "cat_id IS NULL";
1309 }
1310
1311 $tmp_result = db_query($link, "SELECT id
1312 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
1313
1314 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1315
1316 $tmp_feed = $tmp_line["id"];
1317
1318 db_query($link, "UPDATE ttrss_user_entries
1319 SET unread = false,last_read = NOW()
1320 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
1321 }
1322 } else if ($feed == -2) {
1323
1324 db_query($link, "UPDATE ttrss_user_entries
1325 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1326 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1327 AND unread = true AND owner_uid = $owner_uid");
1328 }
1329
1330 } else if ($feed > 0) {
1331
1332 db_query($link, "UPDATE ttrss_user_entries
1333 SET unread = false,last_read = NOW()
1334 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
1335
1336 } else if ($feed < 0 && $feed > -10) { // special, like starred
1337
1338 if ($feed == -1) {
1339 db_query($link, "UPDATE ttrss_user_entries
1340 SET unread = false,last_read = NOW()
1341 WHERE marked = true AND owner_uid = $owner_uid");
1342 }
1343
1344 if ($feed == -2) {
1345 db_query($link, "UPDATE ttrss_user_entries
1346 SET unread = false,last_read = NOW()
1347 WHERE published = true AND owner_uid = $owner_uid");
1348 }
1349
1350 if ($feed == -3) {
1351
1352 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1353
1354 if (DB_TYPE == "pgsql") {
1355 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1356 } else {
1357 $match_part = "updated > DATE_SUB(NOW(),
1358 INTERVAL $intl HOUR) ";
1359 }
1360
1361 $result = db_query($link, "SELECT id FROM ttrss_entries,
1362 ttrss_user_entries WHERE $match_part AND
1363 unread = true AND
1364 ttrss_user_entries.ref_id = ttrss_entries.id AND
1365 owner_uid = $owner_uid");
1366
1367 $affected_ids = array();
1368
1369 while ($line = db_fetch_assoc($result)) {
1370 array_push($affected_ids, $line["id"]);
1371 }
1372
1373 catchupArticlesById($link, $affected_ids, 0);
1374 }
1375
1376 if ($feed == -4) {
1377 db_query($link, "UPDATE ttrss_user_entries
1378 SET unread = false,last_read = NOW()
1379 WHERE owner_uid = $owner_uid");
1380 }
1381
1382 } else if ($feed < -10) { // label
1383
1384 $label_id = -$feed - 11;
1385
1386 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1387 SET unread = false, last_read = NOW()
1388 WHERE label_id = '$label_id' AND unread = true
1389 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1390
1391 }
1392
1393 ccache_update($link, $feed, $owner_uid, $cat_view);
1394
1395 } else { // tag
1396 db_query($link, "BEGIN");
1397
1398 $tag_name = db_escape_string($feed);
1399
1400 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1401 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1402
1403 while ($line = db_fetch_assoc($result)) {
1404 db_query($link, "UPDATE ttrss_user_entries SET
1405 unread = false, last_read = NOW()
1406 WHERE int_id = " . $line["post_int_id"]);
1407 }
1408 db_query($link, "COMMIT");
1409 }
1410 }
1411
1412 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1413
1414 if (!$omode) $omode = "flc";
1415
1416 $data = getGlobalCounters($link);
1417
1418 $data = array_merge($data, getVirtCounters($link));
1419
1420 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1421 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1422 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1423 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1424
1425 return $data;
1426 }
1427
1428 function getCategoryTitle($link, $cat_id) {
1429
1430 if ($cat_id == -1) {
1431 return __("Special");
1432 } else if ($cat_id == -2) {
1433 return __("Labels");
1434 } else {
1435
1436 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1437 id = '$cat_id'");
1438
1439 if (db_num_rows($result) == 1) {
1440 return db_fetch_result($result, 0, "title");
1441 } else {
1442 return "Uncategorized";
1443 }
1444 }
1445 }
1446
1447
1448 function getCategoryCounters($link) {
1449 $ret_arr = array();
1450
1451 /* Labels category */
1452
1453 $cv = array("id" => -2, "kind" => "cat",
1454 "counter" => getCategoryUnread($link, -2));
1455
1456 array_push($ret_arr, $cv);
1457
1458 $age_qpart = getMaxAgeSubquery();
1459
1460 $result = db_query($link, "SELECT id AS cat_id, value AS unread
1461 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1462 WHERE ttrss_cat_counters_cache.feed_id = id AND
1463 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1464
1465 while ($line = db_fetch_assoc($result)) {
1466 $line["cat_id"] = (int) $line["cat_id"];
1467
1468 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1469 "counter" => $line["unread"]);
1470
1471 array_push($ret_arr, $cv);
1472 }
1473
1474 /* Special case: NULL category doesn't actually exist in the DB */
1475
1476 $cv = array("id" => 0, "kind" => "cat",
1477 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
1478
1479 array_push($ret_arr, $cv);
1480
1481 return $ret_arr;
1482 }
1483
1484 function getCategoryUnread($link, $cat, $owner_uid = false) {
1485
1486 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1487
1488 if ($cat >= 0) {
1489
1490 if ($cat != 0) {
1491 $cat_query = "cat_id = '$cat'";
1492 } else {
1493 $cat_query = "cat_id IS NULL";
1494 }
1495
1496 $age_qpart = getMaxAgeSubquery();
1497
1498 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1499 AND owner_uid = " . $owner_uid);
1500
1501 $cat_feeds = array();
1502 while ($line = db_fetch_assoc($result)) {
1503 array_push($cat_feeds, "feed_id = " . $line["id"]);
1504 }
1505
1506 if (count($cat_feeds) == 0) return 0;
1507
1508 $match_part = implode(" OR ", $cat_feeds);
1509
1510 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1511 FROM ttrss_user_entries,ttrss_entries
1512 WHERE unread = true AND ($match_part) AND id = ref_id
1513 AND $age_qpart AND owner_uid = " . $owner_uid);
1514
1515 $unread = 0;
1516
1517 # this needs to be rewritten
1518 while ($line = db_fetch_assoc($result)) {
1519 $unread += $line["unread"];
1520 }
1521
1522 return $unread;
1523 } else if ($cat == -1) {
1524 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
1525 } else if ($cat == -2) {
1526
1527 $result = db_query($link, "
1528 SELECT COUNT(unread) AS unread FROM
1529 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
1530 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
1531 ttrss_labels2.owner_uid = '$owner_uid'
1532 AND unread = true AND feed_id = ttrss_feeds.id
1533 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1534
1535 $unread = db_fetch_result($result, 0, "unread");
1536
1537 return $unread;
1538
1539 }
1540 }
1541
1542 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
1543 if (DB_TYPE == "pgsql") {
1544 return "ttrss_entries.date_updated >
1545 NOW() - INTERVAL '$days days'";
1546 } else {
1547 return "ttrss_entries.date_updated >
1548 DATE_SUB(NOW(), INTERVAL $days DAY)";
1549 }
1550 }
1551
1552 function getFeedUnread($link, $feed, $is_cat = false) {
1553 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1554 }
1555
1556 function getLabelUnread($link, $label_id, $owner_uid = false) {
1557 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1558
1559 $result = db_query($link, "
1560 SELECT COUNT(unread) AS unread FROM
1561 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
1562 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
1563 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
1564 AND unread = true AND feed_id = ttrss_feeds.id
1565 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1566
1567 if (db_num_rows($result) != 0) {
1568 return db_fetch_result($result, 0, "unread");
1569 } else {
1570 return 0;
1571 }
1572 }
1573
1574 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1575 $owner_uid = false) {
1576
1577 $n_feed = (int) $feed;
1578
1579 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1580
1581 if ($unread_only) {
1582 $unread_qpart = "unread = true";
1583 } else {
1584 $unread_qpart = "true";
1585 }
1586
1587 $age_qpart = getMaxAgeSubquery();
1588
1589 if ($is_cat) {
1590 return getCategoryUnread($link, $n_feed, $owner_uid);
1591 } if ($feed != "0" && $n_feed == 0) {
1592
1593 $feed = db_escape_string($feed);
1594
1595 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1596 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1597 AND ref_id = id AND $age_qpart
1598 AND $unread_qpart)) AS count FROM ttrss_tags
1599 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1600 return db_fetch_result($result, 0, "count");
1601
1602 } else if ($n_feed == -1) {
1603 $match_part = "marked = true";
1604 } else if ($n_feed == -2) {
1605 $match_part = "published = true";
1606 } else if ($n_feed == -3) {
1607 $match_part = "unread = true AND score >= 0";
1608
1609 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1610
1611 if (DB_TYPE == "pgsql") {
1612 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1613 } else {
1614 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1615 }
1616 } else if ($n_feed == -4) {
1617 $match_part = "true";
1618 } else if ($n_feed >= 0) {
1619
1620 if ($n_feed != 0) {
1621 $match_part = "feed_id = '$n_feed'";
1622 } else {
1623 $match_part = "feed_id IS NULL";
1624 }
1625
1626 } else if ($feed < -10) {
1627
1628 $label_id = -$feed - 11;
1629
1630 return getLabelUnread($link, $label_id, $owner_uid);
1631
1632 }
1633
1634 if ($match_part) {
1635
1636 if ($n_feed != 0) {
1637 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
1638 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
1639 } else {
1640 $from_qpart = "ttrss_user_entries,ttrss_entries";
1641 $feeds_qpart = '';
1642 }
1643
1644 $query = "SELECT count(int_id) AS unread
1645 FROM $from_qpart WHERE
1646 ttrss_user_entries.ref_id = ttrss_entries.id AND
1647 $age_qpart AND
1648 $feeds_qpart
1649 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1650
1651 $result = db_query($link, $query);
1652
1653 } else {
1654
1655 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1656 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1657 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1658 AND $unread_qpart AND $age_qpart AND
1659 ttrss_tags.owner_uid = " . $owner_uid);
1660 }
1661
1662 $unread = db_fetch_result($result, 0, "unread");
1663
1664 return $unread;
1665 }
1666
1667 function getGlobalUnread($link, $user_id = false) {
1668
1669 if (!$user_id) {
1670 $user_id = $_SESSION["uid"];
1671 }
1672
1673 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1674 WHERE owner_uid = '$user_id' AND feed_id > 0");
1675
1676 $c_id = db_fetch_result($result, 0, "c_id");
1677
1678 return $c_id;
1679 }
1680
1681 function getGlobalCounters($link, $global_unread = -1) {
1682 $ret_arr = array();
1683
1684 if ($global_unread == -1) {
1685 $global_unread = getGlobalUnread($link);
1686 }
1687
1688 $cv = array("id" => "global-unread",
1689 "counter" => $global_unread);
1690
1691 array_push($ret_arr, $cv);
1692
1693 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1694 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1695
1696 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1697
1698 $cv = array("id" => "subscribed-feeds",
1699 "counter" => $subscribed_feeds);
1700
1701 array_push($ret_arr, $cv);
1702
1703 return $ret_arr;
1704 }
1705
1706 function getTagCounters($link) {
1707
1708 $ret_arr = array();
1709
1710 $age_qpart = getMaxAgeSubquery();
1711
1712 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1713 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1714 AND ref_id = id AND $age_qpart
1715 AND unread = true)) AS count FROM ttrss_tags
1716 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1717 ORDER BY count DESC LIMIT 55");
1718
1719 $tags = array();
1720
1721 while ($line = db_fetch_assoc($result)) {
1722 $tags[$line["tag_name"]] += $line["count"];
1723 }
1724
1725 foreach (array_keys($tags) as $tag) {
1726 $unread = $tags[$tag];
1727 $tag = htmlspecialchars($tag);
1728
1729 $cv = array("id" => $tag,
1730 "kind" => "tag",
1731 "counter" => $unread);
1732
1733 array_push($ret_arr, $cv);
1734 }
1735
1736 return $ret_arr;
1737 }
1738
1739 function getVirtCounters($link) {
1740
1741 $ret_arr = array();
1742
1743 for ($i = 0; $i >= -4; $i--) {
1744
1745 $count = getFeedUnread($link, $i);
1746
1747 $cv = array("id" => $i,
1748 "counter" => $count);
1749
1750 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1751 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1752
1753 array_push($ret_arr, $cv);
1754 }
1755
1756 return $ret_arr;
1757 }
1758
1759 function getLabelCounters($link, $descriptions = false) {
1760
1761 $ret_arr = array();
1762
1763 $age_qpart = getMaxAgeSubquery();
1764
1765 $owner_uid = $_SESSION["uid"];
1766
1767 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1768 WHERE owner_uid = '$owner_uid'");
1769
1770 while ($line = db_fetch_assoc($result)) {
1771
1772 $id = -$line["id"] - 11;
1773
1774 $label_name = $line["caption"];
1775 $count = getFeedUnread($link, $id);
1776
1777 $cv = array("id" => $id,
1778 "counter" => $count);
1779
1780 if ($descriptions)
1781 $cv["description"] = $label_name;
1782
1783 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1784 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1785
1786 array_push($ret_arr, $cv);
1787 }
1788
1789 return $ret_arr;
1790 }
1791
1792 function getFeedCounters($link, $active_feed = false) {
1793
1794 $ret_arr = array();
1795
1796 $age_qpart = getMaxAgeSubquery();
1797
1798 $query = "SELECT ttrss_feeds.id,
1799 ttrss_feeds.title,
1800 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1801 last_error, value AS count
1802 FROM ttrss_feeds, ttrss_counters_cache
1803 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1804 AND ttrss_counters_cache.feed_id = id";
1805
1806 $result = db_query($link, $query);
1807 $fctrs_modified = false;
1808
1809 while ($line = db_fetch_assoc($result)) {
1810
1811 $id = $line["id"];
1812 $count = $line["count"];
1813 $last_error = htmlspecialchars($line["last_error"]);
1814
1815 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1816
1817 $has_img = feed_has_icon($id);
1818
1819 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1820 $last_updated = '';
1821
1822 $cv = array("id" => $id,
1823 "updated" => $last_updated,
1824 "counter" => $count,
1825 "has_img" => (int) $has_img);
1826
1827 if ($last_error)
1828 $cv["error"] = $last_error;
1829
1830 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1831 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1832
1833 if ($active_feed && $id == $active_feed)
1834 $cv["title"] = truncate_string($line["title"], 30);
1835
1836 array_push($ret_arr, $cv);
1837
1838 }
1839
1840 return $ret_arr;
1841 }
1842
1843 function get_pgsql_version($link) {
1844 $result = db_query($link, "SELECT version() AS version");
1845 $version = explode(" ", db_fetch_result($result, 0, "version"));
1846 return $version[1];
1847 }
1848
1849 /**
1850 * @return integer Status code:
1851 * 0 - OK, Feed already exists
1852 * 1 - OK, Feed added
1853 * 2 - Invalid URL
1854 * 3 - URL content is HTML, no feeds available
1855 * 4 - URL content is HTML which contains multiple feeds.
1856 * Here you should call extractfeedurls in rpc-backend
1857 * to get all possible feeds.
1858 * 5 - Couldn't download the URL content.
1859 */
1860 function subscribe_to_feed($link, $url, $cat_id = 0,
1861 $auth_login = '', $auth_pass = '', $need_auth = false) {
1862
1863 require_once "include/rssfuncs.php";
1864
1865 $url = fix_url($url);
1866
1867 if (!$url || !validate_feed_url($url)) return 2;
1868
1869 $update_method = 0;
1870
1871 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
1872 WHERE id = ".$_SESSION['uid']);
1873
1874 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
1875
1876 if (!$need_auth || !$has_oauth || strpos($url, '://api.twitter.com') === false) {
1877 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
1878
1879 if (url_is_html($url, $auth_login, $auth_pass)) {
1880 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
1881 if (count($feedUrls) == 0) {
1882 return 3;
1883 } else if (count($feedUrls) > 1) {
1884 return 4;
1885 }
1886 //use feed url as new URL
1887 $url = key($feedUrls);
1888 }
1889
1890 } else {
1891 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
1892 return 5;
1893
1894 $update_method = 3;
1895 }
1896 if ($cat_id == "0" || !$cat_id) {
1897 $cat_qpart = "NULL";
1898 } else {
1899 $cat_qpart = "'$cat_id'";
1900 }
1901
1902 $result = db_query($link,
1903 "SELECT id FROM ttrss_feeds
1904 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1905
1906 if (db_num_rows($result) == 0) {
1907 $result = db_query($link,
1908 "INSERT INTO ttrss_feeds
1909 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1910 VALUES ('".$_SESSION["uid"]."', '$url',
1911 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1912
1913 $result = db_query($link,
1914 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1915 AND owner_uid = " . $_SESSION["uid"]);
1916
1917 $feed_id = db_fetch_result($result, 0, "id");
1918
1919 if ($feed_id) {
1920 update_rss_feed($link, $feed_id, true);
1921 }
1922
1923 return 1;
1924 } else {
1925 return 0;
1926 }
1927 }
1928
1929 function print_feed_select($link, $id, $default_id = "",
1930 $attributes = "", $include_all_feeds = true) {
1931
1932 print "<select id=\"$id\" name=\"$id\" $attributes>";
1933 if ($include_all_feeds) {
1934 print "<option value=\"0\">".__('All feeds')."</option>";
1935 }
1936
1937 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1938 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1939
1940 if (db_num_rows($result) > 0 && $include_all_feeds) {
1941 print "<option disabled>--------</option>";
1942 }
1943
1944 while ($line = db_fetch_assoc($result)) {
1945 if ($line["id"] == $default_id) {
1946 $is_selected = "selected=\"1\"";
1947 } else {
1948 $is_selected = "";
1949 }
1950
1951 $title = truncate_string(htmlspecialchars($line["title"]), 40);
1952
1953 printf("<option $is_selected value='%d'>%s</option>",
1954 $line["id"], $title);
1955 }
1956
1957 print "</select>";
1958 }
1959
1960 function print_feed_cat_select($link, $id, $default_id = "",
1961 $attributes = "", $include_all_cats = true) {
1962
1963 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1964
1965 if ($include_all_cats) {
1966 print "<option value=\"0\">".__('Uncategorized')."</option>";
1967 }
1968
1969 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1970 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1971
1972 if (db_num_rows($result) > 0 && $include_all_cats) {
1973 print "<option disabled=\"1\">--------</option>";
1974 }
1975
1976 while ($line = db_fetch_assoc($result)) {
1977 if ($line["id"] == $default_id) {
1978 $is_selected = "selected=\"1\"";
1979 } else {
1980 $is_selected = "";
1981 }
1982
1983 if ($line["title"])
1984 printf("<option $is_selected value='%d'>%s</option>",
1985 $line["id"], htmlspecialchars($line["title"]));
1986 }
1987
1988 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
1989
1990 print "</select>";
1991 }
1992
1993 function checkbox_to_sql_bool($val) {
1994 return ($val == "on") ? "true" : "false";
1995 }
1996
1997 function getFeedCatTitle($link, $id) {
1998 if ($id == -1) {
1999 return __("Special");
2000 } else if ($id < -10) {
2001 return __("Labels");
2002 } else if ($id > 0) {
2003 $result = db_query($link, "SELECT ttrss_feed_categories.title
2004 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2005 cat_id = ttrss_feed_categories.id");
2006 if (db_num_rows($result) == 1) {
2007 return db_fetch_result($result, 0, "title");
2008 } else {
2009 return __("Uncategorized");
2010 }
2011 } else {
2012 return "getFeedCatTitle($id) failed";
2013 }
2014
2015 }
2016
2017 function getFeedIcon($id) {
2018 switch ($id) {
2019 case 0:
2020 return "images/archive.png";
2021 break;
2022 case -1:
2023 return "images/mark_set.png";
2024 break;
2025 case -2:
2026 return "images/pub_set.png";
2027 break;
2028 case -3:
2029 return "images/fresh.png";
2030 break;
2031 case -4:
2032 return "images/tag.png";
2033 break;
2034 default:
2035 if ($id < -10) {
2036 return "images/label.png";
2037 } else {
2038 if (file_exists(ICONS_DIR . "/$id.ico"))
2039 return ICONS_URL . "/$id.ico";
2040 }
2041 break;
2042 }
2043 }
2044
2045 function getFeedTitle($link, $id) {
2046 if ($id == -1) {
2047 return __("Starred articles");
2048 } else if ($id == -2) {
2049 return __("Published articles");
2050 } else if ($id == -3) {
2051 return __("Fresh articles");
2052 } else if ($id == -4) {
2053 return __("All articles");
2054 } else if ($id === 0 || $id === "0") {
2055 return __("Archived articles");
2056 } else if ($id < -10) {
2057 $label_id = -$id - 11;
2058 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2059 if (db_num_rows($result) == 1) {
2060 return db_fetch_result($result, 0, "caption");
2061 } else {
2062 return "Unknown label ($label_id)";
2063 }
2064
2065 } else if (is_numeric($id) && $id > 0) {
2066 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2067 if (db_num_rows($result) == 1) {
2068 return db_fetch_result($result, 0, "title");
2069 } else {
2070 return "Unknown feed ($id)";
2071 }
2072 } else {
2073 return $id;
2074 }
2075 }
2076
2077 function make_init_params($link) {
2078 $params = array();
2079
2080 $params["theme"] = get_user_theme($link);
2081 $params["theme_options"] = get_user_theme_options($link);
2082
2083 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
2084 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
2085 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
2086 $params["sign_info"] = theme_image($link, "images/sign_info.png");
2087
2088 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2089 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
2090 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
2091 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
2092
2093 $params[strtolower($param)] = (int) get_pref($link, $param);
2094 }
2095
2096 $params["icons_url"] = ICONS_URL;
2097 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
2098 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
2099 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
2100 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
2101 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
2102
2103 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2104 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2105
2106 $max_feed_id = db_fetch_result($result, 0, "mid");
2107 $num_feeds = db_fetch_result($result, 0, "nf");
2108
2109 $params["max_feed_id"] = (int) $max_feed_id;
2110 $params["num_feeds"] = (int) $num_feeds;
2111
2112 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
2113
2114 $params["csrf_token"] = $_SESSION["csrf_token"];
2115
2116 return $params;
2117 }
2118
2119 function make_runtime_info($link) {
2120 $data = array();
2121
2122 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2123 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2124
2125 $max_feed_id = db_fetch_result($result, 0, "mid");
2126 $num_feeds = db_fetch_result($result, 0, "nf");
2127
2128 $data["max_feed_id"] = (int) $max_feed_id;
2129 $data["num_feeds"] = (int) $num_feeds;
2130
2131 $data['last_article_id'] = getLastArticleId($link);
2132 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2133
2134 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
2135
2136 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2137
2138 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2139
2140 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
2141
2142 if ($stamp) {
2143 $stamp_delta = time() - $stamp;
2144
2145 if ($stamp_delta > 1800) {
2146 $stamp_check = 0;
2147 } else {
2148 $stamp_check = 1;
2149 $_SESSION["daemon_stamp_check"] = time();
2150 }
2151
2152 $data['daemon_stamp_ok'] = $stamp_check;
2153
2154 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2155
2156 $data['daemon_stamp'] = $stamp_fmt;
2157 }
2158 }
2159 }
2160
2161 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
2162 $new_version_details = @check_for_update($link);
2163
2164 $data['new_version_available'] = (int) ($new_version_details != false);
2165
2166 $_SESSION["last_version_check"] = time();
2167 }
2168
2169 return $data;
2170 }
2171
2172 function search_to_sql($link, $search, $match_on) {
2173
2174 $search_query_part = "";
2175
2176 $keywords = explode(" ", $search);
2177 $query_keywords = array();
2178
2179 foreach ($keywords as $k) {
2180 if (strpos($k, "-") === 0) {
2181 $k = substr($k, 1);
2182 $not = "NOT";
2183 } else {
2184 $not = "";
2185 }
2186
2187 $commandpair = explode(":", mb_strtolower($k), 2);
2188
2189 if ($commandpair[0] == "note" && $commandpair[1]) {
2190
2191 if ($commandpair[1] == "true")
2192 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2193 else
2194 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2195
2196 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2197
2198 if ($commandpair[1] == "true")
2199 array_push($query_keywords, "($not (marked = true))");
2200 else
2201 array_push($query_keywords, "($not (marked = false))");
2202
2203 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2204
2205 if ($commandpair[1] == "true")
2206 array_push($query_keywords, "($not (published = true))");
2207 else
2208 array_push($query_keywords, "($not (published = false))");
2209
2210 } else if (strpos($k, "@") === 0) {
2211
2212 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2213 $orig_ts = strtotime(substr($k, 1));
2214 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2215
2216 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2217
2218 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2219 } else if ($match_on == "both") {
2220 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2221 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2222 } else if ($match_on == "title") {
2223 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2224 } else if ($match_on == "content") {
2225 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2226 }
2227 }
2228
2229 $search_query_part = implode("AND", $query_keywords);
2230
2231 return $search_query_part;
2232 }
2233
2234
2235 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) {
2236
2237 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2238
2239 $ext_tables_part = "";
2240
2241 if ($search) {
2242
2243 if (SPHINX_ENABLED) {
2244 $ids = join(",", @sphinx_search($search, 0, 500));
2245
2246 if ($ids)
2247 $search_query_part = "ref_id IN ($ids) AND ";
2248 else
2249 $search_query_part = "ref_id = -1 AND ";
2250
2251 } else {
2252 $search_query_part = search_to_sql($link, $search, $match_on);
2253 $search_query_part .= " AND ";
2254 }
2255
2256 } else {
2257 $search_query_part = "";
2258 }
2259
2260 if ($filter) {
2261 $filter_query_part = filter_to_sql($filter);
2262 } else {
2263 $filter_query_part = "";
2264 }
2265
2266 if ($since_id) {
2267 $since_id_part = "ttrss_entries.id > $since_id AND ";
2268 } else {
2269 $since_id_part = "";
2270 }
2271
2272 $view_query_part = "";
2273
2274 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
2275 if ($search) {
2276 $view_query_part = " ";
2277 } else if ($feed != -1) {
2278 $unread = getFeedUnread($link, $feed, $cat_view);
2279 if ($unread > 0) {
2280 $view_query_part = " unread = true AND ";
2281 }
2282 }
2283 }
2284
2285 if ($view_mode == "marked") {
2286 $view_query_part = " marked = true AND ";
2287 }
2288
2289 if ($view_mode == "published") {
2290 $view_query_part = " published = true AND ";
2291 }
2292
2293 if ($view_mode == "unread") {
2294 $view_query_part = " unread = true AND ";
2295 }
2296
2297 if ($view_mode == "updated") {
2298 $view_query_part = " (last_read is null and unread = false) AND ";
2299 }
2300
2301 if ($limit > 0) {
2302 $limit_query_part = "LIMIT " . $limit;
2303 }
2304
2305 $vfeed_query_part = "";
2306
2307 // override query strategy and enable feed display when searching globally
2308 if ($search && $search_mode == "all_feeds") {
2309 $query_strategy_part = "ttrss_entries.id > 0";
2310 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2311 /* tags */
2312 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2313 $query_strategy_part = "ttrss_entries.id > 0";
2314 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2315 id = feed_id) as feed_title,";
2316 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
2317
2318 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2319
2320 $tmp_result = false;
2321
2322 if ($cat_view) {
2323 $tmp_result = db_query($link, "SELECT id
2324 FROM ttrss_feeds WHERE cat_id = '$feed'");
2325 } else {
2326 $tmp_result = db_query($link, "SELECT id
2327 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2328 WHERE id = '$feed') AND id != '$feed'");
2329 }
2330
2331 $cat_siblings = array();
2332
2333 if (db_num_rows($tmp_result) > 0) {
2334 while ($p = db_fetch_assoc($tmp_result)) {
2335 array_push($cat_siblings, "feed_id = " . $p["id"]);
2336 }
2337
2338 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2339 $feed, implode(" OR ", $cat_siblings));
2340
2341 } else {
2342 $query_strategy_part = "ttrss_entries.id > 0";
2343 }
2344
2345 } else if ($feed > 0) {
2346
2347 if ($cat_view) {
2348
2349 if ($feed > 0) {
2350 $query_strategy_part = "cat_id = '$feed'";
2351 } else {
2352 $query_strategy_part = "cat_id IS NULL";
2353 }
2354
2355 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2356
2357 } else {
2358 $query_strategy_part = "feed_id = '$feed'";
2359 }
2360 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2361 $query_strategy_part = "feed_id IS NULL";
2362 } else if ($feed == 0 && $cat_view) { // uncategorized
2363 $query_strategy_part = "cat_id IS NULL";
2364 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2365 } else if ($feed == -1) { // starred virtual feed
2366 $query_strategy_part = "marked = true";
2367 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2368 } else if ($feed == -2) { // published virtual feed OR labels category
2369
2370 if (!$cat_view) {
2371 $query_strategy_part = "published = true";
2372 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2373 } else {
2374 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2375
2376 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2377
2378 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2379 ttrss_user_labels2.article_id = ref_id";
2380
2381 }
2382
2383 } else if ($feed == -3) { // fresh virtual feed
2384 $query_strategy_part = "unread = true AND score >= 0";
2385
2386 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2387
2388 if (DB_TYPE == "pgsql") {
2389 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2390 } else {
2391 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2392 }
2393
2394 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2395 } else if ($feed == -4) { // all articles virtual feed
2396 $query_strategy_part = "true";
2397 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2398 } else if ($feed <= -10) { // labels
2399 $label_id = -$feed - 11;
2400
2401 $query_strategy_part = "label_id = '$label_id' AND
2402 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2403 ttrss_user_labels2.article_id = ref_id";
2404
2405 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2406 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2407
2408 } else {
2409 $query_strategy_part = "id > 0"; // dumb
2410 }
2411
2412 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2413 $date_sort_field = "updated";
2414 } else {
2415 $date_sort_field = "date_entered";
2416 }
2417
2418 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2419 $order_by = "$date_sort_field";
2420 } else {
2421 $order_by = "$date_sort_field DESC";
2422 }
2423
2424 if ($view_mode != "noscores") {
2425 $order_by = "score DESC, $order_by";
2426 }
2427
2428 if ($override_order) {
2429 $order_by = $override_order;
2430 }
2431
2432 $feed_title = "";
2433
2434 if ($search) {
2435 $feed_title = "Search results";
2436 } else {
2437 if ($cat_view) {
2438 $feed_title = getCategoryTitle($link, $feed);
2439 } else {
2440 if (is_numeric($feed) && $feed > 0) {
2441 $result = db_query($link, "SELECT title,site_url,last_error
2442 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2443
2444 $feed_title = db_fetch_result($result, 0, "title");
2445 $feed_site_url = db_fetch_result($result, 0, "site_url");
2446 $last_error = db_fetch_result($result, 0, "last_error");
2447 } else {
2448 $feed_title = getFeedTitle($link, $feed);
2449 }
2450 }
2451 }
2452
2453 $content_query_part = "content as content_preview,";
2454
2455 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2456
2457 if ($feed >= 0) {
2458 $feed_kind = "Feeds";
2459 } else {
2460 $feed_kind = "Labels";
2461 }
2462
2463 if ($limit_query_part) {
2464 $offset_query_part = "OFFSET $offset";
2465 }
2466
2467 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2468 if (!$override_order) {
2469 $order_by = "ttrss_feeds.title, $order_by";
2470 }
2471 }
2472
2473 if ($feed != "0") {
2474 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2475 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2476
2477 } else {
2478 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
2479 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2480 }
2481
2482 $query = "SELECT DISTINCT
2483 date_entered,
2484 guid,
2485 ttrss_entries.id,ttrss_entries.title,
2486 updated,
2487 label_cache,
2488 tag_cache,
2489 always_display_enclosures,
2490 site_url,
2491 note,
2492 num_comments,
2493 comments,
2494 int_id,
2495 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2496 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
2497 $vfeed_query_part
2498 $content_query_part
2499 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
2500 author,score
2501 FROM
2502 $from_qpart
2503 WHERE
2504 $feed_check_qpart
2505 ttrss_user_entries.ref_id = ttrss_entries.id AND
2506 ttrss_user_entries.owner_uid = '$owner_uid' AND
2507 $search_query_part
2508 $filter_query_part
2509 $view_query_part
2510 $since_id_part
2511 $query_strategy_part ORDER BY $order_by
2512 $limit_query_part $offset_query_part";
2513
2514 if ($_REQUEST["debug"]) print $query;
2515
2516 $result = db_query($link, $query);
2517
2518 } else {
2519 // browsing by tag
2520
2521 $select_qpart = "SELECT DISTINCT " .
2522 "date_entered," .
2523 "guid," .
2524 "note," .
2525 "ttrss_entries.id as id," .
2526 "title," .
2527 "updated," .
2528 "unread," .
2529 "feed_id," .
2530 "orig_feed_id," .
2531 "marked," .
2532 "num_comments, " .
2533 "comments, " .
2534 "tag_cache," .
2535 "label_cache," .
2536 "link," .
2537 "last_read," .
2538 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
2539 $since_id_part .
2540 $vfeed_query_part .
2541 $content_query_part .
2542 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
2543 "score ";
2544
2545 $feed_kind = "Tags";
2546 $all_tags = explode(",", $feed);
2547 if ($search_mode == 'any') {
2548 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2549 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2550 $where_qpart = " WHERE " .
2551 "ref_id = ttrss_entries.id AND " .
2552 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2553 "post_int_id = int_id AND $tag_sql AND " .
2554 $view_query_part .
2555 $search_query_part .
2556 $query_strategy_part . " ORDER BY $order_by " .
2557 $limit_query_part;
2558
2559 } else {
2560 $i = 1;
2561 $sub_selects = array();
2562 $sub_ands = array();
2563 foreach ($all_tags as $term) {
2564 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");
2565 $i++;
2566 }
2567 if ($i > 2) {
2568 $x = 1;
2569 $y = 2;
2570 do {
2571 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2572 $x++;
2573 $y++;
2574 } while ($y < $i);
2575 }
2576 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2577 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2578 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2579 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2580 }
2581 // error_log("TAG SQL: " . $tag_sql);
2582 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2583
2584 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2585 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2586 }
2587
2588 return array($result, $feed_title, $feed_site_url, $last_error);
2589
2590 }
2591
2592 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2593 global $purifier;
2594
2595 if (!$owner) $owner = $_SESSION["uid"];
2596
2597 $res = trim($str); if (!$res) return '';
2598
2599 // create global Purifier object if needed
2600 if (!$purifier) {
2601 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
2602
2603 $config = HTMLPurifier_Config::createDefault();
2604
2605 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title|align|hspace],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td,span[class]";
2606
2607 $config->set('HTML.SafeObject', true);
2608 @$config->set('HTML', 'Allowed', $allowed);
2609 $config->set('Output.FlashCompat', true);
2610 $config->set('Attr.EnableID', true);
2611 if (!defined('MOBILE_VERSION')) {
2612 @$config->set('Cache', 'SerializerPath', CACHE_DIR . "/htmlpurifier");
2613 } else {
2614 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR . "/htmlpurifier");
2615 }
2616
2617 $config->set('Filter.YouTube', true);
2618
2619 $purifier = new HTMLPurifier($config);
2620 }
2621
2622 $res = $purifier->purify($res);
2623
2624 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2625 $res = preg_replace('/<img[^>]+>/is', '', $res);
2626 }
2627
2628 if (strpos($res, "href=") === false)
2629 $res = rewrite_urls($res);
2630
2631 $charset_hack = '<head>
2632 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2633 </head>';
2634
2635 $res = trim($res); if (!$res) return '';
2636
2637 libxml_use_internal_errors(true);
2638
2639 $doc = new DOMDocument();
2640 $doc->loadHTML($charset_hack . $res);
2641 $xpath = new DOMXPath($doc);
2642
2643 $entries = $xpath->query('(//a[@href]|//img[@src])');
2644 $br_inserted = 0;
2645
2646 foreach ($entries as $entry) {
2647
2648 if ($site_url) {
2649
2650 if ($entry->hasAttribute('href'))
2651 $entry->setAttribute('href',
2652 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2653
2654 if ($entry->hasAttribute('src'))
2655 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2656 $entry->setAttribute('src',
2657 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2658 }
2659
2660 if (strtolower($entry->nodeName) == "a") {
2661 $entry->setAttribute("target", "_blank");
2662 }
2663
2664 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
2665 $br = $doc->createElement("br");
2666
2667 if ($entry->parentNode->nextSibling) {
2668 $entry->parentNode->insertBefore($br, $entry->nextSibling);
2669 $br_inserted = 1;
2670 }
2671
2672 }
2673 }
2674
2675 $node = $doc->getElementsByTagName('body')->item(0);
2676
2677 return $doc->saveXML($node);
2678 }
2679
2680 /**
2681 * Send by mail a digest of last articles.
2682 *
2683 * @param mixed $link The database connection.
2684 * @param integer $limit The maximum number of articles by digest.
2685 * @return boolean Return false if digests are not enabled.
2686 */
2687 function send_headlines_digests($link, $limit = 100, $debug = true) {
2688
2689 require_once 'lib/phpmailer/class.phpmailer.php';
2690
2691 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2692
2693 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2694
2695 if (DB_TYPE == "pgsql") {
2696 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2697 } else if (DB_TYPE == "mysql") {
2698 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2699 }
2700
2701 $result = db_query($link, "SELECT id,email FROM ttrss_users
2702 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2703
2704 while ($line = db_fetch_assoc($result)) {
2705
2706 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2707 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2708
2709 if ($preferred_ts && time() >= $preferred_ts) {
2710
2711 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2712
2713 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2714
2715 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2716 $digest = $tuple[0];
2717 $headlines_count = $tuple[1];
2718 $affected_ids = $tuple[2];
2719 $digest_text = $tuple[3];
2720
2721 if ($headlines_count > 0) {
2722
2723 $mail = new PHPMailer();
2724
2725 $mail->PluginDir = "lib/phpmailer/";
2726 $mail->SetLanguage("en", "lib/phpmailer/language/");
2727
2728 $mail->CharSet = "UTF-8";
2729
2730 $mail->From = SMTP_FROM_ADDRESS;
2731 $mail->FromName = SMTP_FROM_NAME;
2732 $mail->AddAddress($line["email"], $line["login"]);
2733
2734 if (SMTP_HOST) {
2735 $mail->Host = SMTP_HOST;
2736 $mail->Mailer = "smtp";
2737 $mail->SMTPAuth = SMTP_LOGIN != '';
2738 $mail->Username = SMTP_LOGIN;
2739 $mail->Password = SMTP_PASSWORD;
2740 }
2741
2742 $mail->IsHTML(true);
2743 $mail->Subject = DIGEST_SUBJECT;
2744 $mail->Body = $digest;
2745 $mail->AltBody = $digest_text;
2746
2747 $rc = $mail->Send();
2748
2749 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo;
2750
2751 if ($debug) print "RC=$rc\n";
2752
2753 if ($rc && $do_catchup) {
2754 if ($debug) print "Marking affected articles as read...\n";
2755 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2756 }
2757 } else {
2758 if ($debug) print "No headlines\n";
2759 }
2760
2761 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2762 WHERE id = " . $line["id"]);
2763
2764 }
2765 }
2766 }
2767
2768 if ($debug) _debug("All done.");
2769
2770 }
2771
2772 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2773
2774 require_once "lib/MiniTemplator.class.php";
2775
2776 $tpl = new MiniTemplator;
2777 $tpl_t = new MiniTemplator;
2778
2779 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2780 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2781
2782 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
2783 $tpl->setVariable('CUR_TIME', date('G:i'));
2784
2785 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
2786 $tpl_t->setVariable('CUR_TIME', date('G:i'));
2787
2788 $affected_ids = array();
2789
2790 if (DB_TYPE == "pgsql") {
2791 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2792 } else if (DB_TYPE == "mysql") {
2793 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2794 }
2795
2796 $result = db_query($link, "SELECT ttrss_entries.title,
2797 ttrss_feeds.title AS feed_title,
2798 date_updated,
2799 ttrss_user_entries.ref_id,
2800 link,
2801 SUBSTRING(content, 1, 120) AS excerpt,
2802 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
2803 FROM
2804 ttrss_user_entries,ttrss_entries,ttrss_feeds
2805 WHERE
2806 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2807 AND include_in_digest = true
2808 AND $interval_query
2809 AND ttrss_user_entries.owner_uid = $user_id
2810 AND unread = true
2811 ORDER BY ttrss_feeds.title, date_updated DESC
2812 LIMIT $limit");
2813
2814 $cur_feed_title = "";
2815
2816 $headlines_count = db_num_rows($result);
2817
2818 $headlines = array();
2819
2820 while ($line = db_fetch_assoc($result)) {
2821 array_push($headlines, $line);
2822 }
2823
2824 for ($i = 0; $i < sizeof($headlines); $i++) {
2825
2826 $line = $headlines[$i];
2827
2828 array_push($affected_ids, $line["ref_id"]);
2829
2830 $updated = make_local_datetime($link, $line['last_updated'], false,
2831 $user_id);
2832
2833 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2834 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2835 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2836 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2837 $tpl->setVariable('ARTICLE_EXCERPT',
2838 truncate_string(strip_tags($line["excerpt"]), 100));
2839
2840 $tpl->addBlock('article');
2841
2842 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2843 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2844 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2845 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2846 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2847 // truncate_string(strip_tags($line["excerpt"]), 100));
2848
2849 $tpl_t->addBlock('article');
2850
2851 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
2852 $tpl->addBlock('feed');
2853 $tpl_t->addBlock('feed');
2854 }
2855
2856 }
2857
2858 $tpl->addBlock('digest');
2859 $tpl->generateOutputToString($tmp);
2860
2861 $tpl_t->addBlock('digest');
2862 $tpl_t->generateOutputToString($tmp_t);
2863
2864 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2865 }
2866
2867 function check_for_update($link) {
2868 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2869 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
2870
2871 $version_data = @fetch_file_contents($version_url);
2872
2873 if ($version_data) {
2874 $version_data = json_decode($version_data, true);
2875 if ($version_data && $version_data['version']) {
2876
2877 if (version_compare(VERSION, $version_data['version']) == -1) {
2878 return $version_data;
2879 }
2880 }
2881 }
2882 }
2883 return false;
2884 }
2885
2886 function markArticlesById($link, $ids, $cmode) {
2887
2888 $tmp_ids = array();
2889
2890 foreach ($ids as $id) {
2891 array_push($tmp_ids, "ref_id = '$id'");
2892 }
2893
2894 $ids_qpart = join(" OR ", $tmp_ids);
2895
2896 if ($cmode == 0) {
2897 db_query($link, "UPDATE ttrss_user_entries SET
2898 marked = false,last_read = NOW()
2899 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2900 } else if ($cmode == 1) {
2901 db_query($link, "UPDATE ttrss_user_entries SET
2902 marked = true
2903 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2904 } else {
2905 db_query($link, "UPDATE ttrss_user_entries SET
2906 marked = NOT marked,last_read = NOW()
2907 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2908 }
2909 }
2910
2911 function publishArticlesById($link, $ids, $cmode) {
2912
2913 $tmp_ids = array();
2914
2915 foreach ($ids as $id) {
2916 array_push($tmp_ids, "ref_id = '$id'");
2917 }
2918
2919 $ids_qpart = join(" OR ", $tmp_ids);
2920
2921 if ($cmode == 0) {
2922 db_query($link, "UPDATE ttrss_user_entries SET
2923 published = false,last_read = NOW()
2924 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2925 } else if ($cmode == 1) {
2926 db_query($link, "UPDATE ttrss_user_entries SET
2927 published = true
2928 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2929 } else {
2930 db_query($link, "UPDATE ttrss_user_entries SET
2931 published = NOT published,last_read = NOW()
2932 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2933 }
2934
2935 if (PUBSUBHUBBUB_HUB) {
2936 $rss_link = get_self_url_prefix() .
2937 "/public.php?op=rss&id=-2&key=" .
2938 get_feed_access_key($link, -2, false);
2939
2940 $p = new Publisher(PUBSUBHUBBUB_HUB);
2941
2942 $pubsub_result = $p->publish_update($rss_link);
2943 }
2944 }
2945
2946 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2947
2948 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2949 if (count($ids) == 0) return;
2950
2951 $tmp_ids = array();
2952
2953 foreach ($ids as $id) {
2954 array_push($tmp_ids, "ref_id = '$id'");
2955 }
2956
2957 $ids_qpart = join(" OR ", $tmp_ids);
2958
2959 if ($cmode == 0) {
2960 db_query($link, "UPDATE ttrss_user_entries SET
2961 unread = false,last_read = NOW()
2962 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2963 } else if ($cmode == 1) {
2964 db_query($link, "UPDATE ttrss_user_entries SET
2965 unread = true
2966 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2967 } else {
2968 db_query($link, "UPDATE ttrss_user_entries SET
2969 unread = NOT unread,last_read = NOW()
2970 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2971 }
2972
2973 /* update ccache */
2974
2975 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2976 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2977
2978 while ($line = db_fetch_assoc($result)) {
2979 ccache_update($link, $line["feed_id"], $owner_uid);
2980 }
2981 }
2982
2983 function catchupArticleById($link, $id, $cmode) {
2984
2985 if ($cmode == 0) {
2986 db_query($link, "UPDATE ttrss_user_entries SET
2987 unread = false,last_read = NOW()
2988 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2989 } else if ($cmode == 1) {
2990 db_query($link, "UPDATE ttrss_user_entries SET
2991 unread = true
2992 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2993 } else {
2994 db_query($link, "UPDATE ttrss_user_entries SET
2995 unread = NOT unread,last_read = NOW()
2996 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2997 }
2998
2999 $feed_id = getArticleFeed($link, $id);
3000 ccache_update($link, $feed_id, $_SESSION["uid"]);
3001 }
3002
3003 function make_guid_from_title($title) {
3004 return preg_replace("/[ \"\',.:;]/", "-",
3005 mb_strtolower(strip_tags($title), 'utf-8'));
3006 }
3007
3008 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
3009
3010 global $memcache;
3011
3012 $a_id = db_escape_string($id);
3013
3014 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3015
3016 $query = "SELECT DISTINCT tag_name,
3017 owner_uid as owner FROM
3018 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3019 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
3020
3021 $obj_id = md5("TAGS:$owner_uid:$id");
3022 $tags = array();
3023
3024 if ($memcache && $obj = $memcache->get($obj_id)) {
3025 $tags = $obj;
3026 } else {
3027 /* check cache first */
3028
3029 if ($tag_cache === false) {
3030 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
3031 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3032
3033 $tag_cache = db_fetch_result($result, 0, "tag_cache");
3034 }
3035
3036 if ($tag_cache) {
3037 $tags = explode(",", $tag_cache);
3038 } else {
3039
3040 /* do it the hard way */
3041
3042 $tmp_result = db_query($link, $query);
3043
3044 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3045 array_push($tags, $tmp_line["tag_name"]);
3046 }
3047
3048 /* update the cache */
3049
3050 $tags_str = db_escape_string(join(",", $tags));
3051
3052 db_query($link, "UPDATE ttrss_user_entries
3053 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3054 AND owner_uid = " . $_SESSION["uid"]);
3055 }
3056
3057 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
3058 }
3059
3060 return $tags;
3061 }
3062
3063 function trim_array($array) {
3064 $tmp = $array;
3065 array_walk($tmp, 'trim');
3066 return $tmp;
3067 }
3068
3069 function tag_is_valid($tag) {
3070 if ($tag == '') return false;
3071 if (preg_match("/^[0-9]*$/", $tag)) return false;
3072 if (mb_strlen($tag) > 250) return false;
3073
3074 if (function_exists('iconv')) {
3075 $tag = iconv("utf-8", "utf-8", $tag);
3076 }
3077
3078 if (!$tag) return false;
3079
3080 return true;
3081 }
3082
3083 function render_login_form($link, $mobile = 0) {
3084 switch ($mobile) {
3085 case 0:
3086 require_once "login_form.php";
3087 break;
3088 case 1:
3089 require_once "mobile/login_form.php";
3090 break;
3091 case 2:
3092 require_once "mobile/classic/login_form.php";
3093 }
3094 }
3095
3096 // from http://developer.apple.com/internet/safari/faq.html
3097 function no_cache_incantation() {
3098 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3099 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3100 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3101 header("Cache-Control: post-check=0, pre-check=0", false);
3102 header("Pragma: no-cache"); // HTTP/1.0
3103 }
3104
3105 function format_warning($msg, $id = "") {
3106 global $link;
3107 return "<div class=\"warning\" id=\"$id\">
3108 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3109 }
3110
3111 function format_notice($msg, $id = "") {
3112 global $link;
3113 return "<div class=\"notice\" id=\"$id\">
3114 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3115 }
3116
3117 function format_error($msg, $id = "") {
3118 global $link;
3119 return "<div class=\"error\" id=\"$id\">
3120 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3121 }
3122
3123 function print_notice($msg) {
3124 return print format_notice($msg);
3125 }
3126
3127 function print_warning($msg) {
3128 return print format_warning($msg);
3129 }
3130
3131 function print_error($msg) {
3132 return print format_error($msg);
3133 }
3134
3135
3136 function T_sprintf() {
3137 $args = func_get_args();
3138 return vsprintf(__(array_shift($args)), $args);
3139 }
3140
3141 function format_inline_player($link, $url, $ctype) {
3142
3143 $entry = "";
3144
3145 if (strpos($ctype, "audio/") === 0) {
3146
3147 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3148 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3149 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3150
3151 $id = 'AUDIO-' . uniqid();
3152
3153 $entry .= "<audio id=\"$id\"\">
3154 <source src=\"$url\"></source>
3155 </audio>";
3156
3157 $entry .= "<span onclick=\"player(this)\"
3158 title=\"".__("Click to play")."\" status=\"0\"
3159 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3160
3161 } else {
3162
3163 $entry .= "<object type=\"application/x-shockwave-flash\"
3164 data=\"lib/button/musicplayer.swf?song_url=$url\"
3165 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3166 <param name=\"movie\"
3167 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3168 </object>";
3169 }
3170 }
3171
3172 $filename = substr($url, strrpos($url, "/")+1);
3173
3174 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3175 $filename . " (" . $ctype . ")" . "</a>";
3176
3177 return $entry;
3178 }
3179
3180 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
3181
3182 $rv = array();
3183
3184 $rv['id'] = $id;
3185
3186 /* we can figure out feed_id from article id anyway, why do we
3187 * pass feed_id here? let's ignore the argument :( */
3188
3189 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3190 WHERE ref_id = '$id'");
3191
3192 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3193
3194 $rv['feed_id'] = $feed_id;
3195
3196 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3197
3198 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3199 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3200
3201 if (db_num_rows($result) == 1) {
3202 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3203 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3204 } else {
3205 $rtl_content = false;
3206 $always_display_enclosures = false;
3207 }
3208
3209 if ($rtl_content) {
3210 $rtl_tag = "dir=\"RTL\"";
3211 $rtl_class = "RTL";
3212 } else {
3213 $rtl_tag = "";
3214 $rtl_class = "";
3215 }
3216
3217 if ($mark_as_read) {
3218 $result = db_query($link, "UPDATE ttrss_user_entries
3219 SET unread = false,last_read = NOW()
3220 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3221
3222 ccache_update($link, $feed_id, $_SESSION["uid"]);
3223 }
3224
3225 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3226 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3227 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3228 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3229 num_comments,
3230 tag_cache,
3231 author,
3232 orig_feed_id,
3233 note
3234 FROM ttrss_entries,ttrss_user_entries
3235 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3236
3237 if ($result) {
3238
3239 $line = db_fetch_assoc($result);
3240
3241 if ($line["icon_url"]) {
3242 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3243 } else {
3244 $feed_icon = "&nbsp;";
3245 }
3246
3247 $feed_site_url = $line['site_url'];
3248
3249 $num_comments = $line["num_comments"];
3250 $entry_comments = "";
3251
3252 if ($num_comments > 0) {
3253 if ($line["comments"]) {
3254 $comments_url = $line["comments"];
3255 } else {
3256 $comments_url = $line["link"];
3257 }
3258 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3259 } else {
3260 if ($line["comments"] && $line["link"] != $line["comments"]) {
3261 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
3262 }
3263 }
3264
3265 if ($zoom_mode) {
3266 header("Content-Type: text/html");
3267 $rv['content'] .= "<html><head>
3268 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3269 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3270 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3271 </head><body>";
3272 }
3273
3274 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3275 truncate_string(strip_tags($line['title']), 15) . "</div>";
3276
3277 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3278
3279 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3280 class=\"postHeader\" id=\"POSTHDR-$id\">";
3281
3282 $entry_author = $line["author"];
3283
3284 if ($entry_author) {
3285 $entry_author = __(" - ") . $entry_author;
3286 }
3287
3288 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3289 false, true);
3290
3291 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3292
3293 if ($line["link"]) {
3294 $rv['content'] .= "<div clear='both'><a target='_blank'
3295 title=\"".htmlspecialchars($line['title'])."\"
3296 href=\"" .
3297 $line["link"] . "\">" .
3298 truncate_string($line["title"], 100) .
3299 "<span class='author'>$entry_author</span></a></div>";
3300 } else {
3301 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3302 }
3303
3304 $tag_cache = $line["tag_cache"];
3305
3306 if (!$tag_cache)
3307 $tags = get_article_tags($link, $id);
3308 else
3309 $tags = explode(",", $tag_cache);
3310
3311 $tags_str = format_tags_string($tags, $id);
3312 $tags_str_full = join(", ", $tags);
3313
3314 if (!$tags_str_full) $tags_str_full = __("no tags");
3315
3316 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3317
3318 $rv['content'] .= "<div style='float : right'>
3319 <img src='".theme_image($link, 'images/tag.png')."'
3320 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
3321
3322 if (!$zoom_mode) {
3323 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3324 <a title=\"".__('Edit tags for this article')."\"
3325 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3326
3327 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3328 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3329 position=\"below\">$tags_str_full</div>";
3330
3331 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3332 class='tagsPic' style=\"cursor : pointer\"
3333 onclick=\"postOpenInNewTab(event, $id)\"
3334 alt='Zoom' title='".__('Open article in new tab')."'>";
3335
3336 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS);
3337
3338 foreach ($button_plugins as $p) {
3339 $pclass = trim("${p}_button");
3340
3341 if (class_exists($pclass)) {
3342 $plugin = new $pclass($link);
3343 $rv['content'] .= $plugin->render($id, $line);
3344 }
3345 }
3346
3347 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3348 class='tagsPic' style=\"cursor : pointer\"
3349 onclick=\"closeArticlePanel($id)\"
3350 title='".__('Close article')."'>";
3351
3352 } else {
3353 $tags_str = strip_tags($tags_str);
3354 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3355 }
3356 $rv['content'] .= "</div>";
3357 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3358
3359 if ($line["orig_feed_id"]) {
3360
3361 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3362 WHERE id = ".$line["orig_feed_id"]);
3363
3364 if (db_num_rows($tmp_result) != 0) {
3365
3366 $rv['content'] .= "<div clear='both'>";
3367 $rv['content'] .= __("Originally from:");
3368
3369 $rv['content'] .= "&nbsp;";
3370
3371 $tmp_line = db_fetch_assoc($tmp_result);
3372
3373 $rv['content'] .= "<a target='_blank'
3374 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3375 $tmp_line['title'] . "</a>";
3376
3377 $rv['content'] .= "&nbsp;";
3378
3379 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3380 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3381
3382 $rv['content'] .= "</div>";
3383 }
3384 }
3385
3386 $rv['content'] .= "</div>";
3387
3388 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3389 if ($line['note']) {
3390 $rv['content'] .= format_article_note($id, $line['note']);
3391 }
3392 $rv['content'] .= "</div>";
3393
3394 $rv['content'] .= "<div class=\"postIcon\">" .
3395 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3396 href=\"".htmlspecialchars($feed_site_url)."\">".
3397 $feed_icon . "</a></div>";
3398
3399 $rv['content'] .= "<div class=\"postContent\">";
3400
3401 $article_content = sanitize($link, $line["content"], false, false,
3402 $feed_site_url);
3403
3404 $rv['content'] .= $article_content;
3405
3406 $rv['content'] .= format_article_enclosures($link, $id,
3407 $always_display_enclosures, $article_content);
3408
3409 $rv['content'] .= "</div>";
3410
3411 $rv['content'] .= "</div>";
3412
3413 }
3414
3415 if ($zoom_mode) {
3416 $rv['content'] .= "
3417 <div style=\"text-align : center\">
3418 <button onclick=\"return window.close()\">".
3419 __("Close this window")."</button></div>";
3420 $rv['content'] .= "</body></html>";
3421 }
3422
3423 return $rv;
3424
3425 }
3426
3427 function print_checkpoint($n, $s) {
3428 $ts = getmicrotime();
3429 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3430 return $ts;
3431 }
3432
3433 function sanitize_tag($tag) {
3434 $tag = trim($tag);
3435
3436 $tag = mb_strtolower($tag, 'utf-8');
3437
3438 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3439
3440 // $tag = str_replace('"', "", $tag);
3441 // $tag = str_replace("+", " ", $tag);
3442 $tag = str_replace("technorati tag: ", "", $tag);
3443
3444 return $tag;
3445 }
3446
3447 function get_self_url_prefix() {
3448 return SELF_URL_PATH;
3449 }
3450
3451 function opml_publish_url($link){
3452
3453 $url_path = get_self_url_prefix();
3454 $url_path .= "/opml.php?op=publish&key=" .
3455 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3456
3457 return $url_path;
3458 }
3459
3460 /**
3461 * Purge a feed contents, marked articles excepted.
3462 *
3463 * @param mixed $link The database connection.
3464 * @param integer $id The id of the feed to purge.
3465 * @return void
3466 */
3467 function clear_feed_articles($link, $id) {
3468
3469 if ($id != 0) {
3470 $result = db_query($link, "DELETE FROM ttrss_user_entries
3471 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3472 } else {
3473 $result = db_query($link, "DELETE FROM ttrss_user_entries
3474 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3475 }
3476
3477 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3478 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3479
3480 ccache_update($link, $id, $_SESSION['uid']);
3481 } // function clear_feed_articles
3482
3483 /**
3484 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3485 *
3486 * @return string The Mozilla Firefox feed adding URL.
3487 */
3488 function add_feed_url() {
3489 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3490
3491 $url_path = get_self_url_prefix() .
3492 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
3493 return $url_path;
3494 } // function add_feed_url
3495
3496 function encrypt_password($pass, $salt = '', $mode2 = false) {
3497 if ($salt && $mode2) {
3498 return "MODE2:" . hash('sha256', $salt . $pass);
3499 } else if ($salt) {
3500 return "SHA1X:" . sha1("$salt:$pass");
3501 } else {
3502 return "SHA1:" . sha1($pass);
3503 }
3504 } // function encrypt_password
3505
3506 function sanitize_article_content($text) {
3507 # we don't support CDATA sections in articles, they break our own escaping
3508 $text = preg_replace("/\[\[CDATA/", "", $text);
3509 $text = preg_replace("/\]\]\>/", "", $text);
3510 return $text;
3511 }
3512
3513 function load_filters($link, $feed, $owner_uid, $action_id = false) {
3514 $filters = array();
3515
3516 global $memcache;
3517
3518 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
3519
3520 if ($memcache && $obj = $memcache->get($obj_id)) {
3521
3522 return $obj;
3523
3524 } else {
3525
3526 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
3527
3528 $result = db_query($link, "SELECT reg_exp,
3529 ttrss_filter_types.name AS name,
3530 ttrss_filter_actions.name AS action,
3531 inverse,
3532 action_param,
3533 filter_param
3534 FROM ttrss_filters
3535 LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
3536 ttrss_filter_types,ttrss_filter_actions
3537 WHERE
3538 enabled = true AND
3539 $ftype_query_part
3540 ttrss_filters.owner_uid = $owner_uid AND
3541 ttrss_filter_types.id = filter_type AND
3542 ttrss_filter_actions.id = action_id AND
3543 ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
3544 (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
3545 ttrss_filters.cat_id IS NULL) OR
3546 (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
3547 ORDER BY reg_exp");
3548
3549 while ($line = db_fetch_assoc($result)) {
3550
3551 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
3552 $filter["reg_exp"] = $line["reg_exp"];
3553 $filter["action"] = $line["action"];
3554 $filter["action_param"] = $line["action_param"];
3555 $filter["filter_param"] = $line["filter_param"];
3556 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3557
3558 array_push($filters[$line["name"]], $filter);
3559 }
3560
3561 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
3562
3563 return $filters;
3564 }
3565 }
3566
3567 function get_score_pic($score) {
3568 if ($score > 100) {
3569 return "score_high.png";
3570 } else if ($score > 0) {
3571 return "score_half_high.png";
3572 } else if ($score < -100) {
3573 return "score_low.png";
3574 } else if ($score < 0) {
3575 return "score_half_low.png";
3576 } else {
3577 return "score_neutral.png";
3578 }
3579 }
3580
3581 function feed_has_icon($id) {
3582 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3583 }
3584
3585 function init_connection($link) {
3586 if ($link) {
3587
3588 if (DB_TYPE == "pgsql") {
3589 pg_query($link, "set client_encoding = 'UTF-8'");
3590 pg_set_client_encoding("UNICODE");
3591 pg_query($link, "set datestyle = 'ISO, european'");
3592 pg_query($link, "set TIME ZONE 0");
3593 } else {
3594 db_query($link, "SET time_zone = '+0:0'");
3595
3596 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
3597 db_query($link, "SET NAMES " . MYSQL_CHARSET);
3598 }
3599 }
3600 return true;
3601 } else {
3602 print "Unable to connect to database:" . db_last_error();
3603 return false;
3604 }
3605 }
3606
3607 /* function ccache_zero($link, $feed_id, $owner_uid) {
3608 db_query($link, "UPDATE ttrss_counters_cache SET
3609 value = 0, updated = NOW() WHERE
3610 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3611 } */
3612
3613 function ccache_zero_all($link, $owner_uid) {
3614 db_query($link, "UPDATE ttrss_counters_cache SET
3615 value = 0 WHERE owner_uid = '$owner_uid'");
3616
3617 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3618 value = 0 WHERE owner_uid = '$owner_uid'");
3619 }
3620
3621 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3622
3623 if (!$is_cat) {
3624 $table = "ttrss_counters_cache";
3625 } else {
3626 $table = "ttrss_cat_counters_cache";
3627 }
3628
3629 db_query($link, "DELETE FROM $table WHERE
3630 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3631
3632 }
3633
3634 function ccache_update_all($link, $owner_uid) {
3635
3636 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3637
3638 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3639 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3640
3641 while ($line = db_fetch_assoc($result)) {
3642 ccache_update($link, $line["feed_id"], $owner_uid, true);
3643 }
3644
3645 /* We have to manually include category 0 */
3646
3647 ccache_update($link, 0, $owner_uid, true);
3648
3649 } else {
3650 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3651 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3652
3653 while ($line = db_fetch_assoc($result)) {
3654 print ccache_update($link, $line["feed_id"], $owner_uid);
3655
3656 }
3657
3658 }
3659 }
3660
3661 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3662 $no_update = false) {
3663
3664 if (!is_numeric($feed_id)) return;
3665
3666 if (!$is_cat) {
3667 $table = "ttrss_counters_cache";
3668 if ($feed_id > 0) {
3669 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3670 WHERE id = '$feed_id'");
3671 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3672 }
3673 } else {
3674 $table = "ttrss_cat_counters_cache";
3675 }
3676
3677 if (DB_TYPE == "pgsql") {
3678 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3679 } else if (DB_TYPE == "mysql") {
3680 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3681 }
3682
3683 $result = db_query($link, "SELECT value FROM $table
3684 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3685 LIMIT 1");
3686
3687 if (db_num_rows($result) == 1) {
3688 return db_fetch_result($result, 0, "value");
3689 } else {
3690 if ($no_update) {
3691 return -1;
3692 } else {
3693 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3694 }
3695 }
3696
3697 }
3698
3699 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3700 $update_pcat = true) {
3701
3702 if (!is_numeric($feed_id)) return;
3703
3704 if (!$is_cat && $feed_id > 0) {
3705 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3706 WHERE id = '$feed_id'");
3707 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3708 }
3709
3710 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3711
3712 /* When updating a label, all we need to do is recalculate feed counters
3713 * because labels are not cached */
3714
3715 if ($feed_id < 0) {
3716 ccache_update_all($link, $owner_uid);
3717 return;
3718 }
3719
3720 if (!$is_cat) {
3721 $table = "ttrss_counters_cache";
3722 } else {
3723 $table = "ttrss_cat_counters_cache";
3724 }
3725
3726 if ($is_cat && $feed_id >= 0) {
3727 if ($feed_id != 0) {
3728 $cat_qpart = "cat_id = '$feed_id'";
3729 } else {
3730 $cat_qpart = "cat_id IS NULL";
3731 }
3732
3733 /* Recalculate counters for child feeds */
3734
3735 $result = db_query($link, "SELECT id FROM ttrss_feeds
3736 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3737
3738 while ($line = db_fetch_assoc($result)) {
3739 ccache_update($link, $line["id"], $owner_uid, false, false);
3740 }
3741
3742 $result = db_query($link, "SELECT SUM(value) AS sv
3743 FROM ttrss_counters_cache, ttrss_feeds
3744 WHERE id = feed_id AND $cat_qpart AND
3745 ttrss_feeds.owner_uid = '$owner_uid'");
3746
3747 $unread = (int) db_fetch_result($result, 0, "sv");
3748
3749 } else {
3750 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3751 }
3752
3753 db_query($link, "BEGIN");
3754
3755 $result = db_query($link, "SELECT feed_id FROM $table
3756 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3757
3758 if (db_num_rows($result) == 1) {
3759 db_query($link, "UPDATE $table SET
3760 value = '$unread', updated = NOW() WHERE
3761 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3762
3763 } else {
3764 db_query($link, "INSERT INTO $table
3765 (feed_id, value, owner_uid, updated)
3766 VALUES
3767 ($feed_id, $unread, $owner_uid, NOW())");
3768 }
3769
3770 db_query($link, "COMMIT");
3771
3772 if ($feed_id > 0 && $prev_unread != $unread) {
3773
3774 if (!$is_cat) {
3775
3776 /* Update parent category */
3777
3778 if ($update_pcat) {
3779
3780 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3781 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3782
3783 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3784
3785 ccache_update($link, $cat_id, $owner_uid, true);
3786
3787 }
3788 }
3789 } else if ($feed_id < 0) {
3790 ccache_update_all($link, $owner_uid);
3791 }
3792
3793 return $unread;
3794 }
3795
3796 /* function ccache_cleanup($link, $owner_uid) {
3797
3798 if (DB_TYPE == "pgsql") {
3799 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3800 (SELECT count(*) FROM ttrss_counters_cache AS c2
3801 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3802 AND owner_uid = '$owner_uid'");
3803
3804 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3805 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3806 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3807 AND owner_uid = '$owner_uid'");
3808 } else {
3809 db_query($link, "DELETE c1 FROM
3810 ttrss_counters_cache AS c1,
3811 ttrss_counters_cache AS c2
3812 WHERE
3813 c1.owner_uid = '$owner_uid' AND
3814 c1.owner_uid = c2.owner_uid AND
3815 c1.feed_id = c2.feed_id");
3816
3817 db_query($link, "DELETE c1 FROM
3818 ttrss_cat_counters_cache AS c1,
3819 ttrss_cat_counters_cache AS c2
3820 WHERE
3821 c1.owner_uid = '$owner_uid' AND
3822 c1.owner_uid = c2.owner_uid AND
3823 c1.feed_id = c2.feed_id");
3824
3825 }
3826 } */
3827
3828 function label_find_id($link, $label, $owner_uid) {
3829 $result = db_query($link,
3830 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3831 AND owner_uid = '$owner_uid' LIMIT 1");
3832
3833 if (db_num_rows($result) == 1) {
3834 return db_fetch_result($result, 0, "id");
3835 } else {
3836 return 0;
3837 }
3838 }
3839
3840 function get_article_labels($link, $id) {
3841 global $memcache;
3842
3843 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
3844
3845 $rv = array();
3846
3847 if ($memcache && $obj = $memcache->get($obj_id)) {
3848 return $obj;
3849 } else {
3850
3851 $result = db_query($link, "SELECT label_cache FROM
3852 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3853 $_SESSION["uid"]);
3854
3855 $label_cache = db_fetch_result($result, 0, "label_cache");
3856
3857 if ($label_cache) {
3858
3859 $label_cache = json_decode($label_cache, true);
3860
3861 if ($label_cache["no-labels"] == 1)
3862 return $rv;
3863 else
3864 return $label_cache;
3865 }
3866
3867 $result = db_query($link,
3868 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3869 FROM ttrss_labels2, ttrss_user_labels2
3870 WHERE id = label_id
3871 AND article_id = '$id'
3872 AND owner_uid = ".$_SESSION["uid"] . "
3873 ORDER BY caption");
3874
3875 while ($line = db_fetch_assoc($result)) {
3876 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3877 $line["bg_color"]);
3878 array_push($rv, $rk);
3879 }
3880 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
3881
3882 if (count($rv) > 0)
3883 label_update_cache($link, $id, $rv);
3884 else
3885 label_update_cache($link, $id, array("no-labels" => 1));
3886 }
3887
3888 return $rv;
3889 }
3890
3891
3892 function label_find_caption($link, $label, $owner_uid) {
3893 $result = db_query($link,
3894 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3895 AND owner_uid = '$owner_uid' LIMIT 1");
3896
3897 if (db_num_rows($result) == 1) {
3898 return db_fetch_result($result, 0, "caption");
3899 } else {
3900 return "";
3901 }
3902 }
3903
3904 function label_update_cache($link, $id, $labels = false, $force = false) {
3905
3906 if ($force)
3907 label_clear_cache($link, $id);
3908
3909 if (!$labels)
3910 $labels = get_article_labels($link, $id);
3911
3912 $labels = db_escape_string(json_encode($labels));
3913
3914 db_query($link, "UPDATE ttrss_user_entries SET
3915 label_cache = '$labels' WHERE ref_id = '$id'");
3916
3917 }
3918
3919 function label_clear_cache($link, $id) {
3920
3921 db_query($link, "UPDATE ttrss_user_entries SET
3922 label_cache = '' WHERE ref_id = '$id'");
3923
3924 }
3925
3926 function label_remove_article($link, $id, $label, $owner_uid) {
3927
3928 $label_id = label_find_id($link, $label, $owner_uid);
3929
3930 if (!$label_id) return;
3931
3932 $result = db_query($link,
3933 "DELETE FROM ttrss_user_labels2
3934 WHERE
3935 label_id = '$label_id' AND
3936 article_id = '$id'");
3937
3938 label_clear_cache($link, $id);
3939 }
3940
3941 function label_add_article($link, $id, $label, $owner_uid) {
3942
3943 global $memcache;
3944
3945 if ($memcache) {
3946 $obj_id = md5("LABELS:$id:$owner_uid");
3947 $memcache->delete($obj_id);
3948 }
3949
3950 $label_id = label_find_id($link, $label, $owner_uid);
3951
3952 if (!$label_id) return;
3953
3954 $result = db_query($link,
3955 "SELECT
3956 article_id FROM ttrss_labels2, ttrss_user_labels2
3957 WHERE
3958 label_id = id AND
3959 label_id = '$label_id' AND
3960 article_id = '$id' AND owner_uid = '$owner_uid'
3961 LIMIT 1");
3962
3963 if (db_num_rows($result) == 0) {
3964 db_query($link, "INSERT INTO ttrss_user_labels2
3965 (label_id, article_id) VALUES ('$label_id', '$id')");
3966 }
3967
3968 label_clear_cache($link, $id);
3969
3970 }
3971
3972 function label_remove($link, $id, $owner_uid) {
3973 global $memcache;
3974
3975 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3976
3977 if ($memcache) {
3978 $obj_id = md5("LABELS:$id:$owner_uid");
3979 $memcache->delete($obj_id);
3980 }
3981
3982 db_query($link, "BEGIN");
3983
3984 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3985 WHERE id = '$id'");
3986
3987 $caption = db_fetch_result($result, 0, "caption");
3988
3989 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3990 AND owner_uid = " . $owner_uid);
3991
3992 if (db_affected_rows($link, $result) != 0 && $caption) {
3993
3994 /* Remove access key for the label */
3995
3996 $ext_id = -11 - $id;
3997
3998 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3999 feed_id = '$ext_id' AND owner_uid = $owner_uid");
4000
4001 /* Disable filters that reference label being removed */
4002
4003 db_query($link, "UPDATE ttrss_filters SET
4004 enabled = false WHERE action_param = '$caption'
4005 AND action_id = 7
4006 AND owner_uid = " . $owner_uid);
4007
4008 /* Remove cached data */
4009
4010 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
4011 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
4012
4013 }
4014
4015 db_query($link, "COMMIT");
4016 }
4017
4018 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
4019
4020 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
4021
4022 db_query($link, "BEGIN");
4023
4024 $result = false;
4025
4026 $result = db_query($link, "SELECT id FROM ttrss_labels2
4027 WHERE caption = '$caption' AND owner_uid = $owner_uid");
4028
4029 if (db_num_rows($result) == 0) {
4030 $result = db_query($link,
4031 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
4032 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
4033
4034 $result = db_affected_rows($link, $result) != 0;
4035 }
4036
4037 db_query($link, "COMMIT");
4038
4039 return $result;
4040 }
4041
4042 function format_tags_string($tags, $id) {
4043
4044 $tags_str = "";
4045 $tags_nolinks_str = "";
4046
4047 $num_tags = 0;
4048
4049 $tag_limit = 6;
4050
4051 $formatted_tags = array();
4052
4053 foreach ($tags as $tag) {
4054 $num_tags++;
4055 $tag_escaped = str_replace("'", "\\'", $tag);
4056
4057 if (mb_strlen($tag) > 30) {
4058 $tag = truncate_string($tag, 30);
4059 }
4060
4061 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4062
4063 array_push($formatted_tags, $tag_str);
4064
4065 $tmp_tags_str = implode(", ", $formatted_tags);
4066
4067 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
4068 break;
4069 }
4070 }
4071
4072 $tags_str = implode(", ", $formatted_tags);
4073
4074 if ($num_tags < count($tags)) {
4075 $tags_str .= ", &hellip;";
4076 }
4077
4078 if ($num_tags == 0) {
4079 $tags_str = __("no tags");
4080 }
4081
4082 return $tags_str;
4083
4084 }
4085
4086 function format_article_labels($labels, $id) {
4087
4088 $labels_str = "";
4089
4090 foreach ($labels as $l) {
4091 $labels_str .= sprintf("<span class='hlLabelRef'
4092 style='color : %s; background-color : %s'>%s</span>",
4093 $l[2], $l[3], $l[1]);
4094 }
4095
4096 return $labels_str;
4097
4098 }
4099
4100 function format_article_note($id, $note) {
4101
4102 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4103 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4104 __('(edit note)')."</div>$note</div>";
4105
4106 return $str;
4107 }
4108
4109 function toggle_collapse_cat($link, $cat_id, $mode) {
4110 if ($cat_id > 0) {
4111 $mode = bool_to_sql_bool($mode);
4112
4113 db_query($link, "UPDATE ttrss_feed_categories SET
4114 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4115 $_SESSION["uid"]);
4116 } else {
4117 $pref_name = '';
4118
4119 switch ($cat_id) {
4120 case -1:
4121 $pref_name = '_COLLAPSED_SPECIAL';
4122 break;
4123 case -2:
4124 $pref_name = '_COLLAPSED_LABELS';
4125 break;
4126 case 0:
4127 $pref_name = '_COLLAPSED_UNCAT';
4128 break;
4129 }
4130
4131 if ($pref_name) {
4132 if ($mode) {
4133 set_pref($link, $pref_name, 'true');
4134 } else {
4135 set_pref($link, $pref_name, 'false');
4136 }
4137 }
4138 }
4139 }
4140
4141 function remove_feed($link, $id, $owner_uid) {
4142
4143 if ($id > 0) {
4144
4145 /* save starred articles in Archived feed */
4146
4147 db_query($link, "BEGIN");
4148
4149 /* prepare feed if necessary */
4150
4151 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4152 WHERE id = '$id'");
4153
4154 if (db_num_rows($result) == 0) {
4155 db_query($link, "INSERT INTO ttrss_archived_feeds
4156 (id, owner_uid, title, feed_url, site_url)
4157 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4158 WHERE id = '$id'");
4159 }
4160
4161 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4162 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4163 marked = true AND owner_uid = $owner_uid");
4164
4165 /* Remove access key for the feed */
4166
4167 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4168 feed_id = '$id' AND owner_uid = $owner_uid");
4169
4170 /* remove the feed */
4171
4172 db_query($link, "DELETE FROM ttrss_feeds
4173 WHERE id = '$id' AND owner_uid = $owner_uid");
4174
4175 db_query($link, "COMMIT");
4176
4177 if (file_exists(ICONS_DIR . "/$id.ico")) {
4178 unlink(ICONS_DIR . "/$id.ico");
4179 }
4180
4181 ccache_remove($link, $id, $owner_uid);
4182
4183 } else {
4184 label_remove($link, -11-$id, $owner_uid);
4185 ccache_remove($link, -11-$id, $owner_uid);
4186 }
4187 }
4188
4189 function add_feed_category($link, $feed_cat) {
4190
4191 if (!$feed_cat) return false;
4192
4193 db_query($link, "BEGIN");
4194
4195 $result = db_query($link,
4196 "SELECT id FROM ttrss_feed_categories
4197 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4198
4199 if (db_num_rows($result) == 0) {
4200
4201 $result = db_query($link,
4202 "INSERT INTO ttrss_feed_categories (owner_uid,title)
4203 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
4204
4205 db_query($link, "COMMIT");
4206
4207 return true;
4208 }
4209
4210 return false;
4211 }
4212
4213 function remove_feed_category($link, $id, $owner_uid) {
4214
4215 db_query($link, "DELETE FROM ttrss_feed_categories
4216 WHERE id = '$id' AND owner_uid = $owner_uid");
4217
4218 ccache_remove($link, $id, $owner_uid, true);
4219 }
4220
4221 function archive_article($link, $id, $owner_uid) {
4222 db_query($link, "BEGIN");
4223
4224 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4225 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4226
4227 if (db_num_rows($result) != 0) {
4228
4229 /* prepare the archived table */
4230
4231 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4232
4233 if ($feed_id) {
4234 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4235 WHERE id = '$feed_id'");
4236
4237 if (db_num_rows($result) == 0) {
4238 db_query($link, "INSERT INTO ttrss_archived_feeds
4239 (id, owner_uid, title, feed_url, site_url)
4240 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4241 WHERE id = '$feed_id'");
4242 }
4243
4244 db_query($link, "UPDATE ttrss_user_entries
4245 SET orig_feed_id = feed_id, feed_id = NULL
4246 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4247 }
4248 }
4249
4250 db_query($link, "COMMIT");
4251 }
4252
4253 function getArticleFeed($link, $id) {
4254 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4255 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4256
4257 if (db_num_rows($result) != 0) {
4258 return db_fetch_result($result, 0, "feed_id");
4259 } else {
4260 return 0;
4261 }
4262 }
4263
4264 /**
4265 * Fixes incomplete URLs by prepending "http://".
4266 * Also replaces feed:// with http://, and
4267 * prepends a trailing slash if the url is a domain name only.
4268 *
4269 * @param string $url Possibly incomplete URL
4270 *
4271 * @return string Fixed URL.
4272 */
4273 function fix_url($url) {
4274 if (strpos($url, '://') === false) {
4275 $url = 'http://' . $url;
4276 } else if (substr($url, 0, 5) == 'feed:') {
4277 $url = 'http:' . substr($url, 5);
4278 }
4279
4280 //prepend slash if the URL has no slash in it
4281 // "http://www.example" -> "http://www.example/"
4282 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
4283 $url .= '/';
4284 }
4285
4286 if ($url != "http:///")
4287 return $url;
4288 else
4289 return '';
4290 }
4291
4292 function validate_feed_url($url) {
4293 $parts = parse_url($url);
4294
4295 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
4296
4297 }
4298
4299 function get_article_enclosures($link, $id) {
4300
4301 global $memcache;
4302
4303 $query = "SELECT * FROM ttrss_enclosures
4304 WHERE post_id = '$id' AND content_url != ''";
4305
4306 $obj_id = md5("ENCLOSURES:$id");
4307
4308 $rv = array();
4309
4310 if ($memcache && $obj = $memcache->get($obj_id)) {
4311 $rv = $obj;
4312 } else {
4313 $result = db_query($link, $query);
4314
4315 if (db_num_rows($result) > 0) {
4316 while ($line = db_fetch_assoc($result)) {
4317 array_push($rv, $line);
4318 }
4319 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
4320 }
4321 }
4322
4323 return $rv;
4324 }
4325
4326 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
4327
4328 $feeds = array();
4329
4330 /* Labels */
4331
4332 if ($cat_id == -4 || $cat_id == -2) {
4333 $counters = getLabelCounters($link, true);
4334
4335 foreach (array_values($counters) as $cv) {
4336
4337 $unread = $cv["counter"];
4338
4339 if ($unread || !$unread_only) {
4340
4341 $row = array(
4342 "id" => $cv["id"],
4343 "title" => $cv["description"],
4344 "unread" => $cv["counter"],
4345 "cat_id" => -2,
4346 );
4347
4348 array_push($feeds, $row);
4349 }
4350 }
4351 }
4352
4353 /* Virtual feeds */
4354
4355 if ($cat_id == -4 || $cat_id == -1) {
4356 foreach (array(-1, -2, -3, -4, 0) as $i) {
4357 $unread = getFeedUnread($link, $i);
4358
4359 if ($unread || !$unread_only) {
4360 $title = getFeedTitle($link, $i);
4361
4362 $row = array(
4363 "id" => $i,
4364 "title" => $title,
4365 "unread" => $unread,
4366 "cat_id" => -1,
4367 );
4368 array_push($feeds, $row);
4369 }
4370
4371 }
4372 }
4373
4374 /* Real feeds */
4375
4376 if ($limit) {
4377 $limit_qpart = "LIMIT $limit OFFSET $offset";
4378 } else {
4379 $limit_qpart = "";
4380 }
4381
4382 if ($cat_id == -4 || $cat_id == -3) {
4383 $result = db_query($link, "SELECT
4384 id, feed_url, cat_id, title, ".
4385 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
4386 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4387 " ORDER BY cat_id, title " . $limit_qpart);
4388 } else {
4389
4390 if ($cat_id)
4391 $cat_qpart = "cat_id = '$cat_id'";
4392 else
4393 $cat_qpart = "cat_id IS NULL";
4394
4395 $result = db_query($link, "SELECT
4396 id, feed_url, cat_id, title, ".
4397 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
4398 FROM ttrss_feeds WHERE
4399 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4400 " ORDER BY cat_id, title " . $limit_qpart);
4401 }
4402
4403 while ($line = db_fetch_assoc($result)) {
4404
4405 $unread = getFeedUnread($link, $line["id"]);
4406
4407 $has_icon = feed_has_icon($line['id']);
4408
4409 if ($unread || !$unread_only) {
4410
4411 $row = array(
4412 "feed_url" => $line["feed_url"],
4413 "title" => $line["title"],
4414 "id" => (int)$line["id"],
4415 "unread" => (int)$unread,
4416 "has_icon" => $has_icon,
4417 "cat_id" => (int)$line["cat_id"],
4418 "last_updated" => strtotime($line["last_updated"])
4419 );
4420
4421 array_push($feeds, $row);
4422 }
4423 }
4424
4425 return $feeds;
4426 }
4427
4428 function api_get_headlines($link, $feed_id, $limit, $offset,
4429 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4430 $include_attachments, $since_id,
4431 $search = "", $search_mode = "", $match_on = "") {
4432
4433 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4434 $view_mode, $is_cat, $search, $search_mode, $match_on,
4435 $order, $offset, 0, false, $since_id);
4436
4437 $result = $qfh_ret[0];
4438 $feed_title = $qfh_ret[1];
4439
4440 $headlines = array();
4441
4442 while ($line = db_fetch_assoc($result)) {
4443 $is_updated = ($line["last_read"] == "" &&
4444 ($line["unread"] != "t" && $line["unread"] != "1"));
4445
4446 $tags = explode(",", $line["tag_cache"]);
4447 $labels = json_decode($line["label_cache"], true);
4448
4449 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4450 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4451
4452 $headline_row = array(
4453 "id" => (int)$line["id"],
4454 "unread" => sql_bool_to_bool($line["unread"]),
4455 "marked" => sql_bool_to_bool($line["marked"]),
4456 "published" => sql_bool_to_bool($line["published"]),
4457 "updated" => strtotime($line["updated"]),
4458 "is_updated" => $is_updated,
4459 "title" => $line["title"],
4460 "link" => $line["link"],
4461 "feed_id" => $line["feed_id"],
4462 "tags" => $tags,
4463 );
4464
4465 if ($include_attachments)
4466 $headline_row['attachments'] = get_article_enclosures($link,
4467 $line['id']);
4468
4469 if ($show_excerpt) {
4470 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4471 $headline_row["excerpt"] = $excerpt;
4472 }
4473
4474 if ($show_content) {
4475 $headline_row["content"] = $line["content_preview"];
4476 }
4477
4478 // unify label output to ease parsing
4479 if ($labels["no-labels"] == 1) $labels = array();
4480
4481 $headline_row["labels"] = $labels;
4482
4483 array_push($headlines, $headline_row);
4484 }
4485
4486 return $headlines;
4487 }
4488
4489 function generate_error_feed($link, $error) {
4490 $reply = array();
4491
4492 $reply['headlines']['id'] = -6;
4493 $reply['headlines']['is_cat'] = false;
4494
4495 $reply['headlines']['toolbar'] = '';
4496 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4497
4498 $reply['headlines-info'] = array("count" => 0,
4499 "vgroup_last_feed" => '',
4500 "unread" => 0,
4501 "disable_cache" => true);
4502
4503 return $reply;
4504 }
4505
4506
4507 function generate_dashboard_feed($link) {
4508 $reply = array();
4509
4510 $reply['headlines']['id'] = -5;
4511 $reply['headlines']['is_cat'] = false;
4512
4513 $reply['headlines']['toolbar'] = '';
4514 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4515
4516 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4517
4518 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4519 WHERE owner_uid = " . $_SESSION['uid']);
4520
4521 $last_updated = db_fetch_result($result, 0, "last_updated");
4522 $last_updated = make_local_datetime($link, $last_updated, false);
4523
4524 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4525
4526 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4527 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4528
4529 $num_errors = db_fetch_result($result, 0, "num_errors");
4530
4531 if ($num_errors > 0) {
4532 $reply['headlines']['content'] .= "<br/>";
4533 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4534 __('Some feeds have update errors (click for details)')."</a>";
4535 }
4536 $reply['headlines']['content'] .= "</span></p>";
4537
4538 $reply['headlines-info'] = array("count" => 0,
4539 "vgroup_last_feed" => '',
4540 "unread" => 0,
4541 "disable_cache" => true);
4542
4543 return $reply;
4544 }
4545
4546 function save_email_address($link, $email) {
4547 // FIXME: implement persistent storage of emails
4548
4549 if (!$_SESSION['stored_emails'])
4550 $_SESSION['stored_emails'] = array();
4551
4552 if (!in_array($email, $_SESSION['stored_emails']))
4553 array_push($_SESSION['stored_emails'], $email);
4554 }
4555
4556 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4557 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4558
4559 $sql_is_cat = bool_to_sql_bool($is_cat);
4560
4561 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4562 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4563 AND owner_uid = " . $owner_uid);
4564
4565 if (db_num_rows($result) == 1) {
4566 $key = db_escape_string(sha1(uniqid(rand(), true)));
4567
4568 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4569 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4570 AND owner_uid = " . $owner_uid);
4571
4572 return $key;
4573
4574 } else {
4575 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4576 }
4577 }
4578
4579 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4580
4581 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4582
4583 $sql_is_cat = bool_to_sql_bool($is_cat);
4584
4585 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4586 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4587 AND owner_uid = " . $owner_uid);
4588
4589 if (db_num_rows($result) == 1) {
4590 return db_fetch_result($result, 0, "access_key");
4591 } else {
4592 $key = db_escape_string(sha1(uniqid(rand(), true)));
4593
4594 $result = db_query($link, "INSERT INTO ttrss_access_keys
4595 (access_key, feed_id, is_cat, owner_uid)
4596 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4597
4598 return $key;
4599 }
4600 return false;
4601 }
4602
4603 /**
4604 * Extracts RSS/Atom feed URLs from the given HTML URL.
4605 *
4606 * @param string $url HTML page URL
4607 *
4608 * @return array Array of feeds. Key is the full URL, value the title
4609 */
4610 function get_feeds_from_html($url, $login = false, $pass = false)
4611 {
4612 $url = fix_url($url);
4613 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
4614
4615 libxml_use_internal_errors(true);
4616
4617 $content = @fetch_file_contents($url, false, $login, $pass);
4618
4619 $doc = new DOMDocument();
4620 $doc->loadHTML($content);
4621 $xpath = new DOMXPath($doc);
4622 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4623 $feedUrls = array();
4624 foreach ($entries as $entry) {
4625 if ($entry->hasAttribute('href')) {
4626 $title = $entry->getAttribute('title');
4627 if ($title == '') {
4628 $title = $entry->getAttribute('type');
4629 }
4630 $feedUrl = rewrite_relative_url(
4631 $baseUrl, $entry->getAttribute('href')
4632 );
4633 $feedUrls[$feedUrl] = $title;
4634 }
4635 }
4636 return $feedUrls;
4637 }
4638
4639 /**
4640 * Checks if the content behind the given URL is a HTML file
4641 *
4642 * @param string $url URL to check
4643 *
4644 * @return boolean True if the URL contains HTML content
4645 */
4646 function url_is_html($url, $login = false, $pass = false) {
4647 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
4648
4649 if (stripos($content, '<html>') === false
4650 && stripos($content, '<html ') === false
4651 ) {
4652 return false;
4653 }
4654
4655 return true;
4656 }
4657
4658 function print_label_select($link, $name, $value, $attributes = "") {
4659
4660 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4661 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4662
4663 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4664 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4665
4666 while ($line = db_fetch_assoc($result)) {
4667
4668 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
4669
4670 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4671 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4672
4673 }
4674
4675 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4676
4677 print "</select>";
4678
4679
4680 }
4681
4682 function format_article_enclosures($link, $id, $always_display_enclosures,
4683 $article_content) {
4684
4685 $result = get_article_enclosures($link, $id);
4686 $rv = '';
4687
4688 if (count($result) > 0) {
4689
4690 $entries_html = array();
4691 $entries = array();
4692
4693 foreach ($result as $line) {
4694
4695 $url = $line["content_url"];
4696 $ctype = $line["content_type"];
4697
4698 if (!$ctype) $ctype = __("unknown type");
4699
4700 # $filename = substr($url, strrpos($url, "/")+1);
4701
4702 $entry = format_inline_player($link, $url, $ctype);
4703
4704 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4705 # $filename . " (" . $ctype . ")" . "</a>";
4706
4707 array_push($entries_html, $entry);
4708
4709 $entry = array();
4710
4711 $entry["type"] = $ctype;
4712 $entry["filename"] = $filename;
4713 $entry["url"] = $url;
4714
4715 array_push($entries, $entry);
4716 }
4717
4718 $rv .= "<div class=\"postEnclosures\">";
4719
4720 if (!get_pref($link, "STRIP_IMAGES")) {
4721 if ($always_display_enclosures ||
4722 !preg_match("/<img/i", $article_content)) {
4723
4724 foreach ($entries as $entry) {
4725
4726 if (preg_match("/image/", $entry["type"]) ||
4727 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4728
4729 $rv .= "<p><img
4730 alt=\"".htmlspecialchars($entry["filename"])."\"
4731 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4732 }
4733 }
4734 }
4735 }
4736
4737 if (count($entries) == 1) {
4738 $rv .= __("Attachment:") . " ";
4739 } else {
4740 $rv .= __("Attachments:") . " ";
4741 }
4742
4743 $rv .= join(", ", $entries_html);
4744
4745 $rv .= "</div>";
4746 }
4747
4748 return $rv;
4749 }
4750
4751 function getLastArticleId($link) {
4752 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4753 WHERE owner_uid = " . $_SESSION["uid"]);
4754
4755 if (db_num_rows($result) == 1) {
4756 return db_fetch_result($result, 0, "id");
4757 } else {
4758 return -1;
4759 }
4760 }
4761
4762 function build_url($parts) {
4763 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4764 }
4765
4766 /**
4767 * Converts a (possibly) relative URL to a absolute one.
4768 *
4769 * @param string $url Base URL (i.e. from where the document is)
4770 * @param string $rel_url Possibly relative URL in the document
4771 *
4772 * @return string Absolute URL
4773 */
4774 function rewrite_relative_url($url, $rel_url) {
4775 if (strpos($rel_url, "://") !== false) {
4776 return $rel_url;
4777 } else if (strpos($rel_url, "/") === 0)
4778 {
4779 $parts = parse_url($url);
4780 $parts['path'] = $rel_url;
4781
4782 return build_url($parts);
4783
4784 } else {
4785 $parts = parse_url($url);
4786 if (!isset($parts['path'])) {
4787 $parts['path'] = '/';
4788 }
4789 $dir = $parts['path'];
4790 if (substr($dir, -1) !== '/') {
4791 $dir = dirname($parts['path']);
4792 $dir !== '/' && $dir .= '/';
4793 }
4794 $parts['path'] = $dir . $rel_url;
4795
4796 return build_url($parts);
4797 }
4798 }
4799
4800 function sphinx_search($query, $offset = 0, $limit = 30) {
4801 require_once 'lib/sphinxapi.php';
4802
4803 $sphinxClient = new SphinxClient();
4804
4805 $sphinxClient->SetServer('localhost', 9312);
4806 $sphinxClient->SetConnectTimeout(1);
4807
4808 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4809 'feed_title' => 20));
4810
4811 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
4812 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
4813 $sphinxClient->SetLimits($offset, $limit, 1000);
4814 $sphinxClient->SetArrayResult(false);
4815 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4816
4817 $result = $sphinxClient->Query($query, SPHINX_INDEX);
4818
4819 $ids = array();
4820
4821 if (is_array($result['matches'])) {
4822 foreach (array_keys($result['matches']) as $int_id) {
4823 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4824 array_push($ids, $ref_id);
4825 }
4826 }
4827
4828 return $ids;
4829 }
4830
4831 function cleanup_tags($link, $days = 14, $limit = 1000) {
4832
4833 if (DB_TYPE == "pgsql") {
4834 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4835 } else if (DB_TYPE == "mysql") {
4836 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4837 }
4838
4839 $tags_deleted = 0;
4840
4841 while ($limit > 0) {
4842 $limit_part = 500;
4843
4844 $query = "SELECT ttrss_tags.id AS id
4845 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4846 WHERE post_int_id = int_id AND $interval_query AND
4847 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4848
4849 $result = db_query($link, $query);
4850
4851 $ids = array();
4852
4853 while ($line = db_fetch_assoc($result)) {
4854 array_push($ids, $line['id']);
4855 }
4856
4857 if (count($ids) > 0) {
4858 $ids = join(",", $ids);
4859 print ".";
4860
4861 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4862 $tags_deleted += db_affected_rows($link, $tmp_result);
4863 } else {
4864 break;
4865 }
4866
4867 $limit -= $limit_part;
4868 }
4869
4870 print "\n";
4871
4872 return $tags_deleted;
4873 }
4874
4875 function print_user_stylesheet($link) {
4876 $value = get_pref($link, 'USER_STYLESHEET');
4877
4878 if ($value) {
4879 print "<style type=\"text/css\">";
4880 print str_replace("<br/>", "\n", $value);
4881 print "</style>";
4882 }
4883
4884 }
4885
4886 /* function rewrite_urls($line) {
4887 global $url_regex;
4888
4889 $urls = null;
4890
4891 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4892 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4893
4894 return $result;
4895 } */
4896
4897 function rewrite_urls($html) {
4898 libxml_use_internal_errors(true);
4899
4900 $charset_hack = '<head>
4901 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4902 </head>';
4903
4904 $doc = new DOMDocument();
4905 $doc->loadHTML($charset_hack . $html);
4906 $xpath = new DOMXPath($doc);
4907
4908 $entries = $xpath->query('//*/text()');
4909
4910 foreach ($entries as $entry) {
4911 if (strstr($entry->wholeText, "://") !== false) {
4912 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4913 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
4914
4915 if ($text != $entry->wholeText) {
4916 $cdoc = new DOMDocument();
4917 $cdoc->loadHTML($charset_hack . $text);
4918
4919
4920 foreach ($cdoc->childNodes as $cnode) {
4921 $cnode = $doc->importNode($cnode, true);
4922
4923 if ($cnode) {
4924 $entry->parentNode->insertBefore($cnode);
4925 }
4926 }
4927
4928 $entry->parentNode->removeChild($entry);
4929
4930 }
4931 }
4932 }
4933
4934 $node = $doc->getElementsByTagName('body')->item(0);
4935
4936 return $doc->saveXML($node);
4937 }
4938
4939 function filter_to_sql($filter) {
4940 $query = "";
4941
4942 if (DB_TYPE == "pgsql")
4943 $reg_qpart = "~";
4944 else
4945 $reg_qpart = "REGEXP";
4946
4947 switch ($filter["type"]) {
4948 case "title":
4949 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4950 $filter['reg_exp'] . "')";
4951 break;
4952 case "content":
4953 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4954 $filter['reg_exp'] . "')";
4955 break;
4956 case "both":
4957 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4958 $filter['reg_exp'] . "') OR LOWER(" .
4959 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
4960 break;
4961 case "tag":
4962 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4963 $filter['reg_exp'] . "')";
4964 break;
4965 case "link":
4966 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4967 $filter['reg_exp'] . "')";
4968 break;
4969 case "date":
4970
4971 if ($filter["filter_param"] == "before")
4972 $cmp_qpart = "<";
4973 else
4974 $cmp_qpart = ">=";
4975
4976 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
4977 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
4978 break;
4979 case "author":
4980 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4981 $filter['reg_exp'] . "')";
4982 break;
4983 }
4984
4985 if ($filter["inverse"])
4986 $query = "NOT ($query)";
4987
4988 if ($query) {
4989 if (DB_TYPE == "pgsql") {
4990 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
4991 } else {
4992 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
4993 }
4994 $query .= " AND ";
4995 }
4996
4997
4998 return $query;
4999 }
5000
5001 // Status codes:
5002 // -1 - never connected
5003 // 0 - no data received
5004 // 1 - data received successfully
5005 // 2 - did not receive valid data
5006 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5007
5008 function get_linked_feeds($link, $instance_id = false) {
5009 if ($instance_id)
5010 $instance_qpart = "id = '$instance_id' AND ";
5011 else
5012 $instance_qpart = "";
5013
5014 if (DB_TYPE == "pgsql") {
5015 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5016 } else {
5017 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5018 }
5019
5020 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5021 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5022
5023 while ($line = db_fetch_assoc($result)) {
5024 $id = $line['id'];
5025
5026 _debug("Updating: " . $line['access_url'] . " ($id)");
5027
5028 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5029 $post_query = 'key=' . $line['access_key'];
5030
5031 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5032
5033 // try doing it the old way
5034 if (!$feeds) {
5035 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5036 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5037 }
5038
5039 if ($feeds) {
5040 $feeds = json_decode($feeds, true);
5041
5042 if ($feeds) {
5043 if ($feeds['error']) {
5044 $status = $feeds['error']['code'] + 10;
5045 } else {
5046 $status = 1;
5047
5048 if (count($feeds['feeds']) > 0) {
5049
5050 db_query($link, "DELETE FROM ttrss_linked_feeds
5051 WHERE instance_id = '$id'");
5052
5053 foreach ($feeds['feeds'] as $feed) {
5054 $feed_url = db_escape_string($feed['feed_url']);
5055 $title = db_escape_string($feed['title']);
5056 $subscribers = db_escape_string($feed['subscribers']);
5057 $site_url = db_escape_string($feed['site_url']);
5058
5059 db_query($link, "INSERT INTO ttrss_linked_feeds
5060 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5061 VALUES
5062 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5063 }
5064 } else {
5065 // received 0 feeds, this might indicate that
5066 // the instance on the other hand is rebuilding feedbrowser cache
5067 // we will try again later
5068
5069 // TODO: maybe perform expiration based on updated here?
5070 }
5071
5072 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5073 }
5074 } else {
5075 $status = 2;
5076 }
5077
5078 } else {
5079 $status = 0;
5080 }
5081
5082 _debug("Status: $status");
5083
5084 db_query($link, "UPDATE ttrss_linked_instances SET
5085 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5086
5087 }
5088 }
5089
5090 function make_feed_browser($link, $search, $limit, $mode = 1) {
5091
5092 $owner_uid = $_SESSION["uid"];
5093 $rv = '';
5094
5095 if ($search) {
5096 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5097 UPPER(title) LIKE UPPER('%$search%'))";
5098 } else {
5099 $search_qpart = "";
5100 }
5101
5102 if ($mode == 1) {
5103 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5104 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5105 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5106 AND owner_uid = '$owner_uid') $search_qpart
5107 ORDER BY subscribers DESC LIMIT $limit"); */
5108
5109 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5110 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5111 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5112 WHERE
5113 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5114 WHERE tf.feed_url = qqq.feed_url
5115 AND owner_uid = '$owner_uid') $search_qpart
5116 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5117
5118 } else if ($mode == 2) {
5119 $result = db_query($link, "SELECT *,
5120 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5121 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5122 FROM
5123 ttrss_archived_feeds
5124 WHERE
5125 (SELECT COUNT(*) FROM ttrss_feeds
5126 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5127 owner_uid = '$owner_uid') = 0 AND
5128 owner_uid = '$owner_uid' $search_qpart
5129 ORDER BY id DESC LIMIT $limit");
5130 }
5131
5132 $feedctr = 0;
5133
5134 while ($line = db_fetch_assoc($result)) {
5135
5136 if ($mode == 1) {
5137
5138 $feed_url = htmlspecialchars($line["feed_url"]);
5139 $site_url = htmlspecialchars($line["site_url"]);
5140 $subscribers = $line["subscribers"];
5141
5142 $check_box = "<input onclick='toggleSelectListRow2(this)'
5143 dojoType=\"dijit.form.CheckBox\"
5144 type=\"checkbox\" \">";
5145
5146 $class = ($feedctr % 2) ? "even" : "odd";
5147
5148 $site_url = "<a target=\"_blank\"
5149 href=\"$site_url\">
5150 <span class=\"fb_feedTitle\">".
5151 htmlspecialchars($line["title"])."</span></a>";
5152
5153 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5154 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5155 style='vertical-align : middle'></a>";
5156
5157 $rv .= "<li>$check_box $feed_url $site_url".
5158 "&nbsp;<span class='subscribers'>($subscribers)</span></li>";
5159
5160 } else if ($mode == 2) {
5161 $feed_url = htmlspecialchars($line["feed_url"]);
5162 $site_url = htmlspecialchars($line["site_url"]);
5163 $title = htmlspecialchars($line["title"]);
5164
5165 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5166 type=\"checkbox\">";
5167
5168 $class = ($feedctr % 2) ? "even" : "odd";
5169
5170 if ($line['articles_archived'] > 0) {
5171 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5172 $archived = "&nbsp;<span class='subscribers'>($archived)</span>";
5173 } else {
5174 $archived = '';
5175 }
5176
5177 $site_url = "<a target=\"_blank\"
5178 href=\"$site_url\">
5179 <span class=\"fb_feedTitle\">".
5180 htmlspecialchars($line["title"])."</span></a>";
5181
5182 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5183 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5184 style='vertical-align : middle'></a>";
5185
5186
5187 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5188 "$check_box $feed_url $site_url $archived</li>";
5189 }
5190
5191 ++$feedctr;
5192 }
5193
5194 if ($feedctr == 0) {
5195 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5196 }
5197
5198 return $rv;
5199 }
5200
5201 if (!function_exists('gzdecode')) {
5202 function gzdecode($string) { // no support for 2nd argument
5203 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5204 base64_encode($string));
5205 }
5206 }
5207
5208 function perform_data_import($link, $filename, $owner_uid) {
5209
5210 $num_imported = 0;
5211 $num_processed = 0;
5212 $num_feeds_created = 0;
5213
5214 $doc = @DOMDocument::load($filename);
5215
5216 if (!$doc) {
5217 $contents = file_get_contents($filename);
5218
5219 if ($contents) {
5220 $data = @gzuncompress($contents);
5221 }
5222
5223 if (!$data) {
5224 $data = @gzdecode($contents);
5225 }
5226
5227 if ($data)
5228 $doc = DOMDocument::loadXML($data);
5229 }
5230
5231 if ($doc) {
5232
5233 $xpath = new DOMXpath($doc);
5234
5235 $container = $doc->firstChild;
5236
5237 if ($container && $container->hasAttribute('schema-version')) {
5238 $schema_version = $container->getAttribute('schema-version');
5239
5240 if ($schema_version != SCHEMA_VERSION) {
5241 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5242 return;
5243 }
5244
5245 } else {
5246 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5247 return;
5248 }
5249
5250 $articles = $xpath->query("//article");
5251
5252 foreach ($articles as $article_node) {
5253 if ($article_node->childNodes) {
5254
5255 $ref_id = 0;
5256
5257 $article = array();
5258
5259 foreach ($article_node->childNodes as $child) {
5260 if ($child->nodeName != 'label_cache')
5261 $article[$child->nodeName] = db_escape_string($child->nodeValue);
5262 else
5263 $article[$child->nodeName] = $child->nodeValue;
5264 }
5265
5266 //print_r($article);
5267
5268 if ($article['guid']) {
5269
5270 ++$num_processed;
5271
5272 //db_query($link, "BEGIN");
5273
5274 //print 'GUID:' . $article['guid'] . "\n";
5275
5276 $result = db_query($link, "SELECT id FROM ttrss_entries
5277 WHERE guid = '".$article['guid']."'");
5278
5279 if (db_num_rows($result) == 0) {
5280
5281 $result = db_query($link,
5282 "INSERT INTO ttrss_entries
5283 (title,
5284 guid,
5285 link,
5286 updated,
5287 content,
5288 content_hash,
5289 no_orig_date,
5290 date_updated,
5291 date_entered,
5292 comments,
5293 num_comments,
5294 author)
5295 VALUES
5296 ('".$article['title']."',
5297 '".$article['guid']."',
5298 '".$article['link']."',
5299 '".$article['updated']."',
5300 '".$article['content']."',
5301 '".sha1($article['content'])."',
5302 false,
5303 NOW(),
5304 NOW(),
5305 '',
5306 '0',
5307 '')");
5308
5309 $result = db_query($link, "SELECT id FROM ttrss_entries
5310 WHERE guid = '".$article['guid']."'");
5311
5312 if (db_num_rows($result) != 0) {
5313 $ref_id = db_fetch_result($result, 0, "id");
5314 }
5315
5316 } else {
5317 $ref_id = db_fetch_result($result, 0, "id");
5318 }
5319
5320 //print "Got ref ID: $ref_id\n";
5321
5322 if ($ref_id) {
5323
5324 $feed_url = $article['feed_url'];
5325 $feed_title = $article['feed_title'];
5326
5327 $feed = 'NULL';
5328
5329 if ($feed_url && $feed_title) {
5330 $result = db_query($link, "SELECT id FROM ttrss_feeds
5331 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5332
5333 if (db_num_rows($result) != 0) {
5334 $feed = db_fetch_result($result, 0, "id");
5335 } else {
5336 // try autocreating feed in Uncategorized...
5337
5338 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5339 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5340
5341 $result = db_query($link, "SELECT id FROM ttrss_feeds
5342 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5343
5344 if (db_num_rows($result) != 0) {
5345 ++$num_feeds_created;
5346
5347 $feed = db_fetch_result($result, 0, "id");
5348 }
5349 }
5350 }
5351
5352 if ($feed != 'NULL')
5353 $feed_qpart = "feed_id = $feed";
5354 else
5355 $feed_qpart = "feed_id IS NULL";
5356
5357 //print "$ref_id / $feed / " . $article['title'] . "\n";
5358
5359 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5360 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5361
5362 if (db_num_rows($result) == 0) {
5363
5364 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5365 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5366 $score = (int) $article['score'];
5367
5368 $tag_cache = $article['tag_cache'];
5369 $label_cache = db_escape_string($article['label_cache']);
5370 $note = $article['note'];
5371
5372 //print "Importing " . $article['title'] . "<br/>";
5373
5374 ++$num_imported;
5375
5376 $result = db_query($link,
5377 "INSERT INTO ttrss_user_entries
5378 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5379 published, score, tag_cache, label_cache, uuid, note)
5380 VALUES ($ref_id, $owner_uid, $feed, false,
5381 NULL, $marked, $published, $score, '$tag_cache',
5382 '$label_cache', '', '$note')");
5383
5384 $label_cache = json_decode($label_cache, true);
5385
5386 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5387 foreach ($label_cache as $label) {
5388
5389 label_create($link, $label[1],
5390 $label[2], $label[3], $owner_uid);
5391
5392 label_add_article($link, $ref_id, $label[1], $owner_uid);
5393
5394 }
5395 }
5396
5397 //db_query($link, "COMMIT");
5398 }
5399 }
5400 }
5401 }
5402 }
5403
5404 print "<p>" .
5405 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5406 $num_processed, $num_imported, $num_feeds_created) .
5407 "</p>";
5408
5409 } else {
5410
5411 print "<p>" . __("Could not load XML document.") . "</p>";
5412
5413 }
5414 }
5415
5416 function get_random_bytes($length) {
5417 if (function_exists('openssl_random_pseudo_bytes')) {
5418 return openssl_random_pseudo_bytes($length);
5419 } else {
5420 $output = "";
5421
5422 for ($i = 0; $i < $length; $i++)
5423 $output .= chr(mt_rand(0, 255));
5424
5425 return $output;
5426 }
5427 }
5428 ?>