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