Take back my plugin - fix a bunch of bugs which counters not updating,

clean things up, sync back with ttrss source
This commit is contained in:
Grant Pannell
2017-05-16 01:10:32 +09:30
parent a7fd1e385e
commit 6d26584d34
3 changed files with 976 additions and 1028 deletions

View File

@@ -1,7 +1,4 @@
<?php <?php
// v1.4.7
class FeverAPI extends Handler { class FeverAPI extends Handler {
const API_LEVEL = 3; const API_LEVEL = 3;
@@ -9,45 +6,184 @@ class FeverAPI extends Handler {
const STATUS_OK = 1; const STATUS_OK = 1;
const STATUS_ERR = 0; const STATUS_ERR = 0;
// debugging only functions with JSON // enable if you need some debug output in your tinytinyrss root
const DEBUG = false; // enable if you need some debug output in your tinytinyrss root const DEBUG = FALSE;
const DEBUG_USER = 0; // your user id you need to debug - look it up in your mysql database and set it to a value bigger than 0 // your user id you need to debug - look it up in your mysql database and set it to a value bigger than 0
const DEBUG_FILE = './debug_fever.txt'; // the file for debugging output const DEBUG_USER = 0;
const ADD_ATTACHED_FILES = 1; //add link in bottom for attached files
private $ID_HACK_FOR_MRREADER = 0; const PLUGIN_NAME = "Fever";
private $id_hack = FALSE;
// add link in bottom for attached files
private $add_attached_files = TRUE;
// output as xml or json
private $xml; private $xml;
// find the user in the db with a particular api key
private function setUser()
{
$apikey = isset($_REQUEST["api_key"]) ? $_REQUEST["api_key"] : "";
// Login for Mr. Reader
if (strlen($apikey) <= 0 &&
isset($_REQUEST["action"]) &&
$_REQUEST["action"] === "login" &&
isset($_REQUEST["email"])&&
isset($_REQUEST["password"]))
{
$email = $_REQUEST["email"];
$password = $_REQUEST["password"];
$apikey = strtoupper(md5($email . ":" . $password));
setcookie("fever_auth", $apikey, time() + max(SESSION_COOKIE_LIFETIME, 60 * 60 * 24));
}
// override for Mr.Reader when doing some stuff
if (strlen($apikey) <= 0 && isset($_COOKIE["fever_auth"]))
{
$apikey = $_COOKIE['fever_auth'];
}
if (strlen($apikey) > 0)
{
$result = $this->dbh->query("SELECT owner_uid, content FROM ttrss_plugin_storage
WHERE name = '". $this->dbh->escape_string(self::PLUGIN_NAME) . "'");
while ($line = $this->dbh->fetch_assoc($result))
{
$obj = unserialize($line["content"], array("allowed_classes" => FALSE));
if ($obj &&
isset($obj["password"]) &&
strtolower($obj["password"]) === strtolower($apikey))
{
$_SESSION["uid"] = $line["owner_uid"];
break;
}
}
if (self::DEBUG_USER > 0)
{
$_SESSION["uid"] = self::DEBUG_USER; // always authenticate and set debug user
}
}
}
// set whether xml or json
private function setXml()
{
$this->xml = false;
if (isset($_REQUEST["api"]))
{
if (strtolower($_REQUEST["api"]) === "xml")
{
$this->xml = true;
}
}
}
private function setIdHack()
{
$this->id_hack = false;
$user_agent = false;
if (isset($_SERVER["HTTP_USER_AGENT"]))
{
$user_agent = $_SERVER["HTTP_USER_AGENT"];
}
// Check for all client in Android except ReadKit in Mac, Mr. Reader and Dalvik
if ($user_agent &&
(strpos($user_agent, "Dalvik") !== FALSE ||
strpos($user_agent, "ReadKit") !== FALSE ||
strpos($user_agent, "Mr. Reader") !== FALSE))
{
$this->id_hack = true;
}
}
// validate the api_key, user preferences
function before($method) {
/* classes/api.php before */
if (parent::before($method)) {
if (self::DEBUG) {
// add request to debug log
error_log(print_r($_REQUEST, true));
}
// set the user from the db
$this->setUser();
// are we xml or json?
$this->setXml();
// do we need to apply the ID hack
$this->setIdHack();
if ($this->xml)
header("Content-Type: text/xml");
else
header("Content-Type: text/json");
// check we have a valid user
if (!$_SESSION["uid"]) {
$this->wrap(self::STATUS_ERR, array("error" => 'NOT_LOGGED_IN'));
return false;
}
// check if user has api access enabled
if ($_SESSION["uid"] && !get_pref('ENABLE_API_ACCESS')) {
$this->wrap(self::STATUS_ERR, array("error" => 'API_DISABLED'));
return false;
}
return true;
}
return false;
}
// always include api_version, status as 'auth' // always include api_version, status as 'auth'
// output json/xml // output json/xml
function wrap($status, $reply) function wrap($status, $reply)
{ {
/* classes/api.php wrap */
$arr = array("api_version" => self::API_LEVEL, $arr = array("api_version" => self::API_LEVEL,
"auth" => $status); "auth" => $status);
if ($status == self::STATUS_OK)
{
$arr["last_refreshed_on_time"] = $this->lastRefreshedOnTime()."";
if (!empty($reply) && is_array($reply)) if (!empty($reply) && is_array($reply))
{
$arr = array_merge($arr, $reply); $arr = array_merge($arr, $reply);
} }
if ($status == self::STATUS_OK)
{
$arr["last_refreshed_on_time"] = (string)$this->lastRefreshedOnTime();
}
$resp = "";
if ($this->xml) if ($this->xml)
{ {
print $this->array_to_xml($arr); $resp = $this->array_to_xml($arr);
} }
else else
{ {
print json_encode($arr); $resp = json_encode($arr);
if (self::DEBUG) {
// debug output
file_put_contents(self::DEBUG_FILE,'answer : '.json_encode($arr)."\n",FILE_APPEND);
} }
print $resp;
if (self::DEBUG)
{
// debug output
error_log(print_r($resp, true));
} }
} }
// fever supports xml wrapped in <response> tags // fever supports xml wrapped in <response> tags
// TODO: holy crap replace this junk
private function array_to_xml($array, $container = 'response', $is_root = true) private function array_to_xml($array, $container = 'response', $is_root = true)
{ {
if (!is_array($array)) return array_to_xml(array($array)); if (!is_array($array)) return array_to_xml(array($array));
@@ -102,9 +238,9 @@ class FeverAPI extends Handler {
// every authenticated method includes last_refreshed_on_time // every authenticated method includes last_refreshed_on_time
private function lastRefreshedOnTime() private function lastRefreshedOnTime()
{ {
$result = $this->dbh->query("SELECT last_updated $result = $this->dbh->query("SELECT " . SUBSTRING_FOR_DATE . "(last_updated,1,19) AS last_updated
FROM ttrss_feeds FROM ttrss_feeds
WHERE owner_uid = " . $_SESSION["uid"] . " WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'
ORDER BY last_updated DESC"); ORDER BY last_updated DESC");
if ($this->dbh->num_rows($result) > 0) if ($this->dbh->num_rows($result) > 0)
@@ -119,59 +255,6 @@ class FeverAPI extends Handler {
return $last_refreshed_on_time; return $last_refreshed_on_time;
} }
// find the user in the db with a particular api key
private function setUser()
{
$apikey = isset($_REQUEST["api_key"])?$_REQUEST["api_key"]:'';
// here comes Mr.Reader special API for logging in
if ((strlen($apikey)==0)&&
(isset($_REQUEST["action"]))&&
($_REQUEST["action"]=='login')&&
(isset($_REQUEST["email"]))&&
(isset($_REQUEST["password"]))) {
$email = $_REQUEST["email"];
$password = $_REQUEST["password"];
$apikey = strtoupper(md5($email.":".$password));
setcookie('fever_auth',$apikey,time()+60*60*24*30);
if (self::DEBUG) {
// debug output
$output = array();
$output['email'] = $email;
$output['apikey'] = $apikey;
file_put_contents(self::DEBUG_FILE,'auth POST: '.json_encode($output)."\n",FILE_APPEND);
}
}
if ((strlen($apikey)==0)&&isset($_COOKIE['fever_auth'])) { // override for Mr.Reader when doing some stuff
$apikey = $_COOKIE['fever_auth'];
}
if (strlen($apikey)>0)
{
$result = $this->dbh->query("SELECT owner_uid
FROM ttrss_plugin_storage
WHERE content = '".db_escape_string('a:1:{s:8:"password";s:32:"'.strtolower($apikey).'";}') . "'");
if ($this->dbh->num_rows($result) > 0)
{
$_SESSION["uid"] = $this->dbh->fetch_result($result, 0, "owner_uid");
}
if (self::DEBUG_USER>0) {
$_SESSION["uid"] = self::DEBUG_USER; // always authenticate and set debug user
}
}
}
// set whether xml or json
private function setXml()
{
$this->xml = false;
if (isset($_REQUEST["api"]))
{
if (strtolower($_REQUEST["api"]) == "xml")
$this->xml = true;
}
}
private function flattenGroups(&$groupsToGroups, &$groups, &$groupsToTitle, $index) private function flattenGroups(&$groupsToGroups, &$groups, &$groupsToTitle, $index)
{ {
foreach ($groupsToGroups[$index] as $item) foreach ($groupsToGroups[$index] as $item)
@@ -190,7 +273,7 @@ class FeverAPI extends Handler {
$result = $this->dbh->query("SELECT id, title, parent_cat $result = $this->dbh->query("SELECT id, title, parent_cat
FROM ttrss_feed_categories FROM ttrss_feed_categories
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'
ORDER BY order_id ASC"); ORDER BY order_id ASC");
$groupsToGroups = array(); $groupsToGroups = array();
@@ -235,9 +318,9 @@ class FeverAPI extends Handler {
{ {
$feeds = array(); $feeds = array();
$result = $this->dbh->query("SELECT id, title, feed_url, site_url, last_updated $result = $this->dbh->query("SELECT id, title, feed_url, site_url, " . SUBSTRING_FOR_DATE . "(last_updated,1,19) AS last_updated
FROM ttrss_feeds FROM ttrss_feeds
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'
ORDER BY order_id ASC"); ORDER BY order_id ASC");
while ($line = $this->dbh->fetch_assoc($result)) while ($line = $this->dbh->fetch_assoc($result))
@@ -247,7 +330,7 @@ class FeverAPI extends Handler {
"title" => $line["title"], "title" => $line["title"],
"url" => $line["feed_url"], "url" => $line["feed_url"],
"site_url" => $line["site_url"], "site_url" => $line["site_url"],
"is_spark" => 0, // unsported "is_spark" => 0, // unsupported
"last_updated_on_time" => strtotime($line["last_updated"]) "last_updated_on_time" => strtotime($line["last_updated"])
)); ));
} }
@@ -260,7 +343,7 @@ class FeverAPI extends Handler {
$result = $this->dbh->query("SELECT id $result = $this->dbh->query("SELECT id
FROM ttrss_feeds FROM ttrss_feeds
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'
ORDER BY order_id ASC"); ORDER BY order_id ASC");
// data = "image/gif;base64,<base64 encoded image> // data = "image/gif;base64,<base64 encoded image>
@@ -287,122 +370,6 @@ class FeverAPI extends Handler {
return $links; return $links;
} }
function rewrite_urls($html) {
libxml_use_internal_errors(true);
$charset_hack = '<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>';
$doc = new DOMDocument();
$doc->loadHTML($charset_hack . $html);
$xpath = new DOMXPath($doc);
$entries = $xpath->query('//*/text()');
foreach ($entries as $entry) {
if (strstr($entry->wholeText, "://") !== false) {
$text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
"<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
if ($text != $entry->wholeText) {
$cdoc = new DOMDocument();
$cdoc->loadHTML($charset_hack . $text);
foreach ($cdoc->childNodes as $cnode) {
$cnode = $doc->importNode($cnode, true);
if ($cnode) {
$entry->parentNode->insertBefore($cnode);
}
}
$entry->parentNode->removeChild($entry);
}
}
}
$node = $doc->getElementsByTagName('body')->item(0);
// http://tt-rss.org/forum/viewtopic.php?f=1&t=970
if ($node)
return $doc->saveXML($node);
else
return $html;
}
function my_sanitize($str, $site_url = false) {
$res = trim($str); if (!$res) return '';
if (strpos($res, "href=") === false)
$res = $this->rewrite_urls($res);
$charset_hack = '<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>';
$res = trim($res); if (!$res) return '';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($charset_hack . $res);
$xpath = new DOMXPath($doc);
$entries = $xpath->query('(//a[@href]|//img[@src])');
foreach ($entries as $entry) {
if ($site_url) {
if ($entry->hasAttribute('href'))
$entry->setAttribute('href',
rewrite_relative_url($site_url, $entry->getAttribute('href')));
if ($entry->hasAttribute('src')) {
$src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
$entry->setAttribute('src', $src);
}
}
if (strtolower($entry->nodeName) == "a") {
$entry->setAttribute("target", "_blank");
}
}
$entries = $xpath->query('//iframe');
foreach ($entries as $entry) {
$entry->setAttribute('sandbox', 'allow-scripts allow-same-origin');
}
$disallowed_attributes = array('id', 'style', 'class');
$entries = $xpath->query('//*');
foreach ($entries as $entry) {
if ($entry->hasAttributes()) {
$attrs_to_remove = array();
foreach ($entry->attributes as $attr) {
if (strpos($attr->nodeName, 'on') === 0) { //remove onclick and other on* attributes
array_push($attrs_to_remove, $attr);
}
if (in_array($attr->nodeName, $disallowed_attributes)) {
array_push($attrs_to_remove, $attr);
}
}
foreach ($attrs_to_remove as $attr) {
$entry->removeAttributeNode($attr);
}
}
}
$doc->removeChild($doc->firstChild); //remove doctype
$res = $doc->saveHTML();
return $res;
}
function formatBytes($bytes, $precision = 2) { function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB'); $units = array('B', 'KB', 'MB', 'GB', 'TB');
@@ -423,7 +390,7 @@ class FeverAPI extends Handler {
$items = array(); $items = array();
$item_limit = 50; $item_limit = 50;
$where = " owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND ref_id = id "; $where = " owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND ref_id = id ";
if (isset($_REQUEST["feed_ids"]) || isset($_REQUEST["group_ids"])) // added 0.3 if (isset($_REQUEST["feed_ids"]) || isset($_REQUEST["group_ids"])) // added 0.3
{ {
@@ -440,7 +407,7 @@ class FeverAPI extends Handler {
foreach ($group_ids as $group_id) foreach ($group_ids as $group_id)
{ {
if (is_numeric($group_id)) if (is_numeric($group_id))
$groups_query .= db_escape_string(intval($group_id)) . ","; $groups_query .= $this->dbh->escape_string(intval($group_id)) . ",";
else else
$num_group_ids--; $num_group_ids--;
} }
@@ -451,7 +418,7 @@ class FeverAPI extends Handler {
$feeds_in_group_result = $this->dbh->query("SELECT id". $feeds_in_group_result = $this->dbh->query("SELECT id".
"FROM ttrss_feeds". "FROM ttrss_feeds".
"WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' " . $groups_query); "WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' " . $groups_query);
$group_feed_ids = array(); $group_feed_ids = array();
while ($line = $this->dbh->fetch_assoc($feeds_in_group_result)) while ($line = $this->dbh->fetch_assoc($feeds_in_group_result))
@@ -467,7 +434,7 @@ class FeverAPI extends Handler {
foreach ($feed_ids as $feed_id) foreach ($feed_ids as $feed_id)
{ {
if (is_numeric($feed_id)) if (is_numeric($feed_id))
$query.= db_escape_string(intval($feed_id)) . ","; $query.= $this->dbh->escape_string(intval($feed_id)) . ",";
else else
$num_feed_ids--; $num_feed_ids--;
} }
@@ -490,7 +457,7 @@ class FeverAPI extends Handler {
if ($max_id) if ($max_id)
{ {
if (!empty($where)) $where .= " AND "; if (!empty($where)) $where .= " AND ";
$where .= "id < " . db_escape_string($max_id) . " "; $where .= "id < " . $this->dbh->escape_string($max_id) . " ";
} }
else if (empty($where)) else if (empty($where))
{ {
@@ -510,7 +477,7 @@ class FeverAPI extends Handler {
foreach ($item_ids as $item_id) foreach ($item_ids as $item_id)
{ {
if (is_numeric($item_id)) if (is_numeric($item_id))
$query .= db_escape_string(intval($item_id)) . ","; $query .= $this->dbh->escape_string(intval($item_id)) . ",";
else else
$num_ids--; $num_ids--;
} }
@@ -532,10 +499,10 @@ class FeverAPI extends Handler {
if ($since_id) if ($since_id)
{ {
if (!empty($where)) $where .= " AND "; if (!empty($where)) $where .= " AND ";
if ($this->ID_HACK_FOR_MRREADER) { if ($this->id_hack) {
$where .= "id > " . db_escape_string($since_id*1000) . " "; // NASTY hack for Mr. Reader 2.0 on iOS and TinyTiny RSS Fever $where .= "id > " . $this->dbh->escape_string($since_id*1000) . " "; // NASTY hack for Mr. Reader 2.0 on iOS and TinyTiny RSS Fever
} else { } else {
$where .= "id > " . db_escape_string($since_id) . " "; $where .= "id > " . $this->dbh->escape_string($since_id) . " ";
} }
} }
else if (empty($where)) else if (empty($where))
@@ -549,34 +516,44 @@ class FeverAPI extends Handler {
$where .= " LIMIT " . $item_limit; $where .= " LIMIT " . $item_limit;
/* classes/api.php getArticle */
// id, feed_id, title, author, html, url, is_saved, is_read, created_on_time // id, feed_id, title, author, html, url, is_saved, is_read, created_on_time
$result = $this->dbh->query("SELECT ref_id, feed_id, title, link, content, id, marked, unread, author, updated $result = $this->dbh->query("SELECT ref_id, feed_id, title, link, content, id, marked, unread, author,
" . SUBSTRING_FOR_DATE . "(updated,1,16) as updated,
(SELECT site_url FROM ttrss_feeds WHERE id = feed_id) AS site_url,
(SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images
FROM ttrss_entries, ttrss_user_entries FROM ttrss_entries, ttrss_user_entries
WHERE " . $where); WHERE " . $where);
while ($line = $this->dbh->fetch_assoc($result)) while ($line = $this->dbh->fetch_assoc($result))
{ {
$line_content = $this->my_sanitize($line["content"], $line["link"]); $line_content = sanitize(
if (ADD_ATTACHED_FILES){ $line["content"],
sql_bool_to_bool($line['hide_images']),
false, $line["site_url"], false, $line["id"]);
if ($this->add_attached_files){
$enclosures = Article::get_article_enclosures($line["id"]); $enclosures = Article::get_article_enclosures($line["id"]);
if (count($enclosures) > 0) { if (count($enclosures) > 0) {
$line_content .= '<ul type="lower-greek">'; $line_content .= '<ul type="lower-greek">';
foreach ($enclosures as $enclosure) { foreach ($enclosures as $enclosure) {
if (!empty($enclosure['content_url'])) { if (!empty($enclosure["content_url"])) {
$enc_type = ''; $enc_type = "";
if (!empty($enclosure['content_type'])) { if (!empty($enclosure["content_type"])) {
$enc_type = ', '.$enclosure['content_type']; $enc_type = ", " . $enclosure["content_type"];
} }
$enc_size = ''; $enc_size = "";
if (!empty($enclosure['duration'])) { if (!empty($enclosure["duration"])) {
$enc_size = ' , '.$this->formatBytes($enclosure['duration']); $enc_size = " , " . $this->formatBytes($enclosure["duration"]);
} }
$line_content .= '<li><a href="'.$enclosure['content_url'].'" target="_blank">'.basename($enclosure['content_url']).$enc_type.$enc_size.'</a>'.'</li>'; $line_content .= '<li><a href="' . $enclosure["content_url"] . '" target="_blank">' . basename($enclosure["content_url"]) . $enc_type . $enc_size . '</a></li>';
} }
} }
$line_content .= '</ul>'; $line_content .= '</ul>';
} }
} }
array_push($items, array("id" => intval($line["id"]), array_push($items, array("id" => intval($line["id"]),
"feed_id" => intval($line["feed_id"]), "feed_id" => intval($line["feed_id"]),
"title" => $line["title"], "title" => $line["title"],
@@ -597,7 +574,7 @@ class FeverAPI extends Handler {
// number of total items // number of total items
$total_items = 0; $total_items = 0;
$where = " owner_uid = '" . db_escape_string($_SESSION["uid"]) . "'"; $where = " owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'";
$result = $this->dbh->query("SELECT COUNT(ref_id) as total_items $result = $this->dbh->query("SELECT COUNT(ref_id) as total_items
FROM ttrss_user_entries FROM ttrss_user_entries
WHERE " . $where); WHERE " . $where);
@@ -616,7 +593,7 @@ class FeverAPI extends Handler {
$result = $this->dbh->query("SELECT id, cat_id $result = $this->dbh->query("SELECT id, cat_id
FROM ttrss_feeds FROM ttrss_feeds
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'
AND cat_id IS NOT NULL AND cat_id IS NOT NULL
ORDER BY id ASC"); ORDER BY id ASC");
@@ -648,7 +625,7 @@ class FeverAPI extends Handler {
$unreadItemIdsCSV = ""; $unreadItemIdsCSV = "";
$result = $this->dbh->query("SELECT ref_id $result = $this->dbh->query("SELECT ref_id
FROM ttrss_user_entries FROM ttrss_user_entries
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND unread"); // ORDER BY red_id DESC WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND unread = true"); // ORDER BY red_id DESC
while ($line = $this->dbh->fetch_assoc($result)) while ($line = $this->dbh->fetch_assoc($result))
{ {
@@ -664,7 +641,7 @@ class FeverAPI extends Handler {
$savedItemIdsCSV = ""; $savedItemIdsCSV = "";
$result = $this->dbh->query("SELECT ref_id $result = $this->dbh->query("SELECT ref_id
FROM ttrss_user_entries FROM ttrss_user_entries
WHERE owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND marked"); WHERE owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND marked = true");
while ($line = $this->dbh->fetch_assoc($result)) while ($line = $this->dbh->fetch_assoc($result))
{ {
@@ -675,8 +652,14 @@ class FeverAPI extends Handler {
return $savedItemIdsCSV; return $savedItemIdsCSV;
} }
function setItem($id, $field_raw, $mode, $before = 0) function setItem($id, $field_raw, $mode)
{ {
/* classes/api.php updateArticle */
$article_ids = array_filter(explode(",", $this->dbh->escape_string($id)), is_numeric);
$mode = (int) $this->dbh->escape_string($mode);
$field_raw = (int)$this->dbh->escape_string($field_raw);
$field = ""; $field = "";
$set_to = ""; $set_to = "";
@@ -700,11 +683,10 @@ class FeverAPI extends Handler {
break; break;
} }
if ($field && $set_to) if ($field && $set_to && count($article_ids) > 0) {
{ $article_ids = join(", ", $article_ids);
$article_ids = db_escape_string($id);
$result = $this->dbh->query("UPDATE ttrss_user_entries SET $field = $set_to $additional_fields WHERE ref_id IN ($article_ids) AND owner_uid = '" . db_escape_string($_SESSION["uid"]) . "'"); $result = $this->dbh->query("UPDATE ttrss_user_entries SET $field = $set_to $additional_fields WHERE ref_id IN ($article_ids) AND owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "'");
$num_updated = $this->dbh->affected_rows($result); $num_updated = $this->dbh->affected_rows($result);
@@ -741,6 +723,8 @@ class FeverAPI extends Handler {
function setFeed($id, $cat, $before=0) function setFeed($id, $cat, $before=0)
{ {
/* classes/feeds.php catchup_feed */
// if before is zero, set it to now so feeds all items are read from before this point in time // if before is zero, set it to now so feeds all items are read from before this point in time
if ($before == 0) if ($before == 0)
$before = time(); $before = time();
@@ -757,8 +741,8 @@ class FeverAPI extends Handler {
SET unread = false, last_read = NOW() WHERE ref_id IN SET unread = false, last_read = NOW() WHERE ref_id IN
(SELECT id FROM (SELECT id FROM
(SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
AND owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND unread = true AND feed_id IN AND owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND unread = true AND feed_id IN
(SELECT id FROM ttrss_feeds WHERE cat_id IN (" . intval($id) . ")) AND date_entered < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)"); (SELECT id FROM ttrss_feeds WHERE cat_id IN (" . intval($id) . ")) AND updated < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)");
} }
// this is "all" to fever, but internally "all" is -4 // this is "all" to fever, but internally "all" is -4
@@ -769,7 +753,7 @@ class FeverAPI extends Handler {
SET unread = false, last_read = NOW() WHERE ref_id IN SET unread = false, last_read = NOW() WHERE ref_id IN
(SELECT id FROM (SELECT id FROM
(SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
AND owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND unread = true AND date_entered < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)"); AND owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND unread = true AND updated < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)");
} }
} }
// not a category // not a category
@@ -779,10 +763,10 @@ class FeverAPI extends Handler {
SET unread = false, last_read = NOW() WHERE ref_id IN SET unread = false, last_read = NOW() WHERE ref_id IN
(SELECT id FROM (SELECT id FROM
(SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
AND owner_uid = '" . db_escape_string($_SESSION["uid"]) . "' AND unread = true AND feed_id = " . intval($id) . " AND date_entered < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)"); AND owner_uid = '" . $this->dbh->escape_string($_SESSION["uid"]) . "' AND unread = true AND feed_id = " . intval($id) . " AND updated < '" . date("Y-m-d H:i:s", $before) . "' ) as tmp)");
} }
CCache::update($id,$_SESSION["uid"], $cat); CCache::update($id, $_SESSION["uid"], $cat);
} }
} }
@@ -836,18 +820,33 @@ class FeverAPI extends Handler {
if (isset($_REQUEST["mark"], $_REQUEST["as"], $_REQUEST["id"])) if (isset($_REQUEST["mark"], $_REQUEST["as"], $_REQUEST["id"]))
{ {
if (is_numeric($_REQUEST["id"])) foreach (explode(",", $_REQUEST["id"]) as $id) {
$this->markId($id);
}
}
/* classes/api.php index */
if ($_SESSION["uid"])
$this->wrap(self::STATUS_OK, $response_arr);
else if (!$_SESSION["uid"])
$this->wrap(self::STATUS_ERR, array("error" => 'UNKNOWN_METHOD'));
}
function markId($id)
{
if (is_numeric($id))
{ {
$before = (isset($_REQUEST["before"])) ? $_REQUEST["before"] : null; $before = (isset($_REQUEST["before"])) ? $_REQUEST["before"] : null;
if ($before > pow(10,10) ) { if ($before !== null && $before > pow(10,10)) {
$before = round($before / 1000); $before = round($before / 1000);
} }
$method_name = "set" . ucfirst($_REQUEST["mark"]) . "As" . ucfirst($_REQUEST["as"]); $method_name = "set" . ucfirst($_REQUEST["mark"]) . "As" . ucfirst($_REQUEST["as"]);
if (method_exists($this, $method_name)) if (method_exists($this, $method_name))
{ {
$id = intval($_REQUEST["id"]); $this->{$method_name}(intval($id), $before);
$this->{$method_name}($id, $before);
switch($_REQUEST["as"]) switch($_REQUEST["as"])
{ {
case "read": case "read":
@@ -863,57 +862,6 @@ class FeverAPI extends Handler {
} }
} }
} }
if ($_SESSION["uid"])
$this->wrap(self::STATUS_OK, $response_arr);
else if (!$_SESSION["uid"])
$this->wrap(self::STATUS_ERR, NULL);
}
// validate the api_key, user preferences
function before($method) {
// Check for all client in Android except ReadKit in Mac, Mr. Reader and Dalvik
if (strpos($_SERVER['HTTP_USER_AGENT'],"Dalvik") !== false ||
strpos($_SERVER['HTTP_USER_AGENT'],"ReadKit") !== false ||
strpos($_SERVER['HTTP_USER_AGENT'],"Mr. Reader") !== false) {
$this->ID_HACK_FOR_MRREADER = 0;
} else {
$this->ID_HACK_FOR_MRREADER = 1; // and readkit and dalvik...
}
if (parent::before($method)) {
if (self::DEBUG) {
// add request to debug log
file_put_contents(self::DEBUG_FILE,'parameter: '.json_encode($_REQUEST)."\n",FILE_APPEND);
}
// set the user from the db
$this->setUser();
// are we xml or json?
$this->setXml();
if ($this->xml)
header("Content-Type: text/xml");
else
header("Content-Type: application/json");
// check we have a valid user
if (!$_SESSION["uid"]) {
$this->wrap(self::STATUS_ERR, NULL);
return false;
}
// check if user has api access enabled
if ($_SESSION["uid"] && !get_pref('ENABLE_API_ACCESS')) {
$this->wrap(self::STATUS_ERR, NULL);
return false;
}
return true;
}
return false;
}
} }
?> ?>

View File

@@ -6,33 +6,31 @@
exit; exit;
} }
/* api/index.php */
error_reporting(E_ERROR | E_PARSE); error_reporting(E_ERROR | E_PARSE);
$tt_root = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))); require_once "../../config.php";
$tt_root2 = $tt_root;
if (file_exists($tt_root."/config.php")) {
require_once $tt_root."/config.php";
} else { //if (file_exists("../../config.php")) {
$tt_root = "../..";
$tt_root2 = dirname(dirname(dirname(__FILE__)));
require_once $tt_root."/config.php";
}
set_include_path(dirname(__FILE__) . PATH_SEPARATOR . set_include_path(dirname(__FILE__) . PATH_SEPARATOR .
$tt_root2 . PATH_SEPARATOR . dirname(dirname(dirname(__FILE__))) . PATH_SEPARATOR .
$tt_root2 . "/include" . PATH_SEPARATOR . dirname(dirname(dirname(__FILE__))) . "/include" . PATH_SEPARATOR .
get_include_path()); get_include_path());
chdir($tt_root); chdir("../..");
define('TTRSS_SESSION_NAME', 'ttrss_api_sid');
define('NO_SESSION_AUTOSTART', true); define('NO_SESSION_AUTOSTART', true);
require_once "autoload.php"; require_once "autoload.php";
require_once "db.php"; require_once "db.php";
require_once "db-prefs.php"; require_once "db-prefs.php";
require_once "functions.php"; require_once "functions.php";
require_once "sessions.php";
require_once "fever_api.php"; require_once "fever_api.php";
ini_set("session.gc_maxlifetime", 86400);
define('AUTH_DISABLE_OTP', true); define('AUTH_DISABLE_OTP', true);
if (defined('ENABLE_GZIP_OUTPUT') && ENABLE_GZIP_OUTPUT && if (defined('ENABLE_GZIP_OUTPUT') && ENABLE_GZIP_OUTPUT &&
@@ -43,17 +41,27 @@
ob_start(); ob_start();
} }
if ($_REQUEST["sid"]) {
session_id($_REQUEST["sid"]);
@session_start();
} else if (defined('_API_DEBUG_HTTP_ENABLED')) {
@session_start();
}
startup_gettext();
if (!init_plugins()) return; if (!init_plugins()) return;
$handler = new FeverAPI(Db::get(), $_REQUEST); $handler = new FeverAPI($_REQUEST);
if ($handler->before($method)) { if ($handler->before()) {
if (method_exists($handler, 'index')) { if (method_exists($handler, 'index')) {
$handler->index($method); $handler->index();
} }
$handler->after(); $handler->after();
} }
ob_end_flush(); header("Api-Content-Length: " . ob_get_length());
ob_end_flush();
?> ?>

View File

@@ -1,26 +1,20 @@
<?php <?php
class Fever extends Plugin { class Fever extends Plugin {
private $host; private $host;
function about() { function about() {
return array(1.47, return array(2.0,
"Emulates the Fever API for Tiny Tiny RSS", "Emulates the Fever API for Tiny Tiny RSS",
"digitaldj & murphy"); "DigitalDJ & murphy");
} }
function init($host) { function init($host) {
$this->host = $host; $this->host = $host;
$host->add_hook($host::HOOK_PREFS_TAB, $this); $host->add_hook($host::HOOK_PREFS_TAB, $this);
} }
function before($method) { /* plugins/main/init.php hook_prefs_tab */
return true;
}
function csrf_ignore($method) {
return true;
}
function hook_prefs_tab($args) { function hook_prefs_tab($args) {
if ($args != "prefPrefs") return; if ($args != "prefPrefs") return;
@@ -47,15 +41,17 @@ class Fever extends Plugin {
//this.reset(); //this.reset();
} }
</script>"; </script>";
print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pluginhandler\" />";
print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"save\" />"; print_hidden("op", "pluginhandler");
print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"plugin\" value=\"fever\" />"; print_hidden("method", "save");
print_hidden("plugin", "fever");
print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\" type=\"password\" name=\"password\" />"; print "<input dojoType=\"dijit.form.ValidationTextBox\" required=\"1\" type=\"password\" name=\"password\" />";
print "<button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Set Password") . "</button>"; print "<button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Set Password") . "</button>";
print "</form>"; print "</form>";
print "<p>" . __("To login with the Fever API, set your server details in your favourite RSS application to: ") . get_self_url_prefix() . "/plugins/fever/" . "</p>"; print "<p>" . __("To login with the Fever API, set your server details in your favourite RSS application to: ") . get_self_url_prefix() . "/plugins/fever/" . "</p>";
print "<p>" . __("Additional details can be found at ") . "<a href=\"http://www.feedafever.com/api\" target=\"_blank\">http://www.feedafever.com/api</a></p>"; print "<p>" . __("Additional details can be found at ") . "<a href=\"http://www.feedafever.com/api\" target=\"_blank\">https://feedafever.com/api</a></p>";
print "<p>" . __("Note: Due to the limitations of the API and some RSS clients (for example, Reeder on iOS), some features are unavailable: \"Special\" Feeds (Published / Tags / Labels / Fresh / Recent), Nested Categories (hierarchy is flattened)") . "</p>"; print "<p>" . __("Note: Due to the limitations of the API and some RSS clients (for example, Reeder on iOS), some features are unavailable: \"Special\" Feeds (Published / Tags / Labels / Fresh / Recent), Nested Categories (hierarchy is flattened)") . "</p>";
@@ -76,10 +72,6 @@ class Fever extends Plugin {
} }
} }
function after() {
}
function api_version() { function api_version() {
return 2; return 2;
} }