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