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