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