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