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