3 class API extends Handler {
12 function before($method) {
13 if (parent::before($method)) {
14 header("Content-Type: text/json");
16 if (!$_SESSION["uid"] && $method != "login" && $method != "isloggedin") {
17 $this->wrap(self::STATUS_ERR, array("error" => 'NOT_LOGGED_IN'));
21 if ($_SESSION["uid"] && $method != "logout" && !get_pref('ENABLE_API_ACCESS')) {
22 $this->wrap(self::STATUS_ERR, array("error" => 'API_DISABLED'));
26 $this->seq = (int) $_REQUEST['seq'];
33 function wrap($status, $reply) {
34 print json_encode(array("seq" => $this->seq,
36 "content" => $reply));
39 function getVersion() {
40 $rv = array("version" => VERSION);
41 $this->wrap(self::STATUS_OK, $rv);
44 function getApiLevel() {
45 $rv = array("level" => self::API_LEVEL);
46 $this->wrap(self::STATUS_OK, $rv);
53 $login = $this->dbh->escape_string($_REQUEST["user"]);
54 $password = $_REQUEST["password"];
55 $password_base64 = base64_decode($_REQUEST["password"]);
57 if (SINGLE_USER_MODE) $login = "admin";
59 $result = $this->dbh->query("SELECT id FROM ttrss_users WHERE login = '$login'");
61 if ($this->dbh->num_rows($result) != 0) {
62 $uid = $this->dbh->fetch_result($result, 0, "id");
68 $this->wrap(self::STATUS_ERR, array("error" => "LOGIN_ERROR"));
72 if (get_pref("ENABLE_API_ACCESS", $uid)) {
73 if (authenticate_user($login, $password)) { // try login with normal password
74 $this->wrap(self::STATUS_OK, array("session_id" => session_id(),
75 "api_level" => self::API_LEVEL));
76 } else if (authenticate_user($login, $password_base64)) { // else try with base64_decoded password
77 $this->wrap(self::STATUS_OK, array("session_id" => session_id(),
78 "api_level" => self::API_LEVEL));
79 } else { // else we are not logged in
80 user_error("Failed login attempt for $login from {$_SERVER['REMOTE_ADDR']}", E_USER_WARNING);
81 $this->wrap(self::STATUS_ERR, array("error" => "LOGIN_ERROR"));
84 $this->wrap(self::STATUS_ERR, array("error" => "API_DISABLED"));
91 $this->wrap(self::STATUS_OK, array("status" => "OK"));
94 function isLoggedIn() {
95 $this->wrap(self::STATUS_OK, array("status" => $_SESSION["uid"] != ''));
98 function getUnread() {
99 $feed_id = $this->dbh->escape_string($_REQUEST["feed_id"]);
100 $is_cat = $this->dbh->escape_string($_REQUEST["is_cat"]);
103 $this->wrap(self::STATUS_OK, array("unread" => getFeedUnread($feed_id, $is_cat)));
105 $this->wrap(self::STATUS_OK, array("unread" => getGlobalUnread()));
109 /* Method added for ttrss-reader for Android */
110 function getCounters() {
111 $this->wrap(self::STATUS_OK, getAllCounters());
114 function getFeeds() {
115 $cat_id = $this->dbh->escape_string($_REQUEST["cat_id"]);
116 $unread_only = sql_bool_to_bool($_REQUEST["unread_only"]);
117 $limit = (int) $this->dbh->escape_string($_REQUEST["limit"]);
118 $offset = (int) $this->dbh->escape_string($_REQUEST["offset"]);
119 $include_nested = sql_bool_to_bool($_REQUEST["include_nested"]);
121 $feeds = $this->api_get_feeds($cat_id, $unread_only, $limit, $offset, $include_nested);
123 $this->wrap(self::STATUS_OK, $feeds);
126 function getCategories() {
127 $unread_only = sql_bool_to_bool($_REQUEST["unread_only"]);
128 $enable_nested = sql_bool_to_bool($_REQUEST["enable_nested"]);
129 $include_empty = sql_bool_to_bool($_REQUEST['include_empty']);
131 // TODO do not return empty categories, return Uncategorized and standard virtual cats
134 $nested_qpart = "parent_cat IS NULL";
136 $nested_qpart = "true";
138 $result = $this->dbh->query("SELECT
139 id, title, order_id, (SELECT COUNT(id) FROM
141 ttrss_feed_categories.id IS NOT NULL AND cat_id = ttrss_feed_categories.id) AS num_feeds,
142 (SELECT COUNT(id) FROM
143 ttrss_feed_categories AS c2 WHERE
144 c2.parent_cat = ttrss_feed_categories.id) AS num_cats
145 FROM ttrss_feed_categories
146 WHERE $nested_qpart AND owner_uid = " .
151 while ($line = $this->dbh->fetch_assoc($result)) {
152 if ($include_empty || $line["num_feeds"] > 0 || $line["num_cats"] > 0) {
153 $unread = getFeedUnread($line["id"], true);
156 $unread += getCategoryChildrenUnread($line["id"]);
158 if ($unread || !$unread_only) {
159 array_push($cats, array("id" => $line["id"],
160 "title" => $line["title"],
162 "order_id" => (int) $line["order_id"],
168 foreach (array(-2,-1,0) as $cat_id) {
169 if ($include_empty || !$this->isCategoryEmpty($cat_id)) {
170 $unread = getFeedUnread($cat_id, true);
172 if ($unread || !$unread_only) {
173 array_push($cats, array("id" => $cat_id,
174 "title" => getCategoryTitle($cat_id),
175 "unread" => $unread));
180 $this->wrap(self::STATUS_OK, $cats);
183 function getHeadlines() {
184 $feed_id = $this->dbh->escape_string($_REQUEST["feed_id"]);
185 if ($feed_id != "") {
187 $limit = (int)$this->dbh->escape_string($_REQUEST["limit"]);
189 if (!$limit || $limit >= 200) $limit = 200;
191 $offset = (int)$this->dbh->escape_string($_REQUEST["skip"]);
192 $filter = $this->dbh->escape_string($_REQUEST["filter"]);
193 $is_cat = sql_bool_to_bool($_REQUEST["is_cat"]);
194 $show_excerpt = sql_bool_to_bool($_REQUEST["show_excerpt"]);
195 $show_content = sql_bool_to_bool($_REQUEST["show_content"]);
196 /* all_articles, unread, adaptive, marked, updated */
197 $view_mode = $this->dbh->escape_string($_REQUEST["view_mode"]);
198 $include_attachments = sql_bool_to_bool($_REQUEST["include_attachments"]);
199 $since_id = (int)$this->dbh->escape_string($_REQUEST["since_id"]);
200 $include_nested = sql_bool_to_bool($_REQUEST["include_nested"]);
201 $sanitize_content = !isset($_REQUEST["sanitize"]) ||
202 sql_bool_to_bool($_REQUEST["sanitize"]);
203 $force_update = sql_bool_to_bool($_REQUEST["force_update"]);
205 $override_order = false;
206 switch ($_REQUEST["order_by"]) {
208 $override_order = "ttrss_entries.title";
211 $override_order = "score DESC, date_entered, updated";
214 $override_order = "updated DESC";
218 /* do not rely on params below */
220 $search = $this->dbh->escape_string($_REQUEST["search"]);
221 $search_mode = $this->dbh->escape_string($_REQUEST["search_mode"]);
223 $headlines = $this->api_get_headlines($feed_id, $limit, $offset,
224 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $override_order,
225 $include_attachments, $since_id, $search, $search_mode,
226 $include_nested, $sanitize_content, $force_update);
228 $this->wrap(self::STATUS_OK, $headlines);
230 $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE'));
234 function updateArticle() {
235 $article_ids = array_filter(explode(",", $this->dbh->escape_string($_REQUEST["article_ids"])), is_numeric);
236 $mode = (int) $this->dbh->escape_string($_REQUEST["mode"]);
237 $data = $this->dbh->escape_string($_REQUEST["data"]);
238 $field_raw = (int)$this->dbh->escape_string($_REQUEST["field"]);
243 switch ($field_raw) {
246 $additional_fields = ",last_marked = NOW()";
249 $field = "published";
250 $additional_fields = ",last_published = NOW()";
254 $additional_fields = ",last_read = NOW()";
268 $set_to = "NOT $field";
272 if ($field == "note") $set_to = "'$data'";
274 if ($field && $set_to && count($article_ids) > 0) {
276 $article_ids = join(", ", $article_ids);
278 $result = $this->dbh->query("UPDATE ttrss_user_entries SET $field = $set_to $additional_fields WHERE ref_id IN ($article_ids) AND owner_uid = " . $_SESSION["uid"]);
280 $num_updated = $this->dbh->affected_rows($result);
282 if ($num_updated > 0 && $field == "unread") {
283 $result = $this->dbh->query("SELECT DISTINCT feed_id FROM ttrss_user_entries
284 WHERE ref_id IN ($article_ids)");
286 while ($line = $this->dbh->fetch_assoc($result)) {
287 ccache_update($line["feed_id"], $_SESSION["uid"]);
291 if ($num_updated > 0 && $field == "published") {
292 if (PUBSUBHUBBUB_HUB) {
293 $rss_link = get_self_url_prefix() .
294 "/public.php?op=rss&id=-2&key=" .
295 get_feed_access_key(-2, false);
297 $p = new Publisher(PUBSUBHUBBUB_HUB);
298 $pubsub_result = $p->publish_update($rss_link);
302 $this->wrap(self::STATUS_OK, array("status" => "OK",
303 "updated" => $num_updated));
306 $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE'));
311 function getArticle() {
313 $article_id = join(",", array_filter(explode(",", $this->dbh->escape_string($_REQUEST["article_id"])), is_numeric));
317 $query = "SELECT id,title,link,content,feed_id,comments,int_id,
318 marked,unread,published,score,note,lang,
319 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
320 author,(SELECT title FROM ttrss_feeds WHERE id = feed_id) AS feed_title
321 FROM ttrss_entries,ttrss_user_entries
322 WHERE id IN ($article_id) AND ref_id = id AND owner_uid = " .
325 $result = $this->dbh->query($query);
329 if ($this->dbh->num_rows($result) != 0) {
331 while ($line = $this->dbh->fetch_assoc($result)) {
333 $attachments = get_article_enclosures($line['id']);
337 "title" => $line["title"],
338 "link" => $line["link"],
339 "labels" => get_article_labels($line['id']),
340 "unread" => sql_bool_to_bool($line["unread"]),
341 "marked" => sql_bool_to_bool($line["marked"]),
342 "published" => sql_bool_to_bool($line["published"]),
343 "comments" => $line["comments"],
344 "author" => $line["author"],
345 "updated" => (int) strtotime($line["updated"]),
346 "content" => $line["content"],
347 "feed_id" => $line["feed_id"],
348 "attachments" => $attachments,
349 "score" => (int)$line["score"],
350 "feed_title" => $line["feed_title"],
351 "note" => $line["note"],
352 "lang" => $line["lang"]
355 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_API) as $p) {
356 $article = $p->hook_render_article_api(array("article" => $article));
360 array_push($articles, $article);
365 $this->wrap(self::STATUS_OK, $articles);
367 $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE'));
371 function getConfig() {
373 "icons_dir" => ICONS_DIR,
374 "icons_url" => ICONS_URL);
376 $config["daemon_is_running"] = file_is_locked("update_daemon.lock");
378 $result = $this->dbh->query("SELECT COUNT(*) AS cf FROM
379 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
381 $num_feeds = $this->dbh->fetch_result($result, 0, "cf");
383 $config["num_feeds"] = (int)$num_feeds;
385 $this->wrap(self::STATUS_OK, $config);
388 function updateFeed() {
389 require_once "include/rssfuncs.php";
391 $feed_id = (int) $this->dbh->escape_string($_REQUEST["feed_id"]);
393 update_rss_feed($feed_id, true);
395 $this->wrap(self::STATUS_OK, array("status" => "OK"));
398 function catchupFeed() {
399 $feed_id = $this->dbh->escape_string($_REQUEST["feed_id"]);
400 $is_cat = $this->dbh->escape_string($_REQUEST["is_cat"]);
402 catchup_feed($feed_id, $is_cat);
404 $this->wrap(self::STATUS_OK, array("status" => "OK"));
408 $pref_name = $this->dbh->escape_string($_REQUEST["pref_name"]);
410 $this->wrap(self::STATUS_OK, array("value" => get_pref($pref_name)));
413 function getLabels() {
414 //$article_ids = array_filter(explode(",", $this->dbh->escape_string($_REQUEST["article_ids"])), is_numeric);
416 $article_id = (int)$_REQUEST['article_id'];
420 $result = $this->dbh->query("SELECT id, caption, fg_color, bg_color
422 WHERE owner_uid = '".$_SESSION['uid']."' ORDER BY caption");
425 $article_labels = get_article_labels($article_id);
427 $article_labels = array();
429 while ($line = $this->dbh->fetch_assoc($result)) {
432 foreach ($article_labels as $al) {
433 if (feed_to_label_id($al[0]) == $line['id']) {
439 array_push($rv, array(
440 "id" => (int)label_to_feed_id($line['id']),
441 "caption" => $line['caption'],
442 "fg_color" => $line['fg_color'],
443 "bg_color" => $line['bg_color'],
444 "checked" => $checked));
447 $this->wrap(self::STATUS_OK, $rv);
450 function setArticleLabel() {
452 $article_ids = array_filter(explode(",", $this->dbh->escape_string($_REQUEST["article_ids"])), is_numeric);
453 $label_id = (int) $this->dbh->escape_string($_REQUEST['label_id']);
454 $assign = (bool) $this->dbh->escape_string($_REQUEST['assign']) == "true";
456 $label = $this->dbh->escape_string(label_find_caption(
457 feed_to_label_id($label_id), $_SESSION["uid"]));
463 foreach ($article_ids as $id) {
466 label_add_article($id, $label, $_SESSION["uid"]);
468 label_remove_article($id, $label, $_SESSION["uid"]);
475 $this->wrap(self::STATUS_OK, array("status" => "OK",
476 "updated" => $num_updated));
480 function index($method) {
481 $plugin = PluginHost::getInstance()->get_api_method(strtolower($method));
483 if ($plugin && method_exists($plugin, $method)) {
484 $reply = $plugin->$method();
486 $this->wrap($reply[0], $reply[1]);
489 $this->wrap(self::STATUS_ERR, array("error" => 'UNKNOWN_METHOD', "method" => $method));
493 function shareToPublished() {
494 $title = $this->dbh->escape_string(strip_tags($_REQUEST["title"]));
495 $url = $this->dbh->escape_string(strip_tags($_REQUEST["url"]));
496 $content = $this->dbh->escape_string(strip_tags($_REQUEST["content"]));
498 if (Article::create_published_article($title, $url, $content, "", $_SESSION["uid"])) {
499 $this->wrap(self::STATUS_OK, array("status" => 'OK'));
501 $this->wrap(self::STATUS_ERR, array("error" => 'Publishing failed'));
505 static function api_get_feeds($cat_id, $unread_only, $limit, $offset, $include_nested = false) {
511 if ($cat_id == -4 || $cat_id == -2) {
512 $counters = getLabelCounters(true);
514 foreach (array_values($counters) as $cv) {
516 $unread = $cv["counter"];
518 if ($unread || !$unread_only) {
521 "id" => (int) $cv["id"],
522 "title" => $cv["description"],
523 "unread" => $cv["counter"],
527 array_push($feeds, $row);
534 if ($cat_id == -4 || $cat_id == -1) {
535 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
536 $unread = getFeedUnread($i);
538 if ($unread || !$unread_only) {
539 $title = getFeedTitle($i);
547 array_push($feeds, $row);
555 if ($include_nested && $cat_id) {
556 $result = db_query("SELECT
557 id, title FROM ttrss_feed_categories
558 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
559 " ORDER BY id, title");
561 while ($line = db_fetch_assoc($result)) {
562 $unread = getFeedUnread($line["id"], true) +
563 getCategoryChildrenUnread($line["id"]);
565 if ($unread || !$unread_only) {
567 "id" => (int) $line["id"],
568 "title" => $line["title"],
572 array_push($feeds, $row);
580 $limit_qpart = "LIMIT $limit OFFSET $offset";
585 if ($cat_id == -4 || $cat_id == -3) {
586 $result = db_query("SELECT
587 id, feed_url, cat_id, title, order_id, ".
588 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
589 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
590 " ORDER BY cat_id, title " . $limit_qpart);
594 $cat_qpart = "cat_id = '$cat_id'";
596 $cat_qpart = "cat_id IS NULL";
598 $result = db_query("SELECT
599 id, feed_url, cat_id, title, order_id, ".
600 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
601 FROM ttrss_feeds WHERE
602 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
603 " ORDER BY cat_id, title " . $limit_qpart);
606 while ($line = db_fetch_assoc($result)) {
608 $unread = getFeedUnread($line["id"]);
610 $has_icon = feed_has_icon($line['id']);
612 if ($unread || !$unread_only) {
615 "feed_url" => $line["feed_url"],
616 "title" => $line["title"],
617 "id" => (int)$line["id"],
618 "unread" => (int)$unread,
619 "has_icon" => $has_icon,
620 "cat_id" => (int)$line["cat_id"],
621 "last_updated" => (int) strtotime($line["last_updated"]),
622 "order_id" => (int) $line["order_id"],
625 array_push($feeds, $row);
632 static function api_get_headlines($feed_id, $limit, $offset,
633 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
634 $include_attachments, $since_id,
635 $search = "", $search_mode = "",
636 $include_nested = false, $sanitize_content = true, $force_update = false) {
638 if ($force_update && $feed_id > 0 && is_numeric($feed_id)) {
639 // Update the feed if required with some basic flood control
642 "SELECT cache_images,".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
643 FROM ttrss_feeds WHERE id = '$feed_id'");
645 if (db_num_rows($result) != 0) {
646 $last_updated = strtotime(db_fetch_result($result, 0, "last_updated"));
647 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
649 if (!$cache_images && time() - $last_updated > 120) {
650 include "rssfuncs.php";
651 update_rss_feed($feed_id, true, true);
653 db_query("UPDATE ttrss_feeds SET last_updated = '1970-01-01', last_update_started = '1970-01-01'
654 WHERE id = '$feed_id'");
659 $qfh_ret = queryFeedHeadlines($feed_id, $limit,
660 $view_mode, $is_cat, $search, $search_mode,
661 $order, $offset, 0, false, $since_id, $include_nested);
663 $result = $qfh_ret[0];
664 $feed_title = $qfh_ret[1];
666 $headlines = array();
668 while ($line = db_fetch_assoc($result)) {
669 $line["content_preview"] = truncate_string(strip_tags($line["content"]), 100);
670 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
671 $line = $p->hook_query_headlines($line, 100, true);
674 $is_updated = ($line["last_read"] == "" &&
675 ($line["unread"] != "t" && $line["unread"] != "1"));
677 $tags = explode(",", $line["tag_cache"]);
679 $label_cache = $line["label_cache"];
683 $label_cache = json_decode($label_cache, true);
686 if ($label_cache["no-labels"] == 1)
689 $labels = $label_cache;
693 if (!is_array($labels)) $labels = get_article_labels($line["id"]);
695 //if (!$tags) $tags = get_article_tags($line["id"]);
696 //if (!$labels) $labels = get_article_labels($line["id"]);
698 $headline_row = array(
699 "id" => (int)$line["id"],
700 "unread" => sql_bool_to_bool($line["unread"]),
701 "marked" => sql_bool_to_bool($line["marked"]),
702 "published" => sql_bool_to_bool($line["published"]),
703 "updated" => (int) strtotime($line["updated"]),
704 "is_updated" => $is_updated,
705 "title" => $line["title"],
706 "link" => $line["link"],
707 "feed_id" => $line["feed_id"],
711 if ($include_attachments)
712 $headline_row['attachments'] = get_article_enclosures(
716 $headline_row["excerpt"] = $line["content_preview"];
720 if ($sanitize_content) {
721 $headline_row["content"] = sanitize(
723 sql_bool_to_bool($line['hide_images']),
724 false, $line["site_url"], false, $line["id"]);
726 $headline_row["content"] = $line["content"];
730 // unify label output to ease parsing
731 if ($labels["no-labels"] == 1) $labels = array();
733 $headline_row["labels"] = $labels;
735 $headline_row["feed_title"] = $line["feed_title"] ? $line["feed_title"] :
738 $headline_row["comments_count"] = (int)$line["num_comments"];
739 $headline_row["comments_link"] = $line["comments"];
741 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
743 $headline_row["author"] = $line["author"];
745 $headline_row["score"] = (int)$line["score"];
746 $headline_row["note"] = $line["note"];
747 $headline_row["lang"] = $line["lang"];
749 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_API) as $p) {
750 $headline_row = $p->hook_render_article_api(array("headline" => $headline_row));
753 array_push($headlines, $headline_row);
759 function unsubscribeFeed() {
760 $feed_id = (int) $this->dbh->escape_string($_REQUEST["feed_id"]);
762 $result = $this->dbh->query("SELECT id FROM ttrss_feeds WHERE
763 id = '$feed_id' AND owner_uid = ".$_SESSION["uid"]);
765 if ($this->dbh->num_rows($result) != 0) {
766 Pref_Feeds::remove_feed($feed_id, $_SESSION["uid"]);
767 $this->wrap(self::STATUS_OK, array("status" => "OK"));
769 $this->wrap(self::STATUS_ERR, array("error" => "FEED_NOT_FOUND"));
773 function subscribeToFeed() {
774 $feed_url = $this->dbh->escape_string($_REQUEST["feed_url"]);
775 $category_id = (int) $this->dbh->escape_string($_REQUEST["category_id"]);
776 $login = $this->dbh->escape_string($_REQUEST["login"]);
777 $password = $this->dbh->escape_string($_REQUEST["password"]);
780 $rc = subscribe_to_feed($feed_url, $category_id, $login, $password);
782 $this->wrap(self::STATUS_OK, array("status" => $rc));
784 $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE'));
788 function getFeedTree() {
789 $include_empty = sql_bool_to_bool($_REQUEST['include_empty']);
791 $pf = new Pref_Feeds($_REQUEST);
793 $_REQUEST['mode'] = 2;
794 $_REQUEST['force_show_empty'] = $include_empty;
797 $data = $pf->makefeedtree();
798 $this->wrap(self::STATUS_OK, array("categories" => $data));
800 $this->wrap(self::STATUS_ERR, array("error" =>
801 'UNABLE_TO_INSTANTIATE_OBJECT'));
806 // only works for labels or uncategorized for the time being
807 private function isCategoryEmpty($id) {
810 $result = $this->dbh->query("SELECT COUNT(*) AS count FROM ttrss_labels2
811 WHERE owner_uid = " . $_SESSION["uid"]);
813 return $this->dbh->fetch_result($result, 0, "count") == 0;
815 } else if ($id == 0) {
816 $result = $this->dbh->query("SELECT COUNT(*) AS count FROM ttrss_feeds
817 WHERE cat_id IS NULL AND owner_uid = " . $_SESSION["uid"]);
819 return $this->dbh->fetch_result($result, 0, "count") == 0;