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