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