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