]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
add cosmetic workaround for get_self_url_prefix() to stop the unwashed whining about...
[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 // we need to placate idiots who don't know any better
3409 function get_self_url_prefix() {
3410 return preg_replace("/\/$/", "", SELF_URL_PATH);
3411 }
3412
3413 function opml_publish_url($link){
3414
3415 $url_path = get_self_url_prefix();
3416 $url_path .= "/opml.php?op=publish&key=" .
3417 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3418
3419 return $url_path;
3420 }
3421
3422 /**
3423 * Purge a feed contents, marked articles excepted.
3424 *
3425 * @param mixed $link The database connection.
3426 * @param integer $id The id of the feed to purge.
3427 * @return void
3428 */
3429 function clear_feed_articles($link, $id) {
3430
3431 if ($id != 0) {
3432 $result = db_query($link, "DELETE FROM ttrss_user_entries
3433 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3434 } else {
3435 $result = db_query($link, "DELETE FROM ttrss_user_entries
3436 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3437 }
3438
3439 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3440 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3441
3442 ccache_update($link, $id, $_SESSION['uid']);
3443 } // function clear_feed_articles
3444
3445 /**
3446 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3447 *
3448 * @return string The Mozilla Firefox feed adding URL.
3449 */
3450 function add_feed_url() {
3451 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3452
3453 $url_path = get_self_url_prefix() .
3454 "/public.php?op=subscribe&feed_url=%s";
3455 return $url_path;
3456 } // function add_feed_url
3457
3458 function encrypt_password($pass, $salt = '', $mode2 = false) {
3459 if ($salt && $mode2) {
3460 return "MODE2:" . hash('sha256', $salt . $pass);
3461 } else if ($salt) {
3462 return "SHA1X:" . sha1("$salt:$pass");
3463 } else {
3464 return "SHA1:" . sha1($pass);
3465 }
3466 } // function encrypt_password
3467
3468 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3469 $filters = array();
3470
3471 $cat_id = (int)getFeedCategory($link, $feed_id);
3472
3473 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3474 owner_uid = $owner_uid AND enabled = true");
3475
3476 $check_cats = join(",", array_merge(
3477 getParentCategories($link, $cat_id, $owner_uid),
3478 array($cat_id)));
3479
3480 while ($line = db_fetch_assoc($result)) {
3481 $filter_id = $line["id"];
3482
3483 $result2 = db_query($link, "SELECT
3484 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3485 FROM ttrss_filters2_rules AS r,
3486 ttrss_filter_types AS t
3487 WHERE
3488 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3489 (feed_id IS NULL OR feed_id = '$feed_id') AND
3490 filter_type = t.id AND filter_id = '$filter_id'");
3491
3492 $rules = array();
3493 $actions = array();
3494
3495 while ($rule_line = db_fetch_assoc($result2)) {
3496 # print_r($rule_line);
3497
3498 $rule = array();
3499 $rule["reg_exp"] = $rule_line["reg_exp"];
3500 $rule["type"] = $rule_line["type_name"];
3501
3502 array_push($rules, $rule);
3503 }
3504
3505 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3506 FROM ttrss_filters2_actions AS a,
3507 ttrss_filter_actions AS t
3508 WHERE
3509 action_id = t.id AND filter_id = '$filter_id'");
3510
3511 while ($action_line = db_fetch_assoc($result2)) {
3512 # print_r($action_line);
3513
3514 $action = array();
3515 $action["type"] = $action_line["type_name"];
3516 $action["param"] = $action_line["action_param"];
3517
3518 array_push($actions, $action);
3519 }
3520
3521
3522 $filter = array();
3523 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3524 $filter["rules"] = $rules;
3525 $filter["actions"] = $actions;
3526
3527 if (count($rules) > 0 && count($actions) > 0) {
3528 array_push($filters, $filter);
3529 }
3530 }
3531
3532 return $filters;
3533 }
3534
3535 function get_score_pic($score) {
3536 if ($score > 100) {
3537 return "score_high.png";
3538 } else if ($score > 0) {
3539 return "score_half_high.png";
3540 } else if ($score < -100) {
3541 return "score_low.png";
3542 } else if ($score < 0) {
3543 return "score_half_low.png";
3544 } else {
3545 return "score_neutral.png";
3546 }
3547 }
3548
3549 function feed_has_icon($id) {
3550 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3551 }
3552
3553 function init_connection($link) {
3554 if ($link) {
3555
3556 if (DB_TYPE == "pgsql") {
3557 pg_query($link, "set client_encoding = 'UTF-8'");
3558 pg_set_client_encoding("UNICODE");
3559 pg_query($link, "set datestyle = 'ISO, european'");
3560 pg_query($link, "set TIME ZONE 0");
3561 } else {
3562 db_query($link, "SET time_zone = '+0:0'");
3563
3564 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
3565 db_query($link, "SET NAMES " . MYSQL_CHARSET);
3566 }
3567 }
3568 return true;
3569 } else {
3570 print "Unable to connect to database:" . db_last_error();
3571 return false;
3572 }
3573 }
3574
3575 /* function ccache_zero($link, $feed_id, $owner_uid) {
3576 db_query($link, "UPDATE ttrss_counters_cache SET
3577 value = 0, updated = NOW() WHERE
3578 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3579 } */
3580
3581 function ccache_zero_all($link, $owner_uid) {
3582 db_query($link, "UPDATE ttrss_counters_cache SET
3583 value = 0 WHERE owner_uid = '$owner_uid'");
3584
3585 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3586 value = 0 WHERE owner_uid = '$owner_uid'");
3587 }
3588
3589 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3590
3591 if (!$is_cat) {
3592 $table = "ttrss_counters_cache";
3593 } else {
3594 $table = "ttrss_cat_counters_cache";
3595 }
3596
3597 db_query($link, "DELETE FROM $table WHERE
3598 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3599
3600 }
3601
3602 function ccache_update_all($link, $owner_uid) {
3603
3604 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3605
3606 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3607 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3608
3609 while ($line = db_fetch_assoc($result)) {
3610 ccache_update($link, $line["feed_id"], $owner_uid, true);
3611 }
3612
3613 /* We have to manually include category 0 */
3614
3615 ccache_update($link, 0, $owner_uid, true);
3616
3617 } else {
3618 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3619 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3620
3621 while ($line = db_fetch_assoc($result)) {
3622 print ccache_update($link, $line["feed_id"], $owner_uid);
3623
3624 }
3625
3626 }
3627 }
3628
3629 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3630 $no_update = false) {
3631
3632 if (!is_numeric($feed_id)) return;
3633
3634 if (!$is_cat) {
3635 $table = "ttrss_counters_cache";
3636 if ($feed_id > 0) {
3637 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3638 WHERE id = '$feed_id'");
3639 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3640 }
3641 } else {
3642 $table = "ttrss_cat_counters_cache";
3643 }
3644
3645 if (DB_TYPE == "pgsql") {
3646 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3647 } else if (DB_TYPE == "mysql") {
3648 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3649 }
3650
3651 $result = db_query($link, "SELECT value FROM $table
3652 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3653 LIMIT 1");
3654
3655 if (db_num_rows($result) == 1) {
3656 return db_fetch_result($result, 0, "value");
3657 } else {
3658 if ($no_update) {
3659 return -1;
3660 } else {
3661 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3662 }
3663 }
3664
3665 }
3666
3667 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3668 $update_pcat = true) {
3669
3670 if (!is_numeric($feed_id)) return;
3671
3672 if (!$is_cat && $feed_id > 0) {
3673 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3674 WHERE id = '$feed_id'");
3675 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3676 }
3677
3678 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3679
3680 /* When updating a label, all we need to do is recalculate feed counters
3681 * because labels are not cached */
3682
3683 if ($feed_id < 0) {
3684 ccache_update_all($link, $owner_uid);
3685 return;
3686 }
3687
3688 if (!$is_cat) {
3689 $table = "ttrss_counters_cache";
3690 } else {
3691 $table = "ttrss_cat_counters_cache";
3692 }
3693
3694 if ($is_cat && $feed_id >= 0) {
3695 if ($feed_id != 0) {
3696 $cat_qpart = "cat_id = '$feed_id'";
3697 } else {
3698 $cat_qpart = "cat_id IS NULL";
3699 }
3700
3701 /* Recalculate counters for child feeds */
3702
3703 $result = db_query($link, "SELECT id FROM ttrss_feeds
3704 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3705
3706 while ($line = db_fetch_assoc($result)) {
3707 ccache_update($link, $line["id"], $owner_uid, false, false);
3708 }
3709
3710 $result = db_query($link, "SELECT SUM(value) AS sv
3711 FROM ttrss_counters_cache, ttrss_feeds
3712 WHERE id = feed_id AND $cat_qpart AND
3713 ttrss_feeds.owner_uid = '$owner_uid'");
3714
3715 $unread = (int) db_fetch_result($result, 0, "sv");
3716
3717 } else {
3718 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3719 }
3720
3721 db_query($link, "BEGIN");
3722
3723 $result = db_query($link, "SELECT feed_id FROM $table
3724 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3725
3726 if (db_num_rows($result) == 1) {
3727 db_query($link, "UPDATE $table SET
3728 value = '$unread', updated = NOW() WHERE
3729 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3730
3731 } else {
3732 db_query($link, "INSERT INTO $table
3733 (feed_id, value, owner_uid, updated)
3734 VALUES
3735 ($feed_id, $unread, $owner_uid, NOW())");
3736 }
3737
3738 db_query($link, "COMMIT");
3739
3740 if ($feed_id > 0 && $prev_unread != $unread) {
3741
3742 if (!$is_cat) {
3743
3744 /* Update parent category */
3745
3746 if ($update_pcat) {
3747
3748 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3749 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3750
3751 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3752
3753 ccache_update($link, $cat_id, $owner_uid, true);
3754
3755 }
3756 }
3757 } else if ($feed_id < 0) {
3758 ccache_update_all($link, $owner_uid);
3759 }
3760
3761 return $unread;
3762 }
3763
3764 /* function ccache_cleanup($link, $owner_uid) {
3765
3766 if (DB_TYPE == "pgsql") {
3767 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3768 (SELECT count(*) FROM ttrss_counters_cache AS c2
3769 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3770 AND owner_uid = '$owner_uid'");
3771
3772 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3773 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3774 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3775 AND owner_uid = '$owner_uid'");
3776 } else {
3777 db_query($link, "DELETE c1 FROM
3778 ttrss_counters_cache AS c1,
3779 ttrss_counters_cache AS c2
3780 WHERE
3781 c1.owner_uid = '$owner_uid' AND
3782 c1.owner_uid = c2.owner_uid AND
3783 c1.feed_id = c2.feed_id");
3784
3785 db_query($link, "DELETE c1 FROM
3786 ttrss_cat_counters_cache AS c1,
3787 ttrss_cat_counters_cache AS c2
3788 WHERE
3789 c1.owner_uid = '$owner_uid' AND
3790 c1.owner_uid = c2.owner_uid AND
3791 c1.feed_id = c2.feed_id");
3792
3793 }
3794 } */
3795
3796 function label_find_id($link, $label, $owner_uid) {
3797 $result = db_query($link,
3798 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3799 AND owner_uid = '$owner_uid' LIMIT 1");
3800
3801 if (db_num_rows($result) == 1) {
3802 return db_fetch_result($result, 0, "id");
3803 } else {
3804 return 0;
3805 }
3806 }
3807
3808 function get_article_labels($link, $id, $owner_uid = false) {
3809 $rv = array();
3810
3811 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3812
3813 $result = db_query($link, "SELECT label_cache FROM
3814 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3815 $owner_uid);
3816
3817 if (db_num_rows($result) > 0) {
3818 $label_cache = db_fetch_result($result, 0, "label_cache");
3819
3820 if ($label_cache) {
3821 $label_cache = json_decode($label_cache, true);
3822
3823 if ($label_cache["no-labels"] == 1)
3824 return $rv;
3825 else
3826 return $label_cache;
3827 }
3828 }
3829
3830 $result = db_query($link,
3831 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3832 FROM ttrss_labels2, ttrss_user_labels2
3833 WHERE id = label_id
3834 AND article_id = '$id'
3835 AND owner_uid = ". $owner_uid . "
3836 ORDER BY caption");
3837
3838 while ($line = db_fetch_assoc($result)) {
3839 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3840 $line["bg_color"]);
3841 array_push($rv, $rk);
3842 }
3843
3844 if (count($rv) > 0)
3845 label_update_cache($link, $owner_uid, $id, $rv);
3846 else
3847 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3848
3849 return $rv;
3850 }
3851
3852
3853 function label_find_caption($link, $label, $owner_uid) {
3854 $result = db_query($link,
3855 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3856 AND owner_uid = '$owner_uid' LIMIT 1");
3857
3858 if (db_num_rows($result) == 1) {
3859 return db_fetch_result($result, 0, "caption");
3860 } else {
3861 return "";
3862 }
3863 }
3864
3865 function get_all_labels($link, $owner_uid) {
3866 $rv = array();
3867
3868 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3869
3870 while ($line = db_fetch_assoc($result)) {
3871 array_push($rv, $line);
3872 }
3873
3874 return $rv;
3875 }
3876
3877 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3878
3879 if ($force)
3880 label_clear_cache($link, $id);
3881
3882 if (!$labels)
3883 $labels = get_article_labels($link, $id);
3884
3885 $labels = db_escape_string(json_encode($labels));
3886
3887 db_query($link, "UPDATE ttrss_user_entries SET
3888 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3889
3890 }
3891
3892 function label_clear_cache($link, $id) {
3893
3894 db_query($link, "UPDATE ttrss_user_entries SET
3895 label_cache = '' WHERE ref_id = '$id'");
3896
3897 }
3898
3899 function label_remove_article($link, $id, $label, $owner_uid) {
3900
3901 $label_id = label_find_id($link, $label, $owner_uid);
3902
3903 if (!$label_id) return;
3904
3905 $result = db_query($link,
3906 "DELETE FROM ttrss_user_labels2
3907 WHERE
3908 label_id = '$label_id' AND
3909 article_id = '$id'");
3910
3911 label_clear_cache($link, $id);
3912 }
3913
3914 function label_add_article($link, $id, $label, $owner_uid) {
3915
3916 $label_id = label_find_id($link, $label, $owner_uid);
3917
3918 if (!$label_id) return;
3919
3920 $result = db_query($link,
3921 "SELECT
3922 article_id FROM ttrss_labels2, ttrss_user_labels2
3923 WHERE
3924 label_id = id AND
3925 label_id = '$label_id' AND
3926 article_id = '$id' AND owner_uid = '$owner_uid'
3927 LIMIT 1");
3928
3929 if (db_num_rows($result) == 0) {
3930 db_query($link, "INSERT INTO ttrss_user_labels2
3931 (label_id, article_id) VALUES ('$label_id', '$id')");
3932 }
3933
3934 label_clear_cache($link, $id);
3935
3936 }
3937
3938 function label_remove($link, $id, $owner_uid) {
3939 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3940
3941 db_query($link, "BEGIN");
3942
3943 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3944 WHERE id = '$id'");
3945
3946 $caption = db_fetch_result($result, 0, "caption");
3947
3948 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3949 AND owner_uid = " . $owner_uid);
3950
3951 if (db_affected_rows($link, $result) != 0 && $caption) {
3952
3953 /* Remove access key for the label */
3954
3955 $ext_id = -11 - $id;
3956
3957 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3958 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3959
3960 /* Disable filters that reference label being removed */
3961
3962 db_query($link, "UPDATE ttrss_filters SET
3963 enabled = false WHERE action_param = '$caption'
3964 AND action_id = 7
3965 AND owner_uid = " . $owner_uid);
3966
3967 /* Remove cached data */
3968
3969 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3970 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3971
3972 }
3973
3974 db_query($link, "COMMIT");
3975 }
3976
3977 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3978
3979 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3980
3981 db_query($link, "BEGIN");
3982
3983 $result = false;
3984
3985 $result = db_query($link, "SELECT id FROM ttrss_labels2
3986 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3987
3988 if (db_num_rows($result) == 0) {
3989 $result = db_query($link,
3990 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3991 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3992
3993 $result = db_affected_rows($link, $result) != 0;
3994 }
3995
3996 db_query($link, "COMMIT");
3997
3998 return $result;
3999 }
4000
4001 function format_tags_string($tags, $id) {
4002
4003 $tags_str = "";
4004 $tags_nolinks_str = "";
4005
4006 $num_tags = 0;
4007
4008 $tag_limit = 6;
4009
4010 $formatted_tags = array();
4011
4012 foreach ($tags as $tag) {
4013 $num_tags++;
4014 $tag_escaped = str_replace("'", "\\'", $tag);
4015
4016 if (mb_strlen($tag) > 30) {
4017 $tag = truncate_string($tag, 30);
4018 }
4019
4020 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4021
4022 array_push($formatted_tags, $tag_str);
4023
4024 $tmp_tags_str = implode(", ", $formatted_tags);
4025
4026 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
4027 break;
4028 }
4029 }
4030
4031 $tags_str = implode(", ", $formatted_tags);
4032
4033 if ($num_tags < count($tags)) {
4034 $tags_str .= ", &hellip;";
4035 }
4036
4037 if ($num_tags == 0) {
4038 $tags_str = __("no tags");
4039 }
4040
4041 return $tags_str;
4042
4043 }
4044
4045 function format_article_labels($labels, $id) {
4046
4047 $labels_str = "";
4048
4049 foreach ($labels as $l) {
4050 $labels_str .= sprintf("<span class='hlLabelRef'
4051 style='color : %s; background-color : %s'>%s</span>",
4052 $l[2], $l[3], $l[1]);
4053 }
4054
4055 return $labels_str;
4056
4057 }
4058
4059 function format_article_note($id, $note) {
4060
4061 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4062 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4063 __('(edit note)')."</div>$note</div>";
4064
4065 return $str;
4066 }
4067
4068 function toggle_collapse_cat($link, $cat_id, $mode) {
4069 if ($cat_id > 0) {
4070 $mode = bool_to_sql_bool($mode);
4071
4072 db_query($link, "UPDATE ttrss_feed_categories SET
4073 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4074 $_SESSION["uid"]);
4075 } else {
4076 $pref_name = '';
4077
4078 switch ($cat_id) {
4079 case -1:
4080 $pref_name = '_COLLAPSED_SPECIAL';
4081 break;
4082 case -2:
4083 $pref_name = '_COLLAPSED_LABELS';
4084 break;
4085 case 0:
4086 $pref_name = '_COLLAPSED_UNCAT';
4087 break;
4088 }
4089
4090 if ($pref_name) {
4091 if ($mode) {
4092 set_pref($link, $pref_name, 'true');
4093 } else {
4094 set_pref($link, $pref_name, 'false');
4095 }
4096 }
4097 }
4098 }
4099
4100 function remove_feed($link, $id, $owner_uid) {
4101
4102 if ($id > 0) {
4103
4104 /* save starred articles in Archived feed */
4105
4106 db_query($link, "BEGIN");
4107
4108 /* prepare feed if necessary */
4109
4110 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4111 WHERE id = '$id'");
4112
4113 if (db_num_rows($result) == 0) {
4114 db_query($link, "INSERT INTO ttrss_archived_feeds
4115 (id, owner_uid, title, feed_url, site_url)
4116 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4117 WHERE id = '$id'");
4118 }
4119
4120 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4121 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4122 marked = true AND owner_uid = $owner_uid");
4123
4124 /* Remove access key for the feed */
4125
4126 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4127 feed_id = '$id' AND owner_uid = $owner_uid");
4128
4129 /* remove the feed */
4130
4131 db_query($link, "DELETE FROM ttrss_feeds
4132 WHERE id = '$id' AND owner_uid = $owner_uid");
4133
4134 db_query($link, "COMMIT");
4135
4136 if (file_exists(ICONS_DIR . "/$id.ico")) {
4137 unlink(ICONS_DIR . "/$id.ico");
4138 }
4139
4140 ccache_remove($link, $id, $owner_uid);
4141
4142 } else {
4143 label_remove($link, -11-$id, $owner_uid);
4144 ccache_remove($link, -11-$id, $owner_uid);
4145 }
4146 }
4147
4148 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
4149 if ($parent_cat_id) {
4150 $parent_qpart = "parent_cat = '$parent_cat_id'";
4151 $parent_insert = "'$parent_cat_id'";
4152 } else {
4153 $parent_qpart = "parent_cat IS NULL";
4154 $parent_insert = "NULL";
4155 }
4156
4157 $result = db_query($link,
4158 "SELECT id FROM ttrss_feed_categories
4159 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4160
4161 if (db_num_rows($result) == 0) {
4162 return false;
4163 } else {
4164 return db_fetch_result($result, 0, "id");
4165 }
4166 }
4167
4168 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
4169
4170 if (!$feed_cat) return false;
4171
4172 db_query($link, "BEGIN");
4173
4174 if ($parent_cat_id) {
4175 $parent_qpart = "parent_cat = '$parent_cat_id'";
4176 $parent_insert = "'$parent_cat_id'";
4177 } else {
4178 $parent_qpart = "parent_cat IS NULL";
4179 $parent_insert = "NULL";
4180 }
4181
4182 $result = db_query($link,
4183 "SELECT id FROM ttrss_feed_categories
4184 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4185
4186 if (db_num_rows($result) == 0) {
4187
4188 $result = db_query($link,
4189 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4190 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
4191
4192 db_query($link, "COMMIT");
4193
4194 return true;
4195 }
4196
4197 return false;
4198 }
4199
4200 function remove_feed_category($link, $id, $owner_uid) {
4201
4202 db_query($link, "DELETE FROM ttrss_feed_categories
4203 WHERE id = '$id' AND owner_uid = $owner_uid");
4204
4205 ccache_remove($link, $id, $owner_uid, true);
4206 }
4207
4208 function archive_article($link, $id, $owner_uid) {
4209 db_query($link, "BEGIN");
4210
4211 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4212 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4213
4214 if (db_num_rows($result) != 0) {
4215
4216 /* prepare the archived table */
4217
4218 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4219
4220 if ($feed_id) {
4221 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4222 WHERE id = '$feed_id'");
4223
4224 if (db_num_rows($result) == 0) {
4225 db_query($link, "INSERT INTO ttrss_archived_feeds
4226 (id, owner_uid, title, feed_url, site_url)
4227 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4228 WHERE id = '$feed_id'");
4229 }
4230
4231 db_query($link, "UPDATE ttrss_user_entries
4232 SET orig_feed_id = feed_id, feed_id = NULL
4233 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4234 }
4235 }
4236
4237 db_query($link, "COMMIT");
4238 }
4239
4240 function getArticleFeed($link, $id) {
4241 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4242 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4243
4244 if (db_num_rows($result) != 0) {
4245 return db_fetch_result($result, 0, "feed_id");
4246 } else {
4247 return 0;
4248 }
4249 }
4250
4251 /**
4252 * Fixes incomplete URLs by prepending "http://".
4253 * Also replaces feed:// with http://, and
4254 * prepends a trailing slash if the url is a domain name only.
4255 *
4256 * @param string $url Possibly incomplete URL
4257 *
4258 * @return string Fixed URL.
4259 */
4260 function fix_url($url) {
4261 if (strpos($url, '://') === false) {
4262 $url = 'http://' . $url;
4263 } else if (substr($url, 0, 5) == 'feed:') {
4264 $url = 'http:' . substr($url, 5);
4265 }
4266
4267 //prepend slash if the URL has no slash in it
4268 // "http://www.example" -> "http://www.example/"
4269 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
4270 $url .= '/';
4271 }
4272
4273 if ($url != "http:///")
4274 return $url;
4275 else
4276 return '';
4277 }
4278
4279 function validate_feed_url($url) {
4280 $parts = parse_url($url);
4281
4282 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
4283
4284 }
4285
4286 function get_article_enclosures($link, $id) {
4287
4288 $query = "SELECT * FROM ttrss_enclosures
4289 WHERE post_id = '$id' AND content_url != ''";
4290
4291 $rv = array();
4292
4293 $result = db_query($link, $query);
4294
4295 if (db_num_rows($result) > 0) {
4296 while ($line = db_fetch_assoc($result)) {
4297 array_push($rv, $line);
4298 }
4299 }
4300
4301 return $rv;
4302 }
4303
4304 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4305
4306 $feeds = array();
4307
4308 /* Labels */
4309
4310 if ($cat_id == -4 || $cat_id == -2) {
4311 $counters = getLabelCounters($link, true);
4312
4313 foreach (array_values($counters) as $cv) {
4314
4315 $unread = $cv["counter"];
4316
4317 if ($unread || !$unread_only) {
4318
4319 $row = array(
4320 "id" => $cv["id"],
4321 "title" => $cv["description"],
4322 "unread" => $cv["counter"],
4323 "cat_id" => -2,
4324 );
4325
4326 array_push($feeds, $row);
4327 }
4328 }
4329 }
4330
4331 /* Virtual feeds */
4332
4333 if ($cat_id == -4 || $cat_id == -1) {
4334 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4335 $unread = getFeedUnread($link, $i);
4336
4337 if ($unread || !$unread_only) {
4338 $title = getFeedTitle($link, $i);
4339
4340 $row = array(
4341 "id" => $i,
4342 "title" => $title,
4343 "unread" => $unread,
4344 "cat_id" => -1,
4345 );
4346 array_push($feeds, $row);
4347 }
4348
4349 }
4350 }
4351
4352 /* Child cats */
4353
4354 if ($include_nested && $cat_id) {
4355 $result = db_query($link, "SELECT
4356 id, title FROM ttrss_feed_categories
4357 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4358 " ORDER BY id, title");
4359
4360 while ($line = db_fetch_assoc($result)) {
4361 $unread = getFeedUnread($link, $line["id"], true) +
4362 getCategoryChildrenUnread($link, $line["id"]);
4363
4364 if ($unread || !$unread_only) {
4365 $row = array(
4366 "id" => $line["id"],
4367 "title" => $line["title"],
4368 "unread" => $unread,
4369 "is_cat" => true,
4370 );
4371 array_push($feeds, $row);
4372 }
4373 }
4374 }
4375
4376 /* Real feeds */
4377
4378 if ($limit) {
4379 $limit_qpart = "LIMIT $limit OFFSET $offset";
4380 } else {
4381 $limit_qpart = "";
4382 }
4383
4384 if ($cat_id == -4 || $cat_id == -3) {
4385 $result = db_query($link, "SELECT
4386 id, feed_url, cat_id, title, order_id, ".
4387 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
4388 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4389 " ORDER BY cat_id, title " . $limit_qpart);
4390 } else {
4391
4392 if ($cat_id)
4393 $cat_qpart = "cat_id = '$cat_id'";
4394 else
4395 $cat_qpart = "cat_id IS NULL";
4396
4397 $result = db_query($link, "SELECT
4398 id, feed_url, cat_id, title, order_id, ".
4399 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
4400 FROM ttrss_feeds WHERE
4401 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4402 " ORDER BY cat_id, title " . $limit_qpart);
4403 }
4404
4405 while ($line = db_fetch_assoc($result)) {
4406
4407 $unread = getFeedUnread($link, $line["id"]);
4408
4409 $has_icon = feed_has_icon($line['id']);
4410
4411 if ($unread || !$unread_only) {
4412
4413 $row = array(
4414 "feed_url" => $line["feed_url"],
4415 "title" => $line["title"],
4416 "id" => (int)$line["id"],
4417 "unread" => (int)$unread,
4418 "has_icon" => $has_icon,
4419 "cat_id" => (int)$line["cat_id"],
4420 "last_updated" => strtotime($line["last_updated"]),
4421 "order_id" => (int) $line["order_id"],
4422 );
4423
4424 array_push($feeds, $row);
4425 }
4426 }
4427
4428 return $feeds;
4429 }
4430
4431 function api_get_headlines($link, $feed_id, $limit, $offset,
4432 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4433 $include_attachments, $since_id,
4434 $search = "", $search_mode = "", $match_on = "",
4435 $include_nested = false, $sanitize_content = true) {
4436
4437 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4438 $view_mode, $is_cat, $search, $search_mode, $match_on,
4439 $order, $offset, 0, false, $since_id, $include_nested);
4440
4441 $result = $qfh_ret[0];
4442 $feed_title = $qfh_ret[1];
4443
4444 $headlines = array();
4445
4446 while ($line = db_fetch_assoc($result)) {
4447 $is_updated = ($line["last_read"] == "" &&
4448 ($line["unread"] != "t" && $line["unread"] != "1"));
4449
4450 $tags = explode(",", $line["tag_cache"]);
4451 $labels = json_decode($line["label_cache"], true);
4452
4453 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4454 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4455
4456 $headline_row = array(
4457 "id" => (int)$line["id"],
4458 "unread" => sql_bool_to_bool($line["unread"]),
4459 "marked" => sql_bool_to_bool($line["marked"]),
4460 "published" => sql_bool_to_bool($line["published"]),
4461 "updated" => strtotime($line["updated"]),
4462 "is_updated" => $is_updated,
4463 "title" => $line["title"],
4464 "link" => $line["link"],
4465 "feed_id" => $line["feed_id"],
4466 "tags" => $tags,
4467 );
4468
4469 if ($include_attachments)
4470 $headline_row['attachments'] = get_article_enclosures($link,
4471 $line['id']);
4472
4473 if ($show_excerpt) {
4474 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4475 $headline_row["excerpt"] = $excerpt;
4476 }
4477
4478 if ($show_content) {
4479
4480 if ($line["cached_content"] != "") {
4481 $line["content_preview"] =& $line["cached_content"];
4482 }
4483
4484 if ($sanitize_content) {
4485 $headline_row["content"] = sanitize($link,
4486 $line["content_preview"], false, false, $line["site_url"]);
4487 } else {
4488 $headline_row["content"] = $line["content_preview"];
4489 }
4490 }
4491
4492 // unify label output to ease parsing
4493 if ($labels["no-labels"] == 1) $labels = array();
4494
4495 $headline_row["labels"] = $labels;
4496
4497 $headline_row["feed_title"] = $line["feed_title"];
4498
4499 $headline_row["comments_count"] = (int)$line["num_comments"];
4500 $headline_row["comments_link"] = $line["comments"];
4501
4502 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4503
4504 array_push($headlines, $headline_row);
4505 }
4506
4507 return $headlines;
4508 }
4509
4510 function generate_error_feed($link, $error) {
4511 $reply = array();
4512
4513 $reply['headlines']['id'] = -6;
4514 $reply['headlines']['is_cat'] = false;
4515
4516 $reply['headlines']['toolbar'] = '';
4517 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4518
4519 $reply['headlines-info'] = array("count" => 0,
4520 "vgroup_last_feed" => '',
4521 "unread" => 0,
4522 "disable_cache" => true);
4523
4524 return $reply;
4525 }
4526
4527
4528 function generate_dashboard_feed($link) {
4529 $reply = array();
4530
4531 $reply['headlines']['id'] = -5;
4532 $reply['headlines']['is_cat'] = false;
4533
4534 $reply['headlines']['toolbar'] = '';
4535 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4536
4537 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4538
4539 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4540 WHERE owner_uid = " . $_SESSION['uid']);
4541
4542 $last_updated = db_fetch_result($result, 0, "last_updated");
4543 $last_updated = make_local_datetime($link, $last_updated, false);
4544
4545 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4546
4547 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4548 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4549
4550 $num_errors = db_fetch_result($result, 0, "num_errors");
4551
4552 if ($num_errors > 0) {
4553 $reply['headlines']['content'] .= "<br/>";
4554 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4555 __('Some feeds have update errors (click for details)')."</a>";
4556 }
4557 $reply['headlines']['content'] .= "</span></p>";
4558
4559 $reply['headlines-info'] = array("count" => 0,
4560 "vgroup_last_feed" => '',
4561 "unread" => 0,
4562 "disable_cache" => true);
4563
4564 return $reply;
4565 }
4566
4567 function save_email_address($link, $email) {
4568 // FIXME: implement persistent storage of emails
4569
4570 if (!$_SESSION['stored_emails'])
4571 $_SESSION['stored_emails'] = array();
4572
4573 if (!in_array($email, $_SESSION['stored_emails']))
4574 array_push($_SESSION['stored_emails'], $email);
4575 }
4576
4577 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4578 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4579
4580 $sql_is_cat = bool_to_sql_bool($is_cat);
4581
4582 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4583 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4584 AND owner_uid = " . $owner_uid);
4585
4586 if (db_num_rows($result) == 1) {
4587 $key = db_escape_string(sha1(uniqid(rand(), true)));
4588
4589 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4590 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4591 AND owner_uid = " . $owner_uid);
4592
4593 return $key;
4594
4595 } else {
4596 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4597 }
4598 }
4599
4600 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4601
4602 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4603
4604 $sql_is_cat = bool_to_sql_bool($is_cat);
4605
4606 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4607 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4608 AND owner_uid = " . $owner_uid);
4609
4610 if (db_num_rows($result) == 1) {
4611 return db_fetch_result($result, 0, "access_key");
4612 } else {
4613 $key = db_escape_string(sha1(uniqid(rand(), true)));
4614
4615 $result = db_query($link, "INSERT INTO ttrss_access_keys
4616 (access_key, feed_id, is_cat, owner_uid)
4617 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4618
4619 return $key;
4620 }
4621 return false;
4622 }
4623
4624 function get_feeds_from_html($url, $content)
4625 {
4626 $url = fix_url($url);
4627 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
4628
4629 libxml_use_internal_errors(true);
4630
4631 $doc = new DOMDocument();
4632 $doc->loadHTML($content);
4633 $xpath = new DOMXPath($doc);
4634 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4635 $feedUrls = array();
4636 foreach ($entries as $entry) {
4637 if ($entry->hasAttribute('href')) {
4638 $title = $entry->getAttribute('title');
4639 if ($title == '') {
4640 $title = $entry->getAttribute('type');
4641 }
4642 $feedUrl = rewrite_relative_url(
4643 $baseUrl, $entry->getAttribute('href')
4644 );
4645 $feedUrls[$feedUrl] = $title;
4646 }
4647 }
4648 return $feedUrls;
4649 }
4650
4651 function is_html($content) {
4652 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4653 }
4654
4655 function url_is_html($url, $login = false, $pass = false) {
4656 return is_html(fetch_file_contents($url, false, $login, $pass));
4657 }
4658
4659 function print_label_select($link, $name, $value, $attributes = "") {
4660
4661 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4662 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4663
4664 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4665 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4666
4667 while ($line = db_fetch_assoc($result)) {
4668
4669 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
4670
4671 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4672 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4673
4674 }
4675
4676 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4677
4678 print "</select>";
4679
4680
4681 }
4682
4683 function format_article_enclosures($link, $id, $always_display_enclosures,
4684 $article_content) {
4685
4686 $result = get_article_enclosures($link, $id);
4687 $rv = '';
4688
4689 if (count($result) > 0) {
4690
4691 $entries_html = array();
4692 $entries = array();
4693
4694 foreach ($result as $line) {
4695
4696 $url = $line["content_url"];
4697 $ctype = $line["content_type"];
4698
4699 if (!$ctype) $ctype = __("unknown type");
4700
4701 $filename = substr($url, strrpos($url, "/")+1);
4702
4703 # $player = format_inline_player($link, $url, $ctype);
4704
4705 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4706 # $filename . " (" . $ctype . ")" . "</a>";
4707
4708 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4709 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4710
4711 array_push($entries_html, $entry);
4712
4713 $entry = array();
4714
4715 $entry["type"] = $ctype;
4716 $entry["filename"] = $filename;
4717 $entry["url"] = $url;
4718
4719 array_push($entries, $entry);
4720 }
4721
4722 if (!get_pref($link, "STRIP_IMAGES")) {
4723 if ($always_display_enclosures ||
4724 !preg_match("/<img/i", $article_content)) {
4725
4726 foreach ($entries as $entry) {
4727
4728 if (preg_match("/image/", $entry["type"]) ||
4729 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4730
4731 $rv .= "<p><img
4732 alt=\"".htmlspecialchars($entry["filename"])."\"
4733 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4734
4735 }
4736 }
4737 }
4738 }
4739
4740 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4741 "<span>" . __('Attachments')."</span>";
4742 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4743
4744 foreach ($entries_html as $entry) { $rv .= $entry; };
4745
4746 $rv .= "</div></div>";
4747 }
4748
4749 return $rv;
4750 }
4751
4752 function getLastArticleId($link) {
4753 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4754 WHERE owner_uid = " . $_SESSION["uid"]);
4755
4756 if (db_num_rows($result) == 1) {
4757 return db_fetch_result($result, 0, "id");
4758 } else {
4759 return -1;
4760 }
4761 }
4762
4763 function build_url($parts) {
4764 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4765 }
4766
4767 /**
4768 * Converts a (possibly) relative URL to a absolute one.
4769 *
4770 * @param string $url Base URL (i.e. from where the document is)
4771 * @param string $rel_url Possibly relative URL in the document
4772 *
4773 * @return string Absolute URL
4774 */
4775 function rewrite_relative_url($url, $rel_url) {
4776 if (strpos($rel_url, "magnet:") === 0) {
4777 return $rel_url;
4778 } else if (strpos($rel_url, "://") !== false) {
4779 return $rel_url;
4780 } else if (strpos($rel_url, "//") === 0) {
4781 # protocol-relative URL (rare but they exist)
4782 return $rel_url;
4783 } else if (strpos($rel_url, "/") === 0)
4784 {
4785 $parts = parse_url($url);
4786 $parts['path'] = $rel_url;
4787
4788 return build_url($parts);
4789
4790 } else {
4791 $parts = parse_url($url);
4792 if (!isset($parts['path'])) {
4793 $parts['path'] = '/';
4794 }
4795 $dir = $parts['path'];
4796 if (substr($dir, -1) !== '/') {
4797 $dir = dirname($parts['path']);
4798 $dir !== '/' && $dir .= '/';
4799 }
4800 $parts['path'] = $dir . $rel_url;
4801
4802 return build_url($parts);
4803 }
4804 }
4805
4806 function sphinx_search($query, $offset = 0, $limit = 30) {
4807 require_once 'lib/sphinxapi.php';
4808
4809 $sphinxClient = new SphinxClient();
4810
4811 $sphinxClient->SetServer('localhost', 9312);
4812 $sphinxClient->SetConnectTimeout(1);
4813
4814 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4815 'feed_title' => 20));
4816
4817 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
4818 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
4819 $sphinxClient->SetLimits($offset, $limit, 1000);
4820 $sphinxClient->SetArrayResult(false);
4821 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4822
4823 $result = $sphinxClient->Query($query, SPHINX_INDEX);
4824
4825 $ids = array();
4826
4827 if (is_array($result['matches'])) {
4828 foreach (array_keys($result['matches']) as $int_id) {
4829 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4830 array_push($ids, $ref_id);
4831 }
4832 }
4833
4834 return $ids;
4835 }
4836
4837 function cleanup_tags($link, $days = 14, $limit = 1000) {
4838
4839 if (DB_TYPE == "pgsql") {
4840 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4841 } else if (DB_TYPE == "mysql") {
4842 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4843 }
4844
4845 $tags_deleted = 0;
4846
4847 while ($limit > 0) {
4848 $limit_part = 500;
4849
4850 $query = "SELECT ttrss_tags.id AS id
4851 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4852 WHERE post_int_id = int_id AND $interval_query AND
4853 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4854
4855 $result = db_query($link, $query);
4856
4857 $ids = array();
4858
4859 while ($line = db_fetch_assoc($result)) {
4860 array_push($ids, $line['id']);
4861 }
4862
4863 if (count($ids) > 0) {
4864 $ids = join(",", $ids);
4865 print ".";
4866
4867 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4868 $tags_deleted += db_affected_rows($link, $tmp_result);
4869 } else {
4870 break;
4871 }
4872
4873 $limit -= $limit_part;
4874 }
4875
4876 print "\n";
4877
4878 return $tags_deleted;
4879 }
4880
4881 function print_user_stylesheet($link) {
4882 $value = get_pref($link, 'USER_STYLESHEET');
4883
4884 if ($value) {
4885 print "<style type=\"text/css\">";
4886 print str_replace("<br/>", "\n", $value);
4887 print "</style>";
4888 }
4889
4890 }
4891
4892 /* function rewrite_urls($line) {
4893 global $url_regex;
4894
4895 $urls = null;
4896
4897 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4898 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4899
4900 return $result;
4901 } */
4902
4903 function rewrite_urls($html) {
4904 libxml_use_internal_errors(true);
4905
4906 $charset_hack = '<head>
4907 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4908 </head>';
4909
4910 $doc = new DOMDocument();
4911 $doc->loadHTML($charset_hack . $html);
4912 $xpath = new DOMXPath($doc);
4913
4914 $entries = $xpath->query('//*/text()');
4915
4916 foreach ($entries as $entry) {
4917 if (strstr($entry->wholeText, "://") !== false) {
4918 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4919 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
4920
4921 if ($text != $entry->wholeText) {
4922 $cdoc = new DOMDocument();
4923 $cdoc->loadHTML($charset_hack . $text);
4924
4925
4926 foreach ($cdoc->childNodes as $cnode) {
4927 $cnode = $doc->importNode($cnode, true);
4928
4929 if ($cnode) {
4930 $entry->parentNode->insertBefore($cnode);
4931 }
4932 }
4933
4934 $entry->parentNode->removeChild($entry);
4935
4936 }
4937 }
4938 }
4939
4940 $node = $doc->getElementsByTagName('body')->item(0);
4941
4942 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4943 if ($node)
4944 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
4945 else
4946 return $html;
4947 }
4948
4949 function filter_to_sql($link, $filter, $owner_uid) {
4950 $query = array();
4951
4952 if (DB_TYPE == "pgsql")
4953 $reg_qpart = "~";
4954 else
4955 $reg_qpart = "REGEXP";
4956
4957 foreach ($filter["rules"] AS $rule) {
4958 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4959 $rule['reg_exp']) !== FALSE;
4960
4961 if ($regexp_valid) {
4962
4963 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4964
4965 switch ($rule["type"]) {
4966 case "title":
4967 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4968 $rule['reg_exp'] . "')";
4969 break;
4970 case "content":
4971 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4972 $rule['reg_exp'] . "')";
4973 break;
4974 case "both":
4975 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4976 $rule['reg_exp'] . "') OR LOWER(" .
4977 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4978 break;
4979 case "tag":
4980 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4981 $rule['reg_exp'] . "')";
4982 break;
4983 case "link":
4984 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4985 $rule['reg_exp'] . "')";
4986 break;
4987 case "author":
4988 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4989 $rule['reg_exp'] . "')";
4990 break;
4991 }
4992
4993 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4994 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4995 }
4996
4997 if (isset($rule["cat_id"])) {
4998
4999 if ($rule["cat_id"] > 0) {
5000 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
5001 array_push($children, $rule["cat_id"]);
5002
5003 $children = join(",", $children);
5004
5005 $cat_qpart = "cat_id IN ($children)";
5006 } else {
5007 $cat_qpart = "cat_id IS NULL";
5008 }
5009
5010 $qpart .= " AND $cat_qpart";
5011 }
5012
5013 array_push($query, "($qpart)");
5014
5015 }
5016 }
5017
5018 if (count($query) > 0) {
5019 return "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
5020 } else {
5021 return "(false)";
5022 }
5023 }
5024
5025 // Status codes:
5026 // -1 - never connected
5027 // 0 - no data received
5028 // 1 - data received successfully
5029 // 2 - did not receive valid data
5030 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5031
5032 function get_linked_feeds($link, $instance_id = false) {
5033 if ($instance_id)
5034 $instance_qpart = "id = '$instance_id' AND ";
5035 else
5036 $instance_qpart = "";
5037
5038 if (DB_TYPE == "pgsql") {
5039 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5040 } else {
5041 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5042 }
5043
5044 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5045 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5046
5047 while ($line = db_fetch_assoc($result)) {
5048 $id = $line['id'];
5049
5050 _debug("Updating: " . $line['access_url'] . " ($id)");
5051
5052 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5053 $post_query = 'key=' . $line['access_key'];
5054
5055 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5056
5057 // try doing it the old way
5058 if (!$feeds) {
5059 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5060 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5061 }
5062
5063 if ($feeds) {
5064 $feeds = json_decode($feeds, true);
5065
5066 if ($feeds) {
5067 if ($feeds['error']) {
5068 $status = $feeds['error']['code'] + 10;
5069
5070 // access denied
5071 if ($status == 16) {
5072 db_query($link, "DELETE FROM ttrss_linked_feeds
5073 WHERE instance_id = '$id'");
5074 }
5075 } else {
5076 $status = 1;
5077
5078 if (count($feeds['feeds']) > 0) {
5079
5080 db_query($link, "DELETE FROM ttrss_linked_feeds
5081 WHERE instance_id = '$id'");
5082
5083 foreach ($feeds['feeds'] as $feed) {
5084 $feed_url = db_escape_string($feed['feed_url']);
5085 $title = db_escape_string($feed['title']);
5086 $subscribers = db_escape_string($feed['subscribers']);
5087 $site_url = db_escape_string($feed['site_url']);
5088
5089 db_query($link, "INSERT INTO ttrss_linked_feeds
5090 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5091 VALUES
5092 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5093 }
5094 } else {
5095 // received 0 feeds, this might indicate that
5096 // the instance on the other hand is rebuilding feedbrowser cache
5097 // we will try again later
5098
5099 // TODO: maybe perform expiration based on updated here?
5100 }
5101
5102 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5103 }
5104 } else {
5105 $status = 2;
5106 }
5107
5108 } else {
5109 $status = 0;
5110 }
5111
5112 _debug("Status: $status");
5113
5114 db_query($link, "UPDATE ttrss_linked_instances SET
5115 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5116
5117 }
5118 }
5119
5120 function make_feed_browser($link, $search, $limit, $mode = 1) {
5121
5122 $owner_uid = $_SESSION["uid"];
5123 $rv = '';
5124
5125 if ($search) {
5126 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5127 UPPER(title) LIKE UPPER('%$search%'))";
5128 } else {
5129 $search_qpart = "";
5130 }
5131
5132 if ($mode == 1) {
5133 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5134 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5135 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5136 AND owner_uid = '$owner_uid') $search_qpart
5137 ORDER BY subscribers DESC LIMIT $limit"); */
5138
5139 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5140 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5141 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5142 WHERE
5143 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5144 WHERE tf.feed_url = qqq.feed_url
5145 AND owner_uid = '$owner_uid') $search_qpart
5146 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5147
5148 } else if ($mode == 2) {
5149 $result = db_query($link, "SELECT *,
5150 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5151 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5152 FROM
5153 ttrss_archived_feeds
5154 WHERE
5155 (SELECT COUNT(*) FROM ttrss_feeds
5156 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5157 owner_uid = '$owner_uid') = 0 AND
5158 owner_uid = '$owner_uid' $search_qpart
5159 ORDER BY id DESC LIMIT $limit");
5160 }
5161
5162 $feedctr = 0;
5163
5164 while ($line = db_fetch_assoc($result)) {
5165
5166 if ($mode == 1) {
5167
5168 $feed_url = htmlspecialchars($line["feed_url"]);
5169 $site_url = htmlspecialchars($line["site_url"]);
5170 $subscribers = $line["subscribers"];
5171
5172 $check_box = "<input onclick='toggleSelectListRow2(this)'
5173 dojoType=\"dijit.form.CheckBox\"
5174 type=\"checkbox\" \">";
5175
5176 $class = ($feedctr % 2) ? "even" : "odd";
5177
5178 $site_url = "<a target=\"_blank\"
5179 href=\"$site_url\">
5180 <span class=\"fb_feedTitle\">".
5181 htmlspecialchars($line["title"])."</span></a>";
5182
5183 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5184 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5185 style='vertical-align : middle'></a>";
5186
5187 $rv .= "<li>$check_box $feed_url $site_url".
5188 "&nbsp;<span class='subscribers'>($subscribers)</span></li>";
5189
5190 } else if ($mode == 2) {
5191 $feed_url = htmlspecialchars($line["feed_url"]);
5192 $site_url = htmlspecialchars($line["site_url"]);
5193 $title = htmlspecialchars($line["title"]);
5194
5195 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5196 type=\"checkbox\">";
5197
5198 $class = ($feedctr % 2) ? "even" : "odd";
5199
5200 if ($line['articles_archived'] > 0) {
5201 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5202 $archived = "&nbsp;<span class='subscribers'>($archived)</span>";
5203 } else {
5204 $archived = '';
5205 }
5206
5207 $site_url = "<a target=\"_blank\"
5208 href=\"$site_url\">
5209 <span class=\"fb_feedTitle\">".
5210 htmlspecialchars($line["title"])."</span></a>";
5211
5212 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5213 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5214 style='vertical-align : middle'></a>";
5215
5216
5217 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5218 "$check_box $feed_url $site_url $archived</li>";
5219 }
5220
5221 ++$feedctr;
5222 }
5223
5224 if ($feedctr == 0) {
5225 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5226 }
5227
5228 return $rv;
5229 }
5230
5231 if (!function_exists('gzdecode')) {
5232 function gzdecode($string) { // no support for 2nd argument
5233 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5234 base64_encode($string));
5235 }
5236 }
5237
5238 function perform_data_import($link, $filename, $owner_uid) {
5239
5240 $num_imported = 0;
5241 $num_processed = 0;
5242 $num_feeds_created = 0;
5243
5244 $doc = @DOMDocument::load($filename);
5245
5246 if (!$doc) {
5247 $contents = file_get_contents($filename);
5248
5249 if ($contents) {
5250 $data = @gzuncompress($contents);
5251 }
5252
5253 if (!$data) {
5254 $data = @gzdecode($contents);
5255 }
5256
5257 if ($data)
5258 $doc = DOMDocument::loadXML($data);
5259 }
5260
5261 if ($doc) {
5262
5263 $xpath = new DOMXpath($doc);
5264
5265 $container = $doc->firstChild;
5266
5267 if ($container && $container->hasAttribute('schema-version')) {
5268 $schema_version = $container->getAttribute('schema-version');
5269
5270 if ($schema_version != SCHEMA_VERSION) {
5271 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5272 return;
5273 }
5274
5275 } else {
5276 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5277 return;
5278 }
5279
5280 $articles = $xpath->query("//article");
5281
5282 foreach ($articles as $article_node) {
5283 if ($article_node->childNodes) {
5284
5285 $ref_id = 0;
5286
5287 $article = array();
5288
5289 foreach ($article_node->childNodes as $child) {
5290 if ($child->nodeName != 'label_cache')
5291 $article[$child->nodeName] = db_escape_string($child->nodeValue);
5292 else
5293 $article[$child->nodeName] = $child->nodeValue;
5294 }
5295
5296 //print_r($article);
5297
5298 if ($article['guid']) {
5299
5300 ++$num_processed;
5301
5302 //db_query($link, "BEGIN");
5303
5304 //print 'GUID:' . $article['guid'] . "\n";
5305
5306 $result = db_query($link, "SELECT id FROM ttrss_entries
5307 WHERE guid = '".$article['guid']."'");
5308
5309 if (db_num_rows($result) == 0) {
5310
5311 $result = db_query($link,
5312 "INSERT INTO ttrss_entries
5313 (title,
5314 guid,
5315 link,
5316 updated,
5317 content,
5318 content_hash,
5319 no_orig_date,
5320 date_updated,
5321 date_entered,
5322 comments,
5323 num_comments,
5324 author)
5325 VALUES
5326 ('".$article['title']."',
5327 '".$article['guid']."',
5328 '".$article['link']."',
5329 '".$article['updated']."',
5330 '".$article['content']."',
5331 '".sha1($article['content'])."',
5332 false,
5333 NOW(),
5334 NOW(),
5335 '',
5336 '0',
5337 '')");
5338
5339 $result = db_query($link, "SELECT id FROM ttrss_entries
5340 WHERE guid = '".$article['guid']."'");
5341
5342 if (db_num_rows($result) != 0) {
5343 $ref_id = db_fetch_result($result, 0, "id");
5344 }
5345
5346 } else {
5347 $ref_id = db_fetch_result($result, 0, "id");
5348 }
5349
5350 //print "Got ref ID: $ref_id\n";
5351
5352 if ($ref_id) {
5353
5354 $feed_url = $article['feed_url'];
5355 $feed_title = $article['feed_title'];
5356
5357 $feed = 'NULL';
5358
5359 if ($feed_url && $feed_title) {
5360 $result = db_query($link, "SELECT id FROM ttrss_feeds
5361 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5362
5363 if (db_num_rows($result) != 0) {
5364 $feed = db_fetch_result($result, 0, "id");
5365 } else {
5366 // try autocreating feed in Uncategorized...
5367
5368 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5369 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5370
5371 $result = db_query($link, "SELECT id FROM ttrss_feeds
5372 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5373
5374 if (db_num_rows($result) != 0) {
5375 ++$num_feeds_created;
5376
5377 $feed = db_fetch_result($result, 0, "id");
5378 }
5379 }
5380 }
5381
5382 if ($feed != 'NULL')
5383 $feed_qpart = "feed_id = $feed";
5384 else
5385 $feed_qpart = "feed_id IS NULL";
5386
5387 //print "$ref_id / $feed / " . $article['title'] . "\n";
5388
5389 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5390 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5391
5392 if (db_num_rows($result) == 0) {
5393
5394 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5395 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5396 $score = (int) $article['score'];
5397
5398 $tag_cache = $article['tag_cache'];
5399 $label_cache = db_escape_string($article['label_cache']);
5400 $note = $article['note'];
5401
5402 //print "Importing " . $article['title'] . "<br/>";
5403
5404 ++$num_imported;
5405
5406 $result = db_query($link,
5407 "INSERT INTO ttrss_user_entries
5408 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5409 published, score, tag_cache, label_cache, uuid, note)
5410 VALUES ($ref_id, $owner_uid, $feed, false,
5411 NULL, $marked, $published, $score, '$tag_cache',
5412 '$label_cache', '', '$note')");
5413
5414 $label_cache = json_decode($label_cache, true);
5415
5416 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5417 foreach ($label_cache as $label) {
5418
5419 label_create($link, $label[1],
5420 $label[2], $label[3], $owner_uid);
5421
5422 label_add_article($link, $ref_id, $label[1], $owner_uid);
5423
5424 }
5425 }
5426
5427 //db_query($link, "COMMIT");
5428 }
5429 }
5430 }
5431 }
5432 }
5433
5434 print "<p>" .
5435 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5436 $num_processed, $num_imported, $num_feeds_created) .
5437 "</p>";
5438
5439 } else {
5440
5441 print "<p>" . __("Could not load XML document.") . "</p>";
5442
5443 }
5444 }
5445
5446 function get_random_bytes($length) {
5447 if (function_exists('openssl_random_pseudo_bytes')) {
5448 return openssl_random_pseudo_bytes($length);
5449 } else {
5450 $output = "";
5451
5452 for ($i = 0; $i < $length; $i++)
5453 $output .= chr(mt_rand(0, 255));
5454
5455 return $output;
5456 }
5457 }
5458
5459 function read_stdin() {
5460 $fp = fopen("php://stdin", "r");
5461
5462 if ($fp) {
5463 $line = trim(fgets($fp));
5464 fclose($fp);
5465 return $line;
5466 }
5467
5468 return null;
5469 }
5470
5471 function tmpdirname($path, $prefix) {
5472 // Use PHP's tmpfile function to create a temporary
5473 // directory name. Delete the file and keep the name.
5474 $tempname = tempnam($path,$prefix);
5475 if (!$tempname)
5476 return false;
5477
5478 if (!unlink($tempname))
5479 return false;
5480
5481 return $tempname;
5482 }
5483
5484 function getFeedCategory($link, $feed) {
5485 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5486 WHERE id = '$feed'");
5487
5488 if (db_num_rows($result) > 0) {
5489 return db_fetch_result($result, 0, "cat_id");
5490 } else {
5491 return false;
5492 }
5493
5494 }
5495
5496 function create_published_article($link, $title, $url, $content, $labels_str,
5497 $owner_uid) {
5498
5499 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
5500 $content_hash = sha1($content);
5501
5502 if ($labels_str != "") {
5503 $labels = explode(",", $labels_str);
5504 } else {
5505 $labels = array();
5506 }
5507
5508 $rc = false;
5509
5510 if (!$title) $title = $url;
5511 if (!$title && !$url) return false;
5512
5513 if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) return false;
5514
5515 db_query($link, "BEGIN");
5516
5517 // only check for our user data here, others might have shared this with different content etc
5518 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
5519 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
5520
5521 if (db_num_rows($result) != 0) {
5522 $ref_id = db_fetch_result($result, 0, "id");
5523
5524 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
5525 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
5526
5527 if (db_num_rows($result) != 0) {
5528 $int_id = db_fetch_result($result, 0, "int_id");
5529
5530 db_query($link, "UPDATE ttrss_entries SET
5531 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
5532
5533 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
5534 int_id = '$int_id' AND owner_uid = '$owner_uid'");
5535 } else {
5536
5537 db_query($link, "INSERT INTO ttrss_user_entries
5538 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5539 VALUES
5540 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5541 }
5542
5543 if (count($labels) != 0) {
5544 foreach ($labels as $label) {
5545 label_add_article($link, $ref_id, trim($label), $owner_uid);
5546 }
5547 }
5548
5549 $rc = true;
5550
5551 } else {
5552 $result = db_query($link, "INSERT INTO ttrss_entries
5553 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
5554 VALUES
5555 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
5556
5557 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
5558
5559 if (db_num_rows($result) != 0) {
5560 $ref_id = db_fetch_result($result, 0, "id");
5561
5562 db_query($link, "INSERT INTO ttrss_user_entries
5563 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5564 VALUES
5565 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5566
5567 if (count($labels) != 0) {
5568 foreach ($labels as $label) {
5569 label_add_article($link, $ref_id, trim($label), $owner_uid);
5570 }
5571 }
5572
5573 $rc = true;
5574 }
5575 }
5576
5577 db_query($link, "COMMIT");
5578
5579 return $rc;
5580 }
5581
5582 ?>