2020-11-01 01:26:11 +00:00
< ? php
/** @ license MIT
* Copyright 2017 J . King , Dustin Wilson et al .
* See LICENSE and AUTHORS files for details */
declare ( strict_types = 1 );
namespace JKingWeb\Arsse\REST\Miniflux ;
use JKingWeb\Arsse\Arsse ;
2020-12-02 23:00:27 +00:00
use JKingWeb\Arsse\Feed ;
use JKingWeb\Arsse\Feed\Exception as FeedException ;
2020-11-01 01:26:11 +00:00
use JKingWeb\Arsse\AbstractException ;
2020-11-30 15:52:32 +00:00
use JKingWeb\Arsse\Db\ExceptionInput ;
2020-11-01 01:26:11 +00:00
use JKingWeb\Arsse\Misc\HTTP ;
2020-12-08 20:34:31 +00:00
use JKingWeb\Arsse\Misc\Date ;
2020-12-02 23:00:27 +00:00
use JKingWeb\Arsse\Misc\ValueInfo as V ;
2020-11-01 01:26:11 +00:00
use JKingWeb\Arsse\REST\Exception ;
2020-11-23 14:31:50 +00:00
use JKingWeb\Arsse\User\ExceptionConflict as UserException ;
2020-11-01 01:26:11 +00:00
use Psr\Http\Message\ServerRequestInterface ;
use Psr\Http\Message\ResponseInterface ;
use Laminas\Diactoros\Response\EmptyResponse ;
2020-12-02 23:00:27 +00:00
use Laminas\Diactoros\Response\JsonResponse as Response ;
2020-11-01 01:26:11 +00:00
class V1 extends \JKingWeb\Arsse\REST\AbstractHandler {
2020-12-02 23:00:27 +00:00
public const VERSION = " 2.0.25 " ;
2020-12-01 17:08:45 +00:00
protected const ACCEPTED_TYPES_OPML = [ " application/xml " , " text/xml " , " text/x-opml " ];
protected const ACCEPTED_TYPES_JSON = [ " application/json " ];
2020-11-30 15:52:32 +00:00
protected const TOKEN_LENGTH = 32 ;
2020-12-02 23:00:27 +00:00
protected const VALID_JSON = [
'url' => " string " ,
'username' => " string " ,
'password' => " string " ,
'user_agent' => " string " ,
];
2020-12-08 20:34:31 +00:00
protected const PATHS = [
2020-11-01 01:26:11 +00:00
'/categories' => [ 'GET' => " getCategories " , 'POST' => " createCategory " ],
'/categories/1' => [ 'PUT' => " updateCategory " , 'DELETE' => " deleteCategory " ],
'/discover' => [ 'POST' => " discoverSubscriptions " ],
'/entries' => [ 'GET' => " getEntries " , 'PUT' => " updateEntries " ],
'/entries/1' => [ 'GET' => " getEntry " ],
'/entries/1/bookmark' => [ 'PUT' => " toggleEntryBookmark " ],
'/export' => [ 'GET' => " opmlExport " ],
'/feeds' => [ 'GET' => " getFeeds " , 'POST' => " createFeed " ],
2020-12-08 20:34:31 +00:00
'/feeds/1' => [ 'GET' => " getFeed " , 'PUT' => " updateFeed " , 'DELETE' => " removeFeed " ],
2020-11-01 01:26:11 +00:00
'/feeds/1/entries/1' => [ 'GET' => " getFeedEntry " ],
'/feeds/1/entries' => [ 'GET' => " getFeedEntries " ],
'/feeds/1/icon' => [ 'GET' => " getFeedIcon " ],
'/feeds/1/refresh' => [ 'PUT' => " refreshFeed " ],
'/feeds/refresh' => [ 'PUT' => " refreshAllFeeds " ],
'/import' => [ 'POST' => " opmlImport " ],
'/me' => [ 'GET' => " getCurrentUser " ],
'/users' => [ 'GET' => " getUsers " , 'POST' => " createUser " ],
2020-12-08 20:34:31 +00:00
'/users/1' => [ 'GET' => " getUserByNum " , 'PUT' => " updateUserByNum " , 'DELETE' => " deleteUser " ],
'/users/*' => [ 'GET' => " getUserById " ],
];
protected const ADMIN_FUNCTIONS = [
'getUsers' => true ,
'getUserByNum' => true ,
'getUserById' => true ,
'createUser' => true ,
'updateUserByNum' => true ,
'deleteUser' => true ,
2020-11-01 01:26:11 +00:00
];
public function __construct () {
}
2020-12-10 04:39:29 +00:00
/** @codeCoverageIgnore */
protected function now () : \DateTimeImmutable {
return Date :: normalize ( " now " );
}
2020-11-23 14:31:50 +00:00
protected function authenticate ( ServerRequestInterface $req ) : bool {
// first check any tokens; this is what Miniflux does
2020-11-30 15:52:32 +00:00
if ( $req -> hasHeader ( " X-Auth-Token " )) {
$t = $req -> getHeader ( " X-Auth-Token " )[ 0 ]; // consider only the first token
if ( strlen ( $t )) { // and only if it is not blank
2020-11-23 14:31:50 +00:00
try {
$d = Arsse :: $db -> tokenLookup ( " miniflux.login " , $t );
} catch ( ExceptionInput $e ) {
return false ;
}
2020-11-30 15:52:32 +00:00
Arsse :: $user -> id = $d [ 'user' ];
2020-11-23 14:31:50 +00:00
return true ;
}
}
// next check HTTP auth
2020-11-01 01:26:11 +00:00
if ( $req -> getAttribute ( " authenticated " , false )) {
Arsse :: $user -> id = $req -> getAttribute ( " authenticatedUser " );
2020-11-30 15:52:32 +00:00
return true ;
2020-11-23 14:31:50 +00:00
}
return false ;
}
2020-12-08 20:34:31 +00:00
protected function isAdmin () : bool {
return ( bool ) Arsse :: $user -> propertiesGet ( Arsse :: $user -> id , false )[ 'admin' ];
}
2020-11-23 14:31:50 +00:00
public function dispatch ( ServerRequestInterface $req ) : ResponseInterface {
// try to authenticate
if ( ! $this -> authenticate ( $req )) {
return new ErrorResponse ( " 401 " , 401 );
2020-11-01 01:26:11 +00:00
}
// get the request path only; this is assumed to already be normalized
$target = parse_url ( $req -> getRequestTarget ())[ 'path' ] ? ? " " ;
2020-11-02 00:09:17 +00:00
$method = $req -> getMethod ();
2020-11-01 01:26:11 +00:00
// handle HTTP OPTIONS requests
2020-11-02 00:09:17 +00:00
if ( $method === " OPTIONS " ) {
2020-11-01 01:26:11 +00:00
return $this -> handleHTTPOptions ( $target );
}
2020-11-02 00:09:17 +00:00
$func = $this -> chooseCall ( $target , $method );
2020-12-01 16:06:29 +00:00
if ( $func instanceof ResponseInterface ) {
return $func ;
}
2020-12-08 20:34:31 +00:00
if (( self :: ADMIN_FUNCTIONS [ $func ] ? ? false ) && ! $this -> isAdmin ()) {
return new ErrorResponse ( " 403 " , 403 );
}
2020-12-02 23:00:27 +00:00
$data = [];
$query = [];
2020-11-02 00:09:17 +00:00
if ( $func === " opmlImport " ) {
if ( ! HTTP :: matchType ( $req , " " , ... [ self :: ACCEPTED_TYPES_OPML ])) {
2020-11-30 15:52:32 +00:00
return new ErrorResponse ( " " , 415 , [ 'Accept' => implode ( " , " , self :: ACCEPTED_TYPES_OPML )]);
2020-11-02 00:09:17 +00:00
}
$data = ( string ) $req -> getBody ();
} elseif ( $method === " POST " || $method === " PUT " ) {
2020-11-30 15:52:32 +00:00
$data = @ json_decode (( string ) $req -> getBody (), true );
2020-11-02 00:09:17 +00:00
if ( json_last_error () !== \JSON_ERROR_NONE ) {
// if the body could not be parsed as JSON, return "400 Bad Request"
2020-11-23 14:31:50 +00:00
return new ErrorResponse ([ " invalidBodyJSON " , json_last_error_msg ()], 400 );
2020-11-02 00:09:17 +00:00
}
2020-12-02 23:00:27 +00:00
$data = $this -> normalizeBody (( array ) $data );
if ( $data instanceof ResponseInterface ) {
return $data ;
}
} elseif ( $method === " GET " ) {
$query = $req -> getQueryParams ();
2020-11-02 00:09:17 +00:00
}
try {
$path = explode ( " / " , ltrim ( $target , " / " ));
2020-12-02 23:00:27 +00:00
return $this -> $func ( $path , $query , $data );
2020-11-02 00:09:17 +00:00
// @codeCoverageIgnoreStart
} catch ( Exception $e ) {
// if there was a REST exception return 400
return new EmptyResponse ( 400 );
} catch ( AbstractException $e ) {
// if there was any other Arsse exception return 500
return new EmptyResponse ( 500 );
}
// @codeCoverageIgnoreEnd
2020-11-01 01:26:11 +00:00
}
protected function normalizePathIds ( string $url ) : string {
$path = explode ( " / " , $url );
// any path components which are database IDs (integers greater than zero) should be replaced with "1", for easier comparison (we don't care about the specific ID)
for ( $a = 0 ; $a < sizeof ( $path ); $a ++ ) {
2020-12-02 23:00:27 +00:00
if ( V :: id ( $path [ $a ])) {
2020-11-01 01:26:11 +00:00
$path [ $a ] = " 1 " ;
}
}
2020-11-02 00:09:17 +00:00
// handle special case "Get User By User Name", which can have any non-numeric string, non-empty as the last component
if ( sizeof ( $path ) === 3 && $path [ 0 ] === " " && $path [ 1 ] === " users " && ! preg_match ( " /^(?: \ d+)? $ / " , $path [ 2 ])) {
$path [ 2 ] = " * " ;
}
2020-11-01 01:26:11 +00:00
return implode ( " / " , $path );
}
protected function handleHTTPOptions ( string $url ) : ResponseInterface {
// normalize the URL path: change any IDs to 1 for easier comparison
$url = $this -> normalizePathIDs ( $url );
2020-12-08 20:34:31 +00:00
if ( isset ( self :: PATHS [ $url ])) {
2020-11-01 01:26:11 +00:00
// if the path is supported, respond with the allowed methods and other metadata
2020-12-08 20:34:31 +00:00
$allowed = array_keys ( self :: PATHS [ $url ]);
2020-11-01 01:26:11 +00:00
// if GET is allowed, so is HEAD
if ( in_array ( " GET " , $allowed )) {
array_unshift ( $allowed , " HEAD " );
}
return new EmptyResponse ( 204 , [
2020-12-01 17:08:45 +00:00
'Allow' => implode ( " , " , $allowed ),
2020-11-02 00:09:17 +00:00
'Accept' => implode ( " , " , $url === " /import " ? self :: ACCEPTED_TYPES_OPML : self :: ACCEPTED_TYPES_JSON ),
2020-11-01 01:26:11 +00:00
]);
} else {
// if the path is not supported, return 404
return new EmptyResponse ( 404 );
}
}
2020-12-01 16:06:29 +00:00
protected function chooseCall ( string $url , string $method ) {
2020-11-01 01:26:11 +00:00
// // normalize the URL path: change any IDs to 1 for easier comparison
$url = $this -> normalizePathIds ( $url );
// normalize the HTTP method to uppercase
$method = strtoupper ( $method );
// we now evaluate the supplied URL against every supported path for the selected scope
// the URL is evaluated as an array so as to avoid decoded escapes turning invalid URLs into valid ones
2020-12-08 20:34:31 +00:00
if ( isset ( self :: PATHS [ $url ])) {
2020-11-01 01:26:11 +00:00
// if the path is supported, make sure the method is allowed
2020-12-08 20:34:31 +00:00
if ( isset ( self :: PATHS [ $url ][ $method ])) {
2020-11-02 00:09:17 +00:00
// if it is allowed, return the object method to run, assuming the method exists
2020-12-08 20:34:31 +00:00
assert ( method_exists ( $this , self :: PATHS [ $url ][ $method ]), new \Exception ( " Method is not implemented " ));
return self :: PATHS [ $url ][ $method ];
2020-11-01 01:26:11 +00:00
} else {
// otherwise return 405
2020-12-08 20:34:31 +00:00
return new EmptyResponse ( 405 , [ 'Allow' => implode ( " , " , array_keys ( self :: PATHS [ $url ]))]);
2020-11-01 01:26:11 +00:00
}
} else {
// if the path is not supported, return 404
2020-12-01 16:06:29 +00:00
return new EmptyResponse ( 404 );
2020-11-01 01:26:11 +00:00
}
}
2020-11-23 14:31:50 +00:00
2020-12-02 23:00:27 +00:00
protected function normalizeBody ( array $body ) {
// Miniflux does not attempt to coerce values into different types
foreach ( self :: VALID_JSON as $k => $t ) {
if ( ! isset ( $body [ $k ])) {
$body [ $k ] = null ;
} elseif ( gettype ( $body [ $k ]) !== $t ) {
return new ErrorResponse ([ " invalidInputType " , 'field' => $k , 'expected' => $t , 'actual' => gettype ( $body [ $k ])]);
}
}
return $body ;
}
2020-12-08 20:34:31 +00:00
protected function listUsers ( array $users , bool $reportMissing ) : array {
$out = [];
2020-12-10 04:39:29 +00:00
$now = Date :: transform ( $this -> now (), " iso8601m " );
2020-12-08 20:34:31 +00:00
foreach ( $users as $u ) {
try {
$info = Arsse :: $user -> propertiesGet ( $u , true );
} catch ( UserException $e ) {
if ( $reportMissing ) {
throw $e ;
} else {
continue ;
}
}
$out [] = [
'id' => $info [ 'num' ],
'username' => $u ,
'is_admin' => $info [ 'admin' ] ? ? false ,
'theme' => $info [ 'theme' ] ? ? " light_serif " ,
'language' => $info [ 'lang' ] ? ? " en_US " ,
'timezone' => $info [ 'tz' ] ? ? " UTC " ,
'entry_sorting_direction' => ( $info [ 'sort_asc' ] ? ? false ) ? " asc " : " desc " ,
'entries_per_page' => $info [ 'page_size' ] ? ? 100 ,
'keyboard_shortcuts' => $info [ 'shortcuts' ] ? ? true ,
'show_reading_time' => $info [ 'reading_time' ] ? ? true ,
'last_login_at' => $now ,
'entry_swipe' => $info [ 'swipe' ] ? ? true ,
'extra' => [
'custom_css' => $info [ 'stylesheet' ] ? ? " " ,
],
];
}
return $out ;
}
2020-12-02 23:00:27 +00:00
protected function discoverSubscriptions ( array $path , array $query , array $data ) {
try {
$list = Feed :: discoverAll (( string ) $data [ 'url' ], ( string ) $data [ 'username' ], ( string ) $data [ 'password' ]);
} catch ( FeedException $e ) {
$msg = [
10502 => " fetch404 " ,
10506 => " fetch403 " ,
10507 => " fetch401 " ,
][ $e -> getCode ()] ? ? " fetchOther " ;
return new ErrorResponse ( $msg , 500 );
}
$out = [];
foreach ( $list as $url ) {
// TODO: This needs to be refined once PicoFeed is replaced
$out [] = [ 'title' => " Feed " , 'type' => " rss " , 'url' => $url ];
}
return new Response ( $out );
}
2020-12-08 20:34:31 +00:00
protected function getUsers ( array $path , array $query , array $data ) {
return new Response ( $this -> listUsers ( Arsse :: $user -> list (), false ));
}
protected function getUserById ( array $path , array $query , array $data ) {
try {
2020-12-10 04:39:29 +00:00
return new Response ( $this -> listUsers ([ $path [ 1 ]], true )[ 0 ] ? ? new \stdClass );
2020-12-08 20:34:31 +00:00
} catch ( UserException $e ) {
return new ErrorResponse ( " 404 " , 404 );
}
}
protected function getUserByNum ( array $path , array $query , array $data ) {
return $this -> listUsers ([ Arsse :: $user -> id ], false )[ 0 ] ? ? [];
}
protected function getCurrentUser ( array $path , array $query , array $data ) {
return new Response ( $this -> listUsers ([ Arsse :: $user -> id ], false )[ 0 ] ? ? new \stdClass );
}
2020-11-23 14:31:50 +00:00
public static function tokenGenerate ( string $user , string $label ) : string {
2020-11-30 15:52:32 +00:00
// Miniflux produces tokens in base64url alphabet
$t = str_replace ([ " + " , " / " ], [ " - " , " _ " ], base64_encode ( random_bytes ( self :: TOKEN_LENGTH )));
2020-11-23 14:31:50 +00:00
return Arsse :: $db -> tokenCreate ( $user , " miniflux.login " , $t , null , $label );
}
public static function tokenList ( string $user ) : array {
if ( ! Arsse :: $db -> userExists ( $user )) {
throw new UserException ( " doesNotExist " , [ " action " => __FUNCTION__ , " user " => $user ]);
}
$out = [];
foreach ( Arsse :: $db -> tokenList ( $user , " miniflux.login " ) as $r ) {
$out [] = [ 'label' => $r [ 'data' ], 'id' => $r [ 'id' ]];
}
return $out ;
}
2020-11-01 01:26:11 +00:00
}