]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
implement plugin routing masks, add example plugin
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
6e658547 2 define('EXPECTED_CONFIG_VERSION', 26);
87764a50 3 define('SCHEMA_VERSION', 99);
545ca067 4
23d2471c
AD
5 $fetch_last_error = false;
6
0d421af8 7 function __autoload($class) {
369dbc19
AD
8 $class_file = str_replace("_", "/", strtolower(basename($class)));
9
10 $file = dirname(__FILE__)."/../classes/$class_file.php";
11
0d421af8
AD
12 if (file_exists($file)) {
13 require $file;
14 }
cc85704f 15
0d421af8
AD
16 }
17
d68629dc 18 mb_internal_encoding("UTF-8");
324944f3 19 date_default_timezone_set('UTC');
8a7f5767
CW
20 if (defined('E_DEPRECATED')) {
21 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
22 } else {
23 error_reporting(E_ALL & ~E_NOTICE);
24 }
cce28758 25
40d13c28 26 require_once 'config.php';
cc17c205 27
fc2b26a6
AD
28 if (DB_TYPE == "pgsql") {
29 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
30 } else {
31 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
32 }
33
0c425dc7
AD
34 define('THEME_VERSION_REQUIRED', 1.1);
35
9632f884
AD
36 /**
37 * Return available translations names.
8d505d78 38 *
9632f884
AD
39 * @access public
40 * @return array A array of available translations.
41 */
f8c612d4 42 function get_translations() {
6a214f92 43 $tr = array(
8d505d78 44 "auto" => "Detect automatically",
a3162add 45 "ca_CA" => "Català",
6a214f92 46 "en_US" => "English",
36d0510c 47 "es_ES" => "Español",
a927fe7b 48 "de_DE" => "Deutsch",
6a214f92 49 "fr_FR" => "Français",
e78fd196 50 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 51 "it_IT" => "Italiano",
1d004f12 52 "ja_JP" => "日本語 (Japanese)",
592535d7 53 "nb_NO" => "Norwegian bokmål",
ea45791a 54 "pl_PL" => "Polski",
6a214f92 55 "ru_RU" => "Русский",
9a063469 56 "pt_BR" => "Portuguese/Brazil",
6a214f92 57 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
58
59 return $tr;
60 }
61
7b26a148
AD
62 require_once "lib/accept-to-gettext.php";
63 require_once "lib/gettext/gettext.inc";
aba609e0 64
7b26a148 65 function startup_gettext() {
8d505d78 66
7b26a148
AD
67 # Get locale from Accept-Language header
68 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 69
7b26a148
AD
70 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
71 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
72 }
89cb787e 73
7b26a148
AD
74 /* In login action of mobile version */
75 if ($_POST["language"] && defined('MOBILE_VERSION')) {
76 $lang = $_POST["language"];
afc3cf55
AD
77 } else {
78 $lang = $_SESSION["language"];
7b26a148 79 }
7c33dbd4 80
7b26a148
AD
81 if ($lang) {
82 if (defined('LC_MESSAGES')) {
83 _setlocale(LC_MESSAGES, $lang);
84 } else if (defined('LC_ALL')) {
85 _setlocale(LC_ALL, $lang);
8d039718 86 }
aba609e0 87
7b26a148
AD
88 if (defined('MOBILE_VERSION')) {
89 _bindtextdomain("messages", "../locale");
90 } else {
91 _bindtextdomain("messages", "locale");
92 }
865220a4 93
7b26a148
AD
94 _textdomain("messages");
95 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 96 }
7b26a148
AD
97 }
98
99 startup_gettext();
cc17c205 100
b619ff15 101 require_once 'db-prefs.php';
8911ac8b 102 require_once 'version.php';
40d13c28 103
a3ee2a38
AD
104 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
105
a18a4f38
AD
106 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
107 define('MAGPIE_USER_AGENT', SELF_USER_AGENT);
108
500943a4
AD
109 ini_set('user_agent', SELF_USER_AGENT);
110
b0f379df 111 require_once 'lib/pubsubhubbub/publisher.php';
acccafe3 112 require_once 'lib/htmLawed.php';
010efc9b 113
7d96bfcd
AD
114 $tz_offset = -1;
115 $utc_tz = new DateTimeZone('UTC');
116 $schema_version = false;
117
45004d43
AD
118 /**
119 * Print a timestamped debug message.
8d505d78 120 *
45004d43
AD
121 * @param string $msg The debug message.
122 * @return void
123 */
6f9e33e4 124 function _debug($msg) {
5439d333
RW
125 if (defined('QUIET') && QUIET) {
126 return;
127 }
6f9e33e4 128 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
131 }
6f9e33e4 132 print "[$ts] $msg\n";
45004d43 133 } // function _debug
6f9e33e4 134
9632f884
AD
135 /**
136 * Purge a feed old posts.
8d505d78 137 *
9632f884
AD
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 */
ad507f85
AD
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
146
07d0efe9 147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
8d505d78 148
ad507f85 149 $rows = -1;
4c193675 150
8d505d78 151 $result = db_query($link,
07d0efe9
AD
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
ab954dff
AD
160 if ($purge_interval == -1 || !$purge_interval) {
161 if ($owner_uid) {
162 ccache_update($link, $feed_id, $owner_uid);
163 }
164 return;
165 }
166
07d0efe9
AD
167 if (!$owner_uid) return;
168
3907ef71
AD
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 }
07d0efe9
AD
176
177 if (!$purge_unread) $query_limit = " unread = false AND ";
178
fefa6ca3 179 if (DB_TYPE == "pgsql") {
6e7f8d26
AD
180 $pg_version = get_pgsql_version($link);
181
182 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 183
8d505d78
AD
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
07d0efe9 188 $query_limit
25ea2805 189 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
190
191 } else {
192
8d505d78
AD
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
07d0efe9 198 $query_limit
25ea2805 199 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 200 }
ad507f85
AD
201
202 $rows = pg_affected_rows($result);
8d505d78 203
fefa6ca3 204 } else {
8d505d78 205
30f1746f 206/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 207 marked = false AND feed_id = '$feed_id' AND
8d505d78 208 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
209 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
210
8d505d78
AD
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
07d0efe9 216 $query_limit
25ea2805 217 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
8d505d78 218
ad507f85
AD
219 $rows = mysql_affected_rows($link);
220
221 }
222
ced46404
AD
223 ccache_update($link, $feed_id, $owner_uid);
224
ad507f85 225 if ($debug) {
6f9e33e4 226 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 227 }
9632f884 228 } // function purge_feed
fefa6ca3 229
07d0efe9
AD
230 function feed_purge_interval($link, $feed_id) {
231
8d505d78 232 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
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
8d505d78 239 if ($purge_interval == 0) $purge_interval = get_pref($link,
863be6ca 240 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
241
242 return $purge_interval;
243
244 } else {
245 return -1;
246 }
247 }
248
a2d79981
AD
249 function purge_orphans($link, $do_output = false) {
250
71604ca4 251 // purge orphaned posts in main content table
8d505d78 252 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4 253 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
254
255 if ($do_output) {
256 $rows = db_affected_rows($link, $result);
257 _debug("Purged $rows orphaned posts.");
258 }
c3a8d71a
AD
259 }
260
c7d57b66
AD
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
ae5f7bb1 280 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
8d505d78
AD
281 $login = urlencode($login);
282 $pass = urlencode($pass);
283
23d2471c
AD
284 global $fetch_last_error;
285
3610b48b 286 if (function_exists('curl_init') && !ini_get("open_basedir")) {
4065b60b 287 $ch = curl_init($url);
a1af1574
AD
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);
8d505d78 295 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
5f6804bc 296 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
19929bbe 297 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
268a06dc 298 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
8d505d78 299
ae5f7bb1
AD
300 if ($post_query) {
301 curl_setopt($ch, CURLOPT_POST, true);
302 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
303 }
304
8d505d78
AD
305 if ($login && $pass)
306 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 307
fb074239 308 $contents = @curl_exec($ch);
268a06dc 309
a1af1574 310 if ($contents === false) {
23d2471c 311 $fetch_last_error = curl_error($ch);
a1af1574
AD
312 curl_close($ch);
313 return false;
4065b60b
AD
314 }
315
8d505d78 316 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
a1af1574
AD
317 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
318 curl_close($ch);
4065b60b 319
8d505d78 320 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
a1af1574
AD
321 return false;
322 }
4065b60b 323
a1af1574 324 return $contents;
4065b60b 325 } else {
9949bd15 326 if ($login && $pass ){
8d505d78
AD
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
23d2471c
AD
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;
4065b60b
AD
343 }
344
345 }
78800912 346
9632f884
AD
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
8d505d78 351 *
9632f884
AD
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 */
1bd11fdf 356 function get_favicon_url($url) {
99331724 357
1bd11fdf 358 $favicon_url = false;
ed214298 359
4065b60b 360 if ($html = @fetch_file_contents($url)) {
78800912 361
ed214298 362 libxml_use_internal_errors(true);
c798704b 363
ed214298
AD
364 $doc = new DOMDocument();
365 $doc->loadHTML($html);
366 $xpath = new DOMXPath($doc);
717f5e64 367
a712429e
AD
368 $base = $xpath->query('/html/head/base');
369 foreach ($base as $b) {
370 $url = $b->getAttribute("href");
371 break;
372 }
373
1bd11fdf 374 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
375 if (count($entries) > 0) {
376 foreach ($entries as $entry) {
1bd11fdf
AD
377 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
378 break;
ed214298 379 }
8d505d78 380 }
4065b60b 381 }
c798704b 382
1bd11fdf
AD
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) {
882311d9 390# print "FAVICON [$site_url]: $favicon_url\n";
4065b60b 391
1bd11fdf
AD
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 }
78800912
AD
436 }
437 }
438
f175937c 439 function print_select($id, $default, $values, $attributes = "") {
79f3553b 440 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
441 foreach ($values as $v) {
442 if ($v == $default)
60807300 443 $sel = "selected=\"1\"";
a0d53889
AD
444 else
445 $sel = "";
8d505d78 446
60807300 447 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
448 }
449 print "</select>";
450 }
40d13c28 451
79f3553b
AD
452 function print_select_hash($id, $default, $values, $attributes = "") {
453 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
454 foreach (array_keys($values) as $v) {
455 if ($v == $default)
74d5c8fa 456 $sel = 'selected="selected"';
673d54ca
AD
457 else
458 $sel = "";
8d505d78 459
673d54ca
AD
460 print "<option $sel value=\"$v\">".$values[$v]."</option>";
461 }
462
463 print "</select>";
464 }
465
406d9489
AD
466 function getmicrotime() {
467 list($usec, $sec) = explode(" ",microtime());
468 return ((float)$usec + (float)$sec);
469 }
470
f541eb78 471 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 472 foreach ($values as $v) {
8d505d78 473
77e96719 474 if ($v == $default)
5da169d9 475 $sel = "checked";
77e96719 476 else
5da169d9
AD
477 $sel = "";
478
f541eb78 479 if ($v == $true_is) {
5da169d9
AD
480 $sel .= " value=\"1\"";
481 } else {
482 $sel .= " value=\"0\"";
483 }
8d505d78
AD
484
485 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 486 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
487
488 }
489 }
490
d9084cf2 491 function initialize_user_prefs($link, $uid, $profile = false) {
ff485f1d
AD
492
493 $uid = db_escape_string($uid);
494
d9084cf2
AD
495 if (!$profile) {
496 $profile = "NULL";
f9aa6a89 497 $profile_qpart = "AND profile IS NULL";
d9084cf2 498 } else {
f9aa6a89 499 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
500 }
501
f9aa6a89
AD
502 if (get_schema_version($link) < 63) $profile_qpart = "";
503
ff485f1d
AD
504 db_query($link, "BEGIN");
505
506 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78
AD
507
508 $u_result = db_query($link, "SELECT pref_name
f9aa6a89 509 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
510
511 $active_prefs = array();
512
513 while ($line = db_fetch_assoc($u_result)) {
8d505d78 514 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
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
f9aa6a89
AD
521 if (get_schema_version($link) < 63) {
522 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 523 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
524 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
525
526 } else {
527 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 528 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
529 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
530 }
ff485f1d
AD
531
532 }
533 }
534
535 db_query($link, "COMMIT");
536
537 }
956c7629 538
8de8bfb8
AD
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
0d421af8 549 function authenticate_user($link, $login, $password, $check_only = false) {
c8437f35 550
131b01b3 551 if (!SINGLE_USER_MODE) {
c8437f35 552
0d421af8
AD
553 $user_id = false;
554 $modules = explode(",", AUTH_MODULES);
66917e70 555
0d421af8
AD
556 foreach ($modules as $module) {
557 $module_class = "auth_$module";
558 if (class_exists($module_class)) {
559 $authenticator = new $module_class($link);
3d72afa1 560
0d421af8 561 $user_id = (int) $authenticator->authenticate($login, $password);
42315f8d 562
200e0d4e
AD
563 if ($user_id) {
564 $_SESSION["auth_module"] = $module;
565 break;
566 }
e90053fe
AD
567
568 } else {
0d421af8
AD
569 print T_sprintf("Fatal: authentication module %s not found.", $module);
570 die;
e90053fe 571 }
461766f3
AD
572 }
573
0d421af8
AD
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'");
8d505d78 579
131b01b3
AD
580 $_SESSION["name"] = db_fetch_result($result, 0, "login");
581 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
8484ce22 582 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
8d505d78
AD
583
584 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 585 $_SESSION["uid"]);
8d505d78 586
131b01b3 587 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 588 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
589
590 $_SESSION["last_version_check"] = time();
8d505d78 591
131b01b3 592 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 593
131b01b3
AD
594 return true;
595 }
8d505d78 596
131b01b3 597 return false;
503eb349 598
131b01b3 599 } else {
503eb349 600
131b01b3
AD
601 $_SESSION["uid"] = 1;
602 $_SESSION["name"] = "admin";
787e5ebc 603 $_SESSION["access_level"] = 10;
21e42e5f 604
0d421af8
AD
605 $_SESSION["hide_hello"] = true;
606 $_SESSION["hide_logout"] = true;
607
d5fd183d
AD
608 $_SESSION["auth_module"] = false;
609
21e42e5f
AD
610 if (!$_SESSION["csrf_token"]) {
611 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
612 }
f557cd78 613
0bbba72d 614 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 615
0bbba72d 616 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 617
c8437f35
AD
618 return true;
619 }
c8437f35
AD
620 }
621
e6cb77a0
AD
622 function make_password($length = 8) {
623
85db6213
AD
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;
e6cb77a0
AD
638 }
639
640 // this is called after user is created to initialize default feeds, labels
641 // or whatever else
8d505d78 642
e6cb77a0
AD
643 // user preferences are checked on every login, not here
644
645 function initialize_user($link, $uid) {
646
e6cb77a0 647 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 648 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 649 'http://tt-rss.org/releases.rss')");
3b0feb9b 650
cd2cd415
AD
651 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
652 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 653 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 654 }
e6cb77a0 655
b8aa49bc 656 function logout_user() {
5ccc1cf5
AD
657 session_destroy();
658 if (isset($_COOKIE[session_name()])) {
659 setcookie(session_name(), '', time()-42000, '/');
660 }
b8aa49bc
AD
661 }
662
8484ce22
AD
663 function validate_csrf($csrf_token) {
664 return $csrf_token == $_SESSION['csrf_token'];
665 }
666
916f788a 667 function validate_session($link) {
0f41fce8
AD
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
d769a0f7 685 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
8d505d78 686 $_SESSION["login_error_msg"] =
d769a0f7
AD
687 __("Session failed to validate (incorrect IP)");
688 return false;
689 }
0f41fce8
AD
690
691 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
05044a59 692 return false;
05044a59 693
e6684130
AD
694 if ($_SESSION["uid"]) {
695
8d505d78 696 $result = db_query($link,
e6684130
AD
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
a885f0ec 706/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 707
8e849206 708 //print_r($_SESSION);
d620cfe7
AD
709
710 if (time() > $_SESSION["cookie_lifetime"]) {
711 return false;
712 }
a885f0ec
AD
713 } */
714
916f788a
AD
715 return true;
716 }
717
97acbaf1
AD
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"]);
01a87dff
AD
736 }
737
afc3cf55
AD
738 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
739 setcookie("ttrss_lang", $_SESSION["language"],
740 time() + SESSION_COOKIE_LIFETIME);
b8aa49bc 741 }
b8aa49bc 742 }
afc3cf55 743 }
3547842a 744
411fe209 745 function truncate_string($str, $max_len, $suffix = '&hellip;') {
12db369c 746 if (mb_strlen($str, "utf-8") > $max_len - 3) {
411fe209 747 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
748 } else {
749 return $str;
750 }
751 }
54a60e1a 752
e9823609 753 function theme_image($link, $filename) {
883fee8d
AD
754 if ($link) {
755 $theme_path = get_user_theme_path($link);
e9823609 756
883fee8d
AD
757 if ($theme_path && is_file($theme_path.$filename)) {
758 return $theme_path.$filename;
759 } else {
760 return $filename;
761 }
e9823609
AD
762 } else {
763 return $filename;
764 }
765 }
766
dce46cad 767 function get_user_theme($link) {
e4c51a6c 768
b92fbcd8 769 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
b97e6e02
AD
770 $theme_name = get_pref($link, "_THEME_ID");
771 if (is_dir("themes/$theme_name")) {
772 return $theme_name;
773 } else {
774 return '';
775 }
e4c51a6c 776 } else {
b97e6e02 777 return '';
e4c51a6c 778 }
d9084cf2 779
dce46cad
AD
780 }
781
782 function get_user_theme_path($link) {
c3fddd05 783 $theme_path = '';
dce46cad 784
b92fbcd8 785 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
dce46cad
AD
786 $theme_name = get_pref($link, "_THEME_ID");
787
b97e6e02 788 if ($theme_name && is_dir("themes/$theme_name")) {
dce46cad 789 $theme_path = "themes/$theme_name/";
6ba50622 790 } else {
dce46cad 791 $theme_name = '';
6ba50622 792 }
54a60e1a 793 } else {
dce46cad
AD
794 $theme_path = '';
795 }
796
0c425dc7 797 if ($theme_path) {
8d3cb8c0
AD
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) {
0c425dc7
AD
801 return $theme_path;
802 }
803 }
804 }
805 return '';
dce46cad
AD
806 }
807
e71f2610
AD
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 }
f1f3a642 819 return '';
e71f2610
AD
820 }
821
8d3cb8c0
AD
822 function print_theme_includes($link) {
823
824 $t = get_user_theme_path($link);
825 $time = time();
826
827 if ($t) {
8d505d78 828 print "<link rel=\"stylesheet\" type=\"text/css\"
8d3cb8c0
AD
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 }
e71f2610 836
dce46cad
AD
837 function get_all_themes() {
838 $themes = glob("themes/*");
839
b97e6e02
AD
840 asort($themes);
841
dce46cad
AD
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);
8d505d78 847 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
0c425dc7 848 !$ini['theme']['disabled']) {
dce46cad
AD
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'];
e71f2610 855 $entry["options"] = $ini['theme']['options'];
dce46cad
AD
856 array_push($rv, $entry);
857 }
858 }
54a60e1a 859 }
dce46cad
AD
860
861 return $rv;
54a60e1a 862 }
be773442 863
ab4b768f
AD
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
324944f3
AD
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
7d96bfcd
AD
888 global $utc_tz;
889 global $tz_offset;
324944f3 890
7d96bfcd
AD
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);
324944f3
AD
905 }
906
7d96bfcd 907 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 908
1dc52ae7 909 if (!$no_smart_dt) {
8d505d78 910 return smart_date_time($link, $user_timestamp,
7d96bfcd 911 $tz_offset, $owner_uid);
324944f3
AD
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
2a5c136e
AD
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)) {
be773442 926 return date("G:i", $timestamp);
2a5c136e
AD
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);
be773442 930 } else {
2a5c136e
AD
931 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
932 return date($format, $timestamp);
be773442
AD
933 }
934 }
935
e3c99f3b 936 function sql_bool_to_bool($s) {
36184020 937 if ($s == "t" || $s == "1" || $s == "true") {
e3c99f3b
AD
938 return true;
939 } else {
940 return false;
941 }
942 }
8d505d78 943
badac687
AD
944 function bool_to_sql_bool($s) {
945 if ($s) {
946 return "true";
947 } else {
948 return "false";
949 }
950 }
e3c99f3b 951
fcfa9ef1
AD
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.
199db684 955 function get_schema_version($link, $nocache = false) {
7d96bfcd
AD
956 global $schema_version;
957
958 if (!$schema_version) {
199db684
AD
959 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
960 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 961 $schema_version = $version;
199db684 962 return $version;
7d96bfcd
AD
963 } else {
964 return $schema_version;
965 }
e4c51a6c
AD
966 }
967
6043fb7e 968 function sanity_check($link) {
31303c6b 969 require_once 'errors.php';
ebb948c2 970
6043fb7e 971 $error_code = 0;
7d96bfcd 972 $schema_version = get_schema_version($link, true);
6043fb7e
AD
973
974 if ($schema_version != SCHEMA_VERSION) {
975 $error_code = 5;
976 }
977
aec3ce39
AD
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
f29ba148
AD
985 if (db_escape_string("testTEST") != "testTEST") {
986 $error_code = 12;
987 }
988
ebb948c2 989 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
990 }
991
27981ca3 992 function file_is_locked($filename) {
31a6d42d 993 if (function_exists('flock')) {
fb074239 994 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
995 if ($fp) {
996 if (flock($fp, LOCK_EX | LOCK_NB)) {
997 flock($fp, LOCK_UN);
998 fclose($fp);
999 return false;
1000 }
27981ca3 1001 fclose($fp);
31a6d42d 1002 return true;
e89aed7b
AD
1003 } else {
1004 return false;
27981ca3 1005 }
27981ca3 1006 }
c1fb4a5e 1007 return true; // consider the file always locked and skip the test
27981ca3
AD
1008 }
1009
fcb4c0c9 1010 function make_lockfile($filename) {
cfa43e02 1011 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 1012
82acc36d 1013 if (flock($fp, LOCK_EX | LOCK_NB)) {
4c59adb1
AD
1014 if (function_exists('posix_getpid')) {
1015 fwrite($fp, posix_getpid() . "\n");
1016 }
fcb4c0c9
AD
1017 return $fp;
1018 } else {
1019 return false;
1020 }
1021 }
1022
bf7fcde8 1023 function make_stampfile($filename) {
cfa43e02 1024 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 1025
8e00ae9b 1026 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 1027 fwrite($fp, time() . "\n");
8e00ae9b 1028 flock($fp, LOCK_UN);
bf7fcde8
AD
1029 fclose($fp);
1030 return true;
1031 } else {
1032 return false;
1033 }
1034 }
1035
894ebcf5
AD
1036 function sql_random_function() {
1037 if (DB_TYPE == "mysql") {
1038 return "RAND()";
1039 } else {
1040 return "RANDOM()";
1041 }
1042 }
1043
184f5195 1044 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
c7e51de1
AD
1045
1046 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 1047
37c03d3a 1048 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 1049
705b97b7
AD
1050 $ref_check_qpart = ($max_id &&
1051 !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
184f5195 1052
37c03d3a 1053 if (is_numeric($feed)) {
23aa0d16
AD
1054 if ($cat_view) {
1055
72a2f4f5 1056 if ($feed >= 0) {
f9fca8cb
AD
1057
1058 if ($feed > 0) {
bda6afa2
AD
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)";
f9fca8cb
AD
1065 } else {
1066 $cat_qpart = "cat_id IS NULL";
1067 }
8d505d78 1068
bda6afa2
AD
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");
23aa0d16 1074
f9fca8cb 1075 } else if ($feed == -2) {
23aa0d16 1076
8d505d78
AD
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
184f5195
AD
1080 AND $ref_check_qpart
1081 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
1082 }
1083
1084 } else if ($feed > 0) {
1085
8d505d78
AD
1086 db_query($link, "UPDATE ttrss_user_entries
1087 SET unread = false,last_read = NOW()
184f5195
AD
1088 WHERE feed_id = '$feed'
1089 AND $ref_check_qpart
1090 AND owner_uid = $owner_uid");
8d505d78 1091
23aa0d16
AD
1092 } else if ($feed < 0 && $feed > -10) { // special, like starred
1093
1094 if ($feed == -1) {
8d505d78 1095 db_query($link, "UPDATE ttrss_user_entries
23aa0d16 1096 SET unread = false,last_read = NOW()
184f5195
AD
1097 WHERE marked = true
1098 AND $ref_check_qpart
1099 AND owner_uid = $owner_uid");
23aa0d16 1100 }
e4f4b46f
AD
1101
1102 if ($feed == -2) {
8d505d78 1103 db_query($link, "UPDATE ttrss_user_entries
e4f4b46f 1104 SET unread = false,last_read = NOW()
184f5195
AD
1105 WHERE published = true
1106 AND $ref_check_qpart
1107 AND owner_uid = $owner_uid");
e4f4b46f
AD
1108 }
1109
2d24f032
AD
1110 if ($feed == -3) {
1111
c1d7e6c3
AD
1112 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1113
2d24f032 1114 if (DB_TYPE == "pgsql") {
8d505d78 1115 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1116 } else {
8d505d78 1117 $match_part = "updated > DATE_SUB(NOW(),
c1d7e6c3 1118 INTERVAL $intl HOUR) ";
2d24f032
AD
1119 }
1120
8d505d78 1121 $result = db_query($link, "SELECT id FROM ttrss_entries,
1f3335dc
AD
1122 ttrss_user_entries WHERE $match_part AND
1123 unread = true AND
8d505d78 1124 ttrss_user_entries.ref_id = ttrss_entries.id AND
c7e51de1 1125 owner_uid = $owner_uid");
1f3335dc
AD
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);
2d24f032
AD
1134 }
1135
3584cb11 1136 if ($feed == -4) {
8d505d78 1137 db_query($link, "UPDATE ttrss_user_entries
3584cb11 1138 SET unread = false,last_read = NOW()
184f5195 1139 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
3584cb11
AD
1140 }
1141
23aa0d16
AD
1142 } else if ($feed < -10) { // label
1143
23aa0d16
AD
1144 $label_id = -$feed - 11;
1145
8d505d78
AD
1146 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1147 SET unread = false, last_read = NOW()
338c238d 1148 WHERE label_id = '$label_id' AND unread = true
184f5195 1149 AND $ref_check_qpart
c7e51de1 1150 AND owner_uid = '$owner_uid' AND ref_id = article_id");
23aa0d16 1151
23aa0d16 1152 }
ad0056a8 1153
c7e51de1 1154 ccache_update($link, $feed, $owner_uid, $cat_view);
ad0056a8 1155
23aa0d16
AD
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
c7e51de1 1162 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
23aa0d16
AD
1163
1164 while ($line = db_fetch_assoc($result)) {
1165 db_query($link, "UPDATE ttrss_user_entries SET
8d505d78 1166 unread = false, last_read = NOW()
184f5195 1167 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
23aa0d16
AD
1168 }
1169 db_query($link, "COMMIT");
1170 }
1171 }
1172
4ffa126e 1173 function getAllCounters($link, $omode = "flc", $active_feed = false) {
cf4d339c 1174
e33fe293 1175 if (!$omode) $omode = "flc";
0a6e5382 1176
6a7817c1 1177 $data = getGlobalCounters($link);
8d505d78 1178
6a7817c1
AD
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));
798f5a64 1184 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
6a7817c1
AD
1185
1186 return $data;
8d505d78 1187 }
a9cb1f83 1188
79178062
AD
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 {
f99759da 1203 return __("Uncategorized");
79178062
AD
1204 }
1205 }
1206 }
1207
1208
a9cb1f83 1209 function getCategoryCounters($link) {
6a7817c1 1210 $ret_arr = array();
bba7c4bf 1211
6a7817c1 1212 /* Labels category */
bba7c4bf 1213
8acc449c 1214 $cv = array("id" => -2, "kind" => "cat",
6a7817c1 1215 "counter" => getCategoryUnread($link, -2));
bba7c4bf 1216
6a7817c1 1217 array_push($ret_arr, $cv);
bba7c4bf 1218
2c5f231e
AD
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
8d505d78
AD
1222 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1223 WHERE ttrss_cat_counters_cache.feed_id = id AND
fc9de939 1224 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
31375163 1225 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
1226
1227 while ($line = db_fetch_assoc($result)) {
22fdebff 1228 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 1229
2c5f231e 1230 if ($line["num_children"] > 0) {
99c9e91a 1231 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
2c5f231e
AD
1232 } else {
1233 $child_counter = 0;
1234 }
1235
8acc449c 1236 $cv = array("id" => $line["cat_id"], "kind" => "cat",
0ef32f48 1237 "counter" => $line["unread"] + $child_counter);
6a7817c1
AD
1238
1239 array_push($ret_arr, $cv);
a9cb1f83 1240 }
d232a40f
AD
1241
1242 /* Special case: NULL category doesn't actually exist in the DB */
1243
9798b2b4 1244 $cv = array("id" => 0, "kind" => "cat",
12e6de72 1245 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
d232a40f 1246
6a7817c1
AD
1247 array_push($ret_arr, $cv);
1248
1249 return $ret_arr;
a9cb1f83
AD
1250 }
1251
2c5f231e 1252 // only accepts real cats (>= 0)
99c9e91a 1253 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
2c5f231e
AD
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);
99c9e91a 1263 $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
2c5f231e
AD
1264 }
1265
1266 return $unread;
1267 }
1268
b6d486a3
AD
1269 function getCategoryUnread($link, $cat, $owner_uid = false) {
1270
1271 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 1272
bba7c4bf 1273 if ($cat >= 0) {
18664970 1274
bba7c4bf
AD
1275 if ($cat != 0) {
1276 $cat_query = "cat_id = '$cat'";
1277 } else {
1278 $cat_query = "cat_id IS NULL";
1279 }
14073c0a 1280
8d505d78 1281 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 1282 AND owner_uid = " . $owner_uid);
8d505d78 1283
bba7c4bf
AD
1284 $cat_feeds = array();
1285 while ($line = db_fetch_assoc($result)) {
1286 array_push($cat_feeds, "feed_id = " . $line["id"]);
1287 }
8d505d78 1288
bba7c4bf 1289 if (count($cat_feeds) == 0) return 0;
8d505d78 1290
bba7c4bf 1291 $match_part = implode(" OR ", $cat_feeds);
8d505d78
AD
1292
1293 $result = db_query($link, "SELECT COUNT(int_id) AS unread
687bb90d
AD
1294 FROM ttrss_user_entries
1295 WHERE unread = true AND ($match_part)
1296 AND owner_uid = " . $owner_uid);
8d505d78 1297
bba7c4bf 1298 $unread = 0;
8d505d78 1299
bba7c4bf
AD
1300 # this needs to be rewritten
1301 while ($line = db_fetch_assoc($result)) {
1302 $unread += $line["unread"];
1303 }
8d505d78 1304
bba7c4bf
AD
1305 return $unread;
1306 } else if ($cat == -1) {
59e15af4 1307 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
bba7c4bf 1308 } else if ($cat == -2) {
f295c368 1309
b2531a28 1310 $result = db_query($link, "
8d505d78 1311 SELECT COUNT(unread) AS unread FROM
687bb90d
AD
1312 ttrss_user_entries, ttrss_user_labels2
1313 WHERE article_id = ref_id AND unread = true
b2531a28 1314 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 1315
b2531a28 1316 $unread = db_fetch_result($result, 0, "unread");
f295c368 1317
b2531a28 1318 return $unread;
f295c368 1319
8d505d78 1320 }
f295c368
AD
1321 }
1322
1323 function getFeedUnread($link, $feed, $is_cat = false) {
2627f2d0 1324 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
1325 }
1326
ceb30ba4
AD
1327 function getLabelUnread($link, $label_id, $owner_uid = false) {
1328 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1329
f360b028
AD
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");
ceb30ba4
AD
1332
1333 if (db_num_rows($result) != 0) {
1334 return db_fetch_result($result, 0, "unread");
1335 } else {
1336 return 0;
1337 }
1338 }
1339
2627f2d0
AD
1340 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1341 $owner_uid = false) {
1342
22fdebff 1343 $n_feed = (int) $feed;
687bb90d 1344 $need_entries = false;
f295c368 1345
2627f2d0
AD
1346 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1347
bdb7369b
AD
1348 if ($unread_only) {
1349 $unread_qpart = "unread = true";
1350 } else {
1351 $unread_qpart = "true";
1352 }
1353
f295c368 1354 if ($is_cat) {
8d505d78 1355 return getCategoryUnread($link, $n_feed, $owner_uid);
5417fbd7
AD
1356 } else if ($n_feed == -6) {
1357 return 0;
1358 } else if ($feed != "0" && $n_feed == 0) {
326469fc 1359
c5701e70
AD
1360 $feed = db_escape_string($feed);
1361
326469fc 1362 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
8d505d78 1363 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
687bb90d 1364 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
1365 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1366 return db_fetch_result($result, 0, "count");
1367
f295c368 1368 } else if ($n_feed == -1) {
a9cb1f83 1369 $match_part = "marked = true";
e4f4b46f
AD
1370 } else if ($n_feed == -2) {
1371 $match_part = "published = true";
2d24f032 1372 } else if ($n_feed == -3) {
cd2cc43d 1373 $match_part = "unread = true AND score >= 0";
2d24f032 1374
b71e188e 1375 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 1376
2d24f032 1377 if (DB_TYPE == "pgsql") {
8d505d78 1378 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1379 } else {
7608b38a 1380 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 1381 }
687bb90d
AD
1382
1383 $need_entries = true;
1384
b2531a28
AD
1385 } else if ($n_feed == -4) {
1386 $match_part = "true";
e04c18a2 1387 } else if ($n_feed >= 0) {
831ff047 1388
6e63a7c3
AD
1389 if ($n_feed != 0) {
1390 $match_part = "feed_id = '$n_feed'";
831ff047 1391 } else {
6e63a7c3 1392 $match_part = "feed_id IS NULL";
831ff047 1393 }
6e63a7c3 1394
a9cb1f83 1395 } else if ($feed < -10) {
318260cc 1396
a9cb1f83
AD
1397 $label_id = -$feed - 11;
1398
ceb30ba4 1399 return getLabelUnread($link, $label_id, $owner_uid);
a9cb1f83 1400
a9cb1f83
AD
1401 }
1402
1403 if ($match_part) {
e04c18a2 1404
687bb90d 1405 if ($need_entries) {
e04c18a2 1406 $from_qpart = "ttrss_user_entries,ttrss_entries";
687bb90d
AD
1407 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1408 } else {
1409 $from_qpart = "ttrss_user_entries";
e04c18a2
AD
1410 }
1411
8d505d78 1412 $query = "SELECT count(int_id) AS unread
e04c18a2 1413 FROM $from_qpart WHERE
687bb90d
AD
1414 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1415
1416 //echo "[$feed/$query]\n";
dbfc4365
AD
1417
1418 $result = db_query($link, $query);
8d505d78 1419
a9cb1f83 1420 } else {
8d505d78 1421
a9cb1f83 1422 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
8d505d78
AD
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
687bb90d 1425 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 1426 }
8d505d78 1427
a9cb1f83 1428 $unread = db_fetch_result($result, 0, "unread");
cfb02131 1429
a9cb1f83
AD
1430 return $unread;
1431 }
1432
f3acc32e
AD
1433 function getGlobalUnread($link, $user_id = false) {
1434
1435 if (!$user_id) {
1436 $user_id = $_SESSION["uid"];
1437 }
1438
8a4c759e
AD
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
8d505d78 1442 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 1443
a9cb1f83
AD
1444 return $c_id;
1445 }
1446
1447 function getGlobalCounters($link, $global_unread = -1) {
6a7817c1
AD
1448 $ret_arr = array();
1449
8d505d78 1450 if ($global_unread == -1) {
a9cb1f83
AD
1451 $global_unread = getGlobalUnread($link);
1452 }
6a7817c1 1453
8d505d78 1454 $cv = array("id" => "global-unread",
12e6de72 1455 "counter" => (int) $global_unread);
6a7817c1
AD
1456
1457 array_push($ret_arr, $cv);
7bf7e4d3 1458
8d505d78 1459 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
1460 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1461
1462 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1463
8d505d78 1464 $cv = array("id" => "subscribed-feeds",
12e6de72 1465 "counter" => (int) $subscribed_feeds);
7bf7e4d3 1466
6a7817c1
AD
1467 array_push($ret_arr, $cv);
1468
1469 return $ret_arr;
a9cb1f83
AD
1470 }
1471
3809b278 1472 function getTagCounters($link) {
8d505d78 1473
6a7817c1 1474 $ret_arr = array();
a9cb1f83 1475
8d505d78
AD
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
687bb90d 1478 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
8d505d78 1479 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
ef1ac7c7 1480 ORDER BY count DESC LIMIT 55");
8d505d78 1481
a9cb1f83
AD
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) {
8d505d78 1489 $unread = $tags[$tag];
a9cb1f83 1490 $tag = htmlspecialchars($tag);
6a7817c1
AD
1491
1492 $cv = array("id" => $tag,
8acc449c 1493 "kind" => "tag",
6a7817c1
AD
1494 "counter" => $unread);
1495
1496 array_push($ret_arr, $cv);
1497 }
1498
8d505d78 1499 return $ret_arr;
a9cb1f83
AD
1500 }
1501
6a7817c1 1502 function getVirtCounters($link) {
a9cb1f83 1503
ef393de7 1504 $ret_arr = array();
bdb7369b 1505
e04c18a2 1506 for ($i = 0; $i >= -4; $i--) {
bdb7369b 1507
ceb30ba4 1508 $count = getFeedUnread($link, $i);
6a7817c1
AD
1509
1510 $cv = array("id" => $i,
12e6de72 1511 "counter" => (int) $count);
8d505d78 1512
296c8134
AD
1513// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1514// $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
bdb7369b 1515
6a7817c1 1516 array_push($ret_arr, $cv);
8d505d78 1517 }
0a6e5382
AD
1518
1519 return $ret_arr;
1520 }
1521
11232703 1522 function getLabelCounters($link, $descriptions = false) {
6a7817c1
AD
1523
1524 $ret_arr = array();
0a6e5382 1525
3809b278 1526 $owner_uid = $_SESSION["uid"];
bdb7369b 1527
3809b278
AD
1528 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1529 WHERE owner_uid = '$owner_uid'");
8d505d78 1530
3809b278 1531 while ($line = db_fetch_assoc($result)) {
2d24f032 1532
3809b278 1533 $id = -$line["id"] - 11;
e4f4b46f 1534
3809b278
AD
1535 $label_name = $line["caption"];
1536 $count = getFeedUnread($link, $id);
3809b278 1537
6a7817c1 1538 $cv = array("id" => $id,
12e6de72 1539 "counter" => (int) $count);
11232703
AD
1540
1541 if ($descriptions)
1542 $cv["description"] = $label_name;
a9cb1f83 1543
296c8134
AD
1544// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1545// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
ef393de7 1546
6a7817c1 1547 array_push($ret_arr, $cv);
3809b278 1548 }
8d505d78 1549
ef393de7 1550 return $ret_arr;
a9cb1f83
AD
1551 }
1552
3809b278 1553 function getFeedCounters($link, $active_feed = false) {
a9cb1f83 1554
6a7817c1
AD
1555 $ret_arr = array();
1556
8a4c759e
AD
1557 $query = "SELECT ttrss_feeds.id,
1558 ttrss_feeds.title,
8d505d78 1559 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
1560 last_error, value AS count
1561 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 1562 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
fc9de939 1563 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
55e01d7e 1564 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 1565
14073c0a 1566 $result = db_query($link, $query);
a9cb1f83
AD
1567 $fctrs_modified = false;
1568
1569 while ($line = db_fetch_assoc($result)) {
8d505d78 1570
a9cb1f83 1571 $id = $line["id"];
de0a2122 1572 $count = $line["count"];
a9cb1f83 1573 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 1574
324944f3 1575 $last_updated = make_local_datetime($link, $line['last_updated'], false);
fb1fb4ab 1576
7defa089 1577 $has_img = feed_has_icon($id);
a9cb1f83 1578
428b704d
AD
1579 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1580 $last_updated = '';
1581
6a7817c1 1582 $cv = array("id" => $id,
21884958 1583 "updated" => $last_updated,
12e6de72 1584 "counter" => (int) $count,
6a7817c1 1585 "has_img" => (int) $has_img);
a9cb1f83 1586
6a7817c1
AD
1587 if ($last_error)
1588 $cv["error"] = $last_error;
4ffa126e 1589
296c8134
AD
1590// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1591// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
bdb7369b 1592
6a7817c1 1593 if ($active_feed && $id == $active_feed)
fbc95c5b 1594 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
1595
1596 array_push($ret_arr, $cv);
a9cb1f83 1597
a9cb1f83 1598 }
6a7817c1
AD
1599
1600 return $ret_arr;
a9cb1f83
AD
1601 }
1602
6e7f8d26
AD
1603 function get_pgsql_version($link) {
1604 $result = db_query($link, "SELECT version() AS version");
9949bd15 1605 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
1606 return $version[1];
1607 }
1608
2b8290cd 1609 /**
23d2471c
AD
1610 * @return array (code => Status code, message => error message if available)
1611 *
2b8290cd
CW
1612 * 0 - OK, Feed already exists
1613 * 1 - OK, Feed added
1614 * 2 - Invalid URL
9a8ce956
CW
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.
5414ad4c 1619 * 5 - Couldn't download the URL content.
2b8290cd 1620 */
8d505d78 1621 function subscribe_to_feed($link, $url, $cat_id = 0,
aa60999b 1622 $auth_login = '', $auth_pass = '', $need_auth = false) {
bb0f29a4 1623
23d2471c
AD
1624 global $fetch_last_error;
1625
2c08214a
AD
1626 require_once "include/rssfuncs.php";
1627
f0266f51 1628 $url = fix_url($url);
ec39a02c 1629
23d2471c 1630 if (!$url || !validate_feed_url($url)) return array("code" => 2);
a5819bb3 1631
b3009bcd
AD
1632 $update_method = 0;
1633
759e5132
AD
1634 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1635
1636 if (!$contents) {
304aadb9 1637 return array("code" => 5, "message" => $fetch_last_error);
759e5132
AD
1638 }
1639
1640 if (is_html($contents)) {
1641 $feedUrls = get_feeds_from_html($url, $contents);
304aadb9 1642
304aadb9
AD
1643 if (count($feedUrls) == 0) {
1644 return array("code" => 3);
1645 } else if (count($feedUrls) > 1) {
759e5132 1646 return array("code" => 4, "feeds" => $feedUrls);
f6d8345b 1647 }
304aadb9
AD
1648 //use feed url as new URL
1649 $url = key($feedUrls);
1650 }
f6d8345b 1651
956c7629
AD
1652 if ($cat_id == "0" || !$cat_id) {
1653 $cat_qpart = "NULL";
1654 } else {
1655 $cat_qpart = "'$cat_id'";
1656 }
8d505d78 1657
956c7629 1658 $result = db_query($link,
8d505d78 1659 "SELECT id FROM ttrss_feeds
a5819bb3 1660 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 1661
956c7629 1662 if (db_num_rows($result) == 0) {
956c7629 1663 $result = db_query($link,
8d505d78
AD
1664 "INSERT INTO ttrss_feeds
1665 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1666 VALUES ('".$_SESSION["uid"]."', '$url',
b3009bcd 1667 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
8d505d78 1668
956c7629 1669 $result = db_query($link,
8d505d78 1670 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 1671 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 1672
956c7629 1673 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 1674
956c7629 1675 if ($feed_id) {
c633e370 1676 update_rss_feed($link, $feed_id, true);
956c7629
AD
1677 }
1678
23d2471c 1679 return array("code" => 1);
956c7629 1680 } else {
23d2471c 1681 return array("code" => 0);
956c7629
AD
1682 }
1683 }
1684
8d505d78 1685 function print_feed_select($link, $id, $default_id = "",
4c9d0490
AD
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 }
673d54ca 1695 }
8d505d78 1696
4c9d0490 1697 if (get_pref($link, 'ENABLE_FEED_CATS')) {
673d54ca 1698
4c9d0490
AD
1699 if ($root_id)
1700 $parent_qpart = "parent_cat = '$root_id'";
1701 else
1702 $parent_qpart = "parent_cat IS NULL";
673d54ca 1703
4c9d0490
AD
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 }
673d54ca 1738 }
b1710666 1739
4c9d0490
AD
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 }
b1710666 1761
4c9d0490
AD
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 }
673d54ca 1773 }
8d505d78 1774
4c9d0490
AD
1775 if (!$root_id) {
1776 print "</select>";
1777 }
673d54ca
AD
1778 }
1779
fbf85cf6
AD
1780 function print_feed_cat_select($link, $id, $default_id,
1781 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
8d505d78 1782
fbf85cf6
AD
1783 if (!$root_id) {
1784 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1785 }
673d54ca 1786
fbf85cf6
AD
1787 if ($root_id)
1788 $parent_qpart = "parent_cat = '$root_id'";
1789 else
1790 $parent_qpart = "parent_cat IS NULL";
673d54ca 1791
fbf85cf6
AD
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");
673d54ca 1797
fbf85cf6
AD
1798 while ($line = db_fetch_assoc($result)) {
1799 if ($line["id"] == $default_id) {
1800 $is_selected = "selected=\"1\"";
1801 } else {
1802 $is_selected = "";
1803 }
673d54ca 1804
fbf85cf6
AD
1805 for ($i = 0; $i < $nest_level; $i++)
1806 $line["title"] = " - " . $line["title"];
c00907f2 1807
fbf85cf6
AD
1808 if ($line["title"])
1809 printf("<option $is_selected value='%d'>%s</option>",
1810 $line["id"], htmlspecialchars($line["title"]));
673d54ca 1811
fbf85cf6
AD
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 }
5c7c7da9 1816
fbf85cf6
AD
1817 if (!$root_id) {
1818 if ($include_all_cats) {
1819 if (db_num_rows($result) > 0) {
1820 print "<option disabled=\"1\">--------</option>";
1821 }
7e18f8e7
AD
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>";
fbf85cf6
AD
1830 }
1831 print "</select>";
1832 }
1833 }
8d505d78 1834
14f69488
AD
1835 function checkbox_to_sql_bool($val) {
1836 return ($val == "on") ? "true" : "false";
1837 }
86b682ce
AD
1838
1839 function getFeedCatTitle($link, $id) {
1840 if ($id == -1) {
d1db26aa 1841 return __("Special");
86b682ce 1842 } else if ($id < -10) {
d1db26aa 1843 return __("Labels");
86b682ce 1844 } else if ($id > 0) {
8d505d78 1845 $result = db_query($link, "SELECT ttrss_feed_categories.title
86b682ce
AD
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 {
d1db26aa 1851 return __("Uncategorized");
86b682ce
AD
1852 }
1853 } else {
1854 return "getFeedCatTitle($id) failed";
1855 }
1856
1857 }
1858
9299102f 1859 function getFeedIcon($id) {
af88c48a 1860 switch ($id) {
4bee8b5f
AD
1861 case 0:
1862 return "images/archive.png";
1863 break;
af88c48a 1864 case -1:
f65ffc2d 1865 return "images/mark_set.png";
af88c48a
AD
1866 break;
1867 case -2:
b97e6e02 1868 return "images/pub_set.png";
af88c48a
AD
1869 break;
1870 case -3:
1871 return "images/fresh.png";
1872 break;
1873 case -4:
1874 return "images/tag.png";
1875 break;
5417fbd7
AD
1876 case -6:
1877 return "images/recently_read.png";
1878 break;
af88c48a 1879 default:
4bee8b5f
AD
1880 if ($id < -10) {
1881 return "images/label.png";
1882 } else {
8d505d78 1883 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 1884 return ICONS_URL . "/$id.ico";
4bee8b5f 1885 }
af88c48a
AD
1886 break;
1887 }
1888 }
1889
fd994f1a
AD
1890 function getFeedTitle($link, $id, $cat = false) {
1891 if ($cat) {
8add44ec 1892 return getCategoryTitle($link, $id);
fd994f1a 1893 } else if ($id == -1) {
d1db26aa 1894 return __("Starred articles");
945c243e
AD
1895 } else if ($id == -2) {
1896 return __("Published articles");
2d24f032
AD
1897 } else if ($id == -3) {
1898 return __("Fresh articles");
b2531a28
AD
1899 } else if ($id == -4) {
1900 return __("All articles");
80db1113 1901 } else if ($id === 0 || $id === "0") {
e04c18a2 1902 return __("Archived articles");
5417fbd7
AD
1903 } else if ($id == -6) {
1904 return __("Recently read");
86b682ce 1905 } else if ($id < -10) {
76626c72 1906 $label_id = -$id - 11;
ceb30ba4 1907 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 1908 if (db_num_rows($result) == 1) {
ceb30ba4 1909 return db_fetch_result($result, 0, "caption");
86b682ce
AD
1910 } else {
1911 return "Unknown label ($label_id)";
1912 }
1913
147f5632 1914 } else if (is_numeric($id) && $id > 0) {
86b682ce
AD
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 {
22fdebff 1922 return $id;
86b682ce 1923 }
86b682ce 1924 }
3dd46f19 1925
d8221301 1926 function make_init_params($link) {
f1f3a642 1927 $params = array();
c9268ed5 1928
c4f7ba80
AD
1929 $params["theme"] = get_user_theme($link);
1930 $params["theme_options"] = get_user_theme_options($link);
f6d6e22f 1931
c4f7ba80
AD
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");
be0801a1 1936
f1f3a642
AD
1937 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1938 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
7d12b6c8 1939 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
30b6ee8c 1940 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 1941
c4f7ba80 1942 $params[strtolower($param)] = (int) get_pref($link, $param);
f1f3a642 1943 }
40496720 1944
c4f7ba80
AD
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");
c4f7ba80 1950 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
59b223d7 1951
8cd576a1 1952 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
1953 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1954
8cd576a1
AD
1955 $max_feed_id = db_fetch_result($result, 0, "mid");
1956 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 1957
8cd576a1 1958 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 1959 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 1960
c4f7ba80 1961 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
9b7ecc0a 1962
8484ce22
AD
1963 $params["csrf_token"] = $_SESSION["csrf_token"];
1964
d8221301 1965 return $params;
3ac2b520 1966 }
f54f515f 1967
c4f7ba80 1968 function make_runtime_info($link) {
8cd576a1
AD
1969 $data = array();
1970
1971 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
1972 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1973
8cd576a1
AD
1974 $max_feed_id = db_fetch_result($result, 0, "mid");
1975 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 1976
8cd576a1
AD
1977 $data["max_feed_id"] = (int) $max_feed_id;
1978 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 1979
f8fb4498 1980 $data['last_article_id'] = getLastArticleId($link);
5ae8f858 1981 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
f8fb4498 1982
dbaa4e4a 1983 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
1984
1985 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 1986
9041f58b 1987 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 1988
fb074239 1989 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 1990
8e00ae9b 1991 if ($stamp) {
9041f58b
AD
1992 $stamp_delta = time() - $stamp;
1993
1994 if ($stamp_delta > 1800) {
f6854e44 1995 $stamp_check = 0;
8e00ae9b 1996 } else {
f6854e44
AD
1997 $stamp_check = 1;
1998 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
1999 }
2000
c4f7ba80 2001 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 2002
8e00ae9b
AD
2003 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2004
c4f7ba80 2005 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 2006 }
8e00ae9b 2007 }
71ad883b 2008 }
8e00ae9b 2009
63855db1 2010 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
fb074239 2011 $new_version_details = @check_for_update($link);
d9fa39f1 2012
63855db1 2013 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
2014
2015 $_SESSION["last_version_check"] = time();
27211afe 2016 $_SESSION["version_data"] = $new_version_details;
d9fa39f1
AD
2017 }
2018
c4f7ba80 2019 return $data;
f54f515f 2020 }
ef393de7 2021
b7d1a163 2022 function search_to_sql($link, $search, $match_on) {
ef393de7 2023
88040f57 2024 $search_query_part = "";
e20c9d88 2025
9949bd15 2026 $keywords = explode(" ", $search);
88040f57 2027 $query_keywords = array();
e20c9d88 2028
ab4b768f
AD
2029 foreach ($keywords as $k) {
2030 if (strpos($k, "-") === 0) {
2031 $k = substr($k, 1);
2032 $not = "NOT";
2033 } else {
2034 $not = "";
88040f57 2035 }
e20c9d88 2036
9949bd15 2037 $commandpair = explode(":", mb_strtolower($k), 2);
53003548
AD
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) {
e20c9d88 2061
ab4b768f
AD
2062 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2063 $orig_ts = strtotime(substr($k, 1));
ab4b768f 2064 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 2065
53003548
AD
2066 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2067
ab4b768f
AD
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") {
eb6c7f42 2073 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
ab4b768f 2074 } else if ($match_on == "content") {
eb6c7f42 2075 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
88040f57
AD
2076 }
2077 }
2078
2079 $search_query_part = implode("AND", $query_keywords);
2080
2081 return $search_query_part;
2082 }
2083
67bd0b1f
AD
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
6d8d00e8
AD
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 }
147f5632 2111
09101297 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) {
c36bf4d5
AD
2113
2114 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 2115
c3fddd05
AD
2116 $ext_tables_part = "";
2117
88040f57 2118 if ($search) {
e4f7f8df
AD
2119
2120 if (SPHINX_ENABLED) {
2121 $ids = join(",", @sphinx_search($search, 0, 500));
2122
8d505d78 2123 if ($ids)
e4f7f8df
AD
2124 $search_query_part = "ref_id IN ($ids) AND ";
2125 else
2126 $search_query_part = "ref_id = -1 AND ";
2127
2128 } else {
b7d1a163 2129 $search_query_part = search_to_sql($link, $search, $match_on);
e4f7f8df 2130 $search_query_part .= " AND ";
8d505d78 2131 }
e20c9d88 2132
ef393de7
AD
2133 } else {
2134 $search_query_part = "";
2135 }
2136
36184020 2137 if ($filter) {
4e02f582
AD
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
2680295b 2147 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
dd8c36af
AD
2148
2149 // Try to check if SQL regexp implementation chokes on a valid regexp
2680295b
AD
2150 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2151 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
dd8c36af
AD
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
36184020
AD
2162 } else {
2163 $filter_query_part = "";
2164 }
2165
97e5dbb2
AD
2166 if ($since_id) {
2167 $since_id_part = "ttrss_entries.id > $since_id AND ";
2168 } else {
2169 $since_id_part = "";
2170 }
2171
ef393de7 2172 $view_query_part = "";
8d505d78 2173
7b4d02a8 2174 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
ef393de7
AD
2175 if ($search) {
2176 $view_query_part = " ";
2177 } else if ($feed != -1) {
f295c368 2178 $unread = getFeedUnread($link, $feed, $cat_view);
6d8d00e8 2179
09101297 2180 if ($cat_view && $feed > 0 && $include_children)
99c9e91a 2181 $unread += getCategoryChildrenUnread($link, $feed);
6d8d00e8 2182
ef393de7 2183 if ($unread > 0) {
ff863e00 2184 $view_query_part = " unread = true AND ";
ef393de7
AD
2185 }
2186 }
2187 }
8d505d78 2188
ef393de7
AD
2189 if ($view_mode == "marked") {
2190 $view_query_part = " marked = true AND ";
2191 }
23d72f39
AD
2192
2193 if ($view_mode == "published") {
2194 $view_query_part = " published = true AND ";
2195 }
2196
ef393de7
AD
2197 if ($view_mode == "unread") {
2198 $view_query_part = " unread = true AND ";
2199 }
8b09eac8
AD
2200
2201 if ($view_mode == "updated") {
2202 $view_query_part = " (last_read is null and unread = false) AND ";
2203 }
2204
ef393de7
AD
2205 if ($limit > 0) {
2206 $limit_query_part = "LIMIT " . $limit;
8d505d78 2207 }
ef393de7 2208
8361e724
AD
2209 $allow_archived = false;
2210
ef393de7 2211 $vfeed_query_part = "";
8d505d78 2212
ef393de7
AD
2213 // override query strategy and enable feed display when searching globally
2214 if ($search && $search_mode == "all_feeds") {
7032f2a5 2215 $query_strategy_part = "true";
8d505d78 2216 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 2217 /* tags */
75c648cf 2218 } else if (!is_numeric($feed)) {
7032f2a5 2219 $query_strategy_part = "true";
ef393de7
AD
2220 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2221 id = feed_id) as feed_title,";
7032f2a5 2222 } else if ($search && $search_mode == "this_cat") {
8d505d78 2223 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846 2224
7032f2a5
AD
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;
ef393de7 2232 }
8d505d78 2233
7032f2a5 2234 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
8d505d78 2235
ef393de7 2236 } else {
7032f2a5 2237 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
ef393de7 2238 }
8d505d78 2239
e04c18a2 2240 } else if ($feed > 0) {
8d505d78 2241
ef393de7 2242 if ($cat_view) {
5c365f60 2243
ef393de7 2244 if ($feed > 0) {
09101297
AD
2245 if ($include_children) {
2246 # sub-cats
2247 $subcats = getChildCategories($link, $feed, $owner_uid);
2248
7032f2a5
AD
2249 array_push($subcats, $feed);
2250 $query_strategy_part = "cat_id IN (".
09101297 2251 implode(",", $subcats).")";
7032f2a5 2252
6d8d00e8 2253 } else {
09101297 2254 $query_strategy_part = "cat_id = '$feed'";
6d8d00e8
AD
2255 }
2256
ef393de7
AD
2257 } else {
2258 $query_strategy_part = "cat_id IS NULL";
2259 }
8d505d78 2260
ef393de7 2261 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 2262
8d505d78 2263 } else {
6e63a7c3 2264 $query_strategy_part = "feed_id = '$feed'";
ef393de7 2265 }
bfe5ddfc 2266 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 2267 $query_strategy_part = "feed_id IS NULL";
8361e724 2268 $allow_archived = true;
bfe5ddfc 2269 } else if ($feed == 0 && $cat_view) { // uncategorized
65dd90f2 2270 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
bfe5ddfc 2271 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2272 } else if ($feed == -1) { // starred virtual feed
2273 $query_strategy_part = "marked = true";
2274 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294
AD
2275 $allow_archived = true;
2276
e6a38cde
AD
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,";
8361e724 2282 $allow_archived = true;
46b78149
AD
2283
2284 if (!$override_order) $override_order = "last_read DESC, updated DESC";
e6a38cde
AD
2285 } else {
2286 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2287
2288 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 2289
e6a38cde
AD
2290 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2291 ttrss_user_labels2.article_id = ref_id";
2292
2293 }
5417fbd7 2294 } else if ($feed == -6) { // recently read
5089b30b 2295 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
5417fbd7 2296 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294 2297 $allow_archived = true;
46b78149
AD
2298
2299 if (!$override_order) $override_order = "last_read DESC";
2d24f032 2300 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 2301 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 2302
7a22dc2a 2303 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2304
2d24f032 2305 if (DB_TYPE == "pgsql") {
8d505d78 2306 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2307 } else {
7608b38a 2308 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
2309 }
2310
b2531a28
AD
2311 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2312 } else if ($feed == -4) { // all articles virtual feed
2313 $query_strategy_part = "true";
e4f4b46f 2314 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2315 } else if ($feed <= -10) { // labels
2316 $label_id = -$feed - 11;
3de0261a 2317
ceb30ba4
AD
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";
3de0261a 2321
ef393de7 2322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 2323 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
835fb294 2324 $allow_archived = true;
8d505d78 2325
ef393de7 2326 } else {
835fb294 2327 $query_strategy_part = "true";
ef393de7 2328 }
d6e5706d 2329
b3990c92
AD
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
7a22dc2a 2336 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
b3990c92 2337 $order_by = "$date_sort_field";
8d505d78 2338 } else {
b3990c92 2339 $order_by = "$date_sort_field DESC";
d6e5706d 2340 }
e939722a 2341
7b4d02a8
AD
2342 if ($view_mode != "noscores") {
2343 $order_by = "score DESC, $order_by";
2344 }
48b0c4ec 2345
e939722a
AD
2346 if ($override_order) {
2347 $order_by = $override_order;
2348 }
8d505d78 2349
ef393de7
AD
2350 $feed_title = "";
2351
22fdebff 2352 if ($search) {
7032f2a5 2353 $feed_title = T_sprintf("Search results: %s", $search);
22fdebff 2354 } else {
ef393de7 2355 if ($cat_view) {
22fdebff 2356 $feed_title = getCategoryTitle($link, $feed);
ef393de7 2357 } else {
147f5632 2358 if (is_numeric($feed) && $feed > 0) {
8d505d78 2359 $result = db_query($link, "SELECT title,site_url,last_error
22fdebff 2360 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2361
22fdebff
AD
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);
8d505d78 2367 }
88040f57 2368 }
ef393de7
AD
2369 }
2370
87764a50 2371 $content_query_part = "content as content_preview, cached_content, ";
62129e67 2372
75c648cf 2373 if (is_numeric($feed)) {
8d505d78 2374
ef393de7
AD
2375 if ($feed >= 0) {
2376 $feed_kind = "Feeds";
2377 } else {
2378 $feed_kind = "Labels";
2379 }
8d505d78 2380
95a82c08
AD
2381 if ($limit_query_part) {
2382 $offset_query_part = "OFFSET $offset";
2383 }
2384
7fdf8eca 2385 // proper override_order applied above
d00f22ac 2386 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 2387 if (!$override_order) {
8d505d78 2388 $order_by = "ttrss_feeds.title, $order_by";
7fdf8eca
AD
2389 } else {
2390 $order_by = "ttrss_feeds.title, $override_order";
43fc671f 2391 }
6cfea5c7
AD
2392 }
2393
8361e724 2394 if (!$allow_archived) {
e04c18a2 2395 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 2396 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2397
2398 } else {
835fb294 2399 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
e04c18a2
AD
2400 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2401 }
2402
8d505d78 2403 $query = "SELECT DISTINCT
f9b2d27c 2404 date_entered,
1f64b1be 2405 guid,
ef393de7 2406 ttrss_entries.id,ttrss_entries.title,
46921916 2407 updated,
9c506873
AD
2408 label_cache,
2409 tag_cache,
c0644ee4 2410 always_display_enclosures,
d1fc2f92 2411 site_url,
c7e51de1 2412 note,
13992673
AD
2413 num_comments,
2414 comments,
db16ae50 2415 int_id,
494a64ea 2416 unread,feed_id,marked,published,link,last_read,orig_feed_id,
fc2b26a6 2417 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
ef393de7
AD
2418 $vfeed_query_part
2419 $content_query_part
fc2b26a6 2420 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
ff6e357a 2421 author,score
ef393de7 2422 FROM
e04c18a2 2423 $from_qpart
ef393de7 2424 WHERE
e04c18a2 2425 $feed_check_qpart
ef393de7 2426 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 2427 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 2428 $search_query_part
36184020 2429 $filter_query_part
ef393de7 2430 $view_query_part
97e5dbb2 2431 $since_id_part
ef393de7 2432 $query_strategy_part ORDER BY $order_by
95a82c08 2433 $limit_query_part $offset_query_part";
4bc311fc 2434
b4e75b2a 2435 if ($_REQUEST["debug"]) print $query;
4bc311fc
AD
2436
2437 $result = db_query($link, $query);
8d505d78 2438
ef393de7
AD
2439 } else {
2440 // browsing by tag
8d505d78 2441
147f5632
CM
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," .
d1fc2f92
AD
2453 "num_comments, " .
2454 "comments, " .
c0644ee4
AD
2455 "tag_cache," .
2456 "label_cache," .
147f5632
CM
2457 "link," .
2458 "last_read," .
2459 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
97e5dbb2 2460 $since_id_part .
147f5632
CM
2461 $vfeed_query_part .
2462 $content_query_part .
2463 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
2464 "score ";
2465
ef393de7 2466 $feed_kind = "Tags";
147f5632
CM
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;
8d505d78 2479
147f5632
CM
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);
ef393de7
AD
2507 }
2508
c7188969 2509 return array($result, $feed_title, $feed_site_url, $last_error);
8d505d78 2510
ef393de7
AD
2511 }
2512
b3682750 2513 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
ceb0cab5
AD
2514 if (!$owner) $owner = $_SESSION["uid"];
2515
96811a55
AD
2516 $res = trim($str); if (!$res) return '';
2517
d9f3f57b 2518 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
acccafe3 2519 $res = htmLawed($res, $config);
f826eee1 2520
ceb0cab5 2521 if (get_pref($link, "STRIP_IMAGES", $owner)) {
8dccabed 2522 $res = preg_replace('/<img[^>]+>/is', '', $res);
7514749d 2523 }
8dccabed 2524
46137483
AD
2525 if (strpos($res, "href=") === false)
2526 $res = rewrite_urls($res);
533c0ea6 2527
8cc3c778
AD
2528 $charset_hack = '<head>
2529 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2530 </head>';
2531
96811a55
AD
2532 $res = trim($res); if (!$res) return '';
2533
8cc3c778
AD
2534 libxml_use_internal_errors(true);
2535
2536 $doc = new DOMDocument();
2537 $doc->loadHTML($charset_hack . $res);
2538 $xpath = new DOMXPath($doc);
8d505d78 2539
8cc3c778 2540 $entries = $xpath->query('(//a[@href]|//img[@src])');
3f770c87 2541 $br_inserted = 0;
8cc3c778
AD
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')));
8d505d78 2550
8cc3c778 2551 if ($entry->hasAttribute('src'))
8d505d78 2552 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
b8998470
AD
2553 $entry->setAttribute('src',
2554 rewrite_relative_url($site_url, $entry->getAttribute('src')));
8cc3c778
AD
2555 }
2556
fa403733 2557 if (strtolower($entry->nodeName) == "a") {
c401d5c9 2558 $entry->setAttribute("target", "_blank");
fa403733
AD
2559 }
2560
3f770c87 2561 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
fa403733
AD
2562 $br = $doc->createElement("br");
2563
3f770c87 2564 if ($entry->parentNode->nextSibling) {
fa403733 2565 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3f770c87
AD
2566 $br_inserted = 1;
2567 }
fa403733 2568
8cc3c778 2569 }
8dccabed 2570 }
8d505d78 2571
1f6131f5 2572 $node = $doc->getElementsByTagName('body')->item(0);
8dccabed 2573
7b8ff151 2574 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
183ad07b 2575 }
b72c3ef8 2576
45004d43
AD
2577 /**
2578 * Send by mail a digest of last articles.
8d505d78 2579 *
45004d43
AD
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 */
8437c066 2584 function send_headlines_digests($link, $debug = false) {
9cd7c995 2585
31303c6b
AD
2586 require_once 'lib/phpmailer/class.phpmailer.php';
2587
09e8bdfd 2588 $user_limit = 15; // amount of users to process (e.g. emails to send out)
8437c066 2589 $limit = 1000; // maximum amount of headlines to include
9cd7c995 2590
61c1812f 2591 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
9cd7c995
AD
2592
2593 if (DB_TYPE == "pgsql") {
61c1812f 2594 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
9cd7c995 2595 } else if (DB_TYPE == "mysql") {
61c1812f 2596 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
9cd7c995
AD
2597 }
2598
8d505d78 2599 $result = db_query($link, "SELECT id,email FROM ttrss_users
9cd7c995
AD
2600 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2601
2602 while ($line = db_fetch_assoc($result)) {
dc85be2b 2603
9cd7c995 2604 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
61c1812f 2605 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
9cd7c995 2606
1b9b19af
AD
2607 // try to send digests within 2 hours of preferred time
2608 if ($preferred_ts && time() >= $preferred_ts &&
2609 time() - $preferred_ts <= 7200) {
dc85be2b 2610
61c1812f 2611 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
9cd7c995 2612
61c1812f 2613 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
a8931123 2614
6d490c44
AD
2615 global $tz_offset;
2616
2617 // reset tz_offset global to prevent tz cache clash between users
2618 $tz_offset = -1;
2619
61c1812f
AD
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];
a8931123 2625
61c1812f 2626 if ($headlines_count > 0) {
a8931123 2627
61c1812f 2628 $mail = new PHPMailer();
a8931123 2629
61c1812f
AD
2630 $mail->PluginDir = "lib/phpmailer/";
2631 $mail->SetLanguage("en", "lib/phpmailer/language/");
c7ddac5c 2632
61c1812f
AD
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"]);
a8931123 2638
61c1812f
AD
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 }
a8931123 2646
61c1812f
AD
2647 $mail->IsHTML(true);
2648 $mail->Subject = DIGEST_SUBJECT;
2649 $mail->Body = $digest;
2650 $mail->AltBody = $digest_text;
a8931123 2651
61c1812f 2652 $rc = $mail->Send();
a8931123 2653
61c1812f 2654 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo;
a8931123 2655
61c1812f
AD
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";
dc85be2b 2664 }
019dd98d 2665
61c1812f
AD
2666 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2667 WHERE id = " . $line["id"]);
2668
2669 }
9cd7c995
AD
2670 }
2671 }
2672
036cd3a4 2673 if ($debug) _debug("All done.");
cedd3e89 2674
9cd7c995
AD
2675 }
2676
8437c066 2677 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
c62a2c21 2678
fe7537b5 2679 require_once "lib/MiniTemplator.class.php";
c62a2c21
AD
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
6d490c44
AD
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));
c62a2c21 2692
6d490c44
AD
2693 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2694 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
7e3634d9 2695
dc85be2b
AD
2696 $affected_ids = array();
2697
7e3634d9 2698 if (DB_TYPE == "pgsql") {
25ea2805 2699 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
7e3634d9 2700 } else if (DB_TYPE == "mysql") {
25ea2805 2701 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
7e3634d9
AD
2702 }
2703
2704 $result = db_query($link, "SELECT ttrss_entries.title,
2705 ttrss_feeds.title AS feed_title,
68916212 2706 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
25ea2805 2707 date_updated,
dc85be2b 2708 ttrss_user_entries.ref_id,
7e3634d9 2709 link,
8437c066
AD
2710 score,
2711 content,
fc2b26a6 2712 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
2713 FROM
2714 ttrss_user_entries,ttrss_entries,ttrss_feeds
8437c066
AD
2715 LEFT JOIN
2716 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
8d505d78
AD
2717 WHERE
2718 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3dd9183c 2719 AND include_in_digest = true
7e3634d9 2720 AND $interval_query
448b0abd 2721 AND ttrss_user_entries.owner_uid = $user_id
8d505d78 2722 AND unread = true
8437c066
AD
2723 AND score >= 0
2724 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
7e3634d9
AD
2725 LIMIT $limit");
2726
2727 $cur_feed_title = "";
2728
9cd7c995
AD
2729 $headlines_count = db_num_rows($result);
2730
c62a2c21
AD
2731 $headlines = array();
2732
7e3634d9 2733 while ($line = db_fetch_assoc($result)) {
c62a2c21
AD
2734 array_push($headlines, $line);
2735 }
2736
8d505d78 2737 for ($i = 0; $i < sizeof($headlines); $i++) {
c62a2c21
AD
2738
2739 $line = $headlines[$i];
dc85be2b
AD
2740
2741 array_push($affected_ids, $line["ref_id"]);
2742
324944f3
AD
2743 $updated = make_local_datetime($link, $line['last_updated'], false,
2744 $user_id);
7e3634d9 2745
8437c066
AD
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)) {
8437c066
AD
2753 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2754 }
2755
c62a2c21
AD
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);
8d505d78 2760 $tpl->setVariable('ARTICLE_EXCERPT',
8437c066
AD
2761 truncate_string(strip_tags($line["content"]), 300));
2762// $tpl->setVariable('ARTICLE_CONTENT',
2763// strip_tags($article_content));
7e3634d9 2764
c62a2c21
AD
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);
8d505d78 2771// $tpl_t->setVariable('ARTICLE_EXCERPT',
c62a2c21
AD
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');
7e3634d9
AD
2779 }
2780
7e3634d9
AD
2781 }
2782
c62a2c21
AD
2783 $tpl->addBlock('digest');
2784 $tpl->generateOutputToString($tmp);
2785
2786 $tpl_t->addBlock('digest');
2787 $tpl_t->generateOutputToString($tmp_t);
7e3634d9 2788
c62a2c21 2789 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
7e3634d9
AD
2790 }
2791
73495fd1 2792 function check_for_update($link) {
63855db1
AD
2793 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2794 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
b72c3ef8 2795
63855db1 2796 $version_data = @fetch_file_contents($version_url);
b72c3ef8 2797
63855db1
AD
2798 if ($version_data) {
2799 $version_data = json_decode($version_data, true);
8d505d78 2800 if ($version_data && $version_data['version']) {
f67d9754 2801
63855db1 2802 if (version_compare(VERSION, $version_data['version']) == -1) {
e91ad1e9 2803 return $version_data;
63855db1
AD
2804 }
2805 }
f67d9754 2806 }
b72c3ef8 2807 }
63855db1 2808 return false;
b72c3ef8 2809 }
472782e8 2810
18eddb2c
AD
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) {
8d505d78 2822 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
2823 marked = false,last_read = NOW()
2824 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2825 } else if ($cmode == 1) {
8d505d78 2826 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
2827 marked = true
2828 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2829 } else {
8d505d78 2830 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
2831 marked = NOT marked,last_read = NOW()
2832 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2833 }
2834 }
2835
e4f4b46f
AD
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) {
8d505d78 2847 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
2848 published = false,last_read = NOW()
2849 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2850 } else if ($cmode == 1) {
8d505d78 2851 db_query($link, "UPDATE ttrss_user_entries SET
46b78149 2852 published = true,last_read = NOW()
e4f4b46f
AD
2853 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2854 } else {
8d505d78 2855 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
2856 published = NOT published,last_read = NOW()
2857 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2858 }
2fcec4c4
AD
2859
2860 if (PUBSUBHUBBUB_HUB) {
2861 $rss_link = get_self_url_prefix() .
e0d91d84 2862 "/public.php?op=rss&id=-2&key=" .
2fcec4c4
AD
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 }
e4f4b46f
AD
2869 }
2870
9968d46f
AD
2871 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2872
2873 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 2874 if (count($ids) == 0) return;
472782e8
AD
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) {
8d505d78 2885 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2886 unread = false,last_read = NOW()
9968d46f 2887 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2888 } else if ($cmode == 1) {
8d505d78 2889 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2890 unread = true
9968d46f 2891 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2892 } else {
8d505d78 2893 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2894 unread = NOT unread,last_read = NOW()
9968d46f 2895 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2896 }
0737b95a
AD
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 }
472782e8
AD
2906 }
2907
e097e8be
AD
2908 function catchupArticleById($link, $id, $cmode) {
2909
2910 if ($cmode == 0) {
8d505d78 2911 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
2912 unread = false,last_read = NOW()
2913 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2914 } else if ($cmode == 1) {
8d505d78 2915 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
2916 unread = true
2917 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2918 } else {
8d505d78 2919 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
2920 unread = NOT unread,last_read = NOW()
2921 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2922 }
ab197ae1
AD
2923
2924 $feed_id = getArticleFeed($link, $id);
2925 ccache_update($link, $feed_id, $_SESSION["uid"]);
e097e8be
AD
2926 }
2927
1f64b1be 2928 function make_guid_from_title($title) {
8d505d78 2929 return preg_replace("/[ \"\',.:;]/", "-",
fefef828 2930 mb_strtolower(strip_tags($title), 'utf-8'));
1f64b1be
AD
2931 }
2932
ca5133cb 2933 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
0b126ac2
AD
2934
2935 $a_id = db_escape_string($id);
2936
bc976a8c
AD
2937 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2938
8d505d78 2939 $query = "SELECT DISTINCT tag_name,
0c3d1c68 2940 owner_uid as owner FROM
0b126ac2 2941 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 2942 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 2943
bd3f2ade 2944 $obj_id = md5("TAGS:$owner_uid:$id");
8d505d78 2945 $tags = array();
bd3f2ade 2946
0e4a7d7a 2947 /* check cache first */
490c366d 2948
0e4a7d7a
AD
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");
490c366d 2952
0e4a7d7a
AD
2953 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2954 }
bd3f2ade 2955
0e4a7d7a
AD
2956 if ($tag_cache) {
2957 $tags = explode(",", $tag_cache);
2958 } else {
490c366d 2959
0e4a7d7a 2960 /* do it the hard way */
490c366d 2961
0e4a7d7a 2962 $tmp_result = db_query($link, $query);
490c366d 2963
0e4a7d7a
AD
2964 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2965 array_push($tags, $tmp_line["tag_name"]);
2966 }
490c366d 2967
0e4a7d7a 2968 /* update the cache */
490c366d 2969
0e4a7d7a 2970 $tags_str = db_escape_string(join(",", $tags));
bd3f2ade 2971
0e4a7d7a
AD
2972 db_query($link, "UPDATE ttrss_user_entries
2973 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2974 AND owner_uid = $owner_uid");
0b126ac2
AD
2975 }
2976
2977 return $tags;
2978 }
2979
d62a3b63
AD
2980 function trim_array($array) {
2981 $tmp = $array;
3415b075 2982 array_walk($tmp, 'trim');
d62a3b63
AD
2983 return $tmp;
2984 }
2985
be832a1a 2986 function tag_is_valid($tag) {
ef063748
AD
2987 if ($tag == '') return false;
2988 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 2989 if (mb_strlen($tag) > 250) return false;
ef063748 2990
31365729
AD
2991 if (function_exists('iconv')) {
2992 $tag = iconv("utf-8", "utf-8", $tag);
2993 }
2994
ef063748
AD
2995 if (!$tag) return false;
2996
2997 return true;
be832a1a
AD
2998 }
2999
97acbaf1
AD
3000 function render_login_form($link, $form_id = 0) {
3001 switch ($form_id) {
afb12ed0 3002 case 0:
793185a9 3003 require_once "login_form.php";
afb12ed0
AD
3004 break;
3005 case 1:
793185a9 3006 require_once "mobile/login_form.php";
afb12ed0 3007 break;
793185a9 3008 }
97acbaf1 3009 exit;
01a87dff
AD
3010 }
3011
dc56b3b7
AD
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
42395d28 3021 function format_warning($msg, $id = "") {
883fee8d 3022 global $link;
8d505d78 3023 return "<div class=\"warning\" id=\"$id\">
883fee8d 3024 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
0d32b41e
AD
3025 }
3026
08ac193a 3027 function format_notice($msg, $id = "") {
883fee8d 3028 global $link;
8d505d78 3029 return "<div class=\"notice\" id=\"$id\">
883fee8d 3030 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
0d32b41e
AD
3031 }
3032
08ac193a 3033 function format_error($msg, $id = "") {
883fee8d 3034 global $link;
8d505d78 3035 return "<div class=\"error\" id=\"$id\">
883fee8d 3036 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
68d2f95e
AD
3037 }
3038
4dccf1ed
AD
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
68d2f95e
AD
3047 function print_error($msg) {
3048 return print format_error($msg);
3049 }
3050
3051
4dccf1ed
AD
3052 function T_sprintf() {
3053 $args = func_get_args();
3054 return vsprintf(__(array_shift($args)), $args);
3055 }
3056
51682b23
AD
3057 function format_inline_player($link, $url, $ctype) {
3058
3059 $entry = "";
3060
8d505d78 3061 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
3062
3063 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
8d505d78 3064 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
c3edc667
AD
3065 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3066
3067 $id = 'AUDIO-' . uniqid();
3068
3069 $entry .= "<audio id=\"$id\"\">
3070 <source src=\"$url\"></source>
8d505d78 3071 </audio>";
c3edc667 3072
8d505d78 3073 $entry .= "<span onclick=\"player(this)\"
c3edc667
AD
3074 title=\"".__("Click to play")."\" status=\"0\"
3075 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3076
3077 } else {
8d505d78
AD
3078
3079 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 3080 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
3081 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3082 <param name=\"movie\"
ad95edc2 3083 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 3084 </object>";
c3edc667 3085 }
51682b23
AD
3086 }
3087
c3edc667
AD
3088 $filename = substr($url, strrpos($url, "/")+1);
3089
3090 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3091 $filename . " (" . $ctype . ")" . "</a>";
3092
51682b23
AD
3093 return $entry;
3094 }
3095
64436e10 3096 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
64436e10 3097 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3de0261a 3098
009646d2
AD
3099 $rv = array();
3100
3101 $rv['id'] = $id;
3102
10eb9da8 3103 /* we can figure out feed_id from article id anyway, why do we
e04c18a2 3104 * pass feed_id here? let's ignore the argument :( */
10eb9da8
AD
3105
3106 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3107 WHERE ref_id = '$id'");
3108
e04c18a2 3109 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 3110
009646d2
AD
3111 $rv['feed_id'] = $feed_id;
3112
3113 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 3114
87764a50 3115 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
64436e10 3116 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3de0261a
AD
3117
3118 if (db_num_rows($result) == 1) {
3119 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
54e61a68 3120 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
87764a50 3121 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
3de0261a
AD
3122 } else {
3123 $rtl_content = false;
54e61a68 3124 $always_display_enclosures = false;
87764a50 3125 $cache_content = false;
3de0261a
AD
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) {
8d505d78
AD
3137 $result = db_query($link, "UPDATE ttrss_user_entries
3138 SET unread = false,last_read = NOW()
64436e10 3139 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
8a4c759e 3140
64436e10 3141 ccache_update($link, $feed_id, $owner_uid);
3de0261a
AD
3142 }
3143
7252abe3 3144 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
fc2b26a6 3145 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3de0261a 3146 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
8cc3c778 3147 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3de0261a 3148 num_comments,
9c506873 3149 tag_cache,
c7e51de1 3150 author,
ef83538d 3151 orig_feed_id,
87764a50
AD
3152 note,
3153 cached_content
3de0261a 3154 FROM ttrss_entries,ttrss_user_entries
64436e10 3155 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3de0261a
AD
3156
3157 if ($result) {
3158
3de0261a
AD
3159 $line = db_fetch_assoc($result);
3160
3161 if ($line["icon_url"]) {
8e289ca1 3162 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3de0261a
AD
3163 } else {
3164 $feed_icon = "&nbsp;";
3165 }
3166
8cc3c778
AD
3167 $feed_site_url = $line['site_url'];
3168
3de0261a
AD
3169 $num_comments = $line["num_comments"];
3170 $entry_comments = "";
3171
3172 if ($num_comments > 0) {
3173 if ($line["comments"]) {
6e577ba1 3174 $comments_url = htmlspecialchars($line["comments"]);
3de0261a 3175 } else {
6e577ba1 3176 $comments_url = htmlspecialchars($line["link"]);
3de0261a 3177 }
7514749d 3178 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3de0261a
AD
3179 } else {
3180 if ($line["comments"] && $line["link"] != $line["comments"]) {
6e577ba1 3181 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
8d505d78 3182 }
3de0261a
AD
3183 }
3184
eedfb635
AD
3185 if ($zoom_mode) {
3186 header("Content-Type: text/html");
009646d2 3187 $rv['content'] .= "<html><head>
5bb0cc8e 3188 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
eedfb635
AD
3189 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3190 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3191 </head><body>";
3192 }
3193
5c568973 3194 $title_escaped = htmlspecialchars($line['title']);
2ea9bbfd 3195
009646d2 3196 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
6f3976c9 3197 truncate_string(strip_tags($line['title']), 15) . "</div>";
eedfb635 3198
e54dbacb
AD
3199 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3200 strip_tags($line['title']) . "</div>";
3201
009646d2 3202 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 3203
009646d2 3204 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
bc372fe3 3205 class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
3206
3207 $entry_author = $line["author"];
3208
3209 if ($entry_author) {
60164936 3210 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
3211 }
3212
8d505d78 3213 $parsed_updated = make_local_datetime($link, $line["updated"], true,
64436e10 3214 $owner_uid, true);
324944f3 3215
009646d2 3216 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3de0261a
AD
3217
3218 if ($line["link"]) {
c6c010d9 3219 $rv['content'] .= "<div class='postTitle'><a target='_blank'
a64029e5 3220 title=\"".htmlspecialchars($line['title'])."\"
8d505d78 3221 href=\"" .
5c568973 3222 htmlspecialchars($line["link"]) . "\">" .
c6c010d9 3223 $line["title"] .
a64029e5 3224 "<span class='author'>$entry_author</span></a></div>";
3de0261a 3225 } else {
c6c010d9 3226 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
3227 }
3228
9c506873
AD
3229 $tag_cache = $line["tag_cache"];
3230
3231 if (!$tag_cache)
64436e10 3232 $tags = get_article_tags($link, $id, $owner_uid);
9c506873
AD
3233 else
3234 $tags = explode(",", $tag_cache);
3235
0780f4f4
AD
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");
e7544143 3240
3de0261a
AD
3241 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3242
f0755b7c 3243 $rv['content'] .= "<div class='postTags' style='float : right'>
8d505d78 3244 <img src='".theme_image($link, 'images/tag.png')."'
e9823609 3245 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
3246
3247 if (!$zoom_mode) {
009646d2 3248 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 3249 <a title=\"".__('Edit tags for this article')."\"
31a53903 3250 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 3251
0780f4f4
AD
3252 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3253 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3254 position=\"below\">$tags_str_full</div>";
3255
009646d2 3256 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
9ed0b90f 3257 class='tagsPic' style=\"cursor : pointer\"
ca07f49e 3258 onclick=\"postOpenInNewTab(event, $id)\"
6f3976c9 3259 alt='Zoom' title='".__('Open article in new tab')."'>";
c7e51de1 3260
19c73507 3261 global $pluginhost;
f9ac31d6 3262
19c73507
AD
3263 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
3264 $rv['content'] .= $p->hook_article_button($line);
411fe209
AD
3265 }
3266
009646d2 3267 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
6f3976c9 3268 class='tagsPic' style=\"cursor : pointer\"
e3387e2d 3269 onclick=\"closeArticlePanel($id)\"
638e27c8 3270 title='".__('Close article')."'>";
6f3976c9 3271
24ecbcae
AD
3272 } else {
3273 $tags_str = strip_tags($tags_str);
009646d2 3274 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
eedfb635 3275 }
009646d2
AD
3276 $rv['content'] .= "</div>";
3277 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3de0261a 3278
ef83538d
AD
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
009646d2
AD
3286 $rv['content'] .= "<div clear='both'>";
3287 $rv['content'] .= __("Originally from:");
ef83538d 3288
009646d2 3289 $rv['content'] .= "&nbsp;";
ef83538d
AD
3290
3291 $tmp_line = db_fetch_assoc($tmp_result);
3292
009646d2 3293 $rv['content'] .= "<a target='_blank'
ef83538d
AD
3294 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3295 $tmp_line['title'] . "</a>";
3296
009646d2 3297 $rv['content'] .= "&nbsp;";
ef83538d 3298
009646d2 3299 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
11cb9506 3300 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
ef83538d 3301
009646d2 3302 $rv['content'] .= "</div>";
ef83538d
AD
3303 }
3304 }
3305
009646d2 3306 $rv['content'] .= "</div>";
3de0261a 3307
009646d2 3308 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 3309 if ($line['note']) {
009646d2 3310 $rv['content'] .= format_article_note($id, $line['note']);
c7e51de1 3311 }
009646d2 3312 $rv['content'] .= "</div>";
c7e51de1 3313
fcfa9ef1
AD
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
009646d2 3319 $rv['content'] .= "<div class=\"postContent\">";
741b6090 3320
d3d69daa
AD
3321 // N-grams
3322
6f4bd262 3323 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
d3d69daa
AD
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'
6f4bd262 3328 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
d3d69daa
AD
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
87764a50
AD
3346 if ($cache_content && $line["cached_content"] != "") {
3347 $line["content"] =& $line["cached_content"];
3348 }
3349
64436e10 3350 $article_content = sanitize($link, $line["content"], false, $owner_uid,
741b6090
AD
3351 $feed_site_url);
3352
009646d2 3353 $rv['content'] .= $article_content;
db54143e 3354
009646d2
AD
3355 $rv['content'] .= format_article_enclosures($link, $id,
3356 $always_display_enclosures, $article_content);
ce53e200 3357
009646d2 3358 $rv['content'] .= "</div>";
dad14b51 3359
009646d2 3360 $rv['content'] .= "</div>";
3de0261a
AD
3361
3362 }
3363
009646d2
AD
3364 if ($zoom_mode) {
3365 $rv['content'] .= "
eedfb635 3366 <div style=\"text-align : center\">
2ae69126
AD
3367 <button onclick=\"return window.close()\">".
3368 __("Close this window")."</button></div>";
009646d2 3369 $rv['content'] .= "</body></html>";
eedfb635 3370 }
3de0261a 3371
009646d2
AD
3372 return $rv;
3373
3de0261a
AD
3374 }
3375
79178062
AD
3376 function print_checkpoint($n, $s) {
3377 $ts = getmicrotime();
3378 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3379 return $ts;
3380 }
3de0261a 3381
79178062
AD
3382 function sanitize_tag($tag) {
3383 $tag = trim($tag);
52d7e7da 3384
79178062 3385 $tag = mb_strtolower($tag, 'utf-8');
bd202c3f 3386
79178062 3387 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
46921916 3388
79178062
AD
3389// $tag = str_replace('"', "", $tag);
3390// $tag = str_replace("+", " ", $tag);
3391 $tag = str_replace("technorati tag: ", "", $tag);
961f4c73 3392
79178062
AD
3393 return $tag;
3394 }
3de0261a 3395
79178062 3396 function get_self_url_prefix() {
51cc3873
AD
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 }
79178062 3402 }
a9bcfb8f 3403
79178062 3404 function opml_publish_url($link){
3de0261a 3405
79178062
AD
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"]);
3de0261a 3409
79178062
AD
3410 return $url_path;
3411 }
0569a712 3412
79178062
AD
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) {
3de0261a 3421
79178062
AD
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"]);
3de0261a
AD
3428 }
3429
79178062
AD
3430 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3431 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a9bcfb8f 3432
79178062
AD
3433 ccache_update($link, $id, $_SESSION['uid']);
3434 } // function clear_feed_articles
45004d43
AD
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() {
ed102aa0
AD
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() .
97acbaf1 3445 "/public.php?op=subscribe&feed_url=%s";
755a43ee 3446 return $url_path;
45004d43
AD
3447 } // function add_feed_url
3448
e90053fe
AD
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");
1a9f4d3c
AD
3454 } else {
3455 return "SHA1:" . sha1($pass);
3456 }
45004d43
AD
3457 } // function encrypt_password
3458
6aff7845 3459 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
fee840fb
AD
3460 $filters = array();
3461
5574b09e 3462 $cat_id = (int)getFeedCategory($link, $feed_id);
fee840fb 3463
6aff7845
AD
3464 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3465 owner_uid = $owner_uid AND enabled = true");
8d505d78 3466
67bd0b1f
AD
3467 $check_cats = join(",", array_merge(
3468 getParentCategories($link, $cat_id, $owner_uid),
3469 array($cat_id)));
3470
0e4a7d7a 3471 while ($line = db_fetch_assoc($result)) {
6aff7845
AD
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
67bd0b1f 3479 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
6aff7845
AD
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();
ba975b2e 3485
6aff7845
AD
3486 while ($rule_line = db_fetch_assoc($result2)) {
3487# print_r($rule_line);
8d505d78 3488
6aff7845
AD
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);
0e4a7d7a 3510 }
b8ffa322 3511
b8ffa322 3512
6aff7845
AD
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
0e4a7d7a 3523 return $filters;
fee840fb 3524 }
1e36af0c
AD
3525
3526 function get_score_pic($score) {
8d505d78
AD
3527 if ($score > 100) {
3528 return "score_high.png";
3529 } else if ($score > 0) {
883fee8d 3530 return "score_half_high.png";
1cce3aca 3531 } else if ($score < -100) {
883fee8d 3532 return "score_low.png";
1cce3aca 3533 } else if ($score < 0) {
883fee8d 3534 return "score_half_low.png";
8d505d78 3535 } else {
883fee8d 3536 return "score_neutral.png";
1e36af0c
AD
3537 }
3538 }
ec92c9d1 3539
7defa089
AD
3540 function feed_has_icon($id) {
3541 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3542 }
f29ba148
AD
3543
3544 function init_connection($link) {
5f0a3741 3545 if ($link) {
324944f3 3546
5f0a3741
AD
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 }
f29ba148 3558 }
19c73507
AD
3559
3560 global $pluginhost;
3561
3562 $pluginhost = new PluginHost($link);
3563 $pluginhost->load(PLUGINS);
3564
5f0a3741
AD
3565 return true;
3566 } else {
3567 print "Unable to connect to database:" . db_last_error();
3568 return false;
f29ba148
AD
3569 }
3570 }
5e96ca9d 3571
0bfbf1c2 3572 /* function ccache_zero($link, $feed_id, $owner_uid) {
2627f2d0
AD
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'");
0bfbf1c2 3576 } */
2627f2d0 3577
ad0056a8
AD
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
c7e51de1
AD
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
5f4f7adf
AD
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
c5ffeb61
AD
3610 /* We have to manually include category 0 */
3611
3612 ccache_update($link, 0, $owner_uid, true);
3613
8a4c759e 3614 } else {
5f4f7adf
AD
3615 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3616 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
8a4c759e 3617
5f4f7adf
AD
3618 while ($line = db_fetch_assoc($result)) {
3619 print ccache_update($link, $line["feed_id"], $owner_uid);
3620
3621 }
3622
3623 }
3624 }
2627f2d0 3625
8d505d78 3626 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd 3627 $no_update = false) {
8a4c759e 3628
5c432ba4
AD
3629 if (!is_numeric($feed_id)) return;
3630
8a4c759e
AD
3631 if (!$is_cat) {
3632 $table = "ttrss_counters_cache";
32d2181b 3633 if ($feed_id > 0) {
8d505d78 3634 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
32d2181b
AD
3635 WHERE id = '$feed_id'");
3636 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3637 }
8a4c759e
AD
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
8d505d78 3649 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
37fb651d 3650 LIMIT 1");
2627f2d0
AD
3651
3652 if (db_num_rows($result) == 1) {
3653 return db_fetch_result($result, 0, "value");
3654 } else {
6b49a3dd
AD
3655 if ($no_update) {
3656 return -1;
3657 } else {
3658 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3659 }
2627f2d0
AD
3660 }
3661
3662 }
3663
8d505d78 3664 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd
AD
3665 $update_pcat = true) {
3666
5c432ba4
AD
3667 if (!is_numeric($feed_id)) return;
3668
32d2181b 3669 if (!$is_cat && $feed_id > 0) {
8d505d78 3670 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
2e93b64c
AD
3671 WHERE id = '$feed_id'");
3672 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3673 }
3674
43ead405
AD
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 */
c98e43db
AD
3679
3680 if ($feed_id < 0) {
43ead405
AD
3681 ccache_update_all($link, $owner_uid);
3682 return;
c98e43db
AD
3683 }
3684
8a4c759e
AD
3685 if (!$is_cat) {
3686 $table = "ttrss_counters_cache";
3687 } else {
3688 $table = "ttrss_cat_counters_cache";
3689 }
3690
b6d486a3 3691 if ($is_cat && $feed_id >= 0) {
37fb651d
AD
3692 if ($feed_id != 0) {
3693 $cat_qpart = "cat_id = '$feed_id'";
3694 } else {
3695 $cat_qpart = "cat_id IS NULL";
3696 }
3697
6b49a3dd
AD
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
8d505d78
AD
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
37fb651d
AD
3710 ttrss_feeds.owner_uid = '$owner_uid'");
3711
51e196de 3712 $unread = (int) db_fetch_result($result, 0, "sv");
37fb651d 3713
f55b0b12
AD
3714 } else {
3715 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
37fb651d 3716 }
2627f2d0 3717
c7e51de1
AD
3718 db_query($link, "BEGIN");
3719
8a4c759e 3720 $result = db_query($link, "SELECT feed_id FROM $table
2627f2d0
AD
3721 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3722
3723 if (db_num_rows($result) == 1) {
8a4c759e 3724 db_query($link, "UPDATE $table SET
2627f2d0
AD
3725 value = '$unread', updated = NOW() WHERE
3726 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3727
3728 } else {
8a4c759e 3729 db_query($link, "INSERT INTO $table
8d505d78
AD
3730 (feed_id, value, owner_uid, updated)
3731 VALUES
2627f2d0 3732 ($feed_id, $unread, $owner_uid, NOW())");
2627f2d0
AD
3733 }
3734
c7e51de1
AD
3735 db_query($link, "COMMIT");
3736
6b49a3dd 3737 if ($feed_id > 0 && $prev_unread != $unread) {
8a4c759e 3738
37fb651d 3739 if (!$is_cat) {
8a4c759e 3740
6b49a3dd 3741 /* Update parent category */
8a4c759e 3742
6b49a3dd 3743 if ($update_pcat) {
37fb651d 3744
6b49a3dd
AD
3745 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3746 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
8a4c759e 3747
6b49a3dd 3748 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
37fb651d 3749
6b49a3dd 3750 ccache_update($link, $cat_id, $owner_uid, true);
6c2a9b9e 3751
6c2a9b9e 3752 }
8a4c759e 3753 }
5f4f7adf
AD
3754 } else if ($feed_id < 0) {
3755 ccache_update_all($link, $owner_uid);
8a4c759e
AD
3756 }
3757
3758 return $unread;
2627f2d0 3759 }
ceb30ba4 3760
0bfbf1c2 3761 /* function ccache_cleanup($link, $owner_uid) {
3261ca58 3762
cd9da663
AD
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
3261ca58 3772 AND owner_uid = '$owner_uid'");
cd9da663
AD
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 }
0bfbf1c2 3791 } */
3261ca58 3792
ceb30ba4 3793 function label_find_id($link, $label, $owner_uid) {
8d505d78
AD
3794 $result = db_query($link,
3795 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
ceb30ba4
AD
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
bb894b29 3805 function get_article_labels($link, $id, $owner_uid = false) {
814bff66
AD
3806 $rv = array();
3807
bb894b29 3808 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
905ff52a 3809
0e4a7d7a
AD
3810 $result = db_query($link, "SELECT label_cache FROM
3811 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
bb894b29 3812 $owner_uid);
905ff52a 3813
bb894b29
AD
3814 if (db_num_rows($result) > 0) {
3815 $label_cache = db_fetch_result($result, 0, "label_cache");
905ff52a 3816
bb894b29
AD
3817 if ($label_cache) {
3818 $label_cache = json_decode($label_cache, true);
905ff52a 3819
bb894b29
AD
3820 if ($label_cache["no-labels"] == 1)
3821 return $rv;
3822 else
3823 return $label_cache;
3824 }
0e4a7d7a 3825 }
905ff52a 3826
0e4a7d7a
AD
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'
bb894b29 3832 AND owner_uid = ". $owner_uid . "
0e4a7d7a 3833 ORDER BY caption");
905ff52a 3834
0e4a7d7a
AD
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);
814bff66
AD
3839 }
3840
0e4a7d7a 3841 if (count($rv) > 0)
624d649f 3842 label_update_cache($link, $owner_uid, $id, $rv);
0e4a7d7a 3843 else
624d649f 3844 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
0e4a7d7a 3845
814bff66
AD
3846 return $rv;
3847 }
3848
3849
b8a637f3 3850 function label_find_caption($link, $label, $owner_uid) {
8d505d78
AD
3851 $result = db_query($link,
3852 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
b8a637f3
AD
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
b24504b1
AD
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
624d649f 3874 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
905ff52a
AD
3875
3876 if ($force)
3877 label_clear_cache($link, $id);
3878
8d505d78 3879 if (!$labels)
905ff52a
AD
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
624d649f 3885 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
905ff52a
AD
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
933ba4ee
AD
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
8d505d78 3902 $result = db_query($link,
933ba4ee 3903 "DELETE FROM ttrss_user_labels2
8d505d78 3904 WHERE
933ba4ee
AD
3905 label_id = '$label_id' AND
3906 article_id = '$id'");
905ff52a
AD
3907
3908 label_clear_cache($link, $id);
933ba4ee
AD
3909 }
3910
ceb30ba4
AD
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
8d505d78
AD
3917 $result = db_query($link,
3918 "SELECT
ceb30ba4 3919 article_id FROM ttrss_labels2, ttrss_user_labels2
8d505d78
AD
3920 WHERE
3921 label_id = id AND
ceb30ba4
AD
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) {
8d505d78 3927 db_query($link, "INSERT INTO ttrss_user_labels2
ceb30ba4
AD
3928 (label_id, article_id) VALUES ('$label_id', '$id')");
3929 }
905ff52a 3930
8d505d78 3931 label_clear_cache($link, $id);
905ff52a 3932
ceb30ba4 3933 }
1380f8ee
AD
3934
3935 function label_remove($link, $id, $owner_uid) {
905ff52a
AD
3936 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3937
1380f8ee
AD
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'
905ff52a 3946 AND owner_uid = " . $owner_uid);
1380f8ee
AD
3947
3948 if (db_affected_rows($link, $result) != 0 && $caption) {
3949
8801fb01
AD
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
1380f8ee 3957 /* Disable filters that reference label being removed */
8d505d78 3958
1380f8ee
AD
3959 db_query($link, "UPDATE ttrss_filters SET
3960 enabled = false WHERE action_param = '$caption'
3961 AND action_id = 7
905ff52a
AD
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 }
1380f8ee
AD
3970
3971 db_query($link, "COMMIT");
3972 }
79c88e11 3973
b2833b92
AD
3974 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3975
3976 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
6b2ee18d
AD
3977
3978 db_query($link, "BEGIN");
3979
3980 $result = false;
3981
3982 $result = db_query($link, "SELECT id FROM ttrss_labels2
b2833b92 3983 WHERE caption = '$caption' AND owner_uid = $owner_uid");
6b2ee18d
AD
3984
3985 if (db_num_rows($result) == 0) {
3986 $result = db_query($link,
bbefea90 3987 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
b2833b92 3988 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
6b2ee18d
AD
3989
3990 $result = db_affected_rows($link, $result) != 0;
3991 }
3992
3993 db_query($link, "COMMIT");
3994
3995 return $result;
3996 }
3997
307d187c
AD
3998 function format_tags_string($tags, $id) {
3999
4000 $tags_str = "";
4001 $tags_nolinks_str = "";
4002
4003 $num_tags = 0;
4004
d9084cf2 4005 $tag_limit = 6;
307d187c
AD
4006
4007 $formatted_tags = array();
4008
4009 foreach ($tags as $tag) {
4010 $num_tags++;
4011 $tag_escaped = str_replace("'", "\\'", $tag);
4012
275a0af2
AD
4013 if (mb_strlen($tag) > 30) {
4014 $tag = truncate_string($tag, 30);
4015 }
4016
307d187c
AD
4017 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4018
4019 array_push($formatted_tags, $tag_str);
275a0af2
AD
4020
4021 $tmp_tags_str = implode(", ", $formatted_tags);
8d505d78 4022
275a0af2 4023 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
307d187c
AD
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 }
2eb9c95c
AD
4041
4042 function format_article_labels($labels, $id) {
4043
4044 $labels_str = "";
4045
4046 foreach ($labels as $l) {
8d505d78 4047 $labels_str .= sprintf("<span class='hlLabelRef'
2eb9c95c
AD
4048 style='color : %s; background-color : %s'>%s</span>",
4049 $l[2], $l[3], $l[1]);
4050 }
4051
4052 return $labels_str;
4053
4054 }
c7e51de1
AD
4055
4056 function format_article_note($id, $note) {
4057
fcfa9ef1
AD
4058 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4059 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4060 __('(edit note)')."</div>$note</div>";
c7e51de1
AD
4061
4062 return $str;
4063 }
7f969260 4064
fcf70c51 4065 function toggle_collapse_cat($link, $cat_id, $mode) {
7f969260 4066 if ($cat_id > 0) {
fcf70c51
AD
4067 $mode = bool_to_sql_bool($mode);
4068
7f969260 4069 db_query($link, "UPDATE ttrss_feed_categories SET
8d505d78 4070 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
7f969260
AD
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) {
fcf70c51 4088 if ($mode) {
7f969260 4089 set_pref($link, $pref_name, 'true');
fcf70c51
AD
4090 } else {
4091 set_pref($link, $pref_name, 'false');
7f969260
AD
4092 }
4093 }
4094 }
4095 }
7e329f13
AD
4096
4097 function remove_feed($link, $id, $owner_uid) {
4098
4099 if ($id > 0) {
e04c18a2
AD
4100
4101 /* save starred articles in Archived feed */
4102
4103 db_query($link, "BEGIN");
4104
8056ec50
AD
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) {
8d505d78 4111 db_query($link, "INSERT INTO ttrss_archived_feeds
8056ec50
AD
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
74d22f0c 4117 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
8d505d78 4118 orig_feed_id = '$id' WHERE feed_id = '$id' AND
e04c18a2
AD
4119 marked = true AND owner_uid = $owner_uid");
4120
8801fb01
AD
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
e04c18a2
AD
4126 /* remove the feed */
4127
8d505d78 4128 db_query($link, "DELETE FROM ttrss_feeds
7e329f13
AD
4129 WHERE id = '$id' AND owner_uid = $owner_uid");
4130
e04c18a2
AD
4131 db_query($link, "COMMIT");
4132
6d634e00 4133 if (file_exists(ICONS_DIR . "/$id.ico")) {
7e329f13 4134 unlink(ICONS_DIR . "/$id.ico");
6d634e00 4135 }
7e329f13
AD
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
d2a317e3
AD
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) {
c00907f2
AD
4166
4167 if (!$feed_cat) return false;
4168
5c7c7da9
AD
4169 db_query($link, "BEGIN");
4170
d2a317e3
AD
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
5c7c7da9
AD
4179 $result = db_query($link,
4180 "SELECT id FROM ttrss_feed_categories
d2a317e3 4181 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
5c7c7da9
AD
4182
4183 if (db_num_rows($result) == 0) {
8d505d78 4184
5c7c7da9 4185 $result = db_query($link,
d2a317e3
AD
4186 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4187 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
5c7c7da9
AD
4188
4189 db_query($link, "COMMIT");
4190
4191 return true;
4192 }
4193
4194 return false;
8d505d78 4195 }
5c7c7da9 4196
7e329f13
AD
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
16fdac16
AD
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) {
8d505d78 4222 db_query($link, "INSERT INTO ttrss_archived_feeds
16fdac16
AD
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
8d505d78 4228 db_query($link, "UPDATE ttrss_user_entries
16fdac16
AD
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 }
ab197ae1
AD
4236
4237 function getArticleFeed($link, $id) {
8d505d78 4238 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
a545dc31 4239 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
ab197ae1
AD
4240
4241 if (db_num_rows($result) != 0) {
4242 return db_fetch_result($result, 0, "feed_id");
4243 } else {
4244 return 0;
4245 }
4246 }
a5819bb3 4247
f2c6c008
CW
4248 /**
4249 * Fixes incomplete URLs by prepending "http://".
f0266f51
CW
4250 * Also replaces feed:// with http://, and
4251 * prepends a trailing slash if the url is a domain name only.
f2c6c008
CW
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;
f0266f51
CW
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/"
44453773 4266 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
f0266f51 4267 $url .= '/';
f2c6c008 4268 }
ec39a02c
AD
4269
4270 if ($url != "http:///")
4271 return $url;
4272 else
4273 return '';
f2c6c008
CW
4274 }
4275
a5819bb3
AD
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 }
d9084cf2 4282
be35798b
AD
4283 function get_article_enclosures($link, $id) {
4284
8d505d78 4285 $query = "SELECT * FROM ttrss_enclosures
be35798b
AD
4286 WHERE post_id = '$id' AND content_url != ''";
4287
be35798b
AD
4288 $rv = array();
4289
0e4a7d7a 4290 $result = db_query($link, $query);
be35798b 4291
0e4a7d7a
AD
4292 if (db_num_rows($result) > 0) {
4293 while ($line = db_fetch_assoc($result)) {
4294 array_push($rv, $line);
be35798b
AD
4295 }
4296 }
4297
4298 return $rv;
4299 }
4300
48646336 4301 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
911d4c08
AD
4302
4303 $feeds = array();
4304
911d4c08
AD
4305 /* Labels */
4306
fb8d17f3 4307 if ($cat_id == -4 || $cat_id == -2) {
911d4c08
AD
4308 $counters = getLabelCounters($link, true);
4309
11232703 4310 foreach (array_values($counters) as $cv) {
911d4c08 4311
11232703 4312 $unread = $cv["counter"];
8d505d78 4313
911d4c08 4314 if ($unread || !$unread_only) {
8d505d78 4315
911d4c08 4316 $row = array(
11232703
AD
4317 "id" => $cv["id"],
4318 "title" => $cv["description"],
4319 "unread" => $cv["counter"],
911d4c08
AD
4320 "cat_id" => -2,
4321 );
8d505d78 4322
911d4c08
AD
4323 array_push($feeds, $row);
4324 }
4325 }
4326 }
4327
4328 /* Virtual feeds */
4329
fb8d17f3 4330 if ($cat_id == -4 || $cat_id == -1) {
386c4ce6 4331 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
911d4c08
AD
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
8d505d78 4346 }
911d4c08 4347 }
b41c2549 4348
48646336
AD
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"] .
07b63daf 4355 " ORDER BY id, title");
48646336
AD
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
b41c2549
AD
4373 /* Real feeds */
4374
4375 if ($limit) {
4376 $limit_qpart = "LIMIT $limit OFFSET $offset";
4377 } else {
4378 $limit_qpart = "";
4379 }
4380
fb8d17f3 4381 if ($cat_id == -4 || $cat_id == -3) {
8d505d78 4382 $result = db_query($link, "SELECT
c8226ce4 4383 id, feed_url, cat_id, title, order_id, ".
b41c2549 4384 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78 4385 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
4386 " ORDER BY cat_id, title " . $limit_qpart);
4387 } else {
fb8d17f3
AD
4388
4389 if ($cat_id)
4390 $cat_qpart = "cat_id = '$cat_id'";
4391 else
4392 $cat_qpart = "cat_id IS NULL";
4393
8d505d78 4394 $result = db_query($link, "SELECT
c8226ce4 4395 id, feed_url, cat_id, title, order_id, ".
b41c2549 4396 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
4397 FROM ttrss_feeds WHERE
4398 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
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"],
c8226ce4
AD
4417 "last_updated" => strtotime($line["last_updated"]),
4418 "order_id" => (int) $line["order_id"],
b41c2549 4419 );
8d505d78 4420
b41c2549
AD
4421 array_push($feeds, $row);
4422 }
4423 }
4424
911d4c08
AD
4425 return $feeds;
4426 }
4427
4428 function api_get_headlines($link, $feed_id, $limit, $offset,
a0e580b0 4429 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
3e4af5b0 4430 $include_attachments, $since_id,
db9e00e3
AD
4431 $search = "", $search_mode = "", $match_on = "",
4432 $include_nested = false, $sanitize_content = true) {
8d505d78
AD
4433
4434 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
911d4c08 4435 $view_mode, $is_cat, $search, $search_mode, $match_on,
48646336 4436 $order, $offset, 0, false, $since_id, $include_nested);
911d4c08
AD
4437
4438 $result = $qfh_ret[0];
4439 $feed_title = $qfh_ret[1];
4440
4441 $headlines = array();
4442
4443 while ($line = db_fetch_assoc($result)) {
8d505d78 4444 $is_updated = ($line["last_read"] == "" &&
911d4c08
AD
4445 ($line["unread"] != "t" && $line["unread"] != "1"));
4446
97a3b9f0
AD
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
911d4c08
AD
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"]),
9ed133e7 4457 "published" => sql_bool_to_bool($line["published"]),
911d4c08
AD
4458 "updated" => strtotime($line["updated"]),
4459 "is_updated" => $is_updated,
4460 "title" => $line["title"],
4461 "link" => $line["link"],
4462 "feed_id" => $line["feed_id"],
97a3b9f0 4463 "tags" => $tags,
911d4c08
AD
4464 );
4465
a0e580b0
AD
4466 if ($include_attachments)
4467 $headline_row['attachments'] = get_article_enclosures($link,
4468 $line['id']);
4469
911d4c08
AD
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) {
87764a50
AD
4476
4477 if ($line["cached_content"] != "") {
4478 $line["content_preview"] =& $line["cached_content"];
4479 }
4480
db9e00e3
AD
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 }
911d4c08
AD
4487 }
4488
97a3b9f0
AD
4489 // unify label output to ease parsing
4490 if ($labels["no-labels"] == 1) $labels = array();
4491
4492 $headline_row["labels"] = $labels;
4493
b11e9943
AD
4494 $headline_row["feed_title"] = $line["feed_title"];
4495
ff0ff5f0
AD
4496 $headline_row["comments_count"] = (int)$line["num_comments"];
4497 $headline_row["comments_link"] = $line["comments"];
4498
daf0b014
AD
4499 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4500
911d4c08
AD
4501 array_push($headlines, $headline_row);
4502 }
4503
4504 return $headlines;
4505 }
4506
bd202c3f
AD
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 }
fe1087fb 4523
13e785e0 4524
bd202c3f
AD
4525 function generate_dashboard_feed($link) {
4526 $reply = array();
4527
4528 $reply['headlines']['id'] = -5;
4529 $reply['headlines']['is_cat'] = false;
fe1087fb 4530
bd202c3f
AD
4531 $reply['headlines']['toolbar'] = '';
4532 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
fe1087fb 4533
bd202c3f 4534 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5d128c95
AD
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");
324944f3 4540 $last_updated = make_local_datetime($link, $last_updated, false);
5d128c95 4541
bd202c3f 4542 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5d128c95 4543
fe1087fb
AD
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) {
bd202c3f
AD
4550 $reply['headlines']['content'] .= "<br/>";
4551 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
fe1087fb
AD
4552 __('Some feeds have update errors (click for details)')."</a>";
4553 }
bd202c3f 4554 $reply['headlines']['content'] .= "</span></p>";
fe1087fb 4555
bd202c3f 4556 $reply['headlines-info'] = array("count" => 0,
ffbe082d
AD
4557 "vgroup_last_feed" => '',
4558 "unread" => 0,
4559 "disable_cache" => true);
4560
bd202c3f 4561 return $reply;
fe1087fb 4562 }
31a53903
AD
4563
4564 function save_email_address($link, $email) {
4565 // FIXME: implement persistent storage of emails
4566
8d505d78 4567 if (!$_SESSION['stored_emails'])
31a53903
AD
4568 $_SESSION['stored_emails'] = array();
4569
4570 if (!in_array($email, $_SESSION['stored_emails']))
4571 array_push($_SESSION['stored_emails'], $email);
4572 }
8801fb01
AD
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
8d505d78
AD
4579 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4580 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
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'
8d505d78 4587 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
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
8d505d78
AD
4603 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4604 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
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
8d505d78 4612 $result = db_query($link, "INSERT INTO ttrss_access_keys
8801fb01
AD
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 }
f0266f51 4620
759e5132 4621 function get_feeds_from_html($url, $content)
f0266f51
CW
4622 {
4623 $url = fix_url($url);
4624 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
4625
fb074239
AD
4626 libxml_use_internal_errors(true);
4627
f0266f51 4628 $doc = new DOMDocument();
8d505d78 4629 $doc->loadHTML($content);
f0266f51
CW
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 }
923818fc
CW
4639 $feedUrl = rewrite_relative_url(
4640 $baseUrl, $entry->getAttribute('href')
4641 );
f0266f51
CW
4642 $feedUrls[$feedUrl] = $title;
4643 }
4644 }
4645 return $feedUrls;
4646 }
4647
759e5132 4648 function is_html($content) {
32b86711 4649 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
759e5132 4650 }
f33479da 4651
759e5132
AD
4652 function url_is_html($url, $login = false, $pass = false) {
4653 return is_html(fetch_file_contents($url, false, $login, $pass));
f33479da 4654 }
24e2bb3a 4655
d90868d7 4656 function print_label_select($link, $name, $value, $attributes = "") {
24e2bb3a
AD
4657
4658 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4659 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4660
8d505d78 4661 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
d90868d7 4662 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
24e2bb3a
AD
4663
4664 while ($line = db_fetch_assoc($result)) {
4665
4666 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
4667
d90868d7
AD
4668 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4669 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
24e2bb3a
AD
4670
4671 }
4672
d90868d7 4673# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
24e2bb3a
AD
4674
4675 print "</select>";
4676
4677
4678 }
4679
009646d2 4680 function format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51
AD
4681 $article_content) {
4682
4683 $result = get_article_enclosures($link, $id);
009646d2 4684 $rv = '';
8d505d78 4685
dad14b51 4686 if (count($result) > 0) {
8d505d78 4687
dad14b51
AD
4688 $entries_html = array();
4689 $entries = array();
8d505d78 4690
dad14b51 4691 foreach ($result as $line) {
8d505d78 4692
dad14b51
AD
4693 $url = $line["content_url"];
4694 $ctype = $line["content_type"];
8d505d78 4695
dad14b51 4696 if (!$ctype) $ctype = __("unknown type");
8d505d78 4697
749b56bd 4698 $filename = substr($url, strrpos($url, "/")+1);
8d505d78 4699
749b56bd 4700# $player = format_inline_player($link, $url, $ctype);
8d505d78 4701
c3edc667
AD
4702# $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4703# $filename . " (" . $ctype . ")" . "</a>";
8d505d78 4704
749b56bd
AD
4705 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4706 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4707
dad14b51 4708 array_push($entries_html, $entry);
8d505d78 4709
dad14b51 4710 $entry = array();
8d505d78 4711
dad14b51
AD
4712 $entry["type"] = $ctype;
4713 $entry["filename"] = $filename;
4714 $entry["url"] = $url;
8d505d78 4715
dad14b51
AD
4716 array_push($entries, $entry);
4717 }
8d505d78 4718
dad14b51
AD
4719 if (!get_pref($link, "STRIP_IMAGES")) {
4720 if ($always_display_enclosures ||
4721 !preg_match("/<img/i", $article_content)) {
8d505d78 4722
dad14b51 4723 foreach ($entries as $entry) {
8d505d78 4724
dad14b51
AD
4725 if (preg_match("/image/", $entry["type"]) ||
4726 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
8d505d78 4727
009646d2 4728 $rv .= "<p><img
dad14b51
AD
4729 alt=\"".htmlspecialchars($entry["filename"])."\"
4730 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
749b56bd 4731
dad14b51
AD
4732 }
4733 }
4734 }
4735 }
8d505d78 4736
2a3d00bb 4737 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
749b56bd
AD
4738 "<span>" . __('Attachments')."</span>";
4739 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
8d505d78 4740
749b56bd 4741 foreach ($entries_html as $entry) { $rv .= $entry; };
8d505d78 4742
749b56bd 4743 $rv .= "</div></div>";
dad14b51 4744 }
009646d2
AD
4745
4746 return $rv;
dad14b51
AD
4747 }
4748
f8fb4498
AD
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 }
8cc3c778
AD
4759
4760 function build_url($parts) {
4761 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4762 }
4763
f679105c
CW
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 */
8cc3c778 4772 function rewrite_relative_url($url, $rel_url) {
b4520bb8
AD
4773 if (strpos($rel_url, "magnet:") === 0) {
4774 return $rel_url;
4775 } else if (strpos($rel_url, "://") !== false) {
8cc3c778 4776 return $rel_url;
f9052d35 4777 } else if (strpos($rel_url, "//") === 0) {
4778 # protocol-relative URL (rare but they exist)
4779 return $rel_url;
8d505d78 4780 } else if (strpos($rel_url, "/") === 0)
8cc3c778
AD
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);
f679105c
CW
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;
8cc3c778
AD
4798
4799 return build_url($parts);
4800 }
4801 }
4802
e4f7f8df 4803 function sphinx_search($query, $offset = 0, $limit = 30) {
31303c6b
AD
4804 require_once 'lib/sphinxapi.php';
4805
e4f7f8df
AD
4806 $sphinxClient = new SphinxClient();
4807
4808 $sphinxClient->SetServer('localhost', 9312);
4809 $sphinxClient->SetConnectTimeout(1);
4810
8d505d78 4811 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
e4f7f8df
AD
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']));
8d505d78 4819
e4f7f8df
AD
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
868650e4
AD
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
b5ec13fa 4842 $tags_deleted = 0;
868650e4 4843
b5ec13fa
AD
4844 while ($limit > 0) {
4845 $limit_part = 500;
4846
8d505d78
AD
4847 $query = "SELECT ttrss_tags.id AS id
4848 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
b5ec13fa
AD
4849 WHERE post_int_id = int_id AND $interval_query AND
4850 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
8d505d78 4851
b5ec13fa
AD
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";
868650e4 4874
b5ec13fa 4875 return $tags_deleted;
868650e4
AD
4876 }
4877
88e4e597
AD
4878 function print_user_stylesheet($link) {
4879 $value = get_pref($link, 'USER_STYLESHEET');
4880
4881 if ($value) {
4882 print "<style type=\"text/css\">";
5823f9fb 4883 print str_replace("<br/>", "\n", $value);
88e4e597
AD
4884 print "</style>";
4885 }
4886
4887 }
4888
73c32678 4889/* function rewrite_urls($line) {
533c0ea6
AD
4890 global $url_regex;
4891
4892 $urls = null;
4893
8d505d78 4894 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
533c0ea6
AD
4895 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4896
4897 return $result;
73c32678
AD
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
376897af
AD
4939 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4940 if ($node)
7b8ff151 4941 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
376897af
AD
4942 else
4943 return $html;
533c0ea6
AD
4944 }
4945
2680295b 4946 function filter_to_sql($link, $filter, $owner_uid) {
4e02f582 4947 $query = array();
36184020 4948
4e02f582
AD
4949 if (DB_TYPE == "pgsql")
4950 $reg_qpart = "~";
4951 else
4952 $reg_qpart = "REGEXP";
36184020 4953
4e02f582
AD
4954 foreach ($filter["rules"] AS $rule) {
4955 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4956 $rule['reg_exp']) !== FALSE;
36184020 4957
4e02f582 4958 if ($regexp_valid) {
36184020 4959
4e02f582 4960 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
36184020 4961
4e02f582
AD
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 }
36184020 4989
6b218731
AD
4990 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4991 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4e02f582 4992 }
6b8b3af8 4993
4e02f582 4994 if (isset($rule["cat_id"])) {
2680295b
AD
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";
56fbb82c 5008 }
4e02f582
AD
5009
5010 array_push($query, "($qpart)");
5011
56fbb82c 5012 }
4e02f582 5013 }
56fbb82c 5014
4e02f582
AD
5015 if (count($query) > 0) {
5016 return "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
56fbb82c 5017 } else {
4e02f582 5018 return "(false)";
56fbb82c 5019 }
36184020 5020 }
ae5f7bb1
AD
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") {
414d0d1f 5036 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
ae5f7bb1 5037 } else {
81731791 5038 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
ae5f7bb1
AD
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
e0d91d84 5049 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
ae5f7bb1
AD
5050 $post_query = 'key=' . $line['access_key'];
5051
5052 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5053
e0d91d84
AD
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
ae5f7bb1
AD
5060 if ($feeds) {
5061 $feeds = json_decode($feeds, true);
5062
5063 if ($feeds) {
5064 if ($feeds['error']) {
5065 $status = $feeds['error']['code'] + 10;
32532f1c
AD
5066
5067 // access denied
5068 if ($status == 16) {
5069 db_query($link, "DELETE FROM ttrss_linked_feeds
5070 WHERE instance_id = '$id'");
5071 }
ae5f7bb1
AD
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']);
2b9c4bae 5084 $site_url = db_escape_string($feed['site_url']);
ae5f7bb1
AD
5085
5086 db_query($link, "INSERT INTO ttrss_linked_feeds
d61063c7 5087 (feed_url, site_url, title, subscribers, instance_id, created, updated)
ae5f7bb1 5088 VALUES
d61063c7 5089 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
ae5f7bb1
AD
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 }
e0d91d84
AD
5115 }
5116
afcfe6ca 5117 function make_feed_browser($link, $search, $limit, $mode = 1) {
5f0a3741 5118
afcfe6ca
AD
5119 $owner_uid = $_SESSION["uid"];
5120 $rv = '';
5f0a3741 5121
afcfe6ca
AD
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 }
5f0a3741 5128
afcfe6ca
AD
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"); */
5f0a3741 5135
afcfe6ca
AD
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");
5f0a3741 5144
afcfe6ca
AD
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 }
5f0a3741 5158
afcfe6ca 5159 $feedctr = 0;
5f0a3741 5160
afcfe6ca 5161 while ($line = db_fetch_assoc($result)) {
5f0a3741 5162
afcfe6ca 5163 if ($mode == 1) {
5f0a3741 5164
afcfe6ca
AD
5165 $feed_url = htmlspecialchars($line["feed_url"]);
5166 $site_url = htmlspecialchars($line["site_url"]);
5167 $subscribers = $line["subscribers"];
5f0a3741 5168
afcfe6ca
AD
5169 $check_box = "<input onclick='toggleSelectListRow2(this)'
5170 dojoType=\"dijit.form.CheckBox\"
5171 type=\"checkbox\" \">";
5f0a3741 5172
afcfe6ca 5173 $class = ($feedctr % 2) ? "even" : "odd";
5f0a3741 5174
afcfe6ca
AD
5175 $site_url = "<a target=\"_blank\"
5176 href=\"$site_url\">
5177 <span class=\"fb_feedTitle\">".
5178 htmlspecialchars($line["title"])."</span></a>";
5f0a3741 5179
afcfe6ca
AD
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>";
5f0a3741 5183
afcfe6ca
AD
5184 $rv .= "<li>$check_box $feed_url $site_url".
5185 "&nbsp;<span class='subscribers'>($subscribers)</span></li>";
5f0a3741 5186
afcfe6ca
AD
5187 } else if ($mode == 2) {
5188 $feed_url = htmlspecialchars($line["feed_url"]);
5189 $site_url = htmlspecialchars($line["site_url"]);
5190 $title = htmlspecialchars($line["title"]);
5f0a3741 5191
afcfe6ca
AD
5192 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5193 type=\"checkbox\">";
5f0a3741 5194
afcfe6ca 5195 $class = ($feedctr % 2) ? "even" : "odd";
5f0a3741 5196
afcfe6ca
AD
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 }
5f0a3741 5203
afcfe6ca
AD
5204 $site_url = "<a target=\"_blank\"
5205 href=\"$site_url\">
5206 <span class=\"fb_feedTitle\">".
5207 htmlspecialchars($line["title"])."</span></a>";
5f0a3741 5208
afcfe6ca
AD
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>";
5f0a3741
AD
5212
5213
afcfe6ca
AD
5214 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5215 "$check_box $feed_url $site_url $archived</li>";
5216 }
5f0a3741 5217
afcfe6ca
AD
5218 ++$feedctr;
5219 }
5f0a3741 5220
afcfe6ca
AD
5221 if ($feedctr == 0) {
5222 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5223 }
5f0a3741 5224
afcfe6ca 5225 return $rv;
afcfe6ca 5226 }
5f0a3741 5227
3382bce1
AD
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
55f34b81
AD
5235 function perform_data_import($link, $filename, $owner_uid) {
5236
5237 $num_imported = 0;
5238 $num_processed = 0;
5239 $num_feeds_created = 0;
5240
3382bce1
AD
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 }
55f34b81
AD
5257
5258 if ($doc) {
5259
5260 $xpath = new DOMXpath($doc);
a679752a
AD
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
55f34b81
AD
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) {
b2833b92
AD
5287 if ($child->nodeName != 'label_cache')
5288 $article[$child->nodeName] = db_escape_string($child->nodeValue);
5289 else
5290 $article[$child->nodeName] = $child->nodeValue;
55f34b81
AD
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'];
b2833b92 5396 $label_cache = db_escape_string($article['label_cache']);
05b1152b 5397 $note = $article['note'];
55f34b81
AD
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,
05b1152b 5406 published, score, tag_cache, label_cache, uuid, note)
55f34b81 5407 VALUES ($ref_id, $owner_uid, $feed, false,
05b1152b
AD
5408 NULL, $marked, $published, $score, '$tag_cache',
5409 '$label_cache', '', '$note')");
55f34b81 5410
b2833b92
AD
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
55f34b81
AD
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 }
8db5d8ea
AD
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 }
871f0a7a
AD
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 }
e3449aa1
AD
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
6aff7845
AD
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
1b4d1a6b
AD
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
8361e724
AD
5497 $content_hash = sha1($content);
5498
1b4d1a6b
AD
5499 if ($labels_str != "") {
5500 $labels = explode(",", $labels_str);
5501 } else {
5502 $labels = array();
5503 }
5504
d2088ee6
AD
5505 $rc = false;
5506
ecd5a3c8
AD
5507 if (!$title) $title = $url;
5508 if (!$title && !$url) return false;
5509
18cf1358
AD
5510 if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) return false;
5511
d2088ee6
AD
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");
8361e724
AD
5517
5518 if (db_num_rows($result) != 0) {
5519 $ref_id = db_fetch_result($result, 0, "id");
5520
71b6a236 5521 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
d2088ee6 5522 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
71b6a236
AD
5523
5524 if (db_num_rows($result) != 0) {
d2088ee6
AD
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
71b6a236 5530 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
d2088ee6 5531 int_id = '$int_id' AND owner_uid = '$owner_uid'");
71b6a236
AD
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 }
8361e724 5539
1b4d1a6b
AD
5540 if (count($labels) != 0) {
5541 foreach ($labels as $label) {
5542 label_add_article($link, $ref_id, trim($label), $owner_uid);
5543 }
5544 }
5545
d2088ee6 5546 $rc = true;
8361e724 5547
71b6a236
AD
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())");
8361e724 5553
71b6a236
AD
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
1b4d1a6b
AD
5564 if (count($labels) != 0) {
5565 foreach ($labels as $label) {
5566 label_add_article($link, $ref_id, trim($label), $owner_uid);
5567 }
5568 }
5569
d2088ee6 5570 $rc = true;
71b6a236 5571 }
71b6a236 5572 }
d2088ee6
AD
5573
5574 db_query($link, "COMMIT");
5575
5576 return $rc;
8361e724
AD
5577 }
5578
8dcb2b47
AD
5579 function implements_interface($class, $interface) {
5580 return in_array($interface, class_implements($class));
5581 }
5582
40d13c28 5583?>