]> git.wh0rd.org - tt-rss.git/blob - functions.php
config: remove ENABLE_TRANSLATIONS
[tt-rss.git] / functions.php
1 <?php
2
3 date_default_timezone_set('UTC');
4 if (defined('E_DEPRECATED')) {
5 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
6 } else {
7 error_reporting(E_ALL & ~E_NOTICE);
8 }
9
10 require_once 'config.php';
11
12 if (DB_TYPE == "pgsql") {
13 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 } else {
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
16 }
17
18 define('THEME_VERSION_REQUIRED', 1.1);
19
20 /**
21 * Return available translations names.
22 *
23 * @access public
24 * @return array A array of available translations.
25 */
26 function get_translations() {
27 $tr = array(
28 "auto" => "Detect automatically",
29 "ca_CA" => "Català",
30 "en_US" => "English",
31 "es_ES" => "Español",
32 "de_DE" => "Deutsch",
33 "fr_FR" => "Français",
34 "hu_HU" => "Magyar (Hungarian)",
35 "it_IT" => "Italiano",
36 "ja_JP" => "日本語 (Japanese)",
37 "nb_NO" => "Norwegian bokmål",
38 "ru_RU" => "Русский",
39 "pt_BR" => "Portuguese/Brazil",
40 "zh_CN" => "Simplified Chinese");
41
42 return $tr;
43 }
44
45 require_once "lib/accept-to-gettext.php";
46 require_once "lib/gettext/gettext.inc";
47
48 function startup_gettext() {
49
50 # Get locale from Accept-Language header
51 $lang = al2gt(array_keys(get_translations()), "text/html");
52
53 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
54 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
55 }
56
57 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
58 $lang = $_COOKIE["ttrss_lang"];
59 }
60
61 /* In login action of mobile version */
62 if ($_POST["language"] && defined('MOBILE_VERSION')) {
63 $lang = $_POST["language"];
64 $_COOKIE["ttrss_lang"] = $lang;
65 }
66
67 if ($lang) {
68 if (defined('LC_MESSAGES')) {
69 _setlocale(LC_MESSAGES, $lang);
70 } else if (defined('LC_ALL')) {
71 _setlocale(LC_ALL, $lang);
72 }
73
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
76 } else {
77 _bindtextdomain("messages", "locale");
78 }
79
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
82 }
83 }
84
85 startup_gettext();
86
87 if (defined('MEMCACHE_SERVER')) {
88 $memcache = new Memcache;
89 $memcache->connect(MEMCACHE_SERVER, 11211);
90 }
91
92 require_once 'db-prefs.php';
93 require_once 'errors.php';
94 require_once 'version.php';
95
96 require_once 'lib/phpmailer/class.phpmailer.php';
97 require_once 'lib/sphinxapi.php';
98 require_once 'lib/tmhoauth/tmhOAuth.php';
99
100 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
101 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
102 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
103
104 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
105 define('MAGPIE_USER_AGENT', SELF_USER_AGENT);
106
107 ini_set('user_agent', SELF_USER_AGENT);
108
109 require_once "lib/simplepie/simplepie.inc";
110 require_once "lib/magpierss/rss_fetch.inc";
111 require_once 'lib/magpierss/rss_utils.inc';
112 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
113
114 $config = HTMLPurifier_Config::createDefault();
115
116 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s";
117
118 $config->set('HTML', 'Allowed', $allowed);
119 $purifier = new HTMLPurifier($config);
120
121 /**
122 * Print a timestamped debug message.
123 *
124 * @param string $msg The debug message.
125 * @return void
126 */
127 function _debug($msg) {
128 $ts = strftime("%H:%M:%S", time());
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
131 }
132 print "[$ts] $msg\n";
133 } // function _debug
134
135 /**
136 * Purge a feed old posts.
137 *
138 * @param mixed $link A database connection.
139 * @param mixed $feed_id The id of the purged feed.
140 * @param mixed $purge_interval Olderness of purged posts.
141 * @param boolean $debug Set to True to enable the debug. False by default.
142 * @access public
143 * @return void
144 */
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
146
147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
148
149 $rows = -1;
150
151 $result = db_query($link,
152 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
153
154 $owner_uid = false;
155
156 if (db_num_rows($result) == 1) {
157 $owner_uid = db_fetch_result($result, 0, "owner_uid");
158 }
159
160 if ($purge_interval == -1 || !$purge_interval) {
161 if ($owner_uid) {
162 ccache_update($link, $feed_id, $owner_uid);
163 }
164 return;
165 }
166
167 if (!$owner_uid) return;
168
169 if (FORCE_ARTICLE_PURGE == 0) {
170 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
171 $owner_uid, false);
172 } else {
173 $purge_unread = true;
174 $purge_interval = FORCE_ARTICLE_PURGE;
175 }
176
177 if (!$purge_unread) $query_limit = " unread = false AND ";
178
179 if (DB_TYPE == "pgsql") {
180 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
181 marked = false AND feed_id = '$feed_id' AND
182 (SELECT date_updated FROM ttrss_entries WHERE
183 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
184
185 $pg_version = get_pgsql_version($link);
186
187 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
188
189 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
190 ttrss_entries.id = ref_id AND
191 marked = false AND
192 feed_id = '$feed_id' AND
193 $query_limit
194 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
195
196 } else {
197
198 $result = db_query($link, "DELETE FROM ttrss_user_entries
199 USING ttrss_entries
200 WHERE ttrss_entries.id = ref_id AND
201 marked = false AND
202 feed_id = '$feed_id' AND
203 $query_limit
204 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
205 }
206
207 $rows = pg_affected_rows($result);
208
209 } else {
210
211 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
212 marked = false AND feed_id = '$feed_id' AND
213 (SELECT date_updated FROM ttrss_entries WHERE
214 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
215
216 $result = db_query($link, "DELETE FROM ttrss_user_entries
217 USING ttrss_user_entries, ttrss_entries
218 WHERE ttrss_entries.id = ref_id AND
219 marked = false AND
220 feed_id = '$feed_id' AND
221 $query_limit
222 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
223
224 $rows = mysql_affected_rows($link);
225
226 }
227
228 ccache_update($link, $feed_id, $owner_uid);
229
230 if ($debug) {
231 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
232 }
233 } // function purge_feed
234
235 /**
236 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
237 *
238 * @param mixed $link A database connection
239 * @param boolean $do_output Set to true to enable printed output, false by default.
240 * @param integer $limit The maximal number of removed posts.
241 * @access public
242 * @return void
243 */
244 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
245
246 $random_qpart = sql_random_function();
247
248 if ($limit) {
249 $limit_qpart = "LIMIT $limit";
250 } else {
251 $limit_qpart = "";
252 }
253
254 $result = db_query($link,
255 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
256 ORDER BY $random_qpart $limit_qpart");
257
258 while ($line = db_fetch_assoc($result)) {
259
260 $feed_id = $line["id"];
261 $purge_interval = $line["purge_interval"];
262 $owner_uid = $line["owner_uid"];
263
264 if ($purge_interval == 0) {
265
266 $tmp_result = db_query($link,
267 "SELECT value FROM ttrss_user_prefs WHERE
268 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
269
270 if (db_num_rows($tmp_result) != 0) {
271 $purge_interval = db_fetch_result($tmp_result, 0, "value");
272 }
273 }
274
275 if ($do_output) {
276 // print "Feed $feed_id: purge interval = $purge_interval\n";
277 }
278
279 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
280 purge_feed($link, $feed_id, $purge_interval, $do_output);
281 }
282 }
283
284 purge_orphans($link, $do_output);
285
286 } // function global_purge_old_posts */
287
288 function feed_purge_interval($link, $feed_id) {
289
290 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
291 WHERE id = '$feed_id'");
292
293 if (db_num_rows($result) == 1) {
294 $purge_interval = db_fetch_result($result, 0, "purge_interval");
295 $owner_uid = db_fetch_result($result, 0, "owner_uid");
296
297 if ($purge_interval == 0) $purge_interval = get_pref($link,
298 'PURGE_OLD_DAYS', $owner_uid);
299
300 return $purge_interval;
301
302 } else {
303 return -1;
304 }
305 }
306
307 function purge_old_posts($link) {
308
309 $user_id = $_SESSION["uid"];
310
311 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
312 WHERE owner_uid = '$user_id'");
313
314 while ($line = db_fetch_assoc($result)) {
315
316 $feed_id = $line["id"];
317 $purge_interval = $line["purge_interval"];
318
319 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
320
321 if ($purge_interval > 0) {
322 purge_feed($link, $feed_id, $purge_interval);
323 }
324 }
325
326 purge_orphans($link);
327 }
328
329 function purge_orphans($link, $do_output = false) {
330
331 // purge orphaned posts in main content table
332 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
333 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
334
335 if ($do_output) {
336 $rows = db_affected_rows($link, $result);
337 _debug("Purged $rows orphaned posts.");
338 }
339 }
340
341 function get_feed_update_interval($link, $feed_id) {
342 $result = db_query($link, "SELECT owner_uid, update_interval FROM
343 ttrss_feeds WHERE id = '$feed_id'");
344
345 if (db_num_rows($result) == 1) {
346 $update_interval = db_fetch_result($result, 0, "update_interval");
347 $owner_uid = db_fetch_result($result, 0, "owner_uid");
348
349 if ($update_interval != 0) {
350 return $update_interval;
351 } else {
352 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
353 }
354
355 } else {
356 return -1;
357 }
358 }
359
360 function fetch_file_contents($url, $type = false, $login = false, $pass = false) {
361 $login = urlencode($login);
362 $pass = urlencode($pass);
363
364 if (function_exists('curl_init')) {
365 $ch = curl_init($url);
366
367 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
368 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
369 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
370 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
371 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
372 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
373 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
374 curl_setopt($fp, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
375
376 if ($login && $pass)
377 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
378
379 $contents = @curl_exec($ch);
380 if ($contents === false) {
381 curl_close($ch);
382 return false;
383 }
384
385 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
386 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
387 curl_close($ch);
388
389 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
390 return false;
391 }
392
393 return $contents;
394 } else {
395 if ($login && $pass && $updated != 3) {
396 $url_parts = array();
397
398 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
399
400 if ($url_parts[1] && $url_parts[2]) {
401 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
402 }
403 }
404
405 return @file_get_contents($url);
406 }
407
408 }
409
410 /**
411 * Try to determine the favicon URL for a feed.
412 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
413 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
414 *
415 * @param string $url A feed or page URL
416 * @access public
417 * @return mixed The favicon URL, or false if none was found.
418 */
419 function get_favicon_url($url) {
420
421 $favicon_url = false;
422
423 if ($html = @fetch_file_contents($url)) {
424
425 libxml_use_internal_errors(true);
426
427 $doc = new DOMDocument();
428 $doc->loadHTML($html);
429 $xpath = new DOMXPath($doc);
430 $entries = $xpath->query('/html/head/link[@rel="shortcut icon"]');
431
432 if (count($entries) > 0) {
433 foreach ($entries as $entry) {
434 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
435 break;
436 }
437 }
438 }
439
440 if (!$favicon_url)
441 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
442
443 return $favicon_url;
444 } // function get_favicon_url
445
446 function check_feed_favicon($site_url, $feed, $link) {
447 $favicon_url = get_favicon_url($site_url);
448
449 # print "FAVICON [$site_url]: $favicon_url\n";
450
451 $icon_file = ICONS_DIR . "/$feed.ico";
452
453 if ($favicon_url && !file_exists($icon_file)) {
454 $contents = fetch_file_contents($favicon_url, "image");
455
456 if ($contents) {
457 $fp = fopen($icon_file, "w");
458
459 if ($fp) {
460 fwrite($fp, $contents);
461 fclose($fp);
462 chmod($icon_file, 0644);
463 }
464 }
465 }
466 }
467
468 function update_rss_feed($link, $feed, $ignore_daemon = false) {
469
470 global $memcache;
471
472 /* Update all feeds with the same URL to utilize memcache */
473
474 if ($memcache) {
475 $result = db_query($link, "SELECT f1.id
476 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
477 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
478
479 while ($line = db_fetch_assoc($result)) {
480 update_rss_feed_real($link, $line["id"], $ignore_daemon);
481 }
482 } else {
483 update_rss_feed_real($link, $feed, $ignore_daemon);
484 }
485 }
486
487 function update_rss_feed_real($link, $feed, $ignore_daemon = false) {
488
489 global $memcache;
490
491 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
492 return false;
493 }
494
495 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
496 _debug("update_rss_feed: start");
497 }
498
499 if (!$ignore_daemon) {
500
501 if (DB_TYPE == "pgsql") {
502 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
503 } else {
504 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
505 }
506
507 $result = db_query($link, "SELECT id,update_interval,auth_login,
508 auth_pass,cache_images,update_method
509 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
510
511 } else {
512
513 $result = db_query($link, "SELECT id,update_interval,auth_login,
514 feed_url,auth_pass,cache_images,update_method,last_updated,
515 owner_uid
516 FROM ttrss_feeds WHERE id = '$feed'");
517
518 }
519
520 if (db_num_rows($result) == 0) {
521 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
522 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
523 }
524 return false;
525 }
526
527 $update_method = db_fetch_result($result, 0, "update_method");
528 $last_updated = db_fetch_result($result, 0, "last_updated");
529 $owner_uid = db_fetch_result($result, 0, "owner_uid");
530
531 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
532 WHERE id = '$feed'");
533
534 $auth_login = db_fetch_result($result, 0, "auth_login");
535 $auth_pass = db_fetch_result($result, 0, "auth_pass");
536
537 if ($update_method == 0)
538 $update_method = DEFAULT_UPDATE_METHOD + 1;
539
540 // 1 - Magpie
541 // 2 - SimplePie
542 // 3 - Twitter OAuth
543
544 if ($update_method == 2)
545 $use_simplepie = true;
546 else
547 $use_simplepie = false;
548
549 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
550 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
551 }
552
553 if ($update_method == 1) {
554 $auth_login = urlencode($auth_login);
555 $auth_pass = urlencode($auth_pass);
556 }
557
558 $update_interval = db_fetch_result($result, 0, "update_interval");
559 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
560 $fetch_url = db_fetch_result($result, 0, "feed_url");
561
562 if ($update_interval < 0) { return; }
563
564 $feed = db_escape_string($feed);
565
566 if ($auth_login && $auth_pass && $updated != 3) {
567 $url_parts = array();
568 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
569
570 if ($url_parts[1] && $url_parts[2]) {
571 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
572 }
573
574 }
575
576 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
577 _debug("update_rss_feed: fetching [$fetch_url]...");
578 }
579
580 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
581
582 if ($memcache && $obj = $memcache->get($obj_id)) {
583
584 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
585 _debug("update_rss_feed: data found in memcache.");
586 }
587
588 $rss = $obj;
589
590 } else {
591
592 if ($update_method == 3) {
593 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
594 } else if ($update_method == 1) {
595 $rss = @fetch_rss($fetch_url);
596 } else {
597 if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
598 mkdir(SIMPLEPIE_CACHE_DIR);
599 }
600
601 $rss = new SimplePie();
602 $rss->set_useragent(SELF_USER_AGENT);
603 # $rss->set_timeout(10);
604 $rss->set_feed_url($fetch_url);
605 $rss->set_output_encoding('UTF-8');
606
607 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
608
609 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
610 _debug("enabling image cache");
611 }
612
613 $rss->set_image_handler("image.php", 'i');
614 }
615
616 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
617 _debug("feed update interval (sec): " .
618 get_feed_update_interval($link, $feed)*60);
619 }
620
621 if (is_dir(SIMPLEPIE_CACHE_DIR)) {
622 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
623 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
624 }
625
626 $rss->init();
627 }
628
629 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
630 }
631
632 // print_r($rss);
633
634 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
635 _debug("update_rss_feed: fetch done, parsing...");
636 }
637
638 $feed = db_escape_string($feed);
639
640 if ($update_method == 2) {
641 $fetch_ok = !$rss->error();
642 } else {
643 $fetch_ok = !!$rss;
644 }
645
646 if ($fetch_ok) {
647
648 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
649 _debug("update_rss_feed: processing feed data...");
650 }
651
652 // db_query($link, "BEGIN");
653
654 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
655 FROM ttrss_feeds WHERE id = '$feed'");
656
657 $registered_title = db_fetch_result($result, 0, "title");
658 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
659 $orig_site_url = db_fetch_result($result, 0, "site_url");
660
661 $owner_uid = db_fetch_result($result, 0, "owner_uid");
662
663 if ($use_simplepie) {
664 $site_url = $rss->get_link();
665 } else {
666 $site_url = $rss->channel["link"];
667 }
668
669 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
670 _debug("update_rss_feed: checking favicon...");
671 }
672
673 check_feed_favicon($site_url, $feed, $link);
674
675 if (!$registered_title || $registered_title == "[Unknown]") {
676
677 if ($use_simplepie) {
678 $feed_title = db_escape_string($rss->get_title());
679 } else {
680 $feed_title = db_escape_string($rss->channel["title"]);
681 }
682
683 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
684 _debug("update_rss_feed: registering title: $feed_title");
685 }
686
687 db_query($link, "UPDATE ttrss_feeds SET
688 title = '$feed_title' WHERE id = '$feed'");
689 }
690
691 // weird, weird Magpie
692 if (!$use_simplepie) {
693 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
694 }
695
696 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
697 db_query($link, "UPDATE ttrss_feeds SET
698 site_url = '$site_url' WHERE id = '$feed'");
699 }
700
701 // print "I: " . $rss->channel["image"]["url"];
702
703 if (!$use_simplepie) {
704 $icon_url = db_escape_string($rss->image["url"]);
705 } else {
706 $icon_url = db_escape_string($rss->get_image_url());
707 }
708
709 $icon_url = substr($icon_url, 0, 250);
710
711 if ($icon_url && $orig_icon_url != $icon_url) {
712 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
713 }
714
715 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
716 _debug("update_rss_feed: loading filters...");
717 }
718
719 $filters = load_filters($link, $feed, $owner_uid);
720
721 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
722 print_r($filters);
723 }
724
725 if ($use_simplepie) {
726 $iterator = $rss->get_items();
727 } else {
728 $iterator = $rss->items;
729 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
730 if (!$iterator || !is_array($iterator)) $iterator = $rss;
731 }
732
733 if (!is_array($iterator)) {
734 /* db_query($link, "UPDATE ttrss_feeds
735 SET last_error = 'Parse error: can\'t find any articles.'
736 WHERE id = '$feed'"); */
737
738 // clear any errors and mark feed as updated if fetched okay
739 // even if it's blank
740
741 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
742 _debug("update_rss_feed: entry iterator is not an array, no articles?");
743 }
744
745 db_query($link, "UPDATE ttrss_feeds
746 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
747
748 return; // no articles
749 }
750
751 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
752 _debug("update_rss_feed: processing articles...");
753 }
754
755 foreach ($iterator as $item) {
756
757 if ($_REQUEST['xdebug'] == 2) {
758 print_r($item);
759 }
760
761 if ($use_simplepie) {
762 $entry_guid = $item->get_id();
763 if (!$entry_guid) $entry_guid = $item->get_link();
764 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
765
766 } else {
767
768 $entry_guid = $item["id"];
769
770 if (!$entry_guid) $entry_guid = $item["guid"];
771 if (!$entry_guid) $entry_guid = $item["about"];
772 if (!$entry_guid) $entry_guid = $item["link"];
773 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
774 }
775
776 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
777 _debug("update_rss_feed: guid $entry_guid");
778 }
779
780 if (!$entry_guid) continue;
781
782 $entry_timestamp = "";
783
784 if ($use_simplepie) {
785 $entry_timestamp = strtotime($item->get_date());
786 } else {
787 $rss_2_date = $item['pubdate'];
788 $rss_1_date = $item['dc']['date'];
789 $atom_date = $item['issued'];
790 if (!$atom_date) $atom_date = $item['updated'];
791
792 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
793 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
794 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
795
796 }
797
798 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
799 $entry_timestamp = time();
800 $no_orig_date = 'true';
801 } else {
802 $no_orig_date = 'false';
803 }
804
805 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
806
807 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
808 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
809 }
810
811 if ($use_simplepie) {
812 $entry_title = $item->get_title();
813 } else {
814 $entry_title = trim(strip_tags($item["title"]));
815 }
816
817 if ($use_simplepie) {
818 $entry_link = $item->get_link();
819 } else {
820 // strange Magpie workaround
821 $entry_link = $item["link_"];
822 if (!$entry_link) $entry_link = $item["link"];
823 }
824
825 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
826 _debug("update_rss_feed: title $entry_title");
827 }
828
829 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
830
831 $entry_link = strip_tags($entry_link);
832
833 if ($use_simplepie) {
834 $entry_content = $item->get_content();
835 if (!$entry_content) $entry_content = $item->get_description();
836 } else {
837 $entry_content = $item["content:escaped"];
838
839 if (!$entry_content) $entry_content = $item["content:encoded"];
840 if (!$entry_content) $entry_content = $item["content"]["encoded"];
841 if (!$entry_content) $entry_content = $item["content"];
842
843 // Magpie bugs are getting ridiculous
844 if (trim($entry_content) == "Array") $entry_content = false;
845
846 if (!$entry_content) $entry_content = $item["atom_content"];
847 if (!$entry_content) $entry_content = $item["summary"];
848
849 if (!$entry_content ||
850 strlen($entry_content) < strlen($item["description"])) {
851 $entry_content = $item["description"];
852 };
853
854 // WTF
855 if (is_array($entry_content)) {
856 $entry_content = $entry_content["encoded"];
857 if (!$entry_content) $entry_content = $entry_content["escaped"];
858 }
859 }
860
861 if ($_REQUEST["xdebug"] == 2) {
862 print "update_rss_feed: content: ";
863 print_r(htmlspecialchars($entry_content));
864 }
865
866 $entry_content_unescaped = $entry_content;
867
868 if ($use_simplepie) {
869 $entry_comments = strip_tags($item->data["comments"]);
870 if ($item->get_author()) {
871 $entry_author_item = $item->get_author();
872 $entry_author = $entry_author_item->get_name();
873 if (!$entry_author) $entry_author = $entry_author_item->get_email();
874
875 $entry_author = db_escape_string($entry_author);
876 }
877 } else {
878 $entry_comments = strip_tags($item["comments"]);
879
880 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
881
882 if ($item['author']) {
883
884 if (is_array($item['author'])) {
885
886 if (!$entry_author) {
887 $entry_author = db_escape_string(strip_tags($item['author']['name']));
888 }
889
890 if (!$entry_author) {
891 $entry_author = db_escape_string(strip_tags($item['author']['email']));
892 }
893 }
894
895 if (!$entry_author) {
896 $entry_author = db_escape_string(strip_tags($item['author']));
897 }
898 }
899 }
900
901 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
902
903 $entry_guid = db_escape_string(strip_tags($entry_guid));
904 $entry_guid = mb_substr($entry_guid, 0, 250);
905
906 $result = db_query($link, "SELECT id FROM ttrss_entries
907 WHERE guid = '$entry_guid'");
908
909 $entry_content = db_escape_string($entry_content, false);
910
911 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
912
913 $entry_title = db_escape_string($entry_title);
914 $entry_link = db_escape_string($entry_link);
915 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
916 $entry_author = mb_substr($entry_author, 0, 250);
917
918 if ($use_simplepie) {
919 $num_comments = 0; #FIXME#
920 } else {
921 $num_comments = db_escape_string($item["slash"]["comments"]);
922 }
923
924 if (!$num_comments) $num_comments = 0;
925
926 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
927 _debug("update_rss_feed: looking for tags [1]...");
928 }
929
930 // parse <category> entries into tags
931
932 $additional_tags = array();
933
934 if ($use_simplepie) {
935
936 $additional_tags_src = $item->get_categories();
937
938 if (is_array($additional_tags_src)) {
939 foreach ($additional_tags_src as $tobj) {
940 array_push($additional_tags, $tobj->get_term());
941 }
942 }
943
944 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
945 _debug("update_rss_feed: category tags:");
946 print_r($additional_tags);
947 }
948
949 } else {
950
951 $t_ctr = $item['category#'];
952
953 if ($t_ctr == 0) {
954 $additional_tags = array();
955 } else if ($t_ctr > 0) {
956 $additional_tags = array($item['category']);
957
958 if ($item['category@term']) {
959 array_push($additional_tags, $item['category@term']);
960 }
961
962 for ($i = 0; $i <= $t_ctr; $i++ ) {
963 if ($item["category#$i"]) {
964 array_push($additional_tags, $item["category#$i"]);
965 }
966
967 if ($item["category#$i@term"]) {
968 array_push($additional_tags, $item["category#$i@term"]);
969 }
970 }
971 }
972
973 // parse <dc:subject> elements
974
975 $t_ctr = $item['dc']['subject#'];
976
977 if ($t_ctr > 0) {
978 array_push($additional_tags, $item['dc']['subject']);
979
980 for ($i = 0; $i <= $t_ctr; $i++ ) {
981 if ($item['dc']["subject#$i"]) {
982 array_push($additional_tags, $item['dc']["subject#$i"]);
983 }
984 }
985 }
986 }
987
988 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
989 _debug("update_rss_feed: looking for tags [2]...");
990 }
991
992 /* taaaags */
993 // <a href="..." rel="tag">Xorg</a>, //
994
995 $entry_tags = null;
996
997 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
998 $entry_content_unescaped, $entry_tags);
999
1000 $entry_tags = $entry_tags[1];
1001
1002 $entry_tags = array_merge($entry_tags, $additional_tags);
1003 $entry_tags = array_unique($entry_tags);
1004
1005 for ($i = 0; $i < count($entry_tags); $i++)
1006 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1007
1008 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1009 _debug("update_rss_feed: unfiltered tags found:");
1010 print_r($entry_tags);
1011 }
1012
1013 # sanitize content
1014
1015 $entry_content = sanitize_article_content($entry_content);
1016 $entry_title = sanitize_article_content($entry_title);
1017
1018 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1019 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1020 }
1021
1022 db_query($link, "BEGIN");
1023
1024 if (db_num_rows($result) == 0) {
1025
1026 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1027 _debug("update_rss_feed: base guid not found");
1028 }
1029
1030 // base post entry does not exist, create it
1031
1032 $result = db_query($link,
1033 "INSERT INTO ttrss_entries
1034 (title,
1035 guid,
1036 link,
1037 updated,
1038 content,
1039 content_hash,
1040 no_orig_date,
1041 date_updated,
1042 date_entered,
1043 comments,
1044 num_comments,
1045 author)
1046 VALUES
1047 ('$entry_title',
1048 '$entry_guid',
1049 '$entry_link',
1050 '$entry_timestamp_fmt',
1051 '$entry_content',
1052 '$content_hash',
1053 $no_orig_date,
1054 NOW(),
1055 NOW(),
1056 '$entry_comments',
1057 '$num_comments',
1058 '$entry_author')");
1059 } else {
1060 // we keep encountering the entry in feeds, so we need to
1061 // update date_updated column so that we don't get horrible
1062 // dupes when the entry gets purged and reinserted again e.g.
1063 // in the case of SLOW SLOW OMG SLOW updating feeds
1064
1065 $base_entry_id = db_fetch_result($result, 0, "id");
1066
1067 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1068 WHERE id = '$base_entry_id'");
1069 }
1070
1071 // now it should exist, if not - bad luck then
1072
1073 $result = db_query($link, "SELECT
1074 id,content_hash,no_orig_date,title,
1075 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
1076 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
1077 num_comments
1078 FROM
1079 ttrss_entries
1080 WHERE guid = '$entry_guid'");
1081
1082 $entry_ref_id = 0;
1083 $entry_int_id = 0;
1084
1085 if (db_num_rows($result) == 1) {
1086
1087 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1088 _debug("update_rss_feed: base guid found, checking for user record");
1089 }
1090
1091 // this will be used below in update handler
1092 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1093 $orig_title = db_fetch_result($result, 0, "title");
1094 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1095 $orig_date_updated = strtotime(db_fetch_result($result,
1096 0, "date_updated"));
1097
1098 $ref_id = db_fetch_result($result, 0, "id");
1099 $entry_ref_id = $ref_id;
1100
1101 // check for user post link to main table
1102
1103 // do we allow duplicate posts with same GUID in different feeds?
1104 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1105 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1106 } else {
1107 $dupcheck_qpart = "";
1108 }
1109
1110 /* Collect article tags here so we could filter by them: */
1111
1112 $article_filters = get_article_filters($filters, $entry_title,
1113 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1114 $entry_tags);
1115
1116 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1117 _debug("update_rss_feed: article filters: ");
1118 if (count($article_filters) != 0) {
1119 print_r($article_filters);
1120 }
1121 }
1122
1123 if (find_article_filter($article_filters, "filter")) {
1124 db_query($link, "COMMIT"); // close transaction in progress
1125 continue;
1126 }
1127
1128 $score = calculate_article_score($article_filters);
1129
1130 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1131 _debug("update_rss_feed: initial score: $score");
1132 }
1133
1134 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1135 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1136 $dupcheck_qpart";
1137
1138 // if ($_REQUEST["xdebug"]) print "$query\n";
1139
1140 $result = db_query($link, $query);
1141
1142 // okay it doesn't exist - create user entry
1143 if (db_num_rows($result) == 0) {
1144
1145 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1146 _debug("update_rss_feed: user record not found, creating...");
1147 }
1148
1149 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1150 $unread = 'true';
1151 $last_read_qpart = 'NULL';
1152 } else {
1153 $unread = 'false';
1154 $last_read_qpart = 'NOW()';
1155 }
1156
1157 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
1158 $marked = 'true';
1159 } else {
1160 $marked = 'false';
1161 }
1162
1163 if (find_article_filter($article_filters, 'publish')) {
1164 $published = 'true';
1165 } else {
1166 $published = 'false';
1167 }
1168
1169 $result = db_query($link,
1170 "INSERT INTO ttrss_user_entries
1171 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1172 published, score, tag_cache, label_cache)
1173 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1174 $last_read_qpart, $marked, $published, '$score', '', '')");
1175
1176 $result = db_query($link,
1177 "SELECT int_id FROM ttrss_user_entries WHERE
1178 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1179 feed_id = '$feed' LIMIT 1");
1180
1181 if (db_num_rows($result) == 1) {
1182 $entry_int_id = db_fetch_result($result, 0, "int_id");
1183 }
1184 } else {
1185 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1186 _debug("update_rss_feed: user record FOUND");
1187 }
1188
1189 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1190 $entry_int_id = db_fetch_result($result, 0, "int_id");
1191 }
1192
1193 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1194 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1195 }
1196
1197 $post_needs_update = false;
1198
1199 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1200 ($content_hash != $orig_content_hash)) {
1201 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1202 $post_needs_update = true;
1203 }
1204
1205 if (db_escape_string($orig_title) != $entry_title) {
1206 $post_needs_update = true;
1207 }
1208
1209 if ($orig_num_comments != $num_comments) {
1210 $post_needs_update = true;
1211 }
1212
1213 // this doesn't seem to be very reliable
1214 //
1215 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1216 // $post_needs_update = true;
1217 // }
1218
1219 // if post needs update, update it and mark all user entries
1220 // linking to this post as updated
1221 if ($post_needs_update) {
1222
1223 if (defined('DAEMON_EXTENDED_DEBUG')) {
1224 _debug("update_rss_feed: post $entry_guid needs update...");
1225 }
1226
1227 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1228
1229 db_query($link, "UPDATE ttrss_entries
1230 SET title = '$entry_title', content = '$entry_content',
1231 content_hash = '$content_hash',
1232 num_comments = '$num_comments'
1233 WHERE id = '$ref_id'");
1234
1235 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1236 db_query($link, "UPDATE ttrss_user_entries
1237 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1238 } else {
1239 db_query($link, "UPDATE ttrss_user_entries
1240 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1241 }
1242
1243 }
1244 }
1245
1246 db_query($link, "COMMIT");
1247
1248 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1249 _debug("update_rss_feed: assigning labels...");
1250 }
1251
1252 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1253 $owner_uid);
1254
1255 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1256 _debug("update_rss_feed: looking for enclosures...");
1257 }
1258
1259 // enclosures
1260
1261 $enclosures = array();
1262
1263 if ($use_simplepie) {
1264 $encs = $item->get_enclosures();
1265
1266 if (is_array($encs)) {
1267 foreach ($encs as $e) {
1268 $e_item = array(
1269 $e->link, $e->type, $e->length);
1270
1271 array_push($enclosures, $e_item);
1272 }
1273 }
1274
1275 } else {
1276 // <enclosure>
1277
1278 $e_ctr = $item['enclosure#'];
1279
1280 if ($e_ctr > 0) {
1281 $e_item = array($item['enclosure@url'],
1282 $item['enclosure@type'],
1283 $item['enclosure@length']);
1284
1285 array_push($enclosures, $e_item);
1286
1287 for ($i = 0; $i <= $e_ctr; $i++ ) {
1288
1289 if ($item["enclosure#$i@url"]) {
1290 $e_item = array($item["enclosure#$i@url"],
1291 $item["enclosure#$i@type"],
1292 $item["enclosure#$i@length"]);
1293 array_push($enclosures, $e_item);
1294 }
1295 }
1296 }
1297
1298 // <media:content>
1299 // can there be many of those? yes -fox
1300
1301 $m_ctr = $item['media']['content#'];
1302
1303 if ($m_ctr > 0) {
1304 $e_item = array($item['media']['content@url'],
1305 $item['media']['content@medium'],
1306 $item['media']['content@length']);
1307
1308 array_push($enclosures, $e_item);
1309
1310 for ($i = 0; $i <= $m_ctr; $i++ ) {
1311
1312 if ($item["media"]["content#$i@url"]) {
1313 $e_item = array($item["media"]["content#$i@url"],
1314 $item["media"]["content#$i@medium"],
1315 $item["media"]["content#$i@length"]);
1316 array_push($enclosures, $e_item);
1317 }
1318 }
1319
1320 }
1321 }
1322
1323
1324 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1325 _debug("update_rss_feed: article enclosures:");
1326 print_r($enclosures);
1327 }
1328
1329 db_query($link, "BEGIN");
1330
1331 foreach ($enclosures as $enc) {
1332 $enc_url = db_escape_string($enc[0]);
1333 $enc_type = db_escape_string($enc[1]);
1334 $enc_dur = db_escape_string($enc[2]);
1335
1336 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1337 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1338
1339 if (db_num_rows($result) == 0) {
1340 db_query($link, "INSERT INTO ttrss_enclosures
1341 (content_url, content_type, title, duration, post_id) VALUES
1342 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1343 }
1344 }
1345
1346 db_query($link, "COMMIT");
1347
1348 // check for manual tags (we have to do it here since they're loaded from filters)
1349
1350 foreach ($article_filters as $f) {
1351 if ($f[0] == "tag") {
1352
1353 $manual_tags = trim_array(split(",", $f[1]));
1354
1355 foreach ($manual_tags as $tag) {
1356 if (tag_is_valid($tag)) {
1357 array_push($entry_tags, $tag);
1358 }
1359 }
1360 }
1361 }
1362
1363 // Skip boring tags
1364
1365 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1366 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1367
1368 $filtered_tags = array();
1369 $tags_to_cache = array();
1370
1371 if ($entry_tags && is_array($entry_tags)) {
1372 foreach ($entry_tags as $tag) {
1373 if (array_search($tag, $boring_tags) === false) {
1374 array_push($filtered_tags, $tag);
1375 }
1376 }
1377 }
1378
1379 $filtered_tags = array_unique($filtered_tags);
1380
1381 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1382 _debug("update_rss_feed: filtered article tags:");
1383 print_r($filtered_tags);
1384 }
1385
1386 // Save article tags in the database
1387
1388 if (count($filtered_tags) > 0) {
1389
1390 db_query($link, "BEGIN");
1391
1392 foreach ($filtered_tags as $tag) {
1393
1394 $tag = sanitize_tag($tag);
1395 $tag = db_escape_string($tag);
1396
1397 if (!tag_is_valid($tag)) continue;
1398
1399 $result = db_query($link, "SELECT id FROM ttrss_tags
1400 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1401 owner_uid = '$owner_uid' LIMIT 1");
1402
1403 if ($result && db_num_rows($result) == 0) {
1404
1405 db_query($link, "INSERT INTO ttrss_tags
1406 (owner_uid,tag_name,post_int_id)
1407 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1408 }
1409
1410 array_push($tags_to_cache, $tag);
1411 }
1412
1413 /* update the cache */
1414
1415 $tags_to_cache = array_unique($tags_to_cache);
1416
1417 $tags_str = db_escape_string(join(",", $tags_to_cache));
1418
1419 db_query($link, "UPDATE ttrss_user_entries
1420 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1421 AND owner_uid = $owner_uid");
1422
1423 db_query($link, "COMMIT");
1424 }
1425
1426 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1427 _debug("update_rss_feed: article processed");
1428 }
1429 }
1430
1431 if (!$last_updated) {
1432 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1433 _debug("update_rss_feed: new feed, catching it up...");
1434 }
1435 catchup_feed($link, $feed, false, $owner_uid);
1436 }
1437
1438 purge_feed($link, $feed, 0);
1439
1440 db_query($link, "UPDATE ttrss_feeds
1441 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1442
1443 // db_query($link, "COMMIT");
1444
1445 } else {
1446
1447 if ($use_simplepie) {
1448 $error_msg = mb_substr($rss->error(), 0, 250);
1449 } else {
1450 $error_msg = mb_substr(magpie_error(), 0, 250);
1451 }
1452
1453 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1454 _debug("update_rss_feed: error fetching feed: $error_msg");
1455 }
1456
1457 $error_msg = db_escape_string($error_msg);
1458
1459 db_query($link,
1460 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1461 last_updated = NOW() WHERE id = '$feed'");
1462 }
1463
1464 if ($use_simplepie) {
1465 unset($rss);
1466 }
1467
1468 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1469 _debug("update_rss_feed: done");
1470 }
1471
1472 }
1473
1474 function print_select($id, $default, $values, $attributes = "") {
1475 print "<select name=\"$id\" id=\"$id\" $attributes>";
1476 foreach ($values as $v) {
1477 if ($v == $default)
1478 $sel = "selected=\"1\"";
1479 else
1480 $sel = "";
1481
1482 print "<option value=\"$v\" $sel>$v</option>";
1483 }
1484 print "</select>";
1485 }
1486
1487 function print_select_hash($id, $default, $values, $attributes = "") {
1488 print "<select name=\"$id\" id='$id' $attributes>";
1489 foreach (array_keys($values) as $v) {
1490 if ($v == $default)
1491 $sel = 'selected="selected"';
1492 else
1493 $sel = "";
1494
1495 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1496 }
1497
1498 print "</select>";
1499 }
1500
1501 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1502 $matches = array();
1503
1504 if ($filters["title"]) {
1505 foreach ($filters["title"] as $filter) {
1506 $reg_exp = $filter["reg_exp"];
1507 $inverse = $filter["inverse"];
1508 if ((!$inverse && @preg_match("/$reg_exp/i", $title)) ||
1509 ($inverse && !@preg_match("/$reg_exp/i", $title))) {
1510
1511 array_push($matches, array($filter["action"], $filter["action_param"]));
1512 }
1513 }
1514 }
1515
1516 if ($filters["content"]) {
1517 foreach ($filters["content"] as $filter) {
1518 $reg_exp = $filter["reg_exp"];
1519 $inverse = $filter["inverse"];
1520
1521 if ((!$inverse && @preg_match("/$reg_exp/i", $content)) ||
1522 ($inverse && !@preg_match("/$reg_exp/i", $content))) {
1523
1524 array_push($matches, array($filter["action"], $filter["action_param"]));
1525 }
1526 }
1527 }
1528
1529 if ($filters["both"]) {
1530 foreach ($filters["both"] as $filter) {
1531 $reg_exp = $filter["reg_exp"];
1532 $inverse = $filter["inverse"];
1533
1534 if ($inverse) {
1535 if (!@preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1536 array_push($matches, array($filter["action"], $filter["action_param"]));
1537 }
1538 } else {
1539 if (@preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1540 array_push($matches, array($filter["action"], $filter["action_param"]));
1541 }
1542 }
1543 }
1544 }
1545
1546 if ($filters["link"]) {
1547 $reg_exp = $filter["reg_exp"];
1548 foreach ($filters["link"] as $filter) {
1549 $reg_exp = $filter["reg_exp"];
1550 $inverse = $filter["inverse"];
1551
1552 if ((!$inverse && @preg_match("/$reg_exp/i", $link)) ||
1553 ($inverse && !@preg_match("/$reg_exp/i", $link))) {
1554
1555 array_push($matches, array($filter["action"], $filter["action_param"]));
1556 }
1557 }
1558 }
1559
1560 if ($filters["date"]) {
1561 $reg_exp = $filter["reg_exp"];
1562 foreach ($filters["date"] as $filter) {
1563 $date_modifier = $filter["filter_param"];
1564 $inverse = $filter["inverse"];
1565 $check_timestamp = strtotime($filter["reg_exp"]);
1566
1567 # no-op when timestamp doesn't parse to prevent misfires
1568
1569 if ($check_timestamp) {
1570 $match_ok = false;
1571
1572 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1573 $date_modifier == "after" && $timestamp > $check_timestamp) {
1574 $match_ok = true;
1575 }
1576
1577 if ($inverse) $match_ok = !$match_ok;
1578
1579 if ($match_ok) {
1580 array_push($matches, array($filter["action"], $filter["action_param"]));
1581 }
1582 }
1583 }
1584 }
1585
1586 if ($filters["author"]) {
1587 foreach ($filters["author"] as $filter) {
1588 $reg_exp = $filter["reg_exp"];
1589 $inverse = $filter["inverse"];
1590 if ((!$inverse && @preg_match("/$reg_exp/i", $author)) ||
1591 ($inverse && !@preg_match("/$reg_exp/i", $author))) {
1592
1593 array_push($matches, array($filter["action"], $filter["action_param"]));
1594 }
1595 }
1596 }
1597
1598 if ($filters["tag"]) {
1599
1600 $tag_string = join(",", $tags);
1601
1602 foreach ($filters["tag"] as $filter) {
1603 $reg_exp = $filter["reg_exp"];
1604 $inverse = $filter["inverse"];
1605
1606 if ((!$inverse && @preg_match("/$reg_exp/i", $tag_string)) ||
1607 ($inverse && !@preg_match("/$reg_exp/i", $tag_string))) {
1608
1609 array_push($matches, array($filter["action"], $filter["action_param"]));
1610 }
1611 }
1612 }
1613
1614
1615 return $matches;
1616 }
1617
1618 function find_article_filter($filters, $filter_name) {
1619 foreach ($filters as $f) {
1620 if ($f[0] == $filter_name) {
1621 return $f;
1622 };
1623 }
1624 return false;
1625 }
1626
1627 function calculate_article_score($filters) {
1628 $score = 0;
1629
1630 foreach ($filters as $f) {
1631 if ($f[0] == "score") {
1632 $score += $f[1];
1633 };
1634 }
1635 return $score;
1636 }
1637
1638 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1639 foreach ($filters as $f) {
1640 if ($f[0] == "label") {
1641 label_add_article($link, $id, $f[1], $owner_uid);
1642 };
1643 }
1644 }
1645
1646 function getmicrotime() {
1647 list($usec, $sec) = explode(" ",microtime());
1648 return ((float)$usec + (float)$sec);
1649 }
1650
1651 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1652 foreach ($values as $v) {
1653
1654 if ($v == $default)
1655 $sel = "checked";
1656 else
1657 $sel = "";
1658
1659 if ($v == $true_is) {
1660 $sel .= " value=\"1\"";
1661 } else {
1662 $sel .= " value=\"0\"";
1663 }
1664
1665 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1666 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1667
1668 }
1669 }
1670
1671 function initialize_user_prefs($link, $uid, $profile = false) {
1672
1673 $uid = db_escape_string($uid);
1674
1675 if (!$profile) {
1676 $profile = "NULL";
1677 $profile_qpart = "AND profile IS NULL";
1678 } else {
1679 $profile_qpart = "AND profile = '$profile'";
1680 }
1681
1682 if (get_schema_version($link) < 63) $profile_qpart = "";
1683
1684 db_query($link, "BEGIN");
1685
1686 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1687
1688 $u_result = db_query($link, "SELECT pref_name
1689 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1690
1691 $active_prefs = array();
1692
1693 while ($line = db_fetch_assoc($u_result)) {
1694 array_push($active_prefs, $line["pref_name"]);
1695 }
1696
1697 while ($line = db_fetch_assoc($result)) {
1698 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1699 // print "adding " . $line["pref_name"] . "<br>";
1700
1701 if (get_schema_version($link) < 63) {
1702 db_query($link, "INSERT INTO ttrss_user_prefs
1703 (owner_uid,pref_name,value) VALUES
1704 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1705
1706 } else {
1707 db_query($link, "INSERT INTO ttrss_user_prefs
1708 (owner_uid,pref_name,value, profile) VALUES
1709 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1710 }
1711
1712 }
1713 }
1714
1715 db_query($link, "COMMIT");
1716
1717 }
1718
1719 function lookup_user_id($link, $user) {
1720
1721 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1722 login = '$login'");
1723
1724 if (db_num_rows($result) == 1) {
1725 return db_fetch_result($result, 0, "id");
1726 } else {
1727 return false;
1728 }
1729 }
1730
1731 function http_authenticate_user($link) {
1732
1733 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1734
1735 if (!$_SERVER["PHP_AUTH_USER"]) {
1736
1737 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1738 header('HTTP/1.0 401 Unauthorized');
1739 exit;
1740
1741 } else {
1742 $auth_result = authenticate_user($link,
1743 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1744
1745 if (!$auth_result) {
1746 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1747 header('HTTP/1.0 401 Unauthorized');
1748 exit;
1749 }
1750 }
1751
1752 return true;
1753 }
1754
1755 function authenticate_user($link, $login, $password, $force_auth = false) {
1756
1757 if (!SINGLE_USER_MODE) {
1758
1759 $pwd_hash1 = encrypt_password($password);
1760 $pwd_hash2 = encrypt_password($password, $login);
1761 $login = db_escape_string($login);
1762
1763 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1764 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1765
1766 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1767
1768 $query = "SELECT id,login,access_level,pwd_hash
1769 FROM ttrss_users WHERE
1770 login = '$login'";
1771
1772 } else {
1773 $query = "SELECT id,login,access_level,pwd_hash
1774 FROM ttrss_users WHERE
1775 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1776 pwd_hash = '$pwd_hash2')";
1777 }
1778
1779 $result = db_query($link, $query);
1780
1781 if (db_num_rows($result) == 1) {
1782 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1783 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1784 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1785
1786 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1787 $_SESSION["uid"]);
1788
1789 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1790 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1791
1792 $_SESSION["last_version_check"] = time();
1793
1794 initialize_user_prefs($link, $_SESSION["uid"]);
1795
1796 return true;
1797 }
1798
1799 return false;
1800
1801 } else {
1802
1803 $_SESSION["uid"] = 1;
1804 $_SESSION["name"] = "admin";
1805
1806 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1807
1808 initialize_user_prefs($link, $_SESSION["uid"]);
1809
1810 return true;
1811 }
1812 }
1813
1814 function make_password($length = 8) {
1815
1816 $password = "";
1817 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1818
1819 $i = 0;
1820
1821 while ($i < $length) {
1822 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1823
1824 if (!strstr($password, $char)) {
1825 $password .= $char;
1826 $i++;
1827 }
1828 }
1829 return $password;
1830 }
1831
1832 // this is called after user is created to initialize default feeds, labels
1833 // or whatever else
1834
1835 // user preferences are checked on every login, not here
1836
1837 function initialize_user($link, $uid) {
1838
1839 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1840 values ('$uid', 'Tiny Tiny RSS: New Releases',
1841 'http://tt-rss.org/releases.rss')");
1842
1843 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1844 values ('$uid', 'Tiny Tiny RSS: Forum',
1845 'http://tt-rss.org/forum/rss.php')");
1846 }
1847
1848 function logout_user() {
1849 session_destroy();
1850 if (isset($_COOKIE[session_name()])) {
1851 setcookie(session_name(), '', time()-42000, '/');
1852 }
1853 }
1854
1855 function get_script_urlpath() {
1856 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1857 }
1858
1859 function validate_session($link) {
1860 if (SINGLE_USER_MODE) return true;
1861
1862 $check_ip = $_SESSION['ip_address'];
1863
1864 switch (SESSION_CHECK_ADDRESS) {
1865 case 0:
1866 $check_ip = '';
1867 break;
1868 case 1:
1869 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1870 break;
1871 case 2:
1872 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1873 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1874 break;
1875 };
1876
1877 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
1878 $_SESSION["login_error_msg"] =
1879 __("Session failed to validate (incorrect IP)");
1880 return false;
1881 }
1882
1883 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
1884 return false;
1885
1886 if ($_SESSION["uid"]) {
1887
1888 $result = db_query($link,
1889 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1890
1891 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1892
1893 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1894 return false;
1895 }
1896 }
1897
1898 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1899
1900 //print_r($_SESSION);
1901
1902 if (time() > $_SESSION["cookie_lifetime"]) {
1903 return false;
1904 }
1905 } */
1906
1907 return true;
1908 }
1909
1910 function login_sequence($link, $mobile = false) {
1911 if (!SINGLE_USER_MODE) {
1912
1913 $login_action = $_POST["login_action"];
1914
1915 # try to authenticate user if called from login form
1916 if ($login_action == "do_login") {
1917 $login = $_POST["login"];
1918 $password = $_POST["password"];
1919 $remember_me = $_POST["remember_me"];
1920
1921 if (authenticate_user($link, $login, $password)) {
1922 $_POST["password"] = "";
1923
1924 $_SESSION["language"] = $_POST["language"];
1925 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1926 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1927
1928 if ($_POST["profile"]) {
1929
1930 $profile = db_escape_string($_POST["profile"]);
1931
1932 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
1933 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
1934
1935 if (db_num_rows($result) != 0) {
1936 $_SESSION["profile"] = $profile;
1937 $_SESSION["prefs_cache"] = array();
1938 }
1939 }
1940
1941 if ($_REQUEST['return']) {
1942 header("Location: " . $_REQUEST['return']);
1943 } else {
1944 header("Location: " . $_SERVER["REQUEST_URI"]);
1945 }
1946
1947 exit;
1948
1949 return;
1950 } else {
1951 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1952 }
1953 }
1954
1955 if (!$_SESSION["uid"] || !validate_session($link)) {
1956 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1957 && $_SERVER["REMOTE_USER"] && defined('AUTO_LOGIN') && AUTO_LOGIN) {
1958 authenticate_user($link,$_SERVER['REMOTE_USER'],null);
1959 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1960 } else {
1961 render_login_form($link, $mobile);
1962 //header("Location: login.php");
1963 exit;
1964 }
1965 } else {
1966 /* bump login timestamp */
1967 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1968 $_SESSION["uid"]);
1969
1970 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
1971 setcookie("ttrss_lang", $_SESSION["language"],
1972 time() + SESSION_COOKIE_LIFETIME);
1973 }
1974 }
1975
1976 } else {
1977 return authenticate_user($link, "admin", null);
1978 }
1979 }
1980
1981 function truncate_string($str, $max_len, $suffix = '&hellip;') {
1982 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1983 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
1984 } else {
1985 return $str;
1986 }
1987 }
1988
1989 function theme_image($link, $filename) {
1990 if ($link) {
1991 $theme_path = get_user_theme_path($link);
1992
1993 if ($theme_path && is_file($theme_path.$filename)) {
1994 return $theme_path.$filename;
1995 } else {
1996 return $filename;
1997 }
1998 } else {
1999 return $filename;
2000 }
2001 }
2002
2003 function get_user_theme($link) {
2004
2005 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2006 $theme_name = get_pref($link, "_THEME_ID");
2007 if (is_dir("themes/$theme_name")) {
2008 return $theme_name;
2009 } else {
2010 return '';
2011 }
2012 } else {
2013 return '';
2014 }
2015
2016 }
2017
2018 function get_user_theme_path($link) {
2019 $theme_path = '';
2020
2021 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2022 $theme_name = get_pref($link, "_THEME_ID");
2023
2024 if ($theme_name && is_dir("themes/$theme_name")) {
2025 $theme_path = "themes/$theme_name/";
2026 } else {
2027 $theme_name = '';
2028 }
2029 } else {
2030 $theme_path = '';
2031 }
2032
2033 if ($theme_path) {
2034 if (is_file("$theme_path/theme.ini")) {
2035 $ini = parse_ini_file("$theme_path/theme.ini", true);
2036 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
2037 return $theme_path;
2038 }
2039 }
2040 }
2041 return '';
2042 }
2043
2044 function get_user_theme_options($link) {
2045 $t = get_user_theme_path($link);
2046
2047 if ($t) {
2048 if (is_file("$t/theme.ini")) {
2049 $ini = parse_ini_file("$t/theme.ini", true);
2050 if ($ini['theme']['version']) {
2051 return $ini['theme']['options'];
2052 }
2053 }
2054 }
2055 return '';
2056 }
2057
2058 function print_theme_includes($link) {
2059
2060 $t = get_user_theme_path($link);
2061 $time = time();
2062
2063 if ($t) {
2064 print "<link rel=\"stylesheet\" type=\"text/css\"
2065 href=\"$t/theme.css?$time \">";
2066 if (file_exists("$t/theme.js")) {
2067 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2068 </script>";
2069 }
2070 }
2071 }
2072
2073 function get_all_themes() {
2074 $themes = glob("themes/*");
2075
2076 asort($themes);
2077
2078 $rv = array();
2079
2080 foreach ($themes as $t) {
2081 if (is_file("$t/theme.ini")) {
2082 $ini = parse_ini_file("$t/theme.ini", true);
2083 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
2084 !$ini['theme']['disabled']) {
2085 $entry = array();
2086 $entry["path"] = $t;
2087 $entry["base"] = basename($t);
2088 $entry["name"] = $ini['theme']['name'];
2089 $entry["version"] = $ini['theme']['version'];
2090 $entry["author"] = $ini['theme']['author'];
2091 $entry["options"] = $ini['theme']['options'];
2092 array_push($rv, $entry);
2093 }
2094 }
2095 }
2096
2097 return $rv;
2098 }
2099
2100 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2101
2102 try {
2103 $source_tz = new DateTimeZone($source_tz);
2104 } catch (Exception $e) {
2105 $source_tz = new DateTimeZone('UTC');
2106 }
2107
2108 try {
2109 $dest_tz = new DateTimeZone($dest_tz);
2110 } catch (Exception $e) {
2111 $dest_tz = new DateTimeZone('UTC');
2112 }
2113
2114 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2115 return $dt->format('U') + $dest_tz->getOffset($dt);
2116 }
2117
2118 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2119 $no_smart_dt = false) {
2120
2121 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2122 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2123
2124 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2125
2126 try {
2127 $user_tz = new DateTimeZone($user_tz_string);
2128 } catch (Exception $e) {
2129 $user_tz = new DateTimeZone('UTC');
2130 }
2131
2132 # We store date in UTC internally
2133 $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
2134 $user_timestamp = $dt->format('U') + $user_tz->getOffset($dt);
2135
2136 if (!$no_smart_dt && get_pref($link, 'HEADLINES_SMART_DATE', $owner_uid)) {
2137 return smart_date_time($link, $user_timestamp,
2138 $user_tz->getOffset($dt), $owner_uid);
2139 } else {
2140 if ($long)
2141 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2142 else
2143 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2144
2145 return date($format, $user_timestamp);
2146 }
2147 }
2148
2149 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2150 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2151
2152 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
2153 return date("G:i", $timestamp);
2154 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
2155 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2156 return date($format, $timestamp);
2157 } else {
2158 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2159 return date($format, $timestamp);
2160 }
2161 }
2162
2163 function smart_date($timestamp) {
2164 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2165 return "Today";
2166 } else if (date("Y", $timestamp) == date("Y")) {
2167 return date("D m", $timestamp);
2168 } else {
2169 return date("Y/m/d", $timestamp);
2170 }
2171 }
2172
2173 function sql_bool_to_string($s) {
2174 if ($s == "t" || $s == "1") {
2175 return "true";
2176 } else {
2177 return "false";
2178 }
2179 }
2180
2181 function sql_bool_to_bool($s) {
2182 if ($s == "t" || $s == "1") {
2183 return true;
2184 } else {
2185 return false;
2186 }
2187 }
2188
2189 function bool_to_sql_bool($s) {
2190 if ($s) {
2191 return "true";
2192 } else {
2193 return "false";
2194 }
2195 }
2196
2197 function toggleEvenOdd($a) {
2198 if ($a == "even")
2199 return "odd";
2200 else
2201 return "even";
2202 }
2203
2204 function get_schema_version($link, $nocache = false) {
2205 if (!$_SESSION["schema_version"] || $nocache) {
2206 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2207 $version = db_fetch_result($result, 0, "schema_version");
2208 $_SESSION["schema_version"] = $version;
2209 return $version;
2210 } else {
2211 return $_SESSION["schema_version"];
2212 }
2213 }
2214
2215 function sanity_check($link) {
2216
2217 global $ERRORS;
2218
2219 $error_code = 0;
2220 $schema_version = get_schema_version($link);
2221
2222 if ($schema_version != SCHEMA_VERSION) {
2223 $error_code = 5;
2224 }
2225
2226 if (DB_TYPE == "mysql") {
2227 $result = db_query($link, "SELECT true", false);
2228 if (db_num_rows($result) != 1) {
2229 $error_code = 10;
2230 }
2231 }
2232
2233 if (db_escape_string("testTEST") != "testTEST") {
2234 $error_code = 12;
2235 }
2236
2237 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2238 }
2239
2240 function file_is_locked($filename) {
2241 if (function_exists('flock')) {
2242 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
2243 if ($fp) {
2244 if (flock($fp, LOCK_EX | LOCK_NB)) {
2245 flock($fp, LOCK_UN);
2246 fclose($fp);
2247 return false;
2248 }
2249 fclose($fp);
2250 return true;
2251 } else {
2252 return false;
2253 }
2254 }
2255 return true; // consider the file always locked and skip the test
2256 }
2257
2258 function make_lockfile($filename) {
2259 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2260
2261 if (flock($fp, LOCK_EX | LOCK_NB)) {
2262 if (function_exists('posix_getpid')) {
2263 fwrite($fp, posix_getpid() . "\n");
2264 }
2265 return $fp;
2266 } else {
2267 return false;
2268 }
2269 }
2270
2271 function make_stampfile($filename) {
2272 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2273
2274 if (flock($fp, LOCK_EX | LOCK_NB)) {
2275 fwrite($fp, time() . "\n");
2276 flock($fp, LOCK_UN);
2277 fclose($fp);
2278 return true;
2279 } else {
2280 return false;
2281 }
2282 }
2283
2284 function sql_random_function() {
2285 if (DB_TYPE == "mysql") {
2286 return "RAND()";
2287 } else {
2288 return "RANDOM()";
2289 }
2290 }
2291
2292 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2293
2294 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2295
2296 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2297
2298 if ($cat_view) {
2299
2300 if ($feed >= 0) {
2301
2302 if ($feed > 0) {
2303 $cat_qpart = "cat_id = '$feed'";
2304 } else {
2305 $cat_qpart = "cat_id IS NULL";
2306 }
2307
2308 $tmp_result = db_query($link, "SELECT id
2309 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2310
2311 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2312
2313 $tmp_feed = $tmp_line["id"];
2314
2315 db_query($link, "UPDATE ttrss_user_entries
2316 SET unread = false,last_read = NOW()
2317 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2318 }
2319 } else if ($feed == -2) {
2320
2321
2322 db_query($link, "UPDATE ttrss_user_entries
2323 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2324 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2325 AND unread = true AND owner_uid = $owner_uid");
2326 }
2327
2328 } else if ($feed > 0) {
2329
2330 db_query($link, "UPDATE ttrss_user_entries
2331 SET unread = false,last_read = NOW()
2332 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2333
2334 } else if ($feed < 0 && $feed > -10) { // special, like starred
2335
2336 if ($feed == -1) {
2337 db_query($link, "UPDATE ttrss_user_entries
2338 SET unread = false,last_read = NOW()
2339 WHERE marked = true AND owner_uid = $owner_uid");
2340 }
2341
2342 if ($feed == -2) {
2343 db_query($link, "UPDATE ttrss_user_entries
2344 SET unread = false,last_read = NOW()
2345 WHERE published = true AND owner_uid = $owner_uid");
2346 }
2347
2348 if ($feed == -3) {
2349
2350 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2351
2352 if (DB_TYPE == "pgsql") {
2353 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2354 } else {
2355 $match_part = "updated > DATE_SUB(NOW(),
2356 INTERVAL $intl HOUR) ";
2357 }
2358
2359 $result = db_query($link, "SELECT id FROM ttrss_entries,
2360 ttrss_user_entries WHERE $match_part AND
2361 unread = true AND
2362 ttrss_user_entries.ref_id = ttrss_entries.id AND
2363 owner_uid = $owner_uid");
2364
2365 $affected_ids = array();
2366
2367 while ($line = db_fetch_assoc($result)) {
2368 array_push($affected_ids, $line["id"]);
2369 }
2370
2371 catchupArticlesById($link, $affected_ids, 0);
2372 }
2373
2374 if ($feed == -4) {
2375 db_query($link, "UPDATE ttrss_user_entries
2376 SET unread = false,last_read = NOW()
2377 WHERE owner_uid = $owner_uid");
2378 }
2379
2380 } else if ($feed < -10) { // label
2381
2382 $label_id = -$feed - 11;
2383
2384 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2385 SET unread = false, last_read = NOW()
2386 WHERE label_id = '$label_id' AND unread = true
2387 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2388
2389 }
2390
2391 ccache_update($link, $feed, $owner_uid, $cat_view);
2392
2393 } else { // tag
2394 db_query($link, "BEGIN");
2395
2396 $tag_name = db_escape_string($feed);
2397
2398 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2399 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2400
2401 while ($line = db_fetch_assoc($result)) {
2402 db_query($link, "UPDATE ttrss_user_entries SET
2403 unread = false, last_read = NOW()
2404 WHERE int_id = " . $line["post_int_id"]);
2405 }
2406 db_query($link, "COMMIT");
2407 }
2408 }
2409
2410 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2411
2412 if (!$omode) $omode = "flc";
2413
2414 $data = getGlobalCounters($link);
2415
2416 $data = array_merge($data, getVirtCounters($link));
2417
2418 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2419 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2420 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2421 if (strchr($omode, "c")) {
2422 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2423 $data = array_merge($data, getCategoryCounters($link));
2424 }
2425 }
2426
2427 return $data;
2428 }
2429
2430 function getCategoryCounters($link) {
2431 $ret_arr = array();
2432
2433 /* Labels category */
2434
2435 $cv = array("id" => -2, "kind" => "cat",
2436 "counter" => getCategoryUnread($link, -2));
2437
2438 array_push($ret_arr, $cv);
2439
2440 $age_qpart = getMaxAgeSubquery();
2441
2442 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2443 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2444 WHERE ttrss_cat_counters_cache.feed_id = id AND
2445 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2446
2447 while ($line = db_fetch_assoc($result)) {
2448 $line["cat_id"] = (int) $line["cat_id"];
2449
2450 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2451 "counter" => $line["unread"]);
2452
2453 array_push($ret_arr, $cv);
2454 }
2455
2456 /* Special case: NULL category doesn't actually exist in the DB */
2457
2458 $cv = array("id" => 0, "kind" => "cat",
2459 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2460
2461 array_push($ret_arr, $cv);
2462
2463 return $ret_arr;
2464 }
2465
2466 function getCategoryUnread($link, $cat, $owner_uid = false) {
2467
2468 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2469
2470 if ($cat >= 0) {
2471
2472 if ($cat != 0) {
2473 $cat_query = "cat_id = '$cat'";
2474 } else {
2475 $cat_query = "cat_id IS NULL";
2476 }
2477
2478 $age_qpart = getMaxAgeSubquery();
2479
2480 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2481 AND owner_uid = " . $owner_uid);
2482
2483 $cat_feeds = array();
2484 while ($line = db_fetch_assoc($result)) {
2485 array_push($cat_feeds, "feed_id = " . $line["id"]);
2486 }
2487
2488 if (count($cat_feeds) == 0) return 0;
2489
2490 $match_part = implode(" OR ", $cat_feeds);
2491
2492 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2493 FROM ttrss_user_entries,ttrss_entries
2494 WHERE unread = true AND ($match_part) AND id = ref_id
2495 AND $age_qpart AND owner_uid = " . $owner_uid);
2496
2497 $unread = 0;
2498
2499 # this needs to be rewritten
2500 while ($line = db_fetch_assoc($result)) {
2501 $unread += $line["unread"];
2502 }
2503
2504 return $unread;
2505 } else if ($cat == -1) {
2506 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
2507 } else if ($cat == -2) {
2508
2509 $result = db_query($link, "
2510 SELECT COUNT(unread) AS unread FROM
2511 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2512 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2513 ttrss_labels2.owner_uid = '$owner_uid'
2514 AND unread = true AND feed_id = ttrss_feeds.id
2515 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2516
2517 $unread = db_fetch_result($result, 0, "unread");
2518
2519 return $unread;
2520
2521 }
2522 }
2523
2524 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2525 if (DB_TYPE == "pgsql") {
2526 return "ttrss_entries.date_updated >
2527 NOW() - INTERVAL '$days days'";
2528 } else {
2529 return "ttrss_entries.date_updated >
2530 DATE_SUB(NOW(), INTERVAL $days DAY)";
2531 }
2532 }
2533
2534 function getFeedUnread($link, $feed, $is_cat = false) {
2535 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2536 }
2537
2538 function getLabelUnread($link, $label_id, $owner_uid = false) {
2539 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2540
2541 $result = db_query($link, "
2542 SELECT COUNT(unread) AS unread FROM
2543 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2544 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2545 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2546 AND unread = true AND feed_id = ttrss_feeds.id
2547 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2548
2549 if (db_num_rows($result) != 0) {
2550 return db_fetch_result($result, 0, "unread");
2551 } else {
2552 return 0;
2553 }
2554 }
2555
2556 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2557 $owner_uid = false) {
2558
2559 $n_feed = (int) $feed;
2560
2561 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2562
2563 if ($unread_only) {
2564 $unread_qpart = "unread = true";
2565 } else {
2566 $unread_qpart = "true";
2567 }
2568
2569 $age_qpart = getMaxAgeSubquery();
2570
2571 if ($is_cat) {
2572 return getCategoryUnread($link, $n_feed, $owner_uid);
2573 } if ($feed != "0" && $n_feed == 0) {
2574
2575 $feed = db_escape_string($feed);
2576
2577 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2578 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2579 AND ref_id = id AND $age_qpart
2580 AND $unread_qpart)) AS count FROM ttrss_tags
2581 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2582 return db_fetch_result($result, 0, "count");
2583
2584 } else if ($n_feed == -1) {
2585 $match_part = "marked = true";
2586 } else if ($n_feed == -2) {
2587 $match_part = "published = true";
2588 } else if ($n_feed == -3) {
2589 $match_part = "unread = true AND score >= 0";
2590
2591 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2592
2593 if (DB_TYPE == "pgsql") {
2594 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2595 } else {
2596 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2597 }
2598 } else if ($n_feed == -4) {
2599 $match_part = "true";
2600 } else if ($n_feed >= 0) {
2601
2602 if ($n_feed != 0) {
2603 $match_part = "feed_id = '$n_feed'";
2604 } else {
2605 $match_part = "feed_id IS NULL";
2606 }
2607
2608 } else if ($feed < -10) {
2609
2610 $label_id = -$feed - 11;
2611
2612 return getLabelUnread($link, $label_id, $owner_uid);
2613
2614 }
2615
2616 if ($match_part) {
2617
2618 if ($n_feed != 0) {
2619 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2620 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2621 } else {
2622 $from_qpart = "ttrss_user_entries,ttrss_entries";
2623 $feeds_qpart = '';
2624 }
2625
2626 $query = "SELECT count(int_id) AS unread
2627 FROM $from_qpart WHERE
2628 ttrss_user_entries.ref_id = ttrss_entries.id AND
2629 $age_qpart AND
2630 $feeds_qpart
2631 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2632
2633 $result = db_query($link, $query);
2634
2635 } else {
2636
2637 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2638 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2639 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2640 AND $unread_qpart AND $age_qpart AND
2641 ttrss_tags.owner_uid = " . $owner_uid);
2642 }
2643
2644 $unread = db_fetch_result($result, 0, "unread");
2645
2646 return $unread;
2647 }
2648
2649 function getGlobalUnread($link, $user_id = false) {
2650
2651 if (!$user_id) {
2652 $user_id = $_SESSION["uid"];
2653 }
2654
2655 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2656 WHERE owner_uid = '$user_id' AND feed_id > 0");
2657
2658 $c_id = db_fetch_result($result, 0, "c_id");
2659
2660 return $c_id;
2661 }
2662
2663 function getGlobalCounters($link, $global_unread = -1) {
2664 $ret_arr = array();
2665
2666 if ($global_unread == -1) {
2667 $global_unread = getGlobalUnread($link);
2668 }
2669
2670 $cv = array("id" => "global-unread",
2671 "counter" => $global_unread);
2672
2673 array_push($ret_arr, $cv);
2674
2675 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2676 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2677
2678 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2679
2680 $cv = array("id" => "subscribed-feeds",
2681 "counter" => $subscribed_feeds);
2682
2683 array_push($ret_arr, $cv);
2684
2685 return $ret_arr;
2686 }
2687
2688 function getSubscribedFeeds($link) {
2689 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2690 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2691
2692 return db_fetch_result($result, 0, "fn");
2693 }
2694
2695 function getTagCounters($link) {
2696
2697 $ret_arr = array();
2698
2699 $age_qpart = getMaxAgeSubquery();
2700
2701 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2702 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2703 AND ref_id = id AND $age_qpart
2704 AND unread = true)) AS count FROM ttrss_tags
2705 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2706 ORDER BY count DESC LIMIT 55");
2707
2708 $tags = array();
2709
2710 while ($line = db_fetch_assoc($result)) {
2711 $tags[$line["tag_name"]] += $line["count"];
2712 }
2713
2714 foreach (array_keys($tags) as $tag) {
2715 $unread = $tags[$tag];
2716 $tag = htmlspecialchars($tag);
2717
2718 $cv = array("id" => $tag,
2719 "kind" => "tag",
2720 "counter" => $unread);
2721
2722 array_push($ret_arr, $cv);
2723 }
2724
2725 return $ret_arr;
2726 }
2727
2728 function getVirtCounters($link) {
2729
2730 $ret_arr = array();
2731
2732 for ($i = 0; $i >= -4; $i--) {
2733
2734 $count = getFeedUnread($link, $i);
2735
2736 $cv = array("id" => $i,
2737 "counter" => $count);
2738
2739 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2740 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2741
2742 array_push($ret_arr, $cv);
2743 }
2744
2745 return $ret_arr;
2746 }
2747
2748 function getLabelCounters($link, $descriptions = false) {
2749
2750 $ret_arr = array();
2751
2752 $age_qpart = getMaxAgeSubquery();
2753
2754 $owner_uid = $_SESSION["uid"];
2755
2756 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2757 WHERE owner_uid = '$owner_uid'");
2758
2759 while ($line = db_fetch_assoc($result)) {
2760
2761 $id = -$line["id"] - 11;
2762
2763 $label_name = $line["caption"];
2764 $count = getFeedUnread($link, $id);
2765
2766 $cv = array("id" => $id,
2767 "counter" => $count);
2768
2769 if ($descriptions)
2770 $cv["description"] = $label_name;
2771
2772 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2773 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2774
2775 array_push($ret_arr, $cv);
2776 }
2777
2778 return $ret_arr;
2779 }
2780
2781 function getFeedCounters($link, $active_feed = false) {
2782
2783 $ret_arr = array();
2784
2785 $age_qpart = getMaxAgeSubquery();
2786
2787 $query = "SELECT ttrss_feeds.id,
2788 ttrss_feeds.title,
2789 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2790 last_error, value AS count
2791 FROM ttrss_feeds, ttrss_counters_cache
2792 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2793 AND ttrss_counters_cache.feed_id = id";
2794
2795 $result = db_query($link, $query);
2796 $fctrs_modified = false;
2797
2798 while ($line = db_fetch_assoc($result)) {
2799
2800 $id = $line["id"];
2801 $count = $line["count"];
2802 $last_error = htmlspecialchars($line["last_error"]);
2803
2804 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2805
2806 $has_img = feed_has_icon($id);
2807
2808 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2809 $last_updated = '';
2810
2811 $cv = array("id" => $id,
2812 "updated" => $last_updated,
2813 "counter" => $count,
2814 "has_img" => (int) $has_img);
2815
2816 if ($last_error)
2817 $cv["error"] = $last_error;
2818
2819 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2820 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2821
2822 if ($active_feed && $id == $active_feed)
2823 $cv["title"] = truncate_string($line["title"], 30);
2824
2825 array_push($ret_arr, $cv);
2826
2827 }
2828
2829 return $ret_arr;
2830 }
2831
2832 function get_pgsql_version($link) {
2833 $result = db_query($link, "SELECT version() AS version");
2834 $version = split(" ", db_fetch_result($result, 0, "version"));
2835 return $version[1];
2836 }
2837
2838 /**
2839 * Subscribes the user to the given feed
2840 *
2841 * @param resource $link Database connection
2842 * @param string $url Feed URL to subscribe to
2843 * @param integer $cat_id Category ID the feed shall be added to
2844 * @param string $auth_login (optional) Feed username
2845 * @param string $auth_pass (optional) Feed password
2846 *
2847 * @return integer Status code:
2848 * 0 - OK, Feed already exists
2849 * 1 - OK, Feed added
2850 * 2 - Invalid URL
2851 * 3 - URL content is HTML, no feeds available
2852 * 4 - URL content is HTML which contains multiple feeds.
2853 * Here you should call extractfeedurls in rpc-backend
2854 * to get all possible feeds.
2855 * 5 - Couldn't download the URL content.
2856 */
2857 function subscribe_to_feed($link, $url, $cat_id = 0,
2858 $auth_login = '', $auth_pass = '') {
2859
2860 $url = fix_url($url);
2861
2862 if (!$url || !validate_feed_url($url)) return 2;
2863
2864 $update_method = 0;
2865
2866 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
2867 WHERE id = ".$_SESSION['uid']);
2868
2869 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2870
2871 if (!$has_oauth || strpos($url, '://api.twitter.com') === false) {
2872 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
2873
2874 if (url_is_html($url, $auth_login, $auth_pass)) {
2875 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
2876 if (count($feedUrls) == 0) {
2877 return 3;
2878 } else if (count($feedUrls) > 1) {
2879 return 4;
2880 }
2881 //use feed url as new URL
2882 $url = key($feedUrls);
2883 }
2884
2885 } else {
2886 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
2887 return 5;
2888
2889 $update_method = 3;
2890 }
2891 if ($cat_id == "0" || !$cat_id) {
2892 $cat_qpart = "NULL";
2893 } else {
2894 $cat_qpart = "'$cat_id'";
2895 }
2896
2897 $result = db_query($link,
2898 "SELECT id FROM ttrss_feeds
2899 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2900
2901 if (db_num_rows($result) == 0) {
2902 $result = db_query($link,
2903 "INSERT INTO ttrss_feeds
2904 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2905 VALUES ('".$_SESSION["uid"]."', '$url',
2906 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
2907
2908 $result = db_query($link,
2909 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2910 AND owner_uid = " . $_SESSION["uid"]);
2911
2912 $feed_id = db_fetch_result($result, 0, "id");
2913
2914 if ($feed_id) {
2915 update_rss_feed($link, $feed_id, true);
2916 }
2917
2918 return 1;
2919 } else {
2920 return 0;
2921 }
2922 }
2923
2924 function print_feed_select($link, $id, $default_id = "",
2925 $attributes = "", $include_all_feeds = true) {
2926
2927 print "<select id=\"$id\" name=\"$id\" $attributes>";
2928 if ($include_all_feeds) {
2929 print "<option value=\"0\">".__('All feeds')."</option>";
2930 }
2931
2932 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2933 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2934
2935 if (db_num_rows($result) > 0 && $include_all_feeds) {
2936 print "<option disabled>--------</option>";
2937 }
2938
2939 while ($line = db_fetch_assoc($result)) {
2940 if ($line["id"] == $default_id) {
2941 $is_selected = "selected=\"1\"";
2942 } else {
2943 $is_selected = "";
2944 }
2945
2946 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2947
2948 printf("<option $is_selected value='%d'>%s</option>",
2949 $line["id"], $title);
2950 }
2951
2952 print "</select>";
2953 }
2954
2955 function print_feed_cat_select($link, $id, $default_id = "",
2956 $attributes = "", $include_all_cats = true) {
2957
2958 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
2959
2960 if ($include_all_cats) {
2961 print "<option value=\"0\">".__('Uncategorized')."</option>";
2962 }
2963
2964 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2965 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2966
2967 if (db_num_rows($result) > 0 && $include_all_cats) {
2968 print "<option disabled=\"1\">--------</option>";
2969 }
2970
2971 while ($line = db_fetch_assoc($result)) {
2972 if ($line["id"] == $default_id) {
2973 $is_selected = "selected=\"1\"";
2974 } else {
2975 $is_selected = "";
2976 }
2977
2978 if ($line["title"])
2979 printf("<option $is_selected value='%d'>%s</option>",
2980 $line["id"], htmlspecialchars($line["title"]));
2981 }
2982
2983 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
2984
2985 print "</select>";
2986 }
2987
2988 function checkbox_to_sql_bool($val) {
2989 return ($val == "on") ? "true" : "false";
2990 }
2991
2992 function getFeedCatTitle($link, $id) {
2993 if ($id == -1) {
2994 return __("Special");
2995 } else if ($id < -10) {
2996 return __("Labels");
2997 } else if ($id > 0) {
2998 $result = db_query($link, "SELECT ttrss_feed_categories.title
2999 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3000 cat_id = ttrss_feed_categories.id");
3001 if (db_num_rows($result) == 1) {
3002 return db_fetch_result($result, 0, "title");
3003 } else {
3004 return __("Uncategorized");
3005 }
3006 } else {
3007 return "getFeedCatTitle($id) failed";
3008 }
3009
3010 }
3011
3012 function getFeedIcon($id) {
3013 switch ($id) {
3014 case 0:
3015 return "images/archive.png";
3016 break;
3017 case -1:
3018 return "images/mark_set.png";
3019 break;
3020 case -2:
3021 return "images/pub_set.png";
3022 break;
3023 case -3:
3024 return "images/fresh.png";
3025 break;
3026 case -4:
3027 return "images/tag.png";
3028 break;
3029 default:
3030 if ($id < -10) {
3031 return "images/label.png";
3032 } else {
3033 if (file_exists(ICONS_DIR . "/$id.ico"))
3034 return ICONS_URL . "/$id.ico";
3035 }
3036 break;
3037 }
3038 }
3039
3040 function getFeedTitle($link, $id) {
3041 if ($id == -1) {
3042 return __("Starred articles");
3043 } else if ($id == -2) {
3044 return __("Published articles");
3045 } else if ($id == -3) {
3046 return __("Fresh articles");
3047 } else if ($id == -4) {
3048 return __("All articles");
3049 } else if ($id === 0 || $id === "0") {
3050 return __("Archived articles");
3051 } else if ($id < -10) {
3052 $label_id = -$id - 11;
3053 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3054 if (db_num_rows($result) == 1) {
3055 return db_fetch_result($result, 0, "caption");
3056 } else {
3057 return "Unknown label ($label_id)";
3058 }
3059
3060 } else if ($id > 0) {
3061 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3062 if (db_num_rows($result) == 1) {
3063 return db_fetch_result($result, 0, "title");
3064 } else {
3065 return "Unknown feed ($id)";
3066 }
3067 } else {
3068 return $id;
3069 }
3070 }
3071
3072 function get_session_cookie_name() {
3073 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
3074 }
3075
3076 function make_init_params($link) {
3077 $params = array();
3078
3079 $params["theme"] = get_user_theme($link);
3080 $params["theme_options"] = get_user_theme_options($link);
3081 $params["daemon_enabled"] = ENABLE_UPDATE_DAEMON;
3082
3083 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3084 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3085 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3086 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3087
3088 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3089 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3090 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3091 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3092
3093 $params[strtolower($param)] = (int) get_pref($link, $param);
3094 }
3095
3096 $params["icons_url"] = ICONS_URL;
3097 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
3098 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3099 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3100 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3101 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3102
3103 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3104 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3105
3106 $max_feed_id = db_fetch_result($result, 0, "mid");
3107 $num_feeds = db_fetch_result($result, 0, "nf");
3108
3109 $params["max_feed_id"] = (int) $max_feed_id;
3110 $params["num_feeds"] = (int) $num_feeds;
3111
3112 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3113
3114 return $params;
3115 }
3116
3117 function print_runtime_info($link) {
3118 print "<runtime-info><![CDATA[";
3119 print json_encode(make_runtime_info($link));
3120 print "]]></runtime-info>";
3121 }
3122
3123 function make_runtime_info($link) {
3124 $data = array();
3125
3126 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3127 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3128
3129 $max_feed_id = db_fetch_result($result, 0, "mid");
3130 $num_feeds = db_fetch_result($result, 0, "nf");
3131
3132 $data["max_feed_id"] = (int) $max_feed_id;
3133 $data["num_feeds"] = (int) $num_feeds;
3134
3135 $data['last_article_id'] = getLastArticleId($link);
3136 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3137
3138 if (ENABLE_UPDATE_DAEMON) {
3139
3140 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3141
3142 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3143
3144 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
3145
3146 if ($stamp) {
3147 $stamp_delta = time() - $stamp;
3148
3149 if ($stamp_delta > 1800) {
3150 $stamp_check = 0;
3151 } else {
3152 $stamp_check = 1;
3153 $_SESSION["daemon_stamp_check"] = time();
3154 }
3155
3156 $data['daemon_stamp_ok'] = $stamp_check;
3157
3158 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3159
3160 $data['daemon_stamp'] = $stamp_fmt;
3161 }
3162 }
3163 }
3164
3165 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
3166 $new_version_details = @check_for_update($link);
3167
3168 $data['new_version_available'] = (int) ($new_version_details != false);
3169
3170 $_SESSION["last_version_check"] = time();
3171 }
3172
3173 return $data;
3174 }
3175
3176 function getSearchSql($link, $search, $match_on) {
3177
3178 $search_query_part = "";
3179
3180 $keywords = split(" ", $search);
3181 $query_keywords = array();
3182
3183 foreach ($keywords as $k) {
3184 if (strpos($k, "-") === 0) {
3185 $k = substr($k, 1);
3186 $not = "NOT";
3187 } else {
3188 $not = "";
3189 }
3190
3191 if (strpos($k, "@") === 0) {
3192
3193 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3194 $orig_ts = strtotime(substr($k, 1));
3195
3196 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3197
3198 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
3199 } else if ($match_on == "both") {
3200 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3201 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3202 } else if ($match_on == "title") {
3203 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3204 } else if ($match_on == "content") {
3205 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3206 }
3207 }
3208
3209 $search_query_part = implode("AND", $query_keywords);
3210
3211 return $search_query_part;
3212 }
3213
3214 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3215
3216 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3217
3218 $ext_tables_part = "";
3219
3220 if ($search) {
3221
3222 if (SPHINX_ENABLED) {
3223 $ids = join(",", @sphinx_search($search, 0, 500));
3224
3225 if ($ids)
3226 $search_query_part = "ref_id IN ($ids) AND ";
3227 else
3228 $search_query_part = "ref_id = -1 AND ";
3229
3230 } else {
3231 $search_query_part = getSearchSql($link, $search, $match_on);
3232 $search_query_part .= " AND ";
3233 }
3234
3235 } else {
3236 $search_query_part = "";
3237 }
3238
3239 $view_query_part = "";
3240
3241 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3242 if ($search) {
3243 $view_query_part = " ";
3244 } else if ($feed != -1) {
3245 $unread = getFeedUnread($link, $feed, $cat_view);
3246 if ($unread > 0) {
3247 $view_query_part = " unread = true AND ";
3248 }
3249 }
3250 }
3251
3252 if ($view_mode == "marked") {
3253 $view_query_part = " marked = true AND ";
3254 }
3255
3256 if ($view_mode == "published") {
3257 $view_query_part = " published = true AND ";
3258 }
3259
3260 if ($view_mode == "unread") {
3261 $view_query_part = " unread = true AND ";
3262 }
3263
3264 if ($view_mode == "updated") {
3265 $view_query_part = " (last_read is null and unread = false) AND ";
3266 }
3267
3268 if ($limit > 0) {
3269 $limit_query_part = "LIMIT " . $limit;
3270 }
3271
3272 $vfeed_query_part = "";
3273
3274 // override query strategy and enable feed display when searching globally
3275 if ($search && $search_mode == "all_feeds") {
3276 $query_strategy_part = "ttrss_entries.id > 0";
3277 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3278 /* tags */
3279 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3280 $query_strategy_part = "ttrss_entries.id > 0";
3281 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3282 id = feed_id) as feed_title,";
3283 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3284
3285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3286
3287 $tmp_result = false;
3288
3289 if ($cat_view) {
3290 $tmp_result = db_query($link, "SELECT id
3291 FROM ttrss_feeds WHERE cat_id = '$feed'");
3292 } else {
3293 $tmp_result = db_query($link, "SELECT id
3294 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3295 WHERE id = '$feed') AND id != '$feed'");
3296 }
3297
3298 $cat_siblings = array();
3299
3300 if (db_num_rows($tmp_result) > 0) {
3301 while ($p = db_fetch_assoc($tmp_result)) {
3302 array_push($cat_siblings, "feed_id = " . $p["id"]);
3303 }
3304
3305 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3306 $feed, implode(" OR ", $cat_siblings));
3307
3308 } else {
3309 $query_strategy_part = "ttrss_entries.id > 0";
3310 }
3311
3312 } else if ($feed > 0) {
3313
3314 if ($cat_view) {
3315
3316 if ($feed > 0) {
3317 $query_strategy_part = "cat_id = '$feed'";
3318 } else {
3319 $query_strategy_part = "cat_id IS NULL";
3320 }
3321
3322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3323
3324 } else {
3325 $query_strategy_part = "feed_id = '$feed'";
3326 }
3327 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3328 $query_strategy_part = "feed_id IS NULL";
3329 } else if ($feed == 0 && $cat_view) { // uncategorized
3330 $query_strategy_part = "cat_id IS NULL";
3331 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3332 } else if ($feed == -1) { // starred virtual feed
3333 $query_strategy_part = "marked = true";
3334 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3335 } else if ($feed == -2) { // published virtual feed OR labels category
3336
3337 if (!$cat_view) {
3338 $query_strategy_part = "published = true";
3339 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3340 } else {
3341 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3342
3343 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3344
3345 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3346 ttrss_user_labels2.article_id = ref_id";
3347
3348 }
3349
3350 } else if ($feed == -3) { // fresh virtual feed
3351 $query_strategy_part = "unread = true AND score >= 0";
3352
3353 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3354
3355 if (DB_TYPE == "pgsql") {
3356 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3357 } else {
3358 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3359 }
3360
3361 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3362 } else if ($feed == -4) { // all articles virtual feed
3363 $query_strategy_part = "true";
3364 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3365 } else if ($feed <= -10) { // labels
3366 $label_id = -$feed - 11;
3367
3368 $query_strategy_part = "label_id = '$label_id' AND
3369 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3370 ttrss_user_labels2.article_id = ref_id";
3371
3372 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3373 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3374
3375 } else {
3376 $query_strategy_part = "id > 0"; // dumb
3377 }
3378
3379 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3380 $date_sort_field = "updated";
3381 } else {
3382 $date_sort_field = "date_entered";
3383 }
3384
3385 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3386 $order_by = "$date_sort_field";
3387 } else {
3388 $order_by = "$date_sort_field DESC";
3389 }
3390
3391 if ($view_mode != "noscores") {
3392 $order_by = "score DESC, $order_by";
3393 }
3394
3395 if ($override_order) {
3396 $order_by = $override_order;
3397 }
3398
3399 $feed_title = "";
3400
3401 if ($search) {
3402 $feed_title = "Search results";
3403 } else {
3404 if ($cat_view) {
3405 $feed_title = getCategoryTitle($link, $feed);
3406 } else {
3407 if ((int)$feed == $feed && $feed > 0) {
3408 $result = db_query($link, "SELECT title,site_url,last_error
3409 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3410
3411 $feed_title = db_fetch_result($result, 0, "title");
3412 $feed_site_url = db_fetch_result($result, 0, "site_url");
3413 $last_error = db_fetch_result($result, 0, "last_error");
3414 } else {
3415 $feed_title = getFeedTitle($link, $feed);
3416 }
3417 }
3418 }
3419
3420 $content_query_part = "content as content_preview,";
3421
3422 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3423
3424 if ($feed >= 0) {
3425 $feed_kind = "Feeds";
3426 } else {
3427 $feed_kind = "Labels";
3428 }
3429
3430 if ($limit_query_part) {
3431 $offset_query_part = "OFFSET $offset";
3432 }
3433
3434 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3435 if (!$override_order) {
3436 $order_by = "ttrss_feeds.title, $order_by";
3437 }
3438 }
3439
3440 if ($feed != "0") {
3441 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3442 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3443
3444 } else {
3445 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3446 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3447 }
3448
3449 $query = "SELECT DISTINCT
3450 date_entered,
3451 guid,
3452 ttrss_entries.id,ttrss_entries.title,
3453 updated,
3454 note,
3455 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3456 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3457 $vfeed_query_part
3458 $content_query_part
3459 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3460 author,score
3461 FROM
3462 $from_qpart
3463 WHERE
3464 $feed_check_qpart
3465 ttrss_user_entries.ref_id = ttrss_entries.id AND
3466 ttrss_user_entries.owner_uid = '$owner_uid' AND
3467 $search_query_part
3468 $view_query_part
3469 $query_strategy_part ORDER BY $order_by
3470 $limit_query_part $offset_query_part";
3471
3472 if ($_REQUEST["debug"]) print $query;
3473
3474 $result = db_query($link, $query);
3475
3476 } else {
3477 // browsing by tag
3478
3479 $feed_kind = "Tags";
3480
3481 $result = db_query($link, "SELECT DISTINCT
3482 date_entered,
3483 guid,
3484 note,
3485 ttrss_entries.id as id,title,
3486 updated,
3487 unread,feed_id,orig_feed_id,
3488 marked,link,last_read,
3489 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3490 $vfeed_query_part
3491 $content_query_part
3492 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3493 score
3494 FROM
3495 ttrss_entries,ttrss_user_entries,ttrss_tags
3496 WHERE
3497 ref_id = ttrss_entries.id AND
3498 ttrss_user_entries.owner_uid = '$owner_uid' AND
3499 post_int_id = int_id AND tag_name = '$feed' AND
3500 $view_query_part
3501 $search_query_part
3502 $query_strategy_part ORDER BY $order_by
3503 $limit_query_part");
3504 }
3505
3506 return array($result, $feed_title, $feed_site_url, $last_error);
3507
3508 }
3509
3510 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3511 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3512
3513 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3514 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3515 "margin-bottom : 1em; color : #9a8c59;";
3516
3517 if (!$limit) $limit = 30;
3518
3519 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3520 $date_sort_field = "updated";
3521 } else {
3522 $date_sort_field = "date_entered";
3523 }
3524
3525 $qfh_ret = queryFeedHeadlines($link, $feed,
3526 $limit, $view_mode, $is_cat, $search, $search_mode,
3527 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3528
3529 $result = $qfh_ret[0];
3530 $feed_title = htmlspecialchars($qfh_ret[1]);
3531 $feed_site_url = $qfh_ret[2];
3532 $last_error = $qfh_ret[3];
3533
3534 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3535
3536 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3537 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3538 <rss version=\"2.0\">
3539 <channel>
3540 <title>$feed_title</title>
3541 <link>$feed_site_url</link>
3542 <description>Feed generated by Tiny Tiny RSS</description>";
3543
3544 while ($line = db_fetch_assoc($result)) {
3545 print "<item>";
3546 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3547 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3548
3549 $tags = get_article_tags($link, $line["id"], $owner_uid);
3550
3551 foreach ($tags as $tag) {
3552 print "<category>" . htmlspecialchars($tag) . "</category>";
3553 }
3554
3555 $rfc822_date = date('r', strtotime($line["updated"]));
3556
3557 print "<pubDate>$rfc822_date</pubDate>";
3558
3559 if ($line["author"]) {
3560 print "<author>" . htmlspecialchars($line["author"]) . "</author>";
3561 }
3562
3563 print "<title><![CDATA[" .
3564 htmlspecialchars($line["title"]) . "]]></title>";
3565
3566 print "<description><![CDATA[";
3567
3568 if ($line["note"]) {
3569 print "<div style='$note_style'>";
3570 print $line["note"];
3571 print "</div>";
3572 }
3573
3574 print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3575 print "]]></description>";
3576
3577 $enclosures = get_article_enclosures($link, $line["id"]);
3578
3579 foreach ($enclosures as $e) {
3580 $type = htmlspecialchars($e['content_type']);
3581 $url = htmlspecialchars($e['content_url']);
3582 $length = $e['duration'];
3583 print "<enclosure url=\"$url\" type=\"$type\" length=\"$length\"/>";
3584 }
3585
3586 print "</item>";
3587 }
3588
3589 print "</channel></rss>";
3590
3591 }
3592
3593 function getCategoryTitle($link, $cat_id) {
3594
3595 if ($cat_id == -1) {
3596 return __("Special");
3597 } else if ($cat_id == -2) {
3598 return __("Labels");
3599 } else {
3600
3601 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3602 id = '$cat_id'");
3603
3604 if (db_num_rows($result) == 1) {
3605 return db_fetch_result($result, 0, "title");
3606 } else {
3607 return "Uncategorized";
3608 }
3609 }
3610 }
3611
3612 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3613 global $purifier;
3614
3615 if (!$owner) $owner = $_SESSION["uid"];
3616
3617 $res = trim($str); if (!$res) return '';
3618
3619 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3620 $res = $purifier->purify($res);
3621 }
3622
3623 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3624 $res = preg_replace('/<img[^>]+>/is', '', $res);
3625 }
3626
3627 if (strpos($res, "href=") === false)
3628 $res = rewrite_urls($res);
3629
3630 $charset_hack = '<head>
3631 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3632 </head>';
3633
3634 $res = trim($res); if (!$res) return '';
3635
3636 libxml_use_internal_errors(true);
3637
3638 $doc = new DOMDocument();
3639 $doc->loadHTML($charset_hack . $res);
3640 $xpath = new DOMXPath($doc);
3641
3642 $entries = $xpath->query('(//a[@href]|//img[@src])');
3643 $br_inserted = 0;
3644
3645 foreach ($entries as $entry) {
3646
3647 if ($site_url) {
3648
3649 if ($entry->hasAttribute('href'))
3650 $entry->setAttribute('href',
3651 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3652
3653 if ($entry->hasAttribute('src'))
3654 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3655 $entry->setAttribute('src',
3656 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3657 }
3658
3659 if (strtolower($entry->nodeName) == "a") {
3660 $entry->setAttribute("target", "_blank");
3661 }
3662
3663 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
3664 $br = $doc->createElement("br");
3665
3666 if ($entry->parentNode->nextSibling) {
3667 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3668 $br_inserted = 1;
3669 }
3670
3671 }
3672 }
3673
3674 $node = $doc->getElementsByTagName('body')->item(0);
3675
3676 return $doc->saveXML($node);
3677 }
3678
3679 /**
3680 * Send by mail a digest of last articles.
3681 *
3682 * @param mixed $link The database connection.
3683 * @param integer $limit The maximum number of articles by digest.
3684 * @return boolean Return false if digests are not enabled.
3685 */
3686 function send_headlines_digests($link, $limit = 100) {
3687
3688 if (!DIGEST_ENABLE) return false;
3689
3690 $user_limit = DIGEST_EMAIL_LIMIT;
3691 $days = 1;
3692
3693 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3694
3695 if (DB_TYPE == "pgsql") {
3696 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3697 } else if (DB_TYPE == "mysql") {
3698 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3699 }
3700
3701 $result = db_query($link, "SELECT id,email FROM ttrss_users
3702 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3703
3704 while ($line = db_fetch_assoc($result)) {
3705
3706 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3707 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3708
3709 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3710
3711 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3712 $digest = $tuple[0];
3713 $headlines_count = $tuple[1];
3714 $affected_ids = $tuple[2];
3715 $digest_text = $tuple[3];
3716
3717 if ($headlines_count > 0) {
3718
3719 $mail = new PHPMailer();
3720
3721 $mail->PluginDir = "lib/phpmailer/";
3722 $mail->SetLanguage("en", "lib/phpmailer/language/");
3723
3724 $mail->CharSet = "UTF-8";
3725
3726 $mail->From = DIGEST_FROM_ADDRESS;
3727 $mail->FromName = DIGEST_FROM_NAME;
3728 $mail->AddAddress($line["email"], $line["login"]);
3729
3730 if (DIGEST_SMTP_HOST) {
3731 $mail->Host = DIGEST_SMTP_HOST;
3732 $mail->Mailer = "smtp";
3733 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
3734 $mail->Username = DIGEST_SMTP_LOGIN;
3735 $mail->Password = DIGEST_SMTP_PASSWORD;
3736 }
3737
3738 $mail->IsHTML(true);
3739 $mail->Subject = DIGEST_SUBJECT;
3740 $mail->Body = $digest;
3741 $mail->AltBody = $digest_text;
3742
3743 $rc = $mail->Send();
3744
3745 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3746
3747 print "RC=$rc\n";
3748
3749 if ($rc && $do_catchup) {
3750 print "Marking affected articles as read...\n";
3751 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3752 }
3753 } else {
3754 print "No headlines\n";
3755 }
3756
3757 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3758 WHERE id = " . $line["id"]);
3759 }
3760 }
3761
3762 print "All done.\n";
3763
3764 }
3765
3766 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3767
3768 require_once "lib/MiniTemplator.class.php";
3769
3770 $tpl = new MiniTemplator;
3771 $tpl_t = new MiniTemplator;
3772
3773 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3774 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3775
3776 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3777 $tpl->setVariable('CUR_TIME', date('G:i'));
3778
3779 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3780 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3781
3782 $affected_ids = array();
3783
3784 if (DB_TYPE == "pgsql") {
3785 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3786 } else if (DB_TYPE == "mysql") {
3787 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3788 }
3789
3790 $result = db_query($link, "SELECT ttrss_entries.title,
3791 ttrss_feeds.title AS feed_title,
3792 date_updated,
3793 ttrss_user_entries.ref_id,
3794 link,
3795 SUBSTRING(content, 1, 120) AS excerpt,
3796 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
3797 FROM
3798 ttrss_user_entries,ttrss_entries,ttrss_feeds
3799 WHERE
3800 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3801 AND include_in_digest = true
3802 AND $interval_query
3803 AND ttrss_user_entries.owner_uid = $user_id
3804 AND unread = true
3805 ORDER BY ttrss_feeds.title, date_updated DESC
3806 LIMIT $limit");
3807
3808 $cur_feed_title = "";
3809
3810 $headlines_count = db_num_rows($result);
3811
3812 $headlines = array();
3813
3814 while ($line = db_fetch_assoc($result)) {
3815 array_push($headlines, $line);
3816 }
3817
3818 for ($i = 0; $i < sizeof($headlines); $i++) {
3819
3820 $line = $headlines[$i];
3821
3822 array_push($affected_ids, $line["ref_id"]);
3823
3824 $updated = make_local_datetime($link, $line['last_updated'], false,
3825 $user_id);
3826
3827 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3828 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3829 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3830 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3831 $tpl->setVariable('ARTICLE_EXCERPT',
3832 truncate_string(strip_tags($line["excerpt"]), 100));
3833
3834 $tpl->addBlock('article');
3835
3836 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3837 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3838 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3839 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3840 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3841 // truncate_string(strip_tags($line["excerpt"]), 100));
3842
3843 $tpl_t->addBlock('article');
3844
3845 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3846 $tpl->addBlock('feed');
3847 $tpl_t->addBlock('feed');
3848 }
3849
3850 }
3851
3852 $tpl->addBlock('digest');
3853 $tpl->generateOutputToString($tmp);
3854
3855 $tpl_t->addBlock('digest');
3856 $tpl_t->generateOutputToString($tmp_t);
3857
3858 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3859 }
3860
3861 function check_for_update($link) {
3862 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
3863 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
3864
3865 $version_data = @fetch_file_contents($version_url);
3866
3867 if ($version_data) {
3868 $version_data = json_decode($version_data, true);
3869 if ($version_data && $version_data['version']) {
3870
3871 if (version_compare(VERSION, $version_data['version']) == -1) {
3872 return $version_data;
3873 }
3874 }
3875 }
3876 }
3877 return false;
3878 }
3879
3880 function markArticlesById($link, $ids, $cmode) {
3881
3882 $tmp_ids = array();
3883
3884 foreach ($ids as $id) {
3885 array_push($tmp_ids, "ref_id = '$id'");
3886 }
3887
3888 $ids_qpart = join(" OR ", $tmp_ids);
3889
3890 if ($cmode == 0) {
3891 db_query($link, "UPDATE ttrss_user_entries SET
3892 marked = false,last_read = NOW()
3893 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3894 } else if ($cmode == 1) {
3895 db_query($link, "UPDATE ttrss_user_entries SET
3896 marked = true
3897 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3898 } else {
3899 db_query($link, "UPDATE ttrss_user_entries SET
3900 marked = NOT marked,last_read = NOW()
3901 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3902 }
3903 }
3904
3905 function publishArticlesById($link, $ids, $cmode) {
3906
3907 $tmp_ids = array();
3908
3909 foreach ($ids as $id) {
3910 array_push($tmp_ids, "ref_id = '$id'");
3911 }
3912
3913 $ids_qpart = join(" OR ", $tmp_ids);
3914
3915 if ($cmode == 0) {
3916 db_query($link, "UPDATE ttrss_user_entries SET
3917 published = false,last_read = NOW()
3918 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3919 } else if ($cmode == 1) {
3920 db_query($link, "UPDATE ttrss_user_entries SET
3921 published = true
3922 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3923 } else {
3924 db_query($link, "UPDATE ttrss_user_entries SET
3925 published = NOT published,last_read = NOW()
3926 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3927 }
3928 }
3929
3930 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3931
3932 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3933 if (count($ids) == 0) return;
3934
3935 $tmp_ids = array();
3936
3937 foreach ($ids as $id) {
3938 array_push($tmp_ids, "ref_id = '$id'");
3939 }
3940
3941 $ids_qpart = join(" OR ", $tmp_ids);
3942
3943 if ($cmode == 0) {
3944 db_query($link, "UPDATE ttrss_user_entries SET
3945 unread = false,last_read = NOW()
3946 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3947 } else if ($cmode == 1) {
3948 db_query($link, "UPDATE ttrss_user_entries SET
3949 unread = true
3950 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3951 } else {
3952 db_query($link, "UPDATE ttrss_user_entries SET
3953 unread = NOT unread,last_read = NOW()
3954 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3955 }
3956
3957 /* update ccache */
3958
3959 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3960 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3961
3962 while ($line = db_fetch_assoc($result)) {
3963 ccache_update($link, $line["feed_id"], $owner_uid);
3964 }
3965 }
3966
3967 function catchupArticleById($link, $id, $cmode) {
3968
3969 if ($cmode == 0) {
3970 db_query($link, "UPDATE ttrss_user_entries SET
3971 unread = false,last_read = NOW()
3972 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3973 } else if ($cmode == 1) {
3974 db_query($link, "UPDATE ttrss_user_entries SET
3975 unread = true
3976 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3977 } else {
3978 db_query($link, "UPDATE ttrss_user_entries SET
3979 unread = NOT unread,last_read = NOW()
3980 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3981 }
3982
3983 $feed_id = getArticleFeed($link, $id);
3984 ccache_update($link, $feed_id, $_SESSION["uid"]);
3985 }
3986
3987 function make_guid_from_title($title) {
3988 return preg_replace("/[ \"\',.:;]/", "-",
3989 mb_strtolower(strip_tags($title), 'utf-8'));
3990 }
3991
3992 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
3993 $feed_id, $is_cat, $search, $match_on,
3994 $search_mode, $view_mode, $error) {
3995
3996 $page_prev_link = "viewFeedGoPage(-1)";
3997 $page_next_link = "viewFeedGoPage(1)";
3998 $page_first_link = "viewFeedGoPage(0)";
3999
4000 $catchup_page_link = "catchupPage()";
4001 $catchup_feed_link = "catchupCurrentFeed()";
4002 $catchup_sel_link = "catchupSelection()";
4003
4004 $archive_sel_link = "archiveSelection()";
4005 $delete_sel_link = "deleteSelection()";
4006
4007 $sel_all_link = "selectArticles('all')";
4008 $sel_unread_link = "selectArticles('unread')";
4009 $sel_none_link = "selectArticles('none')";
4010 $sel_inv_link = "selectArticles('invert')";
4011
4012 $tog_unread_link = "selectionToggleUnread()";
4013 $tog_marked_link = "selectionToggleMarked()";
4014 $tog_published_link = "selectionTogglePublished()";
4015
4016 $reply = "<div id=\"subtoolbar_main\">";
4017
4018 $reply .= __('Select:')."
4019 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4020 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4021 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4022 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4023
4024 $reply .= " ";
4025
4026 $reply .= "<select dojoType=\"dijit.form.Select\"
4027 onchange=\"headlineActionsChange(this)\">";
4028 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4029
4030 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4031
4032 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4033 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4034 <option value=\"$tog_published_link\">".__('Published')."</option>";
4035
4036 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4037
4038 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4039
4040 if ($feed_id != "0") {
4041 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4042 } else {
4043 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4044 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4045
4046 }
4047
4048 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4049 "</option>";
4050
4051 $rss_link = htmlspecialchars(get_self_url_prefix() .
4052 "/backend.php?op=rss&id=$feed_id&is_cat=$is_cat&view_mode=$view_mode$search_q");
4053
4054 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4055
4056 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4057
4058 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4059
4060 $reply .= "</select>";
4061
4062 $reply .= "</div>";
4063
4064 $reply .= "<div id=\"subtoolbar_ftitle\">";
4065
4066 if ($feed_site_url) {
4067 $target = "target=\"_blank\"";
4068 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4069 truncate_string($feed_title,30)."</a>";
4070
4071 if ($error) {
4072 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4073 }
4074
4075 } else {
4076 if ($feed_id < -10) {
4077 $label_id = -11-$feed_id;
4078
4079 $result = db_query($link, "SELECT fg_color, bg_color
4080 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4081 $_SESSION["uid"]);
4082
4083 if (db_num_rows($result) != 0) {
4084 $fg_color = db_fetch_result($result, 0, "fg_color");
4085 $bg_color = db_fetch_result($result, 0, "bg_color");
4086
4087 $reply .= "<span style='background : $bg_color; color : $fg_color'>";
4088 $reply .= $feed_title;
4089 $reply .= "</span>";
4090 } else {
4091 $reply .= $feed_title;
4092 }
4093
4094 } else {
4095 $reply .= $feed_title;
4096 }
4097 }
4098
4099 if ($search) {
4100 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4101 } else {
4102 $search_q = "";
4103 }
4104
4105 // Adaptive doesn't really make any sense for generated feeds
4106 // All Articles is the default, so no need to insert it either
4107 if ($view_mode == "adaptive" || $view_mode == "all_articles")
4108 $view_mode = "";
4109 else
4110 $view_mode = "&view-mode=$view_mode";
4111
4112 $reply .= "
4113 <a href=\"#\"
4114 title=\"".__("View as RSS feed")."\"
4115 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4116 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4117
4118 $reply .= "</div>";
4119
4120 return $reply;
4121 }
4122
4123 function outputFeedList($link, $special = true) {
4124
4125 $feedlist = array();
4126
4127 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4128
4129 $feedlist['identifier'] = 'id';
4130 $feedlist['label'] = 'name';
4131 $feedlist['items'] = array();
4132
4133 $owner_uid = $_SESSION["uid"];
4134
4135 /* virtual feeds */
4136
4137 if ($special) {
4138
4139 if ($enable_cats) {
4140 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4141 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4142 } else {
4143 $cat['items'] = array();
4144 }
4145
4146 foreach (array(-4, -3, -1, -2, 0) as $i) {
4147 array_push($cat['items'], feedlist_init_feed($link, $i));
4148 }
4149
4150 if ($enable_cats) {
4151 array_push($feedlist['items'], $cat);
4152 } else {
4153 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4154 }
4155
4156 $result = db_query($link, "SELECT * FROM
4157 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4158
4159 if (db_num_rows($result) > 0) {
4160
4161 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4162 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4163 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4164 } else {
4165 $cat['items'] = array();
4166 }
4167
4168 while ($line = db_fetch_assoc($result)) {
4169
4170 $label_id = -$line['id'] - 11;
4171 $count = getFeedUnread($link, $label_id);
4172
4173 $feed = feedlist_init_feed($link, $label_id, false, $count);
4174
4175 $feed['fg_color'] = $line['fg_color'];
4176 $feed['bg_color'] = $line['bg_color'];
4177
4178 array_push($cat['items'], $feed);
4179 }
4180
4181 if ($enable_cats) {
4182 array_push($feedlist['items'], $cat);
4183 } else {
4184 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4185 }
4186 }
4187 }
4188
4189 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4190 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4191 $order_by_qpart = "order_id,category,unread DESC,title";
4192 } else {
4193 $order_by_qpart = "order_id,category,title";
4194 }
4195 } else {
4196 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4197 $order_by_qpart = "unread DESC,title";
4198 } else {
4199 $order_by_qpart = "title";
4200 }
4201 } */
4202
4203 /* real feeds */
4204
4205 if ($enable_cats)
4206 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4207 ttrss_feeds.order_id,title";
4208 else
4209 $order_by_qpart = "title";
4210
4211 $age_qpart = getMaxAgeSubquery();
4212
4213 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4214 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4215 cat_id,last_error,
4216 ttrss_feed_categories.title AS category,
4217 ttrss_feed_categories.collapsed,
4218 value AS unread
4219 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4220 ON (ttrss_feed_categories.id = cat_id)
4221 LEFT JOIN ttrss_counters_cache
4222 ON
4223 (ttrss_feeds.id = feed_id)
4224 WHERE
4225 ttrss_feeds.owner_uid = '$owner_uid'
4226 ORDER BY $order_by_qpart";
4227
4228 $result = db_query($link, $query);
4229
4230 $actid = $_REQUEST["actid"];
4231
4232 if (db_num_rows($result) > 0) {
4233
4234 $category = "";
4235
4236 if (!$enable_cats)
4237 $cat['items'] = array();
4238 else
4239 $cat = false;
4240
4241 while ($line = db_fetch_assoc($result)) {
4242
4243 $feed = htmlspecialchars(trim($line["title"]));
4244
4245 if (!$feed) $feed = "[Untitled]";
4246
4247 $feed_id = $line["id"];
4248 $unread = $line["unread"];
4249
4250 $cat_id = $line["cat_id"];
4251 $tmp_category = $line["category"];
4252 if (!$tmp_category) $tmp_category = __("Uncategorized");
4253
4254 if ($category != $tmp_category && $enable_cats) {
4255
4256 $category = $tmp_category;
4257
4258 $collapsed = sql_bool_to_bool($line["collapsed"]);
4259
4260 // workaround for NULL category
4261 if ($category == __("Uncategorized")) {
4262 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4263 }
4264
4265 if ($cat) array_push($feedlist['items'], $cat);
4266
4267 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4268 }
4269
4270 $updated = make_local_datetime($link, $line["updated_noms"], false);
4271
4272 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4273 $feed, $unread, $line['last_error'], $updated));
4274 }
4275
4276 if ($enable_cats) {
4277 array_push($feedlist['items'], $cat);
4278 } else {
4279 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4280 }
4281
4282 }
4283
4284 return $feedlist;
4285 }
4286
4287 function get_article_tags($link, $id, $owner_uid = 0) {
4288
4289 global $memcache;
4290
4291 $a_id = db_escape_string($id);
4292
4293 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4294
4295 $query = "SELECT DISTINCT tag_name,
4296 owner_uid as owner FROM
4297 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4298 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4299
4300 $obj_id = md5("TAGS:$owner_uid:$id");
4301 $tags = array();
4302
4303 if ($memcache && $obj = $memcache->get($obj_id)) {
4304 $tags = $obj;
4305 } else {
4306 /* check cache first */
4307
4308 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4309 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4310
4311 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4312
4313 if ($tag_cache) {
4314 $tags = explode(",", $tag_cache);
4315 } else {
4316
4317 /* do it the hard way */
4318
4319 $tmp_result = db_query($link, $query);
4320
4321 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4322 array_push($tags, $tmp_line["tag_name"]);
4323 }
4324
4325 /* update the cache */
4326
4327 $tags_str = db_escape_string(join(",", $tags));
4328
4329 db_query($link, "UPDATE ttrss_user_entries
4330 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4331 AND owner_uid = " . $_SESSION["uid"]);
4332 }
4333
4334 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4335 }
4336
4337 return $tags;
4338 }
4339
4340 function trim_value(&$value) {
4341 $value = trim($value);
4342 }
4343
4344 function trim_array($array) {
4345 $tmp = $array;
4346 array_walk($tmp, 'trim_value');
4347 return $tmp;
4348 }
4349
4350 function tag_is_valid($tag) {
4351 if ($tag == '') return false;
4352 if (preg_match("/^[0-9]*$/", $tag)) return false;
4353 if (mb_strlen($tag) > 250) return false;
4354
4355 if (function_exists('iconv')) {
4356 $tag = iconv("utf-8", "utf-8", $tag);
4357 }
4358
4359 if (!$tag) return false;
4360
4361 return true;
4362 }
4363
4364 function render_login_form($link, $mobile = 0) {
4365 switch ($mobile) {
4366 case 0:
4367 require_once "login_form.php";
4368 break;
4369 case 1:
4370 require_once "mobile/login_form.php";
4371 break;
4372 case 2:
4373 require_once "mobile/classic/login_form.php";
4374 }
4375 }
4376
4377 // from http://developer.apple.com/internet/safari/faq.html
4378 function no_cache_incantation() {
4379 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4380 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4381 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4382 header("Cache-Control: post-check=0, pre-check=0", false);
4383 header("Pragma: no-cache"); // HTTP/1.0
4384 }
4385
4386 function format_warning($msg, $id = "") {
4387 global $link;
4388 return "<div class=\"warning\" id=\"$id\">
4389 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4390 }
4391
4392 function format_notice($msg, $id = "") {
4393 global $link;
4394 return "<div class=\"notice\" id=\"$id\">
4395 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4396 }
4397
4398 function format_error($msg, $id = "") {
4399 global $link;
4400 return "<div class=\"error\" id=\"$id\">
4401 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4402 }
4403
4404 function print_notice($msg) {
4405 return print format_notice($msg);
4406 }
4407
4408 function print_warning($msg) {
4409 return print format_warning($msg);
4410 }
4411
4412 function print_error($msg) {
4413 return print format_error($msg);
4414 }
4415
4416
4417 function T_sprintf() {
4418 $args = func_get_args();
4419 return vsprintf(__(array_shift($args)), $args);
4420 }
4421
4422 function format_inline_player($link, $url, $ctype) {
4423
4424 $entry = "";
4425
4426 if (strpos($ctype, "audio/") === 0) {
4427
4428 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4429 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4430 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4431
4432 $id = 'AUDIO-' . uniqid();
4433
4434 $entry .= "<audio id=\"$id\"\">
4435 <source src=\"$url\"></source>
4436 </audio>";
4437
4438 $entry .= "<span onclick=\"player(this)\"
4439 title=\"".__("Click to play")."\" status=\"0\"
4440 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4441
4442 } else {
4443
4444 $entry .= "<object type=\"application/x-shockwave-flash\"
4445 data=\"extras/button/musicplayer.swf?song_url=$url\"
4446 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4447 <param name=\"movie\"
4448 value=\"extras/button/musicplayer.swf?song_url=$url\" />
4449 </object>";
4450 }
4451 }
4452
4453 $filename = substr($url, strrpos($url, "/")+1);
4454
4455 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4456 $filename . " (" . $ctype . ")" . "</a>";
4457
4458 return $entry;
4459 }
4460
4461 function format_article($link, $id, $feed_id, $mark_as_read = true,
4462 $zoom_mode = false) {
4463
4464 $rv = array();
4465
4466 $rv['id'] = $id;
4467
4468 /* we can figure out feed_id from article id anyway, why do we
4469 * pass feed_id here? let's ignore the argument :( */
4470
4471 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4472 WHERE ref_id = '$id'");
4473
4474 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4475
4476 $rv['feed_id'] = $feed_id;
4477
4478 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4479
4480 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4481 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4482
4483 if (db_num_rows($result) == 1) {
4484 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4485 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4486 } else {
4487 $rtl_content = false;
4488 $always_display_enclosures = false;
4489 }
4490
4491 if ($rtl_content) {
4492 $rtl_tag = "dir=\"RTL\"";
4493 $rtl_class = "RTL";
4494 } else {
4495 $rtl_tag = "";
4496 $rtl_class = "";
4497 }
4498
4499 if ($mark_as_read) {
4500 $result = db_query($link, "UPDATE ttrss_user_entries
4501 SET unread = false,last_read = NOW()
4502 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4503
4504 ccache_update($link, $feed_id, $_SESSION["uid"]);
4505 }
4506
4507 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4508 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4509 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4510 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4511 num_comments,
4512 author,
4513 orig_feed_id,
4514 note
4515 FROM ttrss_entries,ttrss_user_entries
4516 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4517
4518 if ($result) {
4519
4520 $line = db_fetch_assoc($result);
4521
4522 if ($line["icon_url"]) {
4523 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4524 } else {
4525 $feed_icon = "&nbsp;";
4526 }
4527
4528 $feed_site_url = $line['site_url'];
4529
4530 $num_comments = $line["num_comments"];
4531 $entry_comments = "";
4532
4533 if ($num_comments > 0) {
4534 if ($line["comments"]) {
4535 $comments_url = $line["comments"];
4536 } else {
4537 $comments_url = $line["link"];
4538 }
4539 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4540 } else {
4541 if ($line["comments"] && $line["link"] != $line["comments"]) {
4542 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4543 }
4544 }
4545
4546 if ($zoom_mode) {
4547 header("Content-Type: text/html");
4548 $rv['content'] .= "<html><head>
4549 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4550 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4551 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4552 </head><body>";
4553 }
4554
4555 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4556 truncate_string(strip_tags($line['title']), 15) . "</div>";
4557
4558 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4559
4560 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4561 class=\"postHeader\" id=\"POSTHDR-$id\">";
4562
4563 $entry_author = $line["author"];
4564
4565 if ($entry_author) {
4566 $entry_author = __(" - ") . $entry_author;
4567 }
4568
4569 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4570 false, true);
4571
4572 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4573
4574 if ($line["link"]) {
4575 $rv['content'] .= "<div clear='both'><a target='_blank'
4576 title=\"".htmlspecialchars($line['title'])."\"
4577 href=\"" .
4578 $line["link"] . "\">" .
4579 truncate_string($line["title"], 100) .
4580 "<span class='author'>$entry_author</span></a></div>";
4581 } else {
4582 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4583 }
4584
4585 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4586
4587 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4588
4589 $rv['content'] .= "<div style='float : right'>
4590 <img src='".theme_image($link, 'images/tag.png')."'
4591 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
4592
4593 if (!$zoom_mode) {
4594 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4595 <a title=\"".__('Edit tags for this article')."\"
4596 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4597
4598 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4599 class='tagsPic' style=\"cursor : pointer\"
4600 onclick=\"postOpenInNewTab(event, $id)\"
4601 alt='Zoom' title='".__('Open article in new tab')."'>";
4602
4603 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4604
4605 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4606 class='tagsPic' style=\"cursor : pointer\"
4607 onclick=\"editArticleNote($id)\"
4608 alt='PubNote' title='".__('Edit article note')."'>";
4609
4610 if (DIGEST_ENABLE) {
4611 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4612 class='tagsPic' style=\"cursor : pointer\"
4613 onclick=\"emailArticle($id)\"
4614 alt='Zoom' title='".__('Forward by email')."'>";
4615 }
4616
4617 if (ENABLE_TWEET_BUTTON) {
4618 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4619 class='tagsPic' style=\"cursor : pointer\"
4620 onclick=\"tweetArticle($id)\"
4621 alt='Zoom' title='".__('Share on Twitter')."'>";
4622 }
4623
4624 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4625 class='tagsPic' style=\"cursor : pointer\"
4626 onclick=\"closeArticlePanel($id)\"
4627 alt='Zoom' title='".__('Close this panel')."'>";
4628
4629 } else {
4630 $tags_str = strip_tags($tags_str);
4631 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4632 }
4633 $rv['content'] .= "</div>";
4634 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4635
4636 if ($line["orig_feed_id"]) {
4637
4638 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4639 WHERE id = ".$line["orig_feed_id"]);
4640
4641 if (db_num_rows($tmp_result) != 0) {
4642
4643 $rv['content'] .= "<div clear='both'>";
4644 $rv['content'] .= __("Originally from:");
4645
4646 $rv['content'] .= "&nbsp;";
4647
4648 $tmp_line = db_fetch_assoc($tmp_result);
4649
4650 $rv['content'] .= "<a target='_blank'
4651 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4652 $tmp_line['title'] . "</a>";
4653
4654 $rv['content'] .= "&nbsp;";
4655
4656 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4657 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4658
4659 $rv['content'] .= "</div>";
4660 }
4661 }
4662
4663 $rv['content'] .= "</div>";
4664
4665 $rv['content'] .= "<div class=\"postIcon\">" .
4666 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4667 href=\"".htmlspecialchars($feed_site_url)."\">".
4668 $feed_icon . "</a></div>";
4669
4670 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4671 if ($line['note']) {
4672 $rv['content'] .= format_article_note($id, $line['note']);
4673 }
4674 $rv['content'] .= "</div>";
4675
4676 $rv['content'] .= "<div class=\"postContent\">";
4677
4678 $article_content = sanitize_rss($link, $line["content"], false, false,
4679 $feed_site_url);
4680
4681 $rv['content'] .= $article_content;
4682
4683 $rv['content'] .= format_article_enclosures($link, $id,
4684 $always_display_enclosures, $article_content);
4685
4686 $rv['content'] .= "</div>";
4687
4688 $rv['content'] .= "</div>";
4689
4690 }
4691
4692 if ($zoom_mode) {
4693 $rv['content'] .= "
4694 <div style=\"text-align : center\">
4695 <button onclick=\"return window.close()\">".
4696 __("Close this window")."</button></div>";
4697 $rv['content'] .= "</body></html>";
4698 }
4699
4700 return $rv;
4701
4702 }
4703
4704 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4705 $next_unread_feed, $offset, $vgr_last_feed = false,
4706 $override_order = false) {
4707
4708 $disable_cache = false;
4709
4710 $reply = array();
4711
4712 $timing_info = getmicrotime();
4713
4714 $topmost_article_ids = array();
4715
4716 if (!$offset) {
4717 $offset = 0;
4718 }
4719
4720 if ($subop == "undefined") $subop = "";
4721
4722 $subop_split = split(":", $subop);
4723
4724 if ($subop == "CatchupSelected") {
4725 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4726 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4727
4728 catchupArticlesById($link, $ids, $cmode);
4729 }
4730
4731 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4732 update_rss_feed($link, $feed, true);
4733 }
4734
4735 if ($subop == "MarkAllRead") {
4736 catchup_feed($link, $feed, $cat_view);
4737
4738 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4739 if ($next_unread_feed) {
4740 $feed = $next_unread_feed;
4741 }
4742 }
4743 }
4744
4745 if ($subop_split[0] == "MarkAllReadGR") {
4746 catchup_feed($link, $subop_split[1], false);
4747 }
4748
4749 // FIXME: might break tag display?
4750
4751 if ($feed > 0 && !$cat_view) {
4752 $result = db_query($link,
4753 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4754
4755 if (db_num_rows($result) == 0) {
4756 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4757 }
4758 }
4759
4760 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4761
4762 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4763 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4764
4765 if (db_num_rows($result) == 1) {
4766 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4767 } else {
4768 $rtl_content = false;
4769 }
4770
4771 if ($rtl_content) {
4772 $rtl_tag = "dir=\"RTL\"";
4773 } else {
4774 $rtl_tag = "";
4775 }
4776 } else {
4777 $rtl_tag = "";
4778 $rtl_content = false;
4779 }
4780
4781 /// START /////////////////////////////////////////////////////////////////////////////////
4782
4783 @$search = db_escape_string($_REQUEST["query"]);
4784
4785 if ($search) {
4786 $disable_cache = true;
4787 }
4788
4789 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4790 @$match_on = db_escape_string($_REQUEST["match_on"]);
4791
4792 if (!$match_on) {
4793 $match_on = "both";
4794 }
4795
4796 $real_offset = $offset * $limit;
4797
4798 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4799
4800 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4801 $search, $search_mode, $match_on, $override_order, $real_offset);
4802
4803 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4804
4805 $result = $qfh_ret[0];
4806 $feed_title = $qfh_ret[1];
4807 $feed_site_url = $qfh_ret[2];
4808 $last_error = $qfh_ret[3];
4809
4810 $vgroup_last_feed = $vgr_last_feed;
4811
4812 /// STOP //////////////////////////////////////////////////////////////////////////////////
4813
4814 if (!$offset) {
4815
4816 if (db_num_rows($result) > 0) {
4817 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4818 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
4819 $last_error);
4820 }
4821 }
4822
4823 $headlines_count = db_num_rows($result);
4824
4825 if (db_num_rows($result) > 0) {
4826
4827 $lnum = $limit*$offset;
4828
4829 $num_unread = 0;
4830 $cur_feed_title = '';
4831
4832 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4833
4834 while ($line = db_fetch_assoc($result)) {
4835
4836 $class = ($lnum % 2) ? "even" : "odd";
4837
4838 $id = $line["id"];
4839 $feed_id = $line["feed_id"];
4840
4841 $labels = get_article_labels($link, $id);
4842
4843 $labels_str = "<span id=\"HLLCTR-$id\">";
4844 $labels_str .= format_article_labels($labels, $id);
4845 $labels_str .= "</span>";
4846
4847 if (count($topmost_article_ids) < 3) {
4848 array_push($topmost_article_ids, $id);
4849 }
4850
4851 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4852
4853 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4854 theme_image($link, 'images/updated.png')."\"
4855 alt=\"Updated\">";
4856 } else {
4857 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4858 alt=\"Updated\">";
4859 }
4860
4861 if (sql_bool_to_bool($line["unread"]) &&
4862 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4863
4864 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4865 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
4866 }
4867
4868 if ($line["unread"] == "t" || $line["unread"] == "1") {
4869 $class .= " Unread";
4870 ++$num_unread;
4871 $is_unread = true;
4872 } else {
4873 $is_unread = false;
4874 }
4875
4876 if ($line["marked"] == "t" || $line["marked"] == "1") {
4877 $marked_pic = "<img id=\"FMPIC-$id\"
4878 src=\"".theme_image($link, 'images/mark_set.png')."\"
4879 class=\"markedPic\" alt=\"Unstar article\"
4880 onclick='javascript:tMark($id)'>";
4881 } else {
4882 $marked_pic = "<img id=\"FMPIC-$id\"
4883 src=\"".theme_image($link, 'images/mark_unset.png')."\"
4884 class=\"markedPic\" alt=\"Star article\"
4885 onclick='javascript:tMark($id)'>";
4886 }
4887
4888 if ($line["published"] == "t" || $line["published"] == "1") {
4889 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4890 'images/pub_set.png')."\"
4891 class=\"markedPic\"
4892 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4893 } else {
4894 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4895 'images/pub_unset.png')."\"
4896 class=\"markedPic\"
4897 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4898 }
4899
4900 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4901 # $line["title"] . "</a>";
4902
4903 # $content_link = "<a
4904 # href=\"" . htmlspecialchars($line["link"]) . "\"
4905 # onclick=\"view($id,$feed_id);\">" .
4906 # $line["title"] . "</a>";
4907
4908 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4909 # $line["title"] . "</a>";
4910
4911 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
4912
4913 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4914 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4915 100);
4916 }
4917
4918 $score = $line["score"];
4919
4920 $score_pic = theme_image($link,
4921 "images/" . get_score_pic($score));
4922
4923 /* $score_title = __("(Click to change)");
4924 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4925 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4926
4927 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
4928 title=\"$score\">";
4929
4930 if ($score > 500) {
4931 $hlc_suffix = "H";
4932 } else if ($score < -100) {
4933 $hlc_suffix = "L";
4934 } else {
4935 $hlc_suffix = "";
4936 }
4937
4938 $entry_author = $line["author"];
4939
4940 if ($entry_author) {
4941 $entry_author = " - $entry_author";
4942 }
4943
4944 $has_feed_icon = feed_has_icon($feed_id);
4945
4946 if ($has_feed_icon) {
4947 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
4948 } else {
4949 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
4950 }
4951
4952 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4953
4954 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4955 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4956
4957 $cur_feed_title = $line["feed_title"];
4958 $vgroup_last_feed = $feed_id;
4959
4960 $cur_feed_title = htmlspecialchars($cur_feed_title);
4961
4962 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
4963
4964 $reply['content'] .= "<div class='cdmFeedTitle'>".
4965 "<div style=\"float : right\">$feed_icon_img</div>".
4966 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
4967 $line["feed_title"]."</a> $vf_catchup_link</div>";
4968
4969 }
4970 }
4971
4972 $mouseover_attrs = "onmouseover='postMouseIn($id)'
4973 onmouseout='postMouseOut($id)'";
4974
4975 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
4976
4977 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
4978
4979 $reply['content'] .= "<div class='hlLeft'>";
4980
4981 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
4982 id=\"RCHK-$id\">";
4983
4984 $reply['content'] .= "$marked_pic";
4985 $reply['content'] .= "$published_pic";
4986
4987 $reply['content'] .= "</div>";
4988
4989 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
4990 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
4991 $reply['content'] .= "<a id=\"RTITLE-$id\"
4992 href=\"" . htmlspecialchars($line["link"]) . "\"
4993 onclick=\"return false;\">" .
4994 $line["title"];
4995
4996 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4997 if ($content_preview) {
4998 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
4999 }
5000 }
5001
5002 $reply['content'] .= "</a></span>";
5003
5004 $reply['content'] .= $labels_str;
5005
5006 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5007 if (@$line["feed_title"]) {
5008 print "<span class=\"hlFeed\">
5009 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5010 $line["feed_title"]."</a>)
5011 </span>";
5012 }
5013 } */
5014
5015 $reply['content'] .= "</div>";
5016
5017 $reply['content'] .= "<div class=\"hlRight\">";
5018 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5019 $reply['content'] .= $score_pic;
5020
5021 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5022
5023 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5024 title=\"".htmlspecialchars($line['feed_title'])."\">
5025 $feed_icon_img<span>";
5026 }
5027
5028 $reply['content'] .= "</div>";
5029 $reply['content'] .= "</div>";
5030
5031 } else {
5032
5033 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5034 if ($feed_id != $vgroup_last_feed) {
5035
5036 $cur_feed_title = $line["feed_title"];
5037 $vgroup_last_feed = $feed_id;
5038
5039 $cur_feed_title = htmlspecialchars($cur_feed_title);
5040
5041 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5042
5043 $has_feed_icon = feed_has_icon($feed_id);
5044
5045 if ($has_feed_icon) {
5046 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5047 } else {
5048 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5049 }
5050
5051 $reply['content'] .= "<div class='cdmFeedTitle'>".
5052 "<div style=\"float : right\">$feed_icon_img</div>".
5053 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5054 $line["feed_title"]."</a> $vf_catchup_link</div>";
5055 }
5056 }
5057
5058 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5059
5060 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5061 onmouseout='postMouseOut($id)'";
5062
5063 $reply['content'] .= "<div class=\"$class\"
5064 id=\"RROW-$id\" $mouseover_attrs'>";
5065
5066 $reply['content'] .= "<div class=\"cdmHeader\">";
5067
5068 $reply['content'] .= "<div style='float : right'>";
5069 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5070 $reply['content'] .= "$score_pic";
5071
5072 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5073 $reply['content'] .= "<span style=\"cursor : pointer\"
5074 title=\"".htmlspecialchars($line["feed_title"])."\"
5075 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5076 }
5077 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5078
5079 $reply['content'] .= "</div>";
5080
5081 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5082 'RROW-$id')\" id=\"RCHK-$id\"/>";
5083
5084 $reply['content'] .= "$marked_pic";
5085 $reply['content'] .= "$published_pic";
5086
5087 $reply['content'] .= "<span id=\"RTITLE-$id\"
5088 onclick=\"return cdmClicked(event, $id);\"
5089 class=\"titleWrap$hlc_suffix\">
5090 <a class=\"title\"
5091 title=\"".htmlspecialchars($line['title'])."\"
5092 target=\"_blank\" href=\"".
5093 htmlspecialchars($line["link"])."\">".
5094 truncate_string($line["title"], 100) .
5095 " $entry_author</a>";
5096
5097 $reply['content'] .= $labels_str;
5098
5099 if (!$expand_cdm)
5100 $content_hidden = "style=\"display : none\"";
5101 else
5102 $excerpt_hidden = "style=\"display : none\"";
5103
5104 $reply['content'] .= "<span $excerpt_hidden
5105 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5106
5107 $reply['content'] .= "</span>";
5108
5109 $reply['content'] .= "</div>";
5110
5111 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5112 onclick=\"return cdmClicked(event, $id);\"
5113 id=\"CICD-$id\">";
5114
5115 $reply['content'] .= "<div class=\"cdmContentInner\">";
5116
5117 if ($line["orig_feed_id"]) {
5118
5119 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5120 WHERE id = ".$line["orig_feed_id"]);
5121
5122 if (db_num_rows($tmp_result) != 0) {
5123
5124 $reply['content'] .= "<div clear='both'>";
5125 $reply['content'] .= __("Originally from:");
5126
5127 $reply['content'] .= "&nbsp;";
5128
5129 $tmp_line = db_fetch_assoc($tmp_result);
5130
5131 $reply['content'] .= "<a target='_blank'
5132 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5133 $tmp_line['title'] . "</a>";
5134
5135 $reply['content'] .= "&nbsp;";
5136
5137 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5138 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5139
5140 $reply['content'] .= "</div>";
5141 }
5142 }
5143
5144 // FIXME: make this less of a hack
5145
5146 $feed_site_url = false;
5147
5148 if ($line["feed_id"]) {
5149 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5150 WHERE id = " . $line["feed_id"]);
5151
5152 if (db_num_rows($tmp_result) == 1) {
5153 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5154 }
5155 }
5156
5157 if ($expand_cdm) {
5158 $article_content = sanitize_rss($link, $line["content_preview"],
5159 false, false, $feed_site_url);
5160
5161 if (!$article_content) $article_content = "&nbsp;";
5162 } else {
5163 $article_content = '';
5164 }
5165
5166 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5167 if ($line['note']) {
5168 $reply['content'] .= format_article_note($id, $line['note']);
5169 }
5170 $reply['content'] .= "</div>";
5171
5172 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5173
5174 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5175 ttrss_feeds WHERE id = ".
5176 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
5177 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5178
5179 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5180 0, "always_display_enclosures"));
5181
5182 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5183 $article_content);
5184
5185 $reply['content'] .= "</div>";
5186
5187 $reply['content'] .= "<div class=\"cdmFooter\">";
5188
5189 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5190
5191 $reply['content'] .= "<img src='".theme_image($link,
5192 'images/tag.png')."' alt='Tags' title='Tags'>
5193 <span id=\"ATSTR-$id\">$tags_str</span>
5194 <a title=\"".__('Edit tags for this article')."\"
5195 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5196
5197 $reply['content'] .= "<div style=\"float : right\">";
5198
5199 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5200 onclick=\"zoomToArticle(event, $id)\"
5201 style=\"cursor : pointer\"
5202 alt='Zoom'
5203 title='".__('Open article in new tab')."'>";
5204
5205 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5206
5207 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5208 style=\"cursor : pointer\" style=\"cursor : pointer\"
5209 onclick=\"editArticleNote($id)\"
5210 alt='PubNote' title='".__('Edit article note')."'>";
5211
5212 if (DIGEST_ENABLE) {
5213 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5214 style=\"cursor : pointer\"
5215 onclick=\"emailArticle($id)\"
5216 alt='Zoom' title='".__('Forward by email')."'>";
5217 }
5218
5219 if (ENABLE_TWEET_BUTTON) {
5220 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5221 class='tagsPic' style=\"cursor : pointer\"
5222 onclick=\"tweetArticle($id)\"
5223 alt='Zoom' title='".__('Share on Twitter')."'>";
5224 }
5225
5226 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5227 style=\"cursor : pointer\" style=\"cursor : pointer\"
5228 onclick=\"dismissArticle($id)\"
5229 alt='Dismiss' title='".__('Dismiss article')."'>";
5230
5231 $reply['content'] .= "</div>";
5232 $reply['content'] .= "</div>";
5233
5234 $reply['content'] .= "</div>";
5235
5236 $reply['content'] .= "</div>";
5237
5238 }
5239
5240 ++$lnum;
5241 }
5242
5243 } else {
5244 $message = "";
5245
5246 switch ($view_mode) {
5247 case "unread":
5248 $message = __("No unread articles found to display.");
5249 break;
5250 case "updated":
5251 $message = __("No updated articles found to display.");
5252 break;
5253 case "marked":
5254 $message = __("No starred articles found to display.");
5255 break;
5256 default:
5257 if ($feed < -10) {
5258 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5259 } else {
5260 $message = __("No articles found to display.");
5261 }
5262 }
5263
5264 if (!$offset && $message) {
5265 $reply['content'] .= "<div class='whiteBox'>$message";
5266
5267 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5268
5269 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5270 WHERE owner_uid = " . $_SESSION['uid']);
5271
5272 $last_updated = db_fetch_result($result, 0, "last_updated");
5273 $last_updated = make_local_datetime($link, $last_updated, false);
5274
5275 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5276
5277 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5278 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5279
5280 $num_errors = db_fetch_result($result, 0, "num_errors");
5281
5282 if ($num_errors > 0) {
5283 $reply['content'] .= "<br/>";
5284 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5285 __('Some feeds have update errors (click for details)')."</a>";
5286 }
5287 $reply['content'] .= "</span></p></div>";
5288 }
5289 }
5290
5291 # if (!$offset) {
5292 # if ($headlines_count > 0) print "</div>";
5293 # print "</div>";
5294 # }
5295
5296 #print "]]></content>";
5297
5298 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5299 $vgroup_last_feed, $reply['content'], $reply['toolbar']);
5300 }
5301
5302 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5303
5304 function printTagCloud($link) {
5305
5306 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5307 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5308 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5309
5310 $result = db_query($link, $query);
5311
5312 $tags = array();
5313
5314 while ($line = db_fetch_assoc($result)) {
5315 $tags[$line["tag_name"]] = $line["count"];
5316 }
5317
5318 ksort($tags);
5319
5320 $max_size = 32; // max font size in pixels
5321 $min_size = 11; // min font size in pixels
5322
5323 // largest and smallest array values
5324 $max_qty = max(array_values($tags));
5325 $min_qty = min(array_values($tags));
5326
5327 // find the range of values
5328 $spread = $max_qty - $min_qty;
5329 if ($spread == 0) { // we don't want to divide by zero
5330 $spread = 1;
5331 }
5332
5333 // set the font-size increment
5334 $step = ($max_size - $min_size) / ($spread);
5335
5336 // loop through the tag array
5337 foreach ($tags as $key => $value) {
5338 // calculate font-size
5339 // find the $value in excess of $min_qty
5340 // multiply by the font-size increment ($size)
5341 // and add the $min_size set above
5342 $size = round($min_size + (($value - $min_qty) * $step));
5343
5344 $key_escaped = str_replace("'", "\\'", $key);
5345
5346 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5347 $size . "px\" title=\"$value articles tagged with " .
5348 $key . '">' . $key . '</a> ';
5349 }
5350 }
5351
5352 function print_checkpoint($n, $s) {
5353 $ts = getmicrotime();
5354 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5355 return $ts;
5356 }
5357
5358 function sanitize_tag($tag) {
5359 $tag = trim($tag);
5360
5361 $tag = mb_strtolower($tag, 'utf-8');
5362
5363 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5364
5365 // $tag = str_replace('"', "", $tag);
5366 // $tag = str_replace("+", " ", $tag);
5367 $tag = str_replace("technorati tag: ", "", $tag);
5368
5369 return $tag;
5370 }
5371
5372 function get_self_url_prefix() {
5373
5374 $url_path = "";
5375
5376 if ($_SERVER['HTTPS'] != "on") {
5377 $url_path = "http://";
5378 } else {
5379 $url_path = "https://";
5380 }
5381
5382 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5383
5384 return $url_path;
5385
5386 }
5387 function opml_publish_url($link){
5388
5389 $url_path = get_self_url_prefix();
5390 $url_path .= "/opml.php?op=publish&key=" .
5391 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5392
5393 return $url_path;
5394 }
5395
5396 /**
5397 * Purge a feed contents, marked articles excepted.
5398 *
5399 * @param mixed $link The database connection.
5400 * @param integer $id The id of the feed to purge.
5401 * @return void
5402 */
5403 function clear_feed_articles($link, $id) {
5404
5405 if ($id != 0) {
5406 $result = db_query($link, "DELETE FROM ttrss_user_entries
5407 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5408 } else {
5409 $result = db_query($link, "DELETE FROM ttrss_user_entries
5410 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5411 }
5412
5413 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5414 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5415
5416 ccache_update($link, $id, $_SESSION['uid']);
5417 } // function clear_feed_articles
5418
5419 /**
5420 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5421 *
5422 * @return string The Mozilla Firefox feed adding URL.
5423 */
5424 function add_feed_url() {
5425 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5426 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5427 return $url_path;
5428 } // function add_feed_url
5429
5430 /**
5431 * Encrypt a password in SHA1.
5432 *
5433 * @param string $pass The password to encrypt.
5434 * @param string $login A optionnal login.
5435 * @return string The encrypted password.
5436 */
5437 function encrypt_password($pass, $login = '') {
5438 if ($login) {
5439 return "SHA1X:" . sha1("$login:$pass");
5440 } else {
5441 return "SHA1:" . sha1($pass);
5442 }
5443 } // function encrypt_password
5444
5445 /**
5446 * Update a feed batch.
5447 * Used by daemons to update n feeds by run.
5448 * Only update feed needing a update, and not being processed
5449 * by another process.
5450 *
5451 * @param mixed $link Database link
5452 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5453 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5454 * @param boolean $debug Set to false to disable debug output. Default to true.
5455 * @return void
5456 */
5457 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5458 // Process all other feeds using last_updated and interval parameters
5459
5460 // Test if the user has loggued in recently. If not, it does not update its feeds.
5461 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5462 if (DB_TYPE == "pgsql") {
5463 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5464 } else {
5465 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5466 }
5467 } else {
5468 $login_thresh_qpart = "";
5469 }
5470
5471 // Test if the feed need a update (update interval exceded).
5472 if (DB_TYPE == "pgsql") {
5473 $update_limit_qpart = "AND ((
5474 ttrss_feeds.update_interval = 0
5475 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5476 ) OR (
5477 ttrss_feeds.update_interval > 0
5478 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5479 ) OR ttrss_feeds.last_updated IS NULL)";
5480 } else {
5481 $update_limit_qpart = "AND ((
5482 ttrss_feeds.update_interval = 0
5483 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5484 ) OR (
5485 ttrss_feeds.update_interval > 0
5486 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5487 ) OR ttrss_feeds.last_updated IS NULL)";
5488 }
5489
5490 // Test if feed is currently being updated by another process.
5491 if (DB_TYPE == "pgsql") {
5492 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5493 } else {
5494 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5495 }
5496
5497 // Test if there is a limit to number of updated feeds
5498 $query_limit = "";
5499 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5500
5501 $random_qpart = sql_random_function();
5502
5503 // We search for feed needing update.
5504 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5505 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5506 ttrss_feeds.update_interval
5507 FROM
5508 ttrss_feeds, ttrss_users, ttrss_user_prefs
5509 WHERE
5510 ttrss_feeds.owner_uid = ttrss_users.id
5511 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5512 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5513 $login_thresh_qpart $update_limit_qpart
5514 $updstart_thresh_qpart
5515 ORDER BY $random_qpart $query_limit");
5516
5517 $user_prefs_cache = array();
5518
5519 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5520
5521 // Here is a little cache magic in order to minimize risk of double feed updates.
5522 $feeds_to_update = array();
5523 while ($line = db_fetch_assoc($result)) {
5524 $feeds_to_update[$line['id']] = $line;
5525 }
5526
5527 // We update the feed last update started date before anything else.
5528 // There is no lag due to feed contents downloads
5529 // It prevent an other process to update the same feed.
5530 $feed_ids = array_keys($feeds_to_update);
5531 if($feed_ids) {
5532 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5533 WHERE id IN (%s)", implode(',', $feed_ids)));
5534 }
5535
5536 // For each feed, we call the feed update function.
5537 while ($line = array_pop($feeds_to_update)) {
5538
5539 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5540
5541 update_rss_feed($link, $line["id"], true);
5542
5543 sleep(1); // prevent flood (FIXME make this an option?)
5544 }
5545
5546 // Send feed digests by email if needed.
5547 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5548
5549 } // function update_daemon_common
5550
5551 function sanitize_article_content($text) {
5552 # we don't support CDATA sections in articles, they break our own escaping
5553 $text = preg_replace("/\[\[CDATA/", "", $text);
5554 $text = preg_replace("/\]\]\>/", "", $text);
5555 return $text;
5556 }
5557
5558 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5559 $filters = array();
5560
5561 global $memcache;
5562
5563 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5564
5565 if ($memcache && $obj = $memcache->get($obj_id)) {
5566
5567 return $obj;
5568
5569 } else {
5570
5571 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5572
5573 $result = db_query($link, "SELECT reg_exp,
5574 ttrss_filter_types.name AS name,
5575 ttrss_filter_actions.name AS action,
5576 inverse,
5577 action_param,
5578 filter_param
5579 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5580 enabled = true AND
5581 $ftype_query_part
5582 owner_uid = $owner_uid AND
5583 ttrss_filter_types.id = filter_type AND
5584 ttrss_filter_actions.id = action_id AND
5585 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5586
5587 while ($line = db_fetch_assoc($result)) {
5588 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5589 $filter["reg_exp"] = $line["reg_exp"];
5590 $filter["action"] = $line["action"];
5591 $filter["action_param"] = $line["action_param"];
5592 $filter["filter_param"] = $line["filter_param"];
5593 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5594
5595 array_push($filters[$line["name"]], $filter);
5596 }
5597
5598 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5599
5600 return $filters;
5601 }
5602 }
5603
5604 function get_score_pic($score) {
5605 if ($score > 100) {
5606 return "score_high.png";
5607 } else if ($score > 0) {
5608 return "score_half_high.png";
5609 } else if ($score < -100) {
5610 return "score_low.png";
5611 } else if ($score < 0) {
5612 return "score_half_low.png";
5613 } else {
5614 return "score_neutral.png";
5615 }
5616 }
5617
5618 function rounded_table_start($classname, $header = "&nbsp;") {
5619 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5620 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5621 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5622 }
5623
5624 function rounded_table_end($footer = "&nbsp;") {
5625 print "</td><td class='right'>&nbsp;</td></tr>";
5626 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5627 print "</table>";
5628 }
5629
5630 function feed_has_icon($id) {
5631 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5632 }
5633
5634 function init_connection($link) {
5635 if (DB_TYPE == "pgsql") {
5636 pg_query($link, "set client_encoding = 'UTF-8'");
5637 pg_set_client_encoding("UNICODE");
5638 pg_query($link, "set datestyle = 'ISO, european'");
5639 pg_query($link, "set TIME ZONE 0");
5640 } else {
5641 db_query($link, "SET time_zone = '+0:0'");
5642
5643 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5644 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5645 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5646 }
5647 }
5648 }
5649
5650 function update_feedbrowser_cache($link) {
5651
5652 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5653 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5654 WHERE tf.feed_url = ttrss_feeds.feed_url
5655 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5656 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5657
5658 db_query($link, "BEGIN");
5659
5660 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5661
5662 $count = 0;
5663
5664 while ($line = db_fetch_assoc($result)) {
5665 $subscribers = db_escape_string($line["subscribers"]);
5666 $feed_url = db_escape_string($line["feed_url"]);
5667 $title = db_escape_string($line["title"]);
5668
5669 $tmp_result = db_query($link, "SELECT subscribers FROM
5670 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5671
5672 if (db_num_rows($tmp_result) == 0) {
5673
5674 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5675 (feed_url, title, subscribers) VALUES ('$feed_url',
5676 '$title', '$subscribers')");
5677
5678 ++$count;
5679
5680 }
5681
5682 }
5683
5684 db_query($link, "COMMIT");
5685
5686 return $count;
5687
5688 }
5689
5690 function ccache_zero($link, $feed_id, $owner_uid) {
5691 db_query($link, "UPDATE ttrss_counters_cache SET
5692 value = 0, updated = NOW() WHERE
5693 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5694 }
5695
5696 function ccache_zero_all($link, $owner_uid) {
5697 db_query($link, "UPDATE ttrss_counters_cache SET
5698 value = 0 WHERE owner_uid = '$owner_uid'");
5699
5700 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5701 value = 0 WHERE owner_uid = '$owner_uid'");
5702 }
5703
5704 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5705
5706 if (!$is_cat) {
5707 $table = "ttrss_counters_cache";
5708 } else {
5709 $table = "ttrss_cat_counters_cache";
5710 }
5711
5712 db_query($link, "DELETE FROM $table WHERE
5713 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5714
5715 }
5716
5717 function ccache_update_all($link, $owner_uid) {
5718
5719 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5720
5721 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5722 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5723
5724 while ($line = db_fetch_assoc($result)) {
5725 ccache_update($link, $line["feed_id"], $owner_uid, true);
5726 }
5727
5728 /* We have to manually include category 0 */
5729
5730 ccache_update($link, 0, $owner_uid, true);
5731
5732 } else {
5733 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5734 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5735
5736 while ($line = db_fetch_assoc($result)) {
5737 print ccache_update($link, $line["feed_id"], $owner_uid);
5738
5739 }
5740
5741 }
5742 }
5743
5744 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5745 $no_update = false) {
5746
5747 if (!is_numeric($feed_id)) return;
5748
5749 if (!$is_cat) {
5750 $table = "ttrss_counters_cache";
5751 if ($feed_id > 0) {
5752 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5753 WHERE id = '$feed_id'");
5754 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5755 }
5756 } else {
5757 $table = "ttrss_cat_counters_cache";
5758 }
5759
5760 if (DB_TYPE == "pgsql") {
5761 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5762 } else if (DB_TYPE == "mysql") {
5763 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5764 }
5765
5766 $result = db_query($link, "SELECT value FROM $table
5767 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5768 LIMIT 1");
5769
5770 if (db_num_rows($result) == 1) {
5771 return db_fetch_result($result, 0, "value");
5772 } else {
5773 if ($no_update) {
5774 return -1;
5775 } else {
5776 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5777 }
5778 }
5779
5780 }
5781
5782 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5783 $update_pcat = true) {
5784
5785 if (!is_numeric($feed_id)) return;
5786
5787 if (!$is_cat && $feed_id > 0) {
5788 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5789 WHERE id = '$feed_id'");
5790 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5791 }
5792
5793 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5794
5795 /* When updating a label, all we need to do is recalculate feed counters
5796 * because labels are not cached */
5797
5798 if ($feed_id < 0) {
5799 ccache_update_all($link, $owner_uid);
5800 return;
5801 }
5802
5803 if (!$is_cat) {
5804 $table = "ttrss_counters_cache";
5805 } else {
5806 $table = "ttrss_cat_counters_cache";
5807 }
5808
5809 if ($is_cat && $feed_id >= 0) {
5810 if ($feed_id != 0) {
5811 $cat_qpart = "cat_id = '$feed_id'";
5812 } else {
5813 $cat_qpart = "cat_id IS NULL";
5814 }
5815
5816 /* Recalculate counters for child feeds */
5817
5818 $result = db_query($link, "SELECT id FROM ttrss_feeds
5819 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5820
5821 while ($line = db_fetch_assoc($result)) {
5822 ccache_update($link, $line["id"], $owner_uid, false, false);
5823 }
5824
5825 $result = db_query($link, "SELECT SUM(value) AS sv
5826 FROM ttrss_counters_cache, ttrss_feeds
5827 WHERE id = feed_id AND $cat_qpart AND
5828 ttrss_feeds.owner_uid = '$owner_uid'");
5829
5830 $unread = (int) db_fetch_result($result, 0, "sv");
5831
5832 } else {
5833 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5834 }
5835
5836 db_query($link, "BEGIN");
5837
5838 $result = db_query($link, "SELECT feed_id FROM $table
5839 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5840
5841 if (db_num_rows($result) == 1) {
5842 db_query($link, "UPDATE $table SET
5843 value = '$unread', updated = NOW() WHERE
5844 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5845
5846 } else {
5847 db_query($link, "INSERT INTO $table
5848 (feed_id, value, owner_uid, updated)
5849 VALUES
5850 ($feed_id, $unread, $owner_uid, NOW())");
5851 }
5852
5853 db_query($link, "COMMIT");
5854
5855 if ($feed_id > 0 && $prev_unread != $unread) {
5856
5857 if (!$is_cat) {
5858
5859 /* Update parent category */
5860
5861 if ($update_pcat) {
5862
5863 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5864 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5865
5866 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5867
5868 ccache_update($link, $cat_id, $owner_uid, true);
5869
5870 }
5871 }
5872 } else if ($feed_id < 0) {
5873 ccache_update_all($link, $owner_uid);
5874 }
5875
5876 return $unread;
5877 }
5878
5879 function label_find_id($link, $label, $owner_uid) {
5880 $result = db_query($link,
5881 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5882 AND owner_uid = '$owner_uid' LIMIT 1");
5883
5884 if (db_num_rows($result) == 1) {
5885 return db_fetch_result($result, 0, "id");
5886 } else {
5887 return 0;
5888 }
5889 }
5890
5891 function get_article_labels($link, $id) {
5892 global $memcache;
5893
5894 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
5895
5896 $rv = array();
5897
5898 if ($memcache && $obj = $memcache->get($obj_id)) {
5899 return $obj;
5900 } else {
5901
5902 $result = db_query($link, "SELECT label_cache FROM
5903 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
5904 $_SESSION["uid"]);
5905
5906 $label_cache = db_fetch_result($result, 0, "label_cache");
5907
5908 if ($label_cache) {
5909
5910 $label_cache = json_decode($label_cache, true);
5911
5912 if ($label_cache["no-labels"] == 1)
5913 return $rv;
5914 else
5915 return $label_cache;
5916 }
5917
5918 $result = db_query($link,
5919 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5920 FROM ttrss_labels2, ttrss_user_labels2
5921 WHERE id = label_id
5922 AND article_id = '$id'
5923 AND owner_uid = ".$_SESSION["uid"] . "
5924 ORDER BY caption");
5925
5926 while ($line = db_fetch_assoc($result)) {
5927 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5928 $line["bg_color"]);
5929 array_push($rv, $rk);
5930 }
5931 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
5932
5933 if (count($rv) > 0)
5934 label_update_cache($link, $id, $rv);
5935 else
5936 label_update_cache($link, $id, array("no-labels" => 1));
5937 }
5938
5939 return $rv;
5940 }
5941
5942
5943 function label_find_caption($link, $label, $owner_uid) {
5944 $result = db_query($link,
5945 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5946 AND owner_uid = '$owner_uid' LIMIT 1");
5947
5948 if (db_num_rows($result) == 1) {
5949 return db_fetch_result($result, 0, "caption");
5950 } else {
5951 return "";
5952 }
5953 }
5954
5955 function label_update_cache($link, $id, $labels = false, $force = false) {
5956
5957 if ($force)
5958 label_clear_cache($link, $id);
5959
5960 if (!$labels)
5961 $labels = get_article_labels($link, $id);
5962
5963 $labels = db_escape_string(json_encode($labels));
5964
5965 db_query($link, "UPDATE ttrss_user_entries SET
5966 label_cache = '$labels' WHERE ref_id = '$id'");
5967
5968 }
5969
5970 function label_clear_cache($link, $id) {
5971
5972 db_query($link, "UPDATE ttrss_user_entries SET
5973 label_cache = '' WHERE ref_id = '$id'");
5974
5975 }
5976
5977 function label_remove_article($link, $id, $label, $owner_uid) {
5978
5979 $label_id = label_find_id($link, $label, $owner_uid);
5980
5981 if (!$label_id) return;
5982
5983 $result = db_query($link,
5984 "DELETE FROM ttrss_user_labels2
5985 WHERE
5986 label_id = '$label_id' AND
5987 article_id = '$id'");
5988
5989 label_clear_cache($link, $id);
5990 }
5991
5992 function label_add_article($link, $id, $label, $owner_uid) {
5993
5994 global $memcache;
5995
5996 if ($memcache) {
5997 $obj_id = md5("LABELS:$id:$owner_uid");
5998 $memcache->delete($obj_id);
5999 }
6000
6001 $label_id = label_find_id($link, $label, $owner_uid);
6002
6003 if (!$label_id) return;
6004
6005 $result = db_query($link,
6006 "SELECT
6007 article_id FROM ttrss_labels2, ttrss_user_labels2
6008 WHERE
6009 label_id = id AND
6010 label_id = '$label_id' AND
6011 article_id = '$id' AND owner_uid = '$owner_uid'
6012 LIMIT 1");
6013
6014 if (db_num_rows($result) == 0) {
6015 db_query($link, "INSERT INTO ttrss_user_labels2
6016 (label_id, article_id) VALUES ('$label_id', '$id')");
6017 }
6018
6019 label_clear_cache($link, $id);
6020
6021 }
6022
6023 function label_remove($link, $id, $owner_uid) {
6024 global $memcache;
6025
6026 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6027
6028 if ($memcache) {
6029 $obj_id = md5("LABELS:$id:$owner_uid");
6030 $memcache->delete($obj_id);
6031 }
6032
6033 db_query($link, "BEGIN");
6034
6035 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6036 WHERE id = '$id'");
6037
6038 $caption = db_fetch_result($result, 0, "caption");
6039
6040 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6041 AND owner_uid = " . $owner_uid);
6042
6043 if (db_affected_rows($link, $result) != 0 && $caption) {
6044
6045 /* Remove access key for the label */
6046
6047 $ext_id = -11 - $id;
6048
6049 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6050 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6051
6052 /* Disable filters that reference label being removed */
6053
6054 db_query($link, "UPDATE ttrss_filters SET
6055 enabled = false WHERE action_param = '$caption'
6056 AND action_id = 7
6057 AND owner_uid = " . $owner_uid);
6058
6059 /* Remove cached data */
6060
6061 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6062 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6063
6064 }
6065
6066 db_query($link, "COMMIT");
6067 }
6068
6069 function label_create($link, $caption) {
6070
6071 db_query($link, "BEGIN");
6072
6073 $result = false;
6074
6075 $result = db_query($link, "SELECT id FROM ttrss_labels2
6076 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6077
6078 if (db_num_rows($result) == 0) {
6079 $result = db_query($link,
6080 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6081 VALUES ('$caption', '".$_SESSION["uid"]."')");
6082
6083 $result = db_affected_rows($link, $result) != 0;
6084 }
6085
6086 db_query($link, "COMMIT");
6087
6088 return $result;
6089 }
6090
6091 function print_labels_headlines_dropdown($link, $feed_id) {
6092 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6093
6094 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6095 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6096
6097 while ($line = db_fetch_assoc($result)) {
6098
6099 $label_id = $line["id"];
6100 $label_caption = $line["caption"];
6101 $id = $line["id"];
6102
6103 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6104 print "<option id=\"LHDL-$id\"
6105 value=\"selectionRemoveLabel($label_id)\">".
6106 __('Remove:') . " $label_caption</option>";
6107 } else {
6108 print "<option id=\"LHDL-$id\"
6109 value=\"selectionAssignLabel($label_id)\">".
6110 __('Assign:') . " $label_caption</option>";
6111 }
6112 }
6113 }
6114
6115 function format_tags_string($tags, $id) {
6116
6117 $tags_str = "";
6118 $tags_nolinks_str = "";
6119
6120 $num_tags = 0;
6121
6122 /* if (get_user_theme($link) == "3pane") {
6123 $tag_limit = 3;
6124 } else {
6125 $tag_limit = 6;
6126 } */
6127
6128 $tag_limit = 6;
6129
6130 $formatted_tags = array();
6131
6132 foreach ($tags as $tag) {
6133 $num_tags++;
6134 $tag_escaped = str_replace("'", "\\'", $tag);
6135
6136 if (mb_strlen($tag) > 30) {
6137 $tag = truncate_string($tag, 30);
6138 }
6139
6140 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6141
6142 array_push($formatted_tags, $tag_str);
6143
6144 $tmp_tags_str = implode(", ", $formatted_tags);
6145
6146 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
6147 break;
6148 }
6149 }
6150
6151 $tags_str = implode(", ", $formatted_tags);
6152
6153 if ($num_tags < count($tags)) {
6154 $tags_str .= ", &hellip;";
6155 }
6156
6157 if ($num_tags == 0) {
6158 $tags_str = __("no tags");
6159 }
6160
6161 return $tags_str;
6162
6163 }
6164
6165 function format_article_labels($labels, $id) {
6166
6167 $labels_str = "";
6168
6169 foreach ($labels as $l) {
6170 $labels_str .= sprintf("<span class='hlLabelRef'
6171 style='color : %s; background-color : %s'>%s</span>",
6172 $l[2], $l[3], $l[1]);
6173 }
6174
6175 return $labels_str;
6176
6177 }
6178
6179 function format_article_note($id, $note) {
6180
6181 $str = "<div class='articleNote' title=\"".__('edit note')."\"
6182 onclick=\"editArticleNote($id)\">$note</div>";
6183
6184 return $str;
6185 }
6186
6187 function toggle_collapse_cat($link, $cat_id, $mode) {
6188 if ($cat_id > 0) {
6189 $mode = bool_to_sql_bool($mode);
6190
6191 db_query($link, "UPDATE ttrss_feed_categories SET
6192 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6193 $_SESSION["uid"]);
6194 } else {
6195 $pref_name = '';
6196
6197 switch ($cat_id) {
6198 case -1:
6199 $pref_name = '_COLLAPSED_SPECIAL';
6200 break;
6201 case -2:
6202 $pref_name = '_COLLAPSED_LABELS';
6203 break;
6204 case 0:
6205 $pref_name = '_COLLAPSED_UNCAT';
6206 break;
6207 }
6208
6209 if ($pref_name) {
6210 if ($mode) {
6211 set_pref($link, $pref_name, 'true');
6212 } else {
6213 set_pref($link, $pref_name, 'false');
6214 }
6215 }
6216 }
6217 }
6218
6219 function remove_feed($link, $id, $owner_uid) {
6220
6221 if ($id > 0) {
6222
6223 /* save starred articles in Archived feed */
6224
6225 db_query($link, "BEGIN");
6226
6227 /* prepare feed if necessary */
6228
6229 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6230 WHERE id = '$id'");
6231
6232 if (db_num_rows($result) == 0) {
6233 db_query($link, "INSERT INTO ttrss_archived_feeds
6234 (id, owner_uid, title, feed_url, site_url)
6235 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6236 WHERE id = '$id'");
6237 }
6238
6239 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6240 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6241 marked = true AND owner_uid = $owner_uid");
6242
6243 /* Remove access key for the feed */
6244
6245 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6246 feed_id = '$id' AND owner_uid = $owner_uid");
6247
6248 /* remove the feed */
6249
6250 db_query($link, "DELETE FROM ttrss_feeds
6251 WHERE id = '$id' AND owner_uid = $owner_uid");
6252
6253 db_query($link, "COMMIT");
6254
6255 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6256 unlink(ICONS_DIR . "/$id.ico");
6257 } */
6258
6259 ccache_remove($link, $id, $owner_uid);
6260
6261 } else {
6262 label_remove($link, -11-$id, $owner_uid);
6263 ccache_remove($link, -11-$id, $owner_uid);
6264 }
6265 }
6266
6267 function add_feed_category($link, $feed_cat) {
6268
6269 if (!$feed_cat) return false;
6270
6271 db_query($link, "BEGIN");
6272
6273 $result = db_query($link,
6274 "SELECT id FROM ttrss_feed_categories
6275 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6276
6277 if (db_num_rows($result) == 0) {
6278
6279 $result = db_query($link,
6280 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6281 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6282
6283 db_query($link, "COMMIT");
6284
6285 return true;
6286 }
6287
6288 return false;
6289 }
6290
6291 function remove_feed_category($link, $id, $owner_uid) {
6292
6293 db_query($link, "DELETE FROM ttrss_feed_categories
6294 WHERE id = '$id' AND owner_uid = $owner_uid");
6295
6296 ccache_remove($link, $id, $owner_uid, true);
6297 }
6298
6299 function archive_article($link, $id, $owner_uid) {
6300 db_query($link, "BEGIN");
6301
6302 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6303 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6304
6305 if (db_num_rows($result) != 0) {
6306
6307 /* prepare the archived table */
6308
6309 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6310
6311 if ($feed_id) {
6312 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6313 WHERE id = '$feed_id'");
6314
6315 if (db_num_rows($result) == 0) {
6316 db_query($link, "INSERT INTO ttrss_archived_feeds
6317 (id, owner_uid, title, feed_url, site_url)
6318 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6319 WHERE id = '$feed_id'");
6320 }
6321
6322 db_query($link, "UPDATE ttrss_user_entries
6323 SET orig_feed_id = feed_id, feed_id = NULL
6324 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6325 }
6326 }
6327
6328 db_query($link, "COMMIT");
6329 }
6330
6331 function getArticleFeed($link, $id) {
6332 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6333 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6334
6335 if (db_num_rows($result) != 0) {
6336 return db_fetch_result($result, 0, "feed_id");
6337 } else {
6338 return 0;
6339 }
6340 }
6341
6342 function make_url_from_parts($parts) {
6343 $url = $parts['scheme'] . '://' . $parts['host'];
6344
6345 if ($parts['path']) $url .= $parts['path'];
6346 if ($parts['query']) $url .= '?' . $parts['query'];
6347
6348 return $url;
6349 }
6350
6351 /**
6352 * Fixes incomplete URLs by prepending "http://".
6353 * Also replaces feed:// with http://, and
6354 * prepends a trailing slash if the url is a domain name only.
6355 *
6356 * @param string $url Possibly incomplete URL
6357 *
6358 * @return string Fixed URL.
6359 */
6360 function fix_url($url) {
6361 if (strpos($url, '://') === false) {
6362 $url = 'http://' . $url;
6363 } else if (substr($url, 0, 5) == 'feed:') {
6364 $url = 'http:' . substr($url, 5);
6365 }
6366
6367 //prepend slash if the URL has no slash in it
6368 // "http://www.example" -> "http://www.example/"
6369 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
6370 $url .= '/';
6371 }
6372
6373 if ($url != "http:///")
6374 return $url;
6375 else
6376 return '';
6377 }
6378
6379 function validate_feed_url($url) {
6380 $parts = parse_url($url);
6381
6382 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6383
6384 }
6385
6386 function get_article_enclosures($link, $id) {
6387
6388 global $memcache;
6389
6390 $query = "SELECT * FROM ttrss_enclosures
6391 WHERE post_id = '$id' AND content_url != ''";
6392
6393 $obj_id = md5("ENCLOSURES:$id");
6394
6395 $rv = array();
6396
6397 if ($memcache && $obj = $memcache->get($obj_id)) {
6398 $rv = $obj;
6399 } else {
6400 $result = db_query($link, $query);
6401
6402 if (db_num_rows($result) > 0) {
6403 while ($line = db_fetch_assoc($result)) {
6404 array_push($rv, $line);
6405 }
6406 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6407 }
6408 }
6409
6410 return $rv;
6411 }
6412
6413 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6414
6415 $feeds = array();
6416
6417 /* Labels */
6418
6419 if ($cat_id == -4 || $cat_id == -2) {
6420 $counters = getLabelCounters($link, true);
6421
6422 foreach (array_values($counters) as $cv) {
6423
6424 $unread = $cv["counter"];
6425
6426 if ($unread || !$unread_only) {
6427
6428 $row = array(
6429 "id" => $cv["id"],
6430 "title" => $cv["description"],
6431 "unread" => $cv["counter"],
6432 "cat_id" => -2,
6433 );
6434
6435 array_push($feeds, $row);
6436 }
6437 }
6438 }
6439
6440 /* Virtual feeds */
6441
6442 if ($cat_id == -4 || $cat_id == -1) {
6443 foreach (array(-1, -2, -3, -4, 0) as $i) {
6444 $unread = getFeedUnread($link, $i);
6445
6446 if ($unread || !$unread_only) {
6447 $title = getFeedTitle($link, $i);
6448
6449 $row = array(
6450 "id" => $i,
6451 "title" => $title,
6452 "unread" => $unread,
6453 "cat_id" => -1,
6454 );
6455 array_push($feeds, $row);
6456 }
6457
6458 }
6459 }
6460
6461 /* Real feeds */
6462
6463 if ($limit) {
6464 $limit_qpart = "LIMIT $limit OFFSET $offset";
6465 } else {
6466 $limit_qpart = "";
6467 }
6468
6469 if ($cat_id == -4 || $cat_id == -3) {
6470 $result = db_query($link, "SELECT
6471 id, feed_url, cat_id, title, ".
6472 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6473 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6474 " ORDER BY cat_id, title " . $limit_qpart);
6475 } else {
6476
6477 if ($cat_id)
6478 $cat_qpart = "cat_id = '$cat_id'";
6479 else
6480 $cat_qpart = "cat_id IS NULL";
6481
6482 $result = db_query($link, "SELECT
6483 id, feed_url, cat_id, title, ".
6484 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6485 FROM ttrss_feeds WHERE
6486 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6487 " ORDER BY cat_id, title " . $limit_qpart);
6488 }
6489
6490 while ($line = db_fetch_assoc($result)) {
6491
6492 $unread = getFeedUnread($link, $line["id"]);
6493
6494 $has_icon = feed_has_icon($line['id']);
6495
6496 if ($unread || !$unread_only) {
6497
6498 $row = array(
6499 "feed_url" => $line["feed_url"],
6500 "title" => $line["title"],
6501 "id" => (int)$line["id"],
6502 "unread" => (int)$unread,
6503 "has_icon" => $has_icon,
6504 "cat_id" => (int)$line["cat_id"],
6505 "last_updated" => strtotime($line["last_updated"])
6506 );
6507
6508 array_push($feeds, $row);
6509 }
6510 }
6511
6512 return $feeds;
6513 }
6514
6515 function api_get_headlines($link, $feed_id, $limit, $offset,
6516 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6517
6518 /* do not rely on params below */
6519
6520 $search = db_escape_string($_REQUEST["search"]);
6521 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6522 $match_on = db_escape_string($_REQUEST["match_on"]);
6523
6524 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6525 $view_mode, $is_cat, $search, $search_mode, $match_on,
6526 $order, $offset);
6527
6528 $result = $qfh_ret[0];
6529 $feed_title = $qfh_ret[1];
6530
6531 $headlines = array();
6532
6533 while ($line = db_fetch_assoc($result)) {
6534 $is_updated = ($line["last_read"] == "" &&
6535 ($line["unread"] != "t" && $line["unread"] != "1"));
6536
6537 $headline_row = array(
6538 "id" => (int)$line["id"],
6539 "unread" => sql_bool_to_bool($line["unread"]),
6540 "marked" => sql_bool_to_bool($line["marked"]),
6541 "published" => sql_bool_to_bool($line["published"]),
6542 "updated" => strtotime($line["updated"]),
6543 "is_updated" => $is_updated,
6544 "title" => $line["title"],
6545 "link" => $line["link"],
6546 "feed_id" => $line["feed_id"],
6547 "tags" => get_article_tags($link, $line["id"]),
6548 );
6549
6550 if ($show_excerpt) {
6551 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6552 $headline_row["excerpt"] = $excerpt;
6553 }
6554
6555 if ($show_content) {
6556 $headline_row["content"] = $line["content_preview"];
6557 }
6558
6559 array_push($headlines, $headline_row);
6560 }
6561
6562 return $headlines;
6563 }
6564
6565 function generate_error_feed($link, $error) {
6566 $reply = array();
6567
6568 $reply['headlines']['id'] = -6;
6569 $reply['headlines']['is_cat'] = false;
6570
6571 $reply['headlines']['toolbar'] = '';
6572 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6573
6574 $reply['headlines-info'] = array("count" => 0,
6575 "vgroup_last_feed" => '',
6576 "unread" => 0,
6577 "disable_cache" => true);
6578
6579 return $reply;
6580 }
6581
6582
6583 function generate_dashboard_feed($link) {
6584 $reply = array();
6585
6586 $reply['headlines']['id'] = -5;
6587 $reply['headlines']['is_cat'] = false;
6588
6589 $reply['headlines']['toolbar'] = '';
6590 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6591
6592 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6593
6594 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6595 WHERE owner_uid = " . $_SESSION['uid']);
6596
6597 $last_updated = db_fetch_result($result, 0, "last_updated");
6598 $last_updated = make_local_datetime($link, $last_updated, false);
6599
6600 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6601
6602 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6603 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6604
6605 $num_errors = db_fetch_result($result, 0, "num_errors");
6606
6607 if ($num_errors > 0) {
6608 $reply['headlines']['content'] .= "<br/>";
6609 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6610 __('Some feeds have update errors (click for details)')."</a>";
6611 }
6612 $reply['headlines']['content'] .= "</span></p>";
6613
6614 $reply['headlines-info'] = array("count" => 0,
6615 "vgroup_last_feed" => '',
6616 "unread" => 0,
6617 "disable_cache" => true);
6618
6619 return $reply;
6620 }
6621
6622 function save_email_address($link, $email) {
6623 // FIXME: implement persistent storage of emails
6624
6625 if (!$_SESSION['stored_emails'])
6626 $_SESSION['stored_emails'] = array();
6627
6628 if (!in_array($email, $_SESSION['stored_emails']))
6629 array_push($_SESSION['stored_emails'], $email);
6630 }
6631
6632 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6633 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6634
6635 $sql_is_cat = bool_to_sql_bool($is_cat);
6636
6637 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6638 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6639 AND owner_uid = " . $owner_uid);
6640
6641 if (db_num_rows($result) == 1) {
6642 $key = db_escape_string(sha1(uniqid(rand(), true)));
6643
6644 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6645 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6646 AND owner_uid = " . $owner_uid);
6647
6648 return $key;
6649
6650 } else {
6651 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6652 }
6653 }
6654
6655 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6656
6657 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6658
6659 $sql_is_cat = bool_to_sql_bool($is_cat);
6660
6661 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6662 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6663 AND owner_uid = " . $owner_uid);
6664
6665 if (db_num_rows($result) == 1) {
6666 return db_fetch_result($result, 0, "access_key");
6667 } else {
6668 $key = db_escape_string(sha1(uniqid(rand(), true)));
6669
6670 $result = db_query($link, "INSERT INTO ttrss_access_keys
6671 (access_key, feed_id, is_cat, owner_uid)
6672 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6673
6674 return $key;
6675 }
6676 return false;
6677 }
6678
6679 /**
6680 * Extracts RSS/Atom feed URLs from the given HTML URL.
6681 *
6682 * @param string $url HTML page URL
6683 *
6684 * @return array Array of feeds. Key is the full URL, value the title
6685 */
6686 function get_feeds_from_html($url, $login = false, $pass = false)
6687 {
6688 $url = fix_url($url);
6689 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
6690
6691 libxml_use_internal_errors(true);
6692
6693 $content = @fetch_file_contents($url, false, $login, $pass);
6694
6695 $doc = new DOMDocument();
6696 $doc->loadHTML($content);
6697 $xpath = new DOMXPath($doc);
6698 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6699 $feedUrls = array();
6700 foreach ($entries as $entry) {
6701 if ($entry->hasAttribute('href')) {
6702 $title = $entry->getAttribute('title');
6703 if ($title == '') {
6704 $title = $entry->getAttribute('type');
6705 }
6706 $feedUrl = rewrite_relative_url(
6707 $baseUrl, $entry->getAttribute('href')
6708 );
6709 $feedUrls[$feedUrl] = $title;
6710 }
6711 }
6712 return $feedUrls;
6713 }
6714
6715 /**
6716 * Checks if the content behind the given URL is a HTML file
6717 *
6718 * @param string $url URL to check
6719 *
6720 * @return boolean True if the URL contains HTML content
6721 */
6722 function url_is_html($url, $login = false, $pass = false) {
6723 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6724
6725 if (stripos($content, '<html>') === false
6726 && stripos($content, '<html ') === false
6727 ) {
6728 return false;
6729 }
6730
6731 return true;
6732 }
6733
6734 function print_label_select($link, $name, $value, $attributes = "") {
6735
6736 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6737 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6738
6739 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6740 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6741
6742 while ($line = db_fetch_assoc($result)) {
6743
6744 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
6745
6746 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6747 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6748
6749 }
6750
6751 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6752
6753 print "</select>";
6754
6755
6756 }
6757
6758 function format_article_enclosures($link, $id, $always_display_enclosures,
6759 $article_content) {
6760
6761 $result = get_article_enclosures($link, $id);
6762 $rv = '';
6763
6764 if (count($result) > 0) {
6765
6766 $entries_html = array();
6767 $entries = array();
6768
6769 foreach ($result as $line) {
6770
6771 $url = $line["content_url"];
6772 $ctype = $line["content_type"];
6773
6774 if (!$ctype) $ctype = __("unknown type");
6775
6776 # $filename = substr($url, strrpos($url, "/")+1);
6777
6778 $entry = format_inline_player($link, $url, $ctype);
6779
6780 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6781 # $filename . " (" . $ctype . ")" . "</a>";
6782
6783 array_push($entries_html, $entry);
6784
6785 $entry = array();
6786
6787 $entry["type"] = $ctype;
6788 $entry["filename"] = $filename;
6789 $entry["url"] = $url;
6790
6791 array_push($entries, $entry);
6792 }
6793
6794 $rv .= "<div class=\"postEnclosures\">";
6795
6796 if (!get_pref($link, "STRIP_IMAGES")) {
6797 if ($always_display_enclosures ||
6798 !preg_match("/<img/i", $article_content)) {
6799
6800 foreach ($entries as $entry) {
6801
6802 if (preg_match("/image/", $entry["type"]) ||
6803 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6804
6805 $rv .= "<p><img
6806 alt=\"".htmlspecialchars($entry["filename"])."\"
6807 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6808 }
6809 }
6810 }
6811 }
6812
6813 if (count($entries) == 1) {
6814 $rv .= __("Attachment:") . " ";
6815 } else {
6816 $rv .= __("Attachments:") . " ";
6817 }
6818
6819 $rv .= join(", ", $entries_html);
6820
6821 $rv .= "</div>";
6822 }
6823
6824 return $rv;
6825 }
6826
6827 function getLastArticleId($link) {
6828 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
6829 WHERE owner_uid = " . $_SESSION["uid"]);
6830
6831 if (db_num_rows($result) == 1) {
6832 return db_fetch_result($result, 0, "id");
6833 } else {
6834 return -1;
6835 }
6836 }
6837
6838 function build_url($parts) {
6839 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
6840 }
6841
6842 /**
6843 * Converts a (possibly) relative URL to a absolute one.
6844 *
6845 * @param string $url Base URL (i.e. from where the document is)
6846 * @param string $rel_url Possibly relative URL in the document
6847 *
6848 * @return string Absolute URL
6849 */
6850 function rewrite_relative_url($url, $rel_url) {
6851 if (strpos($rel_url, "://") !== false) {
6852 return $rel_url;
6853 } else if (strpos($rel_url, "/") === 0)
6854 {
6855 $parts = parse_url($url);
6856 $parts['path'] = $rel_url;
6857
6858 return build_url($parts);
6859
6860 } else {
6861 $parts = parse_url($url);
6862 if (!isset($parts['path'])) {
6863 $parts['path'] = '/';
6864 }
6865 $dir = $parts['path'];
6866 if (substr($dir, -1) !== '/') {
6867 $dir = dirname($parts['path']);
6868 $dir !== '/' && $dir .= '/';
6869 }
6870 $parts['path'] = $dir . $rel_url;
6871
6872 return build_url($parts);
6873 }
6874 }
6875
6876 function sphinx_search($query, $offset = 0, $limit = 30) {
6877 $sphinxClient = new SphinxClient();
6878
6879 $sphinxClient->SetServer('localhost', 9312);
6880 $sphinxClient->SetConnectTimeout(1);
6881
6882 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
6883 'feed_title' => 20));
6884
6885 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
6886 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
6887 $sphinxClient->SetLimits($offset, $limit, 1000);
6888 $sphinxClient->SetArrayResult(false);
6889 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
6890
6891 $result = $sphinxClient->Query($query, SPHINX_INDEX);
6892
6893 $ids = array();
6894
6895 if (is_array($result['matches'])) {
6896 foreach (array_keys($result['matches']) as $int_id) {
6897 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
6898 array_push($ids, $ref_id);
6899 }
6900 }
6901
6902 return $ids;
6903 }
6904
6905 function cleanup_tags($link, $days = 14, $limit = 1000) {
6906
6907 if (DB_TYPE == "pgsql") {
6908 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
6909 } else if (DB_TYPE == "mysql") {
6910 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
6911 }
6912
6913 $tags_deleted = 0;
6914
6915 while ($limit > 0) {
6916 $limit_part = 500;
6917
6918 $query = "SELECT ttrss_tags.id AS id
6919 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
6920 WHERE post_int_id = int_id AND $interval_query AND
6921 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
6922
6923 $result = db_query($link, $query);
6924
6925 $ids = array();
6926
6927 while ($line = db_fetch_assoc($result)) {
6928 array_push($ids, $line['id']);
6929 }
6930
6931 if (count($ids) > 0) {
6932 $ids = join(",", $ids);
6933 print ".";
6934
6935 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
6936 $tags_deleted += db_affected_rows($link, $tmp_result);
6937 } else {
6938 break;
6939 }
6940
6941 $limit -= $limit_part;
6942 }
6943
6944 print "\n";
6945
6946 return $tags_deleted;
6947 }
6948
6949 function feedlist_init_cat($link, $cat_id, $hidden = false) {
6950 $obj = array();
6951 $cat_id = (int) $cat_id;
6952
6953 if ($cat_id > 0) {
6954 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
6955 } else if ($cat_id == 0 || $cat_id == -2) {
6956 $cat_unread = getCategoryUnread($link, $cat_id);
6957 }
6958
6959 $obj['id'] = 'CAT:' . $cat_id;
6960 $obj['items'] = array();
6961 $obj['name'] = getCategoryTitle($link, $cat_id);
6962 $obj['type'] = 'feed';
6963 $obj['unread'] = (int) $cat_unread;
6964 $obj['hidden'] = $hidden;
6965 $obj['bare_id'] = $cat_id;
6966
6967 return $obj;
6968 }
6969
6970 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
6971 $obj = array();
6972 $feed_id = (int) $feed_id;
6973
6974 if (!$title)
6975 $title = getFeedTitle($link, $feed_id, false);
6976
6977 if ($unread === false)
6978 $unread = getFeedUnread($link, $feed_id, false);
6979
6980 $obj['id'] = 'FEED:' . $feed_id;
6981 $obj['name'] = $title;
6982 $obj['unread'] = (int) $unread;
6983 $obj['type'] = 'feed';
6984 $obj['error'] = $error;
6985 $obj['updated'] = $updated;
6986 $obj['icon'] = getFeedIcon($feed_id);
6987 $obj['bare_id'] = $feed_id;
6988
6989 return $obj;
6990 }
6991
6992
6993 function fetch_twitter_rss($link, $url, $owner_uid) {
6994 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
6995 WHERE id = $owner_uid");
6996
6997 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
6998 $url_escaped = db_escape_string($url);
6999
7000 if ($access_token) {
7001
7002 $tmhOAuth = new tmhOAuth(array(
7003 'consumer_key' => CONSUMER_KEY,
7004 'consumer_secret' => CONSUMER_SECRET,
7005 'user_token' => $access_token['oauth_token'],
7006 'user_secret' => $access_token['oauth_token_secret'],
7007 ));
7008
7009 $code = $tmhOAuth->request('GET', $url);
7010
7011 if ($code == 200) {
7012
7013 $content = $tmhOAuth->response['response'];
7014
7015 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING,
7016 MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
7017
7018 return $rss;
7019
7020 } else {
7021
7022 db_query($link, "UPDATE ttrss_feeds
7023 SET last_error = 'OAuth authorization failed ($code).'
7024 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7025 }
7026
7027 } else {
7028
7029 db_query($link, "UPDATE ttrss_feeds
7030 SET last_error = 'OAuth information not found.'
7031 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7032
7033 return false;
7034 }
7035 }
7036
7037 function print_user_stylesheet($link) {
7038 $value = get_pref($link, 'USER_STYLESHEET');
7039
7040 if ($value) {
7041 print "<style type=\"text/css\">";
7042 print str_replace("<br/>", "\n", $value);
7043 print "</style>";
7044 }
7045
7046 }
7047
7048 function rewrite_urls($line) {
7049 global $url_regex;
7050
7051 $urls = null;
7052
7053 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7054 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7055
7056 return $result;
7057 }
7058
7059 ?>