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