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