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