diff options
| author | 2023-01-29 18:53:51 +0100 | |
|---|---|---|
| committer | 2023-01-29 18:53:51 +0100 | |
| commit | 4f316b2ed397bb331ef89f2cd2d8ce92a725ccba (patch) | |
| tree | 6d74cfa825724d483d43b23fdf90aadb1e46262a /p | |
| parent | 2303b29e68d16fbf0a173ab2b4b0ac736041905c (diff) | |
PHPStan level 9 for ./p/ and lib_rss.php (#5049)
And app/FreshRSS.php
Contributes to https://github.com/FreshRSS/FreshRSS/issues/4112
Diffstat (limited to 'p')
| -rw-r--r-- | p/api/fever.php | 190 | ||||
| -rw-r--r-- | p/api/greader.php | 1861 | ||||
| -rw-r--r-- | p/api/pshb.php | 17 | ||||
| -rw-r--r-- | p/ext.php | 16 | ||||
| -rw-r--r-- | p/f.php | 2 | ||||
| -rwxr-xr-x | p/i/index.php | 4 |
6 files changed, 1095 insertions, 995 deletions
diff --git a/p/api/fever.php b/p/api/fever.php index 13907f16d..88bd05d81 100644 --- a/p/api/fever.php +++ b/p/api/fever.php @@ -17,7 +17,7 @@ require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader FreshRSS_Context::initSystem(); // check if API is enabled globally -if (!FreshRSS_Context::$system_conf->api_enabled) { +if (FreshRSS_Context::$system_conf == null || !FreshRSS_Context::$system_conf->api_enabled) { Minz_Log::warning('Fever API: service unavailable!'); Minz_Log::debug('Fever API: serviceUnavailable() ' . debugInfo(), API_LOG); header('HTTP/1.1 503 Service Unavailable'); @@ -29,12 +29,9 @@ Minz_Session::init('FreshRSS', true); // ================================================================================================ // <Debug> -$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576); +$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: '';; -/** - * @return string - */ -function debugInfo() { +function debugInfo(): string { if (function_exists('getallheaders')) { $ALL_HEADERS = getallheaders(); } else { //nginx http://php.net/getallheaders#84262 @@ -62,8 +59,12 @@ function debugInfo() { //Minz_Log::debug(debugInfo(), API_LOG); // </Debug> -class FeverDAO extends Minz_ModelPdo +final class FeverDAO extends Minz_ModelPdo { + /** + * @param array<string|int> $values + * @param array<string,string|int> $bindArray + */ protected function bindParamArray(string $prefix, array $values, array &$bindArray): string { $str = ''; for ($i = 0; $i < count($values); $i++) { @@ -74,9 +75,11 @@ class FeverDAO extends Minz_ModelPdo } /** + * @param array<string|int> $feed_ids + * @param array<string> $entry_ids * @return FreshRSS_Entry[] */ - public function findEntries(array $feed_ids, array $entry_ids, string $max_id, string $since_id) { + public function findEntries(array $feed_ids, array $entry_ids, string $max_id, string $since_id): array { $values = array(); $order = ''; $entryDAO = FreshRSS_Factory::createEntryDao(); @@ -110,36 +113,34 @@ class FeverDAO extends Minz_ModelPdo $sql .= ' LIMIT 50'; $stm = $this->pdo->prepare($sql); - $stm->execute($values); - $result = $stm->fetchAll(PDO::FETCH_ASSOC); + if ($stm && $stm->execute($values)) { + $result = $stm->fetchAll(PDO::FETCH_ASSOC); - $entries = array(); - foreach ($result as $dao) { - $entries[] = FreshRSS_Entry::fromArray($dao); - } + $entries = array(); + foreach ($result as $dao) { + $entries[] = FreshRSS_Entry::fromArray($dao); + } - return $entries; + return $entries; + } + return []; } } /** * Class FeverAPI */ -class FeverAPI +final class FeverAPI { const API_LEVEL = 3; const STATUS_OK = 1; const STATUS_ERR = 0; - /** - * @var FreshRSS_EntryDAO|null - */ - private $entryDAO = null; + /** @var FreshRSS_EntryDAO */ + private $entryDAO; - /** - * @var FreshRSS_FeedDAO|null - */ - private $feedDAO = null; + /** @var FreshRSS_FeedDAO */ + private $feedDAO; /** * Authenticate the user @@ -148,6 +149,9 @@ class FeverAPI * your FreshRSS "username:your-api-password" combination */ private function authenticate(): bool { + if (FreshRSS_Context::$system_conf === null) { + throw new FreshRSS_Context_Exception('System configuration not initialised!'); + } FreshRSS_Context::$user_conf = null; Minz_Session::_param('currentUser'); $feverKey = empty($_POST['api_key']) ? '' : substr(trim($_POST['api_key']), 0, 128); @@ -176,16 +180,12 @@ class FeverAPI public function isAuthenticatedApiUser(): bool { $this->authenticate(); - - if (FreshRSS_Context::$user_conf !== null) { - return true; - } - - return false; + return FreshRSS_Context::$user_conf !== null; } /** * This does all the processing, since the fever api does not have a specific variable that specifies the operation + * @return array<string,mixed> * @throws Exception */ public function process(): array { @@ -226,37 +226,54 @@ class FeverAPI $response_arr['saved_item_ids'] = $this->getSavedItemIds(); } - $id = isset($_REQUEST['id']) ? '' . $_REQUEST['id'] : ''; - if (isset($_REQUEST['mark'], $_REQUEST['as'], $_REQUEST['id']) && ctype_digit($id)) { - $method_name = 'set' . ucfirst($_REQUEST['mark']) . 'As' . ucfirst($_REQUEST['as']); - $allowedMethods = array( - 'setFeedAsRead', 'setGroupAsRead', 'setItemAsRead', - 'setItemAsSaved', 'setItemAsUnread', 'setItemAsUnsaved' - ); - if (in_array($method_name, $allowedMethods)) { - switch (strtolower($_REQUEST['mark'])) { - case 'item': - $this->{$method_name}($id); - break; - case 'feed': - case 'group': - $before = $_REQUEST['before'] ?? ''; - $this->{$method_name}($id, $before); - break; - } + if (isset($_REQUEST['mark'], $_REQUEST['as'], $_REQUEST['id']) && ctype_digit($_REQUEST['id'])) { + $id = intval($_REQUEST['id']); + $before = intval($_REQUEST['before'] ?? '0'); + switch (strtolower($_REQUEST['mark'])) { + case 'item': + switch ($_REQUEST['as']) { + case 'read': + $this->setItemAsRead($id); + break; + case 'saved': + $this->setItemAsSaved($id); + break; + case 'unread': + $this->setItemAsUnread($id); + break; + case 'unsaved': + $this->setItemAsUnsaved($id); + break; + } + break; + case 'feed': + switch ($_REQUEST['as']) { + case 'read': + $this->setFeedAsRead($id, $before); + break; + } + break; + case 'group': + switch ($_REQUEST['as']) { + case 'read': + $this->setFeedAsRead($id, $before); + break; + } + break; + } - switch ($_REQUEST['as']) { - case 'read': - case 'unread': - $response_arr['unread_item_ids'] = $this->getUnreadItemIds(); - break; + switch ($_REQUEST['as']) { + case 'read': + case 'unread': + $response_arr['unread_item_ids'] = $this->getUnreadItemIds(); + break; - case 'saved': - case 'unsaved': - $response_arr['saved_item_ids'] = $this->getSavedItemIds(); - break; - } + case 'saved': + case 'unsaved': + $response_arr['saved_item_ids'] = $this->getSavedItemIds(); + break; } + } return $response_arr; @@ -264,6 +281,7 @@ class FeverAPI /** * Returns the complete JSON, with 'api_version' and status as 'auth'. + * @param array<string,mixed> $reply */ public function wrap(int $status, array $reply = array()): string { $arr = array('api_version' => self::API_LEVEL, 'auth' => $status); @@ -273,7 +291,7 @@ class FeverAPI $arr = array_merge($arr, $reply); } - return json_encode($arr); + return json_encode($arr) ?: ''; } /** @@ -292,6 +310,7 @@ class FeverAPI return $lastUpdate; } + /** @return array<array<string,string|int>> */ protected function getFeeds(): array { $feeds = array(); $myFeeds = $this->feedDAO->listFeeds(); @@ -312,6 +331,7 @@ class FeverAPI return $feeds; } + /** @return array<array<string,int|string>> */ protected function getGroups(): array { $groups = array(); @@ -329,12 +349,15 @@ class FeverAPI return $groups; } + /** @return array<array<string,int|string>> */ protected function getFavicons(): array { + if (FreshRSS_Context::$system_conf == null) { + return []; + } $favicons = array(); $salt = FreshRSS_Context::$system_conf->salt; $myFeeds = $this->feedDAO->listFeeds(); - /** @var FreshRSS_Feed $feed */ foreach ($myFeeds as $feed) { $id = hash('crc32b', $salt . $feed->url()); @@ -345,7 +368,7 @@ class FeverAPI $favicons[] = array( 'id' => $feed->id(), - 'data' => image_type_to_mime_type(exif_imagetype($filename)) . ';base64,' . base64_encode(file_get_contents($filename)) + 'data' => image_type_to_mime_type(exif_imagetype($filename) ?: 0) . ';base64,' . base64_encode(file_get_contents($filename) ?: '') ); } @@ -359,17 +382,19 @@ class FeverAPI return $this->entryDAO->count(); } + /** + * @return array<array<string,int|string>> + */ protected function getFeedsGroup(): array { $groups = array(); $ids = array(); $myFeeds = $this->feedDAO->listFeeds(); - /** @var FreshRSS_Feed $feed */ foreach ($myFeeds as $feed) { $ids[$feed->categoryId()][] = $feed->id(); } - foreach($ids as $category => $feedIds) { + foreach ($ids as $category => $feedIds) { $groups[] = array( 'group_id' => $category, 'feed_ids' => implode(',', $feedIds) @@ -381,13 +406,14 @@ class FeverAPI /** * AFAIK there is no 'hot links' alternative in FreshRSS + * @return array<string> */ protected function getLinks(): array { return array(); } /** - * @param array $ids + * @param array<string> $ids */ protected function entriesToIdList(array $ids = array()): string { return implode(',', array_values($ids)); @@ -398,10 +424,7 @@ class FeverAPI return $this->entriesToIdList($entries); } - /** - * @return string - */ - protected function getSavedItemIds() { + protected function getSavedItemIds(): string { $entries = $this->entryDAO->listIdsWhere('a', '', FreshRSS_Entry::STATE_FAVORITE, 'ASC', 0); return $this->entriesToIdList($entries); } @@ -409,31 +432,32 @@ class FeverAPI /** * @return integer|false */ - protected function setItemAsRead($id) { + protected function setItemAsRead(int $id) { return $this->entryDAO->markRead($id, true); } /** * @return integer|false */ - protected function setItemAsUnread($id) { + protected function setItemAsUnread(int $id) { return $this->entryDAO->markRead($id, false); } /** * @return integer|false */ - protected function setItemAsSaved($id) { + protected function setItemAsSaved(int $id) { return $this->entryDAO->markFavorite($id, true); } /** * @return integer|false */ - protected function setItemAsUnsaved($id) { + protected function setItemAsUnsaved(int $id) { return $this->entryDAO->markFavorite($id, false); } + /** @return array<array<string,string|int>> */ protected function getItems(): array { $feed_ids = array(); $entry_ids = array(); @@ -448,16 +472,16 @@ class FeverAPI if (isset($_REQUEST['group_ids'])) { $categoryDAO = FreshRSS_Factory::createCategoryDao(); $group_ids = explode(',', $_REQUEST['group_ids']); + $feeds = []; foreach ($group_ids as $id) { - /** @var FreshRSS_Category $category */ $category = $categoryDAO->searchById($id); //TODO: Transform to SQL query without loop! Consider FreshRSS_CategoryDAO::listCategories(true) - /** @var FreshRSS_Feed $feed */ - $feeds = []; + if ($category == null) { + continue; + } foreach ($category->feeds() as $feed) { $feeds[] = $feed->id(); } } - $feed_ids = array_unique($feeds); } } @@ -511,30 +535,30 @@ class FeverAPI /** * TODO replace by a dynamic fetch for id <= $before timestamp */ - protected function convertBeforeToId(string $beforeTimestamp): string { - return $beforeTimestamp == '0' ? '0' : $beforeTimestamp . '000000'; + protected function convertBeforeToId(int $beforeTimestamp): string { + return $beforeTimestamp == 0 ? '0' : $beforeTimestamp . '000000'; } /** * @return integer|false */ - protected function setFeedAsRead(string $id, string $before) { + protected function setFeedAsRead(int $id, int $before) { $before = $this->convertBeforeToId($before); - return $this->entryDAO->markReadFeed(intval($id), $before); + return $this->entryDAO->markReadFeed($id, $before); } /** * @return integer|false */ - protected function setGroupAsRead(string $id, string $before) { + protected function setGroupAsRead(int $id, int $before) { $before = $this->convertBeforeToId($before); // special case to mark all items as read - if ($id == '0') { + if ($id == 0) { return $this->entryDAO->markReadEntries($before); } - return $this->entryDAO->markReadCat(intval($id), $before); + return $this->entryDAO->markReadCat($id, $before); } } diff --git a/p/api/greader.php b/p/api/greader.php index a3dad880e..5412bcf1d 100644 --- a/p/api/greader.php +++ b/p/api/greader.php @@ -26,23 +26,15 @@ Server-side API compatible with Google Reader API layer 2 require(__DIR__ . '/../../constants.php'); require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader -$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576); +$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: ''; if (PHP_INT_SIZE < 8) { //32-bit - /** - * @param string $hex - * @return string - */ - function hex2dec($hex) { + function hex2dec(string $hex): string { if (!ctype_xdigit($hex)) return '0'; return gmp_strval(gmp_init($hex, 16), 10); } } else { //64-bit - /** - * @param string $hex - * @return string - */ - function hex2dec($hex) { + function hex2dec(string $hex): string { if (!ctype_xdigit($hex)) return '0'; return '' . hexdec($hex); } @@ -50,24 +42,28 @@ if (PHP_INT_SIZE < 8) { //32-bit define('JSON_OPTIONS', JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -function headerVariable($headerName, $varName) { +function headerVariable(string $headerName, string $varName): string { $header = ''; $upName = 'HTTP_' . strtoupper($headerName); if (isset($_SERVER[$upName])) { - $header = $_SERVER[$upName]; + $header = '' . $_SERVER[$upName]; } elseif (isset($_SERVER['REDIRECT_' . $upName])) { - $header = $_SERVER['REDIRECT_' . $upName]; + $header = '' . $_SERVER['REDIRECT_' . $upName]; } elseif (function_exists('getallheaders')) { $ALL_HEADERS = getallheaders(); if (isset($ALL_HEADERS[$headerName])) { - $header = $ALL_HEADERS[$headerName]; + $header = '' . $ALL_HEADERS[$headerName]; } } parse_str($header, $pairs); - return isset($pairs[$varName]) ? $pairs[$varName] : null; + if (empty($pairs[$varName])) { + return ''; + } + return is_string($pairs[$varName]) ? $pairs[$varName] : ''; } -function multiplePosts($name) { +/** @return array<string> */ +function multiplePosts(string $name): array { //https://bugs.php.net/bug.php?id=51633 global $ORIGINAL_INPUT; $inputs = explode('&', $ORIGINAL_INPUT); @@ -82,10 +78,7 @@ function multiplePosts($name) { return $result; } -/** - * @return string - */ -function debugInfo() { +function debugInfo(): string { if (function_exists('getallheaders')) { $ALL_HEADERS = getallheaders(); } else { //nginx http://php.net/getallheaders#84262 @@ -109,1027 +102,1107 @@ function debugInfo() { return print_r($log, true); } -function badRequest() { - Minz_Log::warning('GReader API: ' . __METHOD__, API_LOG); - Minz_Log::debug('badRequest() ' . debugInfo(), API_LOG); - header('HTTP/1.1 400 Bad Request'); - header('Content-Type: text/plain; charset=UTF-8'); - die('Bad Request!'); -} +final class GReaderAPI { -function unauthorized() { - Minz_Log::warning('GReader API: ' . __METHOD__, API_LOG); - Minz_Log::debug('unauthorized() ' . debugInfo(), API_LOG); - header('HTTP/1.1 401 Unauthorized'); - header('Content-Type: text/plain; charset=UTF-8'); - header('Google-Bad-Token: true'); - die('Unauthorized!'); -} + /** @return never */ + private static function badRequest() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('HTTP/1.1 400 Bad Request'); + header('Content-Type: text/plain; charset=UTF-8'); + die('Bad Request!'); + } -function notImplemented() { - Minz_Log::warning('GReader API: ' . __METHOD__, API_LOG); - Minz_Log::debug('notImplemented() ' . debugInfo(), API_LOG); - header('HTTP/1.1 501 Not Implemented'); - header('Content-Type: text/plain; charset=UTF-8'); - die('Not Implemented!'); -} + /** @return never */ + private static function unauthorized() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('HTTP/1.1 401 Unauthorized'); + header('Content-Type: text/plain; charset=UTF-8'); + header('Google-Bad-Token: true'); + die('Unauthorized!'); + } -function serviceUnavailable() { - Minz_Log::warning('GReader API: ' . __METHOD__, API_LOG); - Minz_Log::debug('serviceUnavailable() ' . debugInfo(), API_LOG); - header('HTTP/1.1 503 Service Unavailable'); - header('Content-Type: text/plain; charset=UTF-8'); - die('Service Unavailable!'); -} + /** @return never */ + private static function internalServerError() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('HTTP/1.1 500 Internal Server Error'); + header('Content-Type: text/plain; charset=UTF-8'); + die('Internal Server Error!'); + } -function checkCompatibility() { - Minz_Log::warning('GReader API: ' . __METHOD__, API_LOG); - Minz_Log::debug('checkCompatibility() ' . debugInfo(), API_LOG); - header('Content-Type: text/plain; charset=UTF-8'); - if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) { - die('FAIL 64-bit or GMP extension! Wrong PHP configuration.'); + /** @return never */ + private static function notImplemented() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('HTTP/1.1 501 Not Implemented'); + header('Content-Type: text/plain; charset=UTF-8'); + die('Not Implemented!'); } - $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); - if ($headerAuth == '') { - die('FAIL get HTTP Authorization header! Wrong Web server configuration.'); + + /** @return never */ + private static function serviceUnavailable() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('HTTP/1.1 503 Service Unavailable'); + header('Content-Type: text/plain; charset=UTF-8'); + die('Service Unavailable!'); } - echo 'PASS'; - exit(); -} -function authorizationToUser() { - //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external - $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); - if ($headerAuth != '') { - $headerAuthX = explode('/', $headerAuth, 2); - if (count($headerAuthX) === 2) { - $user = $headerAuthX[0]; - if (FreshRSS_user_Controller::checkUsername($user)) { - FreshRSS_Context::initUser($user); - if (FreshRSS_Context::$user_conf == null) { - Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.'); - unauthorized(); - } - if (!FreshRSS_Context::$user_conf->enabled) { - Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.'); - unauthorized(); - } - if ($headerAuthX[1] === sha1(FreshRSS_Context::$system_conf->salt . $user . FreshRSS_Context::$user_conf->apiPasswordHash)) { - return $user; + /** @return never */ + private static function checkCompatibility() { + Minz_Log::warning(__METHOD__, API_LOG); + Minz_Log::debug(__METHOD__ . ' ' . debugInfo(), API_LOG); + header('Content-Type: text/plain; charset=UTF-8'); + if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) { + die('FAIL 64-bit or GMP extension! Wrong PHP configuration.'); + } + $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); + if ($headerAuth == '') { + die('FAIL get HTTP Authorization header! Wrong Web server configuration.'); + } + echo 'PASS'; + exit(); + } + + private static function authorizationToUser(): string { + //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external + $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); + if ($headerAuth != '') { + $headerAuthX = explode('/', $headerAuth, 2); + if (count($headerAuthX) === 2) { + $user = $headerAuthX[0]; + if (FreshRSS_user_Controller::checkUsername($user)) { + FreshRSS_Context::initUser($user); + if (FreshRSS_Context::$user_conf == null || FreshRSS_Context::$system_conf == null) { + Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.'); + self::unauthorized(); + } + if (!FreshRSS_Context::$user_conf->enabled) { + Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.'); + self::unauthorized(); + } + if ($headerAuthX[1] === sha1(FreshRSS_Context::$system_conf->salt . $user . FreshRSS_Context::$user_conf->apiPasswordHash)) { + return $user; + } else { + Minz_Log::warning('Invalid API authorisation for user ' . $user); + self::unauthorized(); + } } else { - Minz_Log::warning('Invalid API authorisation for user ' . $user); - unauthorized(); + self::badRequest(); } - } else { - badRequest(); } } + return ''; } - return ''; -} -function clientLogin($email, $pass) { - //https://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html - if (FreshRSS_user_Controller::checkUsername($email)) { - FreshRSS_Context::initUser($email); - if (FreshRSS_Context::$user_conf == null) { - Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.'); - unauthorized(); - } + /** @return never */ + private static function clientLogin(string $email, string $pass) { + //https://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html + if (FreshRSS_user_Controller::checkUsername($email)) { + FreshRSS_Context::initUser($email); + if (FreshRSS_Context::$user_conf == null || FreshRSS_Context::$system_conf == null) { + Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.'); + self::unauthorized(); + } - if (FreshRSS_Context::$user_conf->apiPasswordHash != '' && password_verify($pass, FreshRSS_Context::$user_conf->apiPasswordHash)) { - header('Content-Type: text/plain; charset=UTF-8'); - $auth = $email . '/' . sha1(FreshRSS_Context::$system_conf->salt . $email . FreshRSS_Context::$user_conf->apiPasswordHash); - echo 'SID=', $auth, "\n", - 'LSID=null', "\n", //Vienna RSS - 'Auth=', $auth, "\n"; - exit(); + if (FreshRSS_Context::$user_conf->apiPasswordHash != '' && password_verify($pass, FreshRSS_Context::$user_conf->apiPasswordHash)) { + header('Content-Type: text/plain; charset=UTF-8'); + $auth = $email . '/' . sha1(FreshRSS_Context::$system_conf->salt . $email . FreshRSS_Context::$user_conf->apiPasswordHash); + echo 'SID=', $auth, "\n", + 'LSID=null', "\n", //Vienna RSS + 'Auth=', $auth, "\n"; + exit(); + } else { + Minz_Log::warning('Password API mismatch for user ' . $email); + self::unauthorized(); + } } else { - Minz_Log::warning('Password API mismatch for user ' . $email); - unauthorized(); + self::badRequest(); } - } else { - badRequest(); } - die(); -} -function token($conf) { -//http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/ -//https://github.com/ericmann/gReader-Library/blob/master/greader.class.php - $user = Minz_Session::param('currentUser', '_'); - //Minz_Log::debug('token('. $user . ')', API_LOG); //TODO: Implement real token that expires - $token = str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters - echo $token, "\n"; - exit(); -} + /** + * @return never + */ + private static function token(?FreshRSS_UserConfiguration $conf) { + //http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/ + //https://github.com/ericmann/gReader-Library/blob/master/greader.class.php + if ($conf == null || FreshRSS_Context::$system_conf == null) { + self::unauthorized(); + } + $user = Minz_Session::param('currentUser', '_'); + //Minz_Log::debug('token('. $user . ')', API_LOG); //TODO: Implement real token that expires + $token = str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters + echo $token, "\n"; + exit(); + } -function checkToken(FreshRSS_UserConfiguration $conf, string $token) { -//http://code.google.com/p/google-reader-api/wiki/ActionToken - $user = Minz_Session::param('currentUser', '_'); - if ($user !== '_' && ( //TODO: Check security consequences - $token == '' || //FeedMe - $token === 'x')) { //Reeder - return true; + private static function checkToken(?FreshRSS_UserConfiguration $conf, string $token): bool { + //http://code.google.com/p/google-reader-api/wiki/ActionToken + if ($conf == null || FreshRSS_Context::$system_conf == null) { + self::unauthorized(); + } + $user = Minz_Session::param('currentUser', '_'); + if ($user !== '_' && ( //TODO: Check security consequences + $token == '' || //FeedMe + $token === 'x')) { //Reeder + return true; + } + if ($token === str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z')) { + return true; + } + Minz_Log::warning('Invalid POST token: ' . $token, API_LOG); + self::unauthorized(); } - if ($token === str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z')) { - return true; + + /** @return never */ + private static function userInfo() { + //https://github.com/theoldreader/api#user-info + if (FreshRSS_Context::$user_conf == null) { + self::unauthorized(); + } + $user = Minz_Session::param('currentUser', '_'); + exit(json_encode(array( + 'userId' => $user, + 'userName' => $user, + 'userProfileId' => $user, + 'userEmail' => FreshRSS_Context::$user_conf->mail_login, + ), JSON_OPTIONS)); } - Minz_Log::warning('Invalid POST token: ' . $token, API_LOG); - unauthorized(); -} -function userInfo() { - //https://github.com/theoldreader/api#user-info - $user = Minz_Session::param('currentUser', '_'); - exit(json_encode(array( - 'userId' => $user, - 'userName' => $user, - 'userProfileId' => $user, - 'userEmail' => FreshRSS_Context::$user_conf->mail_login, - ), JSON_OPTIONS)); -} + /** @return never */ + private static function tagList() { + header('Content-Type: application/json; charset=UTF-8'); -function tagList() { - header('Content-Type: application/json; charset=UTF-8'); - - $tags = array( - array('id' => 'user/-/state/com.google/starred'), - //array('id' => 'user/-/state/com.google/broadcast', 'sortid' => '2'), - ); - - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $categories = $categoryDAO->listCategories(true, false); - foreach ($categories as $cat) { - $tags[] = array( - 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), - //'sortid' => $cat->name(), - 'type' => 'folder', //Inoreader + $tags = array( + array('id' => 'user/-/state/com.google/starred'), + //array('id' => 'user/-/state/com.google/broadcast', 'sortid' => '2'), ); - } - $tagDAO = FreshRSS_Factory::createTagDao(); - $labels = $tagDAO->listTags(true); - foreach ($labels as $label) { - $tags[] = array( - 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES), - //'sortid' => $label->name(), - 'type' => 'tag', //Inoreader - 'unread_count' => $label->nbUnread(), //Inoreader - ); - } + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + $categories = $categoryDAO->listCategories(true, false); + foreach ($categories as $cat) { + $tags[] = array( + 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), + //'sortid' => $cat->name(), + 'type' => 'folder', //Inoreader + ); + } - echo json_encode(array('tags' => $tags), JSON_OPTIONS), "\n"; - exit(); -} + $tagDAO = FreshRSS_Factory::createTagDao(); + $labels = $tagDAO->listTags(true); + foreach ($labels as $label) { + $tags[] = array( + 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES), + //'sortid' => $label->name(), + 'type' => 'tag', //Inoreader + 'unread_count' => $label->nbUnread(), //Inoreader + ); + } -function subscriptionExport() { - $user = Minz_Session::param('currentUser', '_'); - $export_service = new FreshRSS_Export_Service($user); - list($filename, $content) = $export_service->generateOpml(); - header('Content-Type: application/xml; charset=UTF-8'); - header('Content-disposition: attachment; filename="' . $filename . '"'); - echo $content; - exit(); -} + echo json_encode(array('tags' => $tags), JSON_OPTIONS), "\n"; + exit(); + } -function subscriptionImport($opml) { - $user = Minz_Session::param('currentUser', '_'); - $importService = new FreshRSS_Import_Service($user); - $importService->importOpml($opml); - if ($importService->lastStatus()) { - list($nbUpdatedFeeds, $feed, $nbNewArticles) = FreshRSS_feed_Controller::actualizeFeed(0, '', true); - invalidateHttpCache($user); - exit('OK'); - } else { - badRequest(); + /** @return never */ + private static function subscriptionExport() { + $user = '' . Minz_Session::param('currentUser', '_'); + $export_service = new FreshRSS_Export_Service($user); + list($filename, $content) = $export_service->generateOpml(); + header('Content-Type: application/xml; charset=UTF-8'); + header('Content-disposition: attachment; filename="' . $filename . '"'); + echo $content; + exit(); } -} -function subscriptionList() { - header('Content-Type: application/json; charset=UTF-8'); - - $salt = FreshRSS_Context::$system_conf->salt; - $faviconsUrl = Minz_Url::display('/f.php?', '', true); - $faviconsUrl = str_replace('/api/greader.php/reader/api/0/subscription', '', $faviconsUrl); //Security if base_url is not set properly - $subscriptions = array(); - - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - foreach ($categoryDAO->listCategories(true, true) as $cat) { - foreach ($cat->feeds() as $feed) { - $subscriptions[] = [ - 'id' => 'feed/' . $feed->id(), - 'title' => escapeToUnicodeAlternative($feed->name(), true), - 'categories' => [ - [ - 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), - 'label' => htmlspecialchars_decode($cat->name(), ENT_QUOTES), - ], - ], - //'sortid' => $feed->name(), - //'firstitemmsec' => 0, - 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES), - 'htmlUrl' => htmlspecialchars_decode($feed->website(), ENT_QUOTES), - 'iconUrl' => $faviconsUrl . hash('crc32b', $salt . $feed->url()), - ]; + /** @return never */ + private static function subscriptionImport(string $opml) { + $user = '' . Minz_Session::param('currentUser', '_'); + $importService = new FreshRSS_Import_Service($user); + $importService->importOpml($opml); + if ($importService->lastStatus()) { + FreshRSS_feed_Controller::actualizeFeed(0, '', true); + invalidateHttpCache($user); + exit('OK'); + } else { + self::badRequest(); } } - echo json_encode(array('subscriptions' => $subscriptions), JSON_OPTIONS), "\n"; - exit(); -} + /** @return never */ + private static function subscriptionList() { + if (FreshRSS_Context::$system_conf == null) { + self::internalServerError(); + } + header('Content-Type: application/json; charset=UTF-8'); + $salt = FreshRSS_Context::$system_conf->salt; + $faviconsUrl = Minz_Url::display('/f.php?', '', true); + $faviconsUrl = str_replace('/api/greader.php/reader/api/0/subscription', '', $faviconsUrl); //Security if base_url is not set properly + $subscriptions = array(); -function subscriptionEdit($streamNames, $titles, $action, $add = '', $remove = '') { - //https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki - switch ($action) { - case 'subscribe': - case 'unsubscribe': - case 'edit': - break; - default: - badRequest(); - } - $addCatId = 0; - $categoryDAO = null; - if ($add != '' || $remove != '') { $categoryDAO = FreshRSS_Factory::createCategoryDao(); - } - $c_name = ''; - if ($add != '' && strpos($add, 'user/') === 0) { //user/-/label/Example ; user/username/label/Example - if (strpos($add, 'user/-/label/') === 0) { - $c_name = substr($add, 13); - } else { - $user = Minz_Session::param('currentUser', '_'); - $prefix = 'user/' . $user . '/label/'; - if (strpos($add, $prefix) === 0) { - $c_name = substr($add, strlen($prefix)); - } else { - $c_name = ''; + foreach ($categoryDAO->listCategories(true, true) as $cat) { + foreach ($cat->feeds() as $feed) { + $subscriptions[] = [ + 'id' => 'feed/' . $feed->id(), + 'title' => escapeToUnicodeAlternative($feed->name(), true), + 'categories' => [ + [ + 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), + 'label' => htmlspecialchars_decode($cat->name(), ENT_QUOTES), + ], + ], + //'sortid' => $feed->name(), + //'firstitemmsec' => 0, + 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES), + 'htmlUrl' => htmlspecialchars_decode($feed->website(), ENT_QUOTES), + 'iconUrl' => $faviconsUrl . hash('crc32b', $salt . $feed->url()), + ]; } } - $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8'); - $cat = $categoryDAO->searchByName($c_name); - $addCatId = $cat == null ? 0 : $cat->id(); - } elseif ($remove != '' && strpos($remove, 'user/-/label/') === 0) { - $addCatId = 1; //Default category - } - $feedDAO = FreshRSS_Factory::createFeedDao(); - if (!is_array($streamNames) || count($streamNames) < 1) { - badRequest(); + + echo json_encode(array('subscriptions' => $subscriptions), JSON_OPTIONS), "\n"; + exit(); } - for ($i = count($streamNames) - 1; $i >= 0; $i--) { - $streamUrl = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338 - if (strpos($streamUrl, 'feed/') === 0) { - $streamUrl = preg_replace('%^(feed/)+%', '', $streamUrl); - $feedId = 0; - if (ctype_digit($streamUrl)) { - if ($action === 'subscribe') { - continue; - } - $feedId = $streamUrl; + + /** + * @param array<string> $streamNames + * @param array<string> $titles + * @return never + */ + private static function subscriptionEdit(array $streamNames, array $titles, string $action, string $add = '', string $remove = '') { + //https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki + switch ($action) { + case 'subscribe': + case 'unsubscribe': + case 'edit': + break; + default: + self::badRequest(); + } + $addCatId = 0; + $categoryDAO = null; + if ($add != '' || $remove != '') { + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + } + $c_name = ''; + if ($add != '' && strpos($add, 'user/') === 0) { //user/-/label/Example ; user/username/label/Example + if (strpos($add, 'user/-/label/') === 0) { + $c_name = substr($add, 13); } else { - $streamUrl = htmlspecialchars($streamUrl, ENT_COMPAT, 'UTF-8'); - $feed = $feedDAO->searchByUrl($streamUrl); - $feedId = $feed == null ? -1 : $feed->id(); + $user = Minz_Session::param('currentUser', '_'); + $prefix = 'user/' . $user . '/label/'; + if (strpos($add, $prefix) === 0) { + $c_name = substr($add, strlen($prefix)); + } else { + $c_name = ''; + } } - $title = isset($titles[$i]) ? $titles[$i] : ''; - $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8'); - switch ($action) { - case 'subscribe': - if ($feedId <= 0) { - $http_auth = ''; - try { - $feed = FreshRSS_feed_Controller::addFeed($streamUrl, $title, $addCatId, $c_name, $http_auth); - continue 2; - } catch (Exception $e) { - Minz_Log::error('subscriptionEdit error subscribe: ' . $e->getMessage(), API_LOG); - } - } - badRequest(); - break; - case 'unsubscribe': - if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) { - badRequest(); + $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8'); + $cat = $categoryDAO->searchByName($c_name); + $addCatId = $cat == null ? 0 : $cat->id(); + } elseif ($remove != '' && strpos($remove, 'user/-/label/') === 0) { + $addCatId = 1; //Default category + } + $feedDAO = FreshRSS_Factory::createFeedDao(); + if (!is_array($streamNames) || count($streamNames) < 1) { + self::badRequest(); + } + for ($i = count($streamNames) - 1; $i >= 0; $i--) { + $streamUrl = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338 + if (strpos($streamUrl, 'feed/') === 0) { + $streamUrl = '' . preg_replace('%^(feed/)+%', '', $streamUrl); + $feedId = 0; + if (ctype_digit($streamUrl)) { + if ($action === 'subscribe') { + continue; } - break; - case 'edit': - if ($feedId > 0) { - if ($addCatId > 0 || $c_name != '') { - FreshRSS_feed_Controller::moveFeed($feedId, $addCatId, $c_name); + $feedId = $streamUrl; + } else { + $streamUrl = htmlspecialchars($streamUrl, ENT_COMPAT, 'UTF-8'); + $feed = $feedDAO->searchByUrl($streamUrl); + $feedId = $feed == null ? -1 : $feed->id(); + } + $title = isset($titles[$i]) ? $titles[$i] : ''; + $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8'); + switch ($action) { + case 'subscribe': + if ($feedId <= 0) { + $http_auth = ''; + try { + $feed = FreshRSS_feed_Controller::addFeed($streamUrl, $title, $addCatId, $c_name, $http_auth); + continue 2; + } catch (Exception $e) { + Minz_Log::error('subscriptionEdit error subscribe: ' . $e->getMessage(), API_LOG); + } } - if ($title != '') { - FreshRSS_feed_Controller::renameFeed($feedId, $title); + self::badRequest(); + // Always exits + case 'unsubscribe': + if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) { + self::badRequest(); } - } else { - badRequest(); - } - break; + break; + case 'edit': + if ($feedId > 0) { + if ($addCatId > 0 || $c_name != '') { + FreshRSS_feed_Controller::moveFeed($feedId, $addCatId, $c_name); + } + if ($title != '') { + FreshRSS_feed_Controller::renameFeed($feedId, $title); + } + } else { + self::badRequest(); + } + break; + } } } + exit('OK'); } - exit('OK'); -} -function quickadd($url) { - try { - $url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8'); - if (substr($url, 0, 5) === 'feed/') { - $url = substr($url, 5); + /** @return never */ + private static function quickadd(string $url) { + try { + $url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8'); + if (substr($url, 0, 5) === 'feed/') { + $url = substr($url, 5); + } + $feed = FreshRSS_feed_Controller::addFeed($url); + exit(json_encode(array( + 'numResults' => 1, + 'query' => $feed->url(), + 'streamId' => 'feed/' . $feed->id(), + 'streamName' => $feed->name(), + ), JSON_OPTIONS)); + } catch (Exception $e) { + Minz_Log::error('quickadd error: ' . $e->getMessage(), API_LOG); + die(json_encode(array( + 'numResults' => 0, + 'error' => $e->getMessage(), + ), JSON_OPTIONS)); } - $feed = FreshRSS_feed_Controller::addFeed($url); - exit(json_encode(array( - 'numResults' => 1, - 'query' => $feed->url(), - 'streamId' => 'feed/' . $feed->id(), - 'streamName' => $feed->name(), - ), JSON_OPTIONS)); - } catch (Exception $e) { - Minz_Log::error('quickadd error: ' . $e->getMessage(), API_LOG); - die(json_encode(array( - 'numResults' => 0, - 'error' => $e->getMessage(), - ), JSON_OPTIONS)); } -} - -function unreadCount() { - //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#unread-count - header('Content-Type: application/json; charset=UTF-8'); - $totalUnreads = 0; - $totalLastUpdate = 0; + /** @return never */ + private static function unreadCount() { + //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#unread-count + header('Content-Type: application/json; charset=UTF-8'); - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $feedDAO = FreshRSS_Factory::createFeedDao(); - $feedsNewestItemUsec = $feedDAO->listFeedsNewestItemUsec(); + $totalUnreads = 0; + $totalLastUpdate = 0; - foreach ($categoryDAO->listCategories(true, true) as $cat) { - $catLastUpdate = 0; - foreach ($cat->feeds() as $feed) { - $lastUpdate = isset($feedsNewestItemUsec['f_' . $feed->id()]) ? $feedsNewestItemUsec['f_' . $feed->id()] : 0; + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feedsNewestItemUsec = $feedDAO->listFeedsNewestItemUsec(); + + foreach ($categoryDAO->listCategories(true, true) as $cat) { + $catLastUpdate = 0; + foreach ($cat->feeds() as $feed) { + $lastUpdate = isset($feedsNewestItemUsec['f_' . $feed->id()]) ? $feedsNewestItemUsec['f_' . $feed->id()] : 0; + $unreadcounts[] = array( + 'id' => 'feed/' . $feed->id(), + 'count' => $feed->nbNotRead(), + 'newestItemTimestampUsec' => '' . $lastUpdate, + ); + if ($catLastUpdate < $lastUpdate) { + $catLastUpdate = $lastUpdate; + } + } $unreadcounts[] = array( - 'id' => 'feed/' . $feed->id(), - 'count' => $feed->nbNotRead(), - 'newestItemTimestampUsec' => '' . $lastUpdate, + 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), + 'count' => $cat->nbNotRead(), + 'newestItemTimestampUsec' => '' . $catLastUpdate, ); - if ($catLastUpdate < $lastUpdate) { - $catLastUpdate = $lastUpdate; + $totalUnreads += $cat->nbNotRead(); + if ($totalLastUpdate < $catLastUpdate) { + $totalLastUpdate = $catLastUpdate; } } - $unreadcounts[] = array( - 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES), - 'count' => $cat->nbNotRead(), - 'newestItemTimestampUsec' => '' . $catLastUpdate, - ); - $totalUnreads += $cat->nbNotRead(); - if ($totalLastUpdate < $catLastUpdate) { - $totalLastUpdate = $catLastUpdate; + + $tagDAO = FreshRSS_Factory::createTagDao(); + $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec(); + foreach ($tagDAO->listTags(true) as $label) { + $lastUpdate = isset($tagsNewestItemUsec['t_' . $label->id()]) ? $tagsNewestItemUsec['t_' . $label->id()] : 0; + $unreadcounts[] = array( + 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES), + 'count' => $label->nbUnread(), + 'newestItemTimestampUsec' => '' . $lastUpdate, + ); } - } - $tagDAO = FreshRSS_Factory::createTagDao(); - $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec(); - foreach ($tagDAO->listTags(true) as $label) { - $lastUpdate = isset($tagsNewestItemUsec['t_' . $label->id()]) ? $tagsNewestItemUsec['t_' . $label->id()] : 0; $unreadcounts[] = array( - 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES), - 'count' => $label->nbUnread(), - 'newestItemTimestampUsec' => '' . $lastUpdate, + 'id' => 'user/-/state/com.google/reading-list', + 'count' => $totalUnreads, + 'newestItemTimestampUsec' => '' . $totalLastUpdate, ); - } - $unreadcounts[] = array( - 'id' => 'user/-/state/com.google/reading-list', - 'count' => $totalUnreads, - 'newestItemTimestampUsec' => '' . $totalLastUpdate, - ); - - echo json_encode(array( - 'max' => $totalUnreads, - 'unreadcounts' => $unreadcounts, - ), JSON_OPTIONS), "\n"; - exit(); -} - -function entriesToArray($entries) { - if (empty($entries)) { - return array(); + echo json_encode(array( + 'max' => $totalUnreads, + 'unreadcounts' => $unreadcounts, + ), JSON_OPTIONS), "\n"; + exit(); } - $catDAO = FreshRSS_Factory::createCategoryDao(); - $categories = $catDAO->listCategories(true); - $tagDAO = FreshRSS_Factory::createTagDao(); - $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries); - if ($entryIdsTagNames == false) { - $entryIdsTagNames = array(); - } + /** + * @param array<FreshRSS_Entry> $entries + * @return array<array<string,mixed>> + */ + private static function entriesToArray(array $entries): array { + if (empty($entries)) { + return array(); + } + $catDAO = FreshRSS_Factory::createCategoryDao(); + $categories = $catDAO->listCategories(true); - $items = array(); - foreach ($entries as $item) { - /** @var FreshRSS_Entry $entry */ - $entry = Minz_ExtensionManager::callHook('entry_before_display', $item); - if ($entry == null) { - continue; + $tagDAO = FreshRSS_Factory::createTagDao(); + $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries); + if ($entryIdsTagNames == false) { + $entryIdsTagNames = array(); } - $feed = FreshRSS_CategoryDAO::findFeed($categories, $entry->feedId()); - $entry->_feed($feed); + $items = array(); + foreach ($entries as $item) { + /** @var FreshRSS_Entry $entry */ + $entry = Minz_ExtensionManager::callHook('entry_before_display', $item); + if ($entry == null) { + continue; + } - if (isset($entryIdsTagNames['e_' . $entry->id()])) { - $entry->_tags($entryIdsTagNames['e_' . $entry->id()]); - } + $feed = FreshRSS_CategoryDAO::findFeed($categories, $entry->feedId()); + $entry->_feed($feed); - $items[] = $entry->toGReader('compat'); + if (isset($entryIdsTagNames['e_' . $entry->id()])) { + $entry->_tags($entryIdsTagNames['e_' . $entry->id()]); + } + + $items[] = $entry->toGReader('compat'); + } + return $items; } - return $items; -} -function streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time) { - switch ($type) { - case 'f': //feed - if ($streamId != '' && !ctype_digit($streamId)) { - $feedDAO = FreshRSS_Factory::createFeedDao(); + /** + * @return array<string|int|FreshRSS_BooleanSearch> + */ + private static function streamContentsFilters(string $type, string $streamId, + string $filter_target, string $exclude_target, int $start_time, int $stop_time): array { + switch ($type) { + case 'f': //feed + if ($streamId != '' && !ctype_digit($streamId)) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8'); + $feed = $feedDAO->searchByUrl($streamId); + $streamId = $feed == null ? -1 : $feed->id(); + } + break; + case 'c': //category or label + $categoryDAO = FreshRSS_Factory::createCategoryDao(); $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8'); - $feed = $feedDAO->searchByUrl($streamId); - $streamId = $feed == null ? -1 : $feed->id(); - } - break; - case 'c': //category or label - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8'); - $cat = $categoryDAO->searchByName($streamId); - if ($cat != null) { - $type = 'c'; - $streamId = $cat->id(); - } else { - $tagDAO = FreshRSS_Factory::createTagDao(); - $tag = $tagDAO->searchByName($streamId); - if ($tag != null) { - $type = 't'; - $streamId = $tag->id(); + $cat = $categoryDAO->searchByName($streamId); + if ($cat != null) { + $type = 'c'; + $streamId = $cat->id(); } else { - $type = 'A'; - $streamId = -1; + $tagDAO = FreshRSS_Factory::createTagDao(); + $tag = $tagDAO->searchByName($streamId); + if ($tag != null) { + $type = 't'; + $streamId = $tag->id(); + } else { + $type = 'A'; + $streamId = -1; + } } - } - break; - } + break; + } - switch ($filter_target) { - case 'user/-/state/com.google/read': - $state = FreshRSS_Entry::STATE_READ; - break; - case 'user/-/state/com.google/unread': - $state = FreshRSS_Entry::STATE_NOT_READ; - break; - case 'user/-/state/com.google/starred': - $state = FreshRSS_Entry::STATE_FAVORITE; - break; - default: - $state = FreshRSS_Entry::STATE_ALL; - break; - } + switch ($filter_target) { + case 'user/-/state/com.google/read': + $state = FreshRSS_Entry::STATE_READ; + break; + case 'user/-/state/com.google/unread': + $state = FreshRSS_Entry::STATE_NOT_READ; + break; + case 'user/-/state/com.google/starred': + $state = FreshRSS_Entry::STATE_FAVORITE; + break; + default: + $state = FreshRSS_Entry::STATE_ALL; + break; + } - switch ($exclude_target) { - case 'user/-/state/com.google/read': - $state &= FreshRSS_Entry::STATE_NOT_READ; - break; - case 'user/-/state/com.google/unread': - $state &= FreshRSS_Entry::STATE_READ; - break; - case 'user/-/state/com.google/starred': - $state &= FreshRSS_Entry::STATE_NOT_FAVORITE; - break; - } + switch ($exclude_target) { + case 'user/-/state/com.google/read': + $state &= FreshRSS_Entry::STATE_NOT_READ; + break; + case 'user/-/state/com.google/unread': + $state &= FreshRSS_Entry::STATE_READ; + break; + case 'user/-/state/com.google/starred': + $state &= FreshRSS_Entry::STATE_NOT_FAVORITE; + break; + } - $searches = new FreshRSS_BooleanSearch(''); - if ($start_time != '') { - $search = new FreshRSS_Search(''); - $search->setMinDate($start_time); - $searches->add($search); - } - if ($stop_time != '') { - $search = new FreshRSS_Search(''); - $search->setMaxDate($stop_time); - $searches->add($search); + $searches = new FreshRSS_BooleanSearch(''); + if ($start_time != '') { + $search = new FreshRSS_Search(''); + $search->setMinDate($start_time); + $searches->add($search); + } + if ($stop_time != '') { + $search = new FreshRSS_Search(''); + $search->setMaxDate($stop_time); + $searches->add($search); + } + + return array($type, $streamId, $state, $searches); } - return array($type, $streamId, $state, $searches); -} + /** @return never */ + private static function streamContents(string $path, string $include_target, int $start_time, int $stop_time, int $count, + string $order, string $filter_target, string $exclude_target, string $continuation) { + //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI + //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed + header('Content-Type: application/json; charset=UTF-8'); + + switch ($path) { + case 'reading-list': + $type = 'A'; + break; + case 'starred': + $type = 's'; + break; + case 'feed': + $type = 'f'; + break; + case 'label': + $type = 'c'; + break; + default: + $type = 'A'; + break; + } -function streamContents($path, $include_target, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation) { -//http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI -//http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed - header('Content-Type: application/json; charset=UTF-8'); + list($type, $include_target, $state, $searches) = + self::streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time); - switch ($path) { - case 'reading-list': - $type = 'A'; - break; - case 'starred': - $type = 's'; - break; - case 'feed': - $type = 'f'; - break; - case 'label': - $type = 'c'; - break; - default: - $type = 'A'; - break; - } + if ($continuation != '') { + $count++; //Shift by one element + } - list($type, $include_target, $state, $searches) = streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time); + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, $searches); + $entries = iterator_to_array($entries); //TODO: Improve - if ($continuation != '') { - $count++; //Shift by one element - } + $items = self::entriesToArray($entries); - $entryDAO = FreshRSS_Factory::createEntryDao(); - $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, $searches); - $entries = iterator_to_array($entries); //TODO: Improve + if ($continuation != '') { + array_shift($items); //Discard first element that was already sent in the previous response + $count--; + } - $items = entriesToArray($entries); + $response = array( + 'id' => 'user/-/state/com.google/reading-list', + 'updated' => time(), + 'items' => $items, + ); + if (count($entries) >= $count) { + $entry = end($entries); + if ($entry != false) { + $response['continuation'] = '' . $entry->id(); + } + } - if ($continuation != '') { - array_shift($items); //Discard first element that was already sent in the previous response - $count--; + echo json_encode($response, JSON_OPTIONS), "\n"; + exit(); } - $response = array( - 'id' => 'user/-/state/com.google/reading-list', - 'updated' => time(), - 'items' => $items, - ); - if (count($entries) >= $count) { - $entry = end($entries); - if ($entry != false) { - $response['continuation'] = '' . $entry->id(); + /** @return never */ + private static function streamContentsItemsIds(string $streamId, int $start_time, int $stop_time, int $count, + string $order, string $filter_target, string $exclude_target, string $continuation) { + //http://code.google.com/p/google-reader-api/wiki/ApiStreamItemsIds + //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI + //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed + $type = 'A'; + $id = ''; + if ($streamId === 'user/-/state/com.google/reading-list') { + $type = 'A'; + } elseif ($streamId === 'user/-/state/com.google/starred') { + $type = 's'; + } elseif (strpos($streamId, 'feed/') === 0) { + $type = 'f'; + $streamId = substr($streamId, 5); + } elseif (strpos($streamId, 'user/-/label/') === 0) { + $type = 'c'; + $streamId = substr($streamId, 13); } - } - - echo json_encode($response, JSON_OPTIONS), "\n"; - exit(); -} -function streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation) { -//http://code.google.com/p/google-reader-api/wiki/ApiStreamItemsIds -//http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI -//http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed - $type = 'A'; - $id = ''; - if ($streamId === 'user/-/state/com.google/reading-list') { - $type = 'A'; - } elseif ($streamId === 'user/-/state/com.google/starred') { - $type = 's'; - } elseif (strpos($streamId, 'feed/') === 0) { - $type = 'f'; - $streamId = substr($streamId, 5); - } elseif (strpos($streamId, 'user/-/label/') === 0) { - $type = 'c'; - $streamId = substr($streamId, 13); - } + list($type, $id, $state, $searches) = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time); - list($type, $id, $state, $searches) = streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time); + if ($continuation != '') { + $count++; //Shift by one element + } - if ($continuation != '') { - $count++; //Shift by one element - } + $entryDAO = FreshRSS_Factory::createEntryDao(); + $ids = $entryDAO->listIdsWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, $searches); + if ($ids === false) { + self::internalServerError(); + } - $entryDAO = FreshRSS_Factory::createEntryDao(); - $ids = $entryDAO->listIdsWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, $searches); + if ($continuation != '') { + array_shift($ids); //Discard first element that was already sent in the previous response + $count--; + } - if ($continuation != '') { - array_shift($ids); //Discard first element that was already sent in the previous response - $count--; - } + if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') { + $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632 + } + $itemRefs = array(); + foreach ($ids as $id) { + $itemRefs[] = array( + 'id' => '' . $id, //64-bit decimal + ); + } - if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') { - $ids[] = 0; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632 - } - $itemRefs = array(); - foreach ($ids as $id) { - $itemRefs[] = array( - 'id' => '' . $id, //64-bit decimal + $response = array( + 'itemRefs' => $itemRefs, ); - } - - $response = array( - 'itemRefs' => $itemRefs, - ); - if (count($ids) >= $count) { - $id = end($ids); - if ($id != false) { - $response['continuation'] = '' . $id; + if (count($ids) >= $count) { + $id = end($ids); + if ($id != false) { + $response['continuation'] = '' . $id; + } } - } - echo json_encode($response, JSON_OPTIONS), "\n"; - exit(); -} + echo json_encode($response, JSON_OPTIONS), "\n"; + exit(); + } -function streamContentsItems($e_ids, $order) { - header('Content-Type: application/json; charset=UTF-8'); + /** + * @param array<string> $e_ids + * @return never + */ + private static function streamContentsItems(array $e_ids, string $order) { + header('Content-Type: application/json; charset=UTF-8'); - foreach ($e_ids as $i => $e_id) { - // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items - if (!ctype_digit($e_id) || $e_id[0] === '0') { - $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/' + foreach ($e_ids as $i => $e_id) { + // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items + if (!ctype_digit($e_id) || $e_id[0] === '0') { + $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/' + } } - } - $entryDAO = FreshRSS_Factory::createEntryDao(); - $entries = $entryDAO->listByIds($e_ids, $order === 'o' ? 'ASC' : 'DESC'); - $entries = iterator_to_array($entries); //TODO: Improve + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entries = $entryDAO->listByIds($e_ids, $order === 'o' ? 'ASC' : 'DESC'); + $entries = iterator_to_array($entries); //TODO: Improve - $items = entriesToArray($entries); + $items = self::entriesToArray($entries); - $response = array( - 'id' => 'user/-/state/com.google/reading-list', - 'updated' => time(), - 'items' => $items, - ); + $response = array( + 'id' => 'user/-/state/com.google/reading-list', + 'updated' => time(), + 'items' => $items, + ); - echo json_encode($response, JSON_OPTIONS), "\n"; - exit(); -} + echo json_encode($response, JSON_OPTIONS), "\n"; + exit(); + } -function editTag($e_ids, $a, $r) { - foreach ($e_ids as $i => $e_id) { - if (!ctype_digit($e_id) || $e_id[0] === '0') { - $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/' + /** + * @param array<string> $e_ids + * @return never + */ + private static function editTag(array $e_ids, string $a, string $r): void { + foreach ($e_ids as $i => $e_id) { + if (!ctype_digit($e_id) || $e_id[0] === '0') { + $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/' + } } - } - $entryDAO = FreshRSS_Factory::createEntryDao(); - $tagDAO = FreshRSS_Factory::createTagDao(); - - switch ($a) { - case 'user/-/state/com.google/read': - $entryDAO->markRead($e_ids, true); - break; - case 'user/-/state/com.google/starred': - $entryDAO->markFavorite($e_ids, true); - break; - /*case 'user/-/state/com.google/tracking-kept-unread': - break; - case 'user/-/state/com.google/like': - break; - case 'user/-/state/com.google/broadcast': - break;*/ - default: - $tagName = ''; - if (strpos($a, 'user/-/label/') === 0) { - $tagName = substr($a, 13); - } else { - $user = Minz_Session::param('currentUser', '_'); - $prefix = 'user/' . $user . '/label/'; - if (strpos($a, $prefix) === 0) { - $tagName = substr($a, strlen($prefix)); + $entryDAO = FreshRSS_Factory::createEntryDao(); + $tagDAO = FreshRSS_Factory::createTagDao(); + + switch ($a) { + case 'user/-/state/com.google/read': + $entryDAO->markRead($e_ids, true); + break; + case 'user/-/state/com.google/starred': + $entryDAO->markFavorite($e_ids, true); + break; + /*case 'user/-/state/com.google/tracking-kept-unread': + break; + case 'user/-/state/com.google/like': + break; + case 'user/-/state/com.google/broadcast': + break;*/ + default: + $tagName = ''; + if (strpos($a, 'user/-/label/') === 0) { + $tagName = substr($a, 13); + } else { + $user = Minz_Session::param('currentUser', '_'); + $prefix = 'user/' . $user . '/label/'; + if (strpos($a, $prefix) === 0) { + $tagName = substr($a, strlen($prefix)); + } } - } - if ($tagName != '') { - $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8'); - $tag = $tagDAO->searchByName($tagName); - if ($tag == null) { - $tagDAO->addTag(array('name' => $tagName)); + if ($tagName != '') { + $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8'); $tag = $tagDAO->searchByName($tagName); - } - if ($tag != null) { - foreach ($e_ids as $e_id) { - $tagDAO->tagEntry($tag->id(), $e_id, true); + if ($tag == null) { + $tagDAO->addTag(array('name' => $tagName)); + $tag = $tagDAO->searchByName($tagName); + } + if ($tag != null) { + foreach ($e_ids as $e_id) { + $tagDAO->tagEntry($tag->id(), $e_id, true); + } } } - } - break; - } - switch ($r) { - case 'user/-/state/com.google/read': - $entryDAO->markRead($e_ids, false); - break; - case 'user/-/state/com.google/starred': - $entryDAO->markFavorite($e_ids, false); - break; - default: - if (strpos($r, 'user/-/label/') === 0) { - $tagName = substr($r, 13); - $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8'); - $tag = $tagDAO->searchByName($tagName); - if ($tag != null) { - foreach ($e_ids as $e_id) { - $tagDAO->tagEntry($tag->id(), $e_id, false); + break; + } + switch ($r) { + case 'user/-/state/com.google/read': + $entryDAO->markRead($e_ids, false); + break; + case 'user/-/state/com.google/starred': + $entryDAO->markFavorite($e_ids, false); + break; + default: + if (strpos($r, 'user/-/label/') === 0) { + $tagName = substr($r, 13); + $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8'); + $tag = $tagDAO->searchByName($tagName); + if ($tag != null) { + foreach ($e_ids as $e_id) { + $tagDAO->tagEntry($tag->id(), $e_id, false); + } } } - } - break; - } + break; + } - exit('OK'); -} + exit('OK'); + } -function renameTag($s, $dest) { - if ($s != '' && strpos($s, 'user/-/label/') === 0 && - $dest != '' && strpos($dest, 'user/-/label/') === 0) { - $s = substr($s, 13); - $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8'); - $dest = substr($dest, 13); - $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8'); + /** @return never */ + private static function renameTag(string $s, string $dest) { + if ($s != '' && strpos($s, 'user/-/label/') === 0 && + $dest != '' && strpos($dest, 'user/-/label/') === 0) { + $s = substr($s, 13); + $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8'); + $dest = substr($dest, 13); + $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8'); - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $cat = $categoryDAO->searchByName($s); - if ($cat != null) { - $categoryDAO->updateCategory($cat->id(), array('name' => $dest)); - exit('OK'); - } else { - $tagDAO = FreshRSS_Factory::createTagDao(); - $tag = $tagDAO->searchByName($s); - if ($tag != null) { - $tagDAO->updateTag($tag->id(), array('name' => $dest)); + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + $cat = $categoryDAO->searchByName($s); + if ($cat != null) { + $categoryDAO->updateCategory($cat->id(), array('name' => $dest)); exit('OK'); + } else { + $tagDAO = FreshRSS_Factory::createTagDao(); + $tag = $tagDAO->searchByName($s); + if ($tag != null) { + $tagDAO->updateTag($tag->id(), array('name' => $dest)); + exit('OK'); + } } } + self::badRequest(); } - badRequest(); -} -function disableTag($s) { - if ($s != '' && strpos($s, 'user/-/label/') === 0) { - $s = substr($s, 13); - $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8'); - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $cat = $categoryDAO->searchByName($s); - if ($cat != null) { - $feedDAO = FreshRSS_Factory::createFeedDao(); - $feedDAO->changeCategory($cat->id(), 0); - if ($cat->id() > 1) { - $categoryDAO->deleteCategory($cat->id()); - } - exit('OK'); - } else { - $tagDAO = FreshRSS_Factory::createTagDao(); - $tag = $tagDAO->searchByName($s); - if ($tag != null) { - $tagDAO->deleteTag($tag->id()); + /** @return never */ + private static function disableTag(string $s) { + if ($s != '' && strpos($s, 'user/-/label/') === 0) { + $s = substr($s, 13); + $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8'); + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + $cat = $categoryDAO->searchByName($s); + if ($cat != null) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feedDAO->changeCategory($cat->id(), 0); + if ($cat->id() > 1) { + $categoryDAO->deleteCategory($cat->id()); + } exit('OK'); + } else { + $tagDAO = FreshRSS_Factory::createTagDao(); + $tag = $tagDAO->searchByName($s); + if ($tag != null) { + $tagDAO->deleteTag($tag->id()); + exit('OK'); + } } } + self::badRequest(); } - badRequest(); -} -function markAllAsRead($streamId, $olderThanId) { - $entryDAO = FreshRSS_Factory::createEntryDao(); - if (strpos($streamId, 'feed/') === 0) { - $f_id = basename($streamId); - if (!ctype_digit($f_id)) { - badRequest(); - } - $f_id = intval($f_id); - $entryDAO->markReadFeed($f_id, $olderThanId); - } elseif (strpos($streamId, 'user/-/label/') === 0) { - $c_name = substr($streamId, 13); - $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8'); - $categoryDAO = FreshRSS_Factory::createCategoryDao(); - $cat = $categoryDAO->searchByName($c_name); - if ($cat != null) { - $entryDAO->markReadCat($cat->id(), $olderThanId); - } else { - $tagDAO = FreshRSS_Factory::createTagDao(); - $tag = $tagDAO->searchByName($c_name); - if ($tag != null) { - $entryDAO->markReadTag($tag->id(), $olderThanId); + /** @return never */ + private static function markAllAsRead(string $streamId, string $olderThanId) { + $entryDAO = FreshRSS_Factory::createEntryDao(); + if (strpos($streamId, 'feed/') === 0) { + $f_id = basename($streamId); + if (!ctype_digit($f_id)) { + self::badRequest(); + } + $f_id = intval($f_id); + $entryDAO->markReadFeed($f_id, $olderThanId); + } elseif (strpos($streamId, 'user/-/label/') === 0) { + $c_name = substr($streamId, 13); + $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8'); + $categoryDAO = FreshRSS_Factory::createCategoryDao(); + $cat = $categoryDAO->searchByName($c_name); + if ($cat != null) { + $entryDAO->markReadCat($cat->id(), $olderThanId); } else { - badRequest(); + $tagDAO = FreshRSS_Factory::createTagDao(); + $tag = $tagDAO->searchByName($c_name); + if ($tag != null) { + $entryDAO->markReadTag($tag->id(), $olderThanId); + } else { + self::badRequest(); + } } + } elseif ($streamId === 'user/-/state/com.google/reading-list') { + $entryDAO->markReadEntries($olderThanId, false, -1); + } else { + self::badRequest(); } - } elseif ($streamId === 'user/-/state/com.google/reading-list') { - $entryDAO->markReadEntries($olderThanId, false, -1); - } else { - badRequest(); + exit('OK'); } - exit('OK'); -} -$pathInfo = ''; -if (empty($_SERVER['PATH_INFO'])) { - if (!empty($_SERVER['ORIG_PATH_INFO'])) { - // Compatibility https://php.net/reserved.variables.server - $pathInfo = $_SERVER['ORIG_PATH_INFO']; - } -} else { - $pathInfo = $_SERVER['PATH_INFO']; -} -$pathInfo = urldecode($pathInfo); -$pathInfo = preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors -if ($pathInfo == '') { - exit('OK'); -} -$pathInfos = explode('/', $pathInfo); -if (count($pathInfos) < 3) { - badRequest(); -} + /** @return never */ + public static function parse() { + global $ORIGINAL_INPUT; -FreshRSS_Context::initSystem(); + $pathInfo = ''; + if (empty($_SERVER['PATH_INFO'])) { + if (!empty($_SERVER['ORIG_PATH_INFO'])) { + // Compatibility https://php.net/reserved.variables.server + $pathInfo = $_SERVER['ORIG_PATH_INFO']; + } + } else { + $pathInfo = $_SERVER['PATH_INFO']; + } + $pathInfo = urldecode($pathInfo); + $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors + if ($pathInfo == '') { + exit('OK'); + } + $pathInfos = explode('/', $pathInfo); + if (count($pathInfos) < 3) { + self::badRequest(); + } -//Minz_Log::debug('----------------------------------------------------------------', API_LOG); -//Minz_Log::debug(debugInfo(), API_LOG); + FreshRSS_Context::initSystem(); -if (!FreshRSS_Context::$system_conf->api_enabled) { - serviceUnavailable(); -} elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') { - checkCompatibility(); -} + //Minz_Log::debug('----------------------------------------------------------------', API_LOG); + //Minz_Log::debug(debugInfo(), API_LOG); -Minz_Session::init('FreshRSS', true); + if (FreshRSS_Context::$system_conf == null || !FreshRSS_Context::$system_conf->api_enabled) { + self::serviceUnavailable(); + } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') { + self::checkCompatibility(); + } -if ($pathInfos[1] !== 'accounts') { - authorizationToUser(); -} -if (FreshRSS_Context::$user_conf != null) { - Minz_Translate::init(FreshRSS_Context::$user_conf->language); - Minz_ExtensionManager::init(); - Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); -} else { - Minz_Translate::init(); -} + Minz_Session::init('FreshRSS', true); -if ($pathInfos[1] === 'accounts') { - if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd'])) { - clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']); - } -} elseif ($pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && isset($pathInfos[3]) && $pathInfos[3] === '0' && isset($pathInfos[4])) { - if (Minz_Session::param('currentUser', '') == '') { - unauthorized(); - } - $timestamp = isset($_GET['ck']) ? intval($_GET['ck']) : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching. - switch ($pathInfos[4]) { - case 'stream': - /* xt=[exclude target] : Used to exclude certain items from the feed. - * For example, using xt=user/-/state/com.google/read will exclude items - * that the current user has marked as read, or xt=feed/[feedurl] will - * exclude items from a particular feed (obviously not useful in this - * request, but xt appears in other listing requests). */ - $exclude_target = isset($_GET['xt']) ? $_GET['xt'] : ''; - $filter_target = isset($_GET['it']) ? $_GET['it'] : ''; - //n=[integer] : The maximum number of results to return. - $count = isset($_GET['n']) ? intval($_GET['n']) : 20; - //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order. - $order = isset($_GET['r']) ? $_GET['r'] : 'd'; - /* ot=[unix timestamp] : The time from which you want to retrieve - * items. Only items that have been crawled by Google Reader after - * this time will be returned. */ - $start_time = isset($_GET['ot']) ? intval($_GET['ot']) : 0; - $stop_time = isset($_GET['nt']) ? intval($_GET['nt']) : 0; - /* Continuation token. If a StreamContents response does not represent - * all items in a timestamp range, it will have a continuation attribute. - * The same request can be re-issued with the value of that attribute put - * in this parameter to get more items */ - $continuation = isset($_GET['c']) ? trim($_GET['c']) : ''; - if (!ctype_digit($continuation)) { - $continuation = ''; + if ($pathInfos[1] !== 'accounts') { + self::authorizationToUser(); + } + if (FreshRSS_Context::$user_conf != null) { + Minz_Translate::init(FreshRSS_Context::$user_conf->language); + Minz_ExtensionManager::init(); + Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); + } else { + Minz_Translate::init(); + } + + if ($pathInfos[1] === 'accounts') { + if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd'])) { + self::clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']); + } + } elseif ($pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && isset($pathInfos[3]) && $pathInfos[3] === '0' && isset($pathInfos[4])) { + if (Minz_Session::param('currentUser', '') == '') { + self::unauthorized(); } - if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') { - if (!isset($pathInfos[6]) && isset($_GET['s'])) { - // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams - $streamIdInfos = explode('/', $_GET['s']); - foreach ($streamIdInfos as $streamIdInfo) { - $pathInfos[] = $streamIdInfo; + $timestamp = isset($_GET['ck']) ? intval($_GET['ck']) : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching. + switch ($pathInfos[4]) { + case 'stream': + /* xt=[exclude target] : Used to exclude certain items from the feed. + * For example, using xt=user/-/state/com.google/read will exclude items + * that the current user has marked as read, or xt=feed/[feedurl] will + * exclude items from a particular feed (obviously not useful in this + * request, but xt appears in other listing requests). */ + $exclude_target = isset($_GET['xt']) ? $_GET['xt'] : ''; + $filter_target = isset($_GET['it']) ? $_GET['it'] : ''; + //n=[integer] : The maximum number of results to return. + $count = isset($_GET['n']) ? intval($_GET['n']) : 20; + //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order. + $order = isset($_GET['r']) ? $_GET['r'] : 'd'; + /* ot=[unix timestamp] : The time from which you want to retrieve + * items. Only items that have been crawled by Google Reader after + * this time will be returned. */ + $start_time = isset($_GET['ot']) ? intval($_GET['ot']) : 0; + $stop_time = isset($_GET['nt']) ? intval($_GET['nt']) : 0; + /* Continuation token. If a StreamContents response does not represent + * all items in a timestamp range, it will have a continuation attribute. + * The same request can be re-issued with the value of that attribute put + * in this parameter to get more items */ + $continuation = isset($_GET['c']) ? trim($_GET['c']) : ''; + if (!ctype_digit($continuation)) { + $continuation = ''; } - } - if (isset($pathInfos[6]) && isset($pathInfos[7])) { - if ($pathInfos[6] === 'feed') { - $include_target = $pathInfos[7]; - if ($include_target != '' && !ctype_digit($include_target)) { - $include_target = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']; - if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) && isset($matches[1])) { - $include_target = urldecode($matches[1]); - } else { - $include_target = ''; + if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') { + if (!isset($pathInfos[6]) && isset($_GET['s'])) { + // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams + $streamIdInfos = explode('/', $_GET['s']); + foreach ($streamIdInfos as $streamIdInfo) { + $pathInfos[] = $streamIdInfo; } } - streamContents($pathInfos[6], $include_target, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation); - } elseif ($pathInfos[6] === 'user' && isset($pathInfos[8]) && isset($pathInfos[9])) { - if ($pathInfos[8] === 'state') { - if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) { - if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') { - $include_target = ''; - streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order, - $filter_target, $exclude_target, $continuation); + if (isset($pathInfos[6]) && isset($pathInfos[7])) { + if ($pathInfos[6] === 'feed') { + $include_target = $pathInfos[7]; + if ($include_target != '' && !ctype_digit($include_target)) { + $include_target = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']; + if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches)) { + $include_target = urldecode($matches[1]); + } else { + $include_target = ''; + } + } + self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time, + $count, $order, $filter_target, $exclude_target, $continuation); + } elseif ($pathInfos[6] === 'user' && isset($pathInfos[8]) && isset($pathInfos[9])) { + if ($pathInfos[8] === 'state') { + if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) { + if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') { + $include_target = ''; + self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order, + $filter_target, $exclude_target, $continuation); + } + } + } elseif ($pathInfos[8] === 'label') { + $include_target = $pathInfos[9]; + self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time, + $count, $order, $filter_target, $exclude_target, $continuation); } } - } elseif ($pathInfos[8] === 'label') { - $include_target = $pathInfos[9]; - streamContents($pathInfos[8], $include_target, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation); + } else { //EasyRSS, FeedMe + $include_target = ''; + self::streamContents('reading-list', $include_target, $start_time, $stop_time, + $count, $order, $filter_target, $exclude_target, $continuation); } - } - } else { //EasyRSS, FeedMe - $include_target = ''; - streamContents('reading-list', $include_target, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation); - } - } elseif ($pathInfos[5] === 'items') { - if ($pathInfos[6] === 'ids' && isset($_GET['s'])) { - /* StreamId for which to fetch the item IDs. The parameter may - * be repeated to fetch the item IDs from multiple streams at once - * (more efficient from a backend perspective than multiple requests). */ - $streamId = $_GET['s']; - streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation); - } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe - $e_ids = multiplePosts('i'); //item IDs - streamContentsItems($e_ids, $order); - } - } - break; - case 'tag': - if (isset($pathInfos[5]) && $pathInfos[5] === 'list') { - $output = isset($_GET['output']) ? $_GET['output'] : ''; - if ($output !== 'json') notImplemented(); - tagList(); - } - break; - case 'subscription': - if (isset($pathInfos[5])) { - switch ($pathInfos[5]) { - case 'export': - subscriptionExport(); - break; - case 'import': - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && $ORIGINAL_INPUT != '') { - subscriptionImport($ORIGINAL_INPUT); + } elseif ($pathInfos[5] === 'items') { + if ($pathInfos[6] === 'ids' && isset($_GET['s'])) { + /* StreamId for which to fetch the item IDs. The parameter may + * be repeated to fetch the item IDs from multiple streams at once + * (more efficient from a backend perspective than multiple requests). */ + $streamId = $_GET['s']; + self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation); + } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe + $e_ids = multiplePosts('i'); //item IDs + self::streamContentsItems($e_ids, $order); } - break; - case 'list': + } + break; + case 'tag': + if (isset($pathInfos[5]) && $pathInfos[5] === 'list') { $output = isset($_GET['output']) ? $_GET['output'] : ''; - if ($output !== 'json') notImplemented(); - subscriptionList(); - break; - case 'edit': - if (isset($_REQUEST['s']) && isset($_REQUEST['ac'])) { - //StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once - $streamNames = empty($_POST['s']) && isset($_GET['s']) ? array($_GET['s']) : multiplePosts('s'); - /* Title to use for the subscription. For the `subscribe` action, - * if not specified then the feed’s current title will be used. Can - * be used with the `edit` action to rename a subscription */ - $titles = empty($_POST['t']) && isset($_GET['t']) ? array($_GET['t']) : multiplePosts('t'); - $action = $_REQUEST['ac']; //Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit` - $add = isset($_REQUEST['a']) ? $_REQUEST['a'] : ''; //StreamId to add the subscription to (generally a user label) - $remove = isset($_REQUEST['r']) ? $_REQUEST['r'] : ''; //StreamId to remove the subscription from (generally a user label) - subscriptionEdit($streamNames, $titles, $action, $add, $remove); - } - break; - case 'quickadd': //https://github.com/theoldreader/api - if (isset($_REQUEST['quickadd'])) { - quickadd($_REQUEST['quickadd']); + if ($output !== 'json') self::notImplemented(); + self::tagList(); + } + break; + case 'subscription': + if (isset($pathInfos[5])) { + switch ($pathInfos[5]) { + case 'export': + self::subscriptionExport(); + // Always exits + case 'import': + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && $ORIGINAL_INPUT != '') { + self::subscriptionImport($ORIGINAL_INPUT); + } + break; + case 'list': + $output = isset($_GET['output']) ? $_GET['output'] : ''; + if ($output !== 'json') self::notImplemented(); + self::subscriptionList(); + // Always exits + case 'edit': + if (isset($_REQUEST['s']) && isset($_REQUEST['ac'])) { + //StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once + $streamNames = empty($_POST['s']) && isset($_GET['s']) ? array($_GET['s']) : multiplePosts('s'); + /* Title to use for the subscription. For the `subscribe` action, + * if not specified then the feed’s current title will be used. Can + * be used with the `edit` action to rename a subscription */ + $titles = empty($_POST['t']) && isset($_GET['t']) ? array($_GET['t']) : multiplePosts('t'); + $action = $_REQUEST['ac']; //Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit` + $add = isset($_REQUEST['a']) ? $_REQUEST['a'] : ''; //StreamId to add the subscription to (generally a user label) + $remove = isset($_REQUEST['r']) ? $_REQUEST['r'] : ''; //StreamId to remove the subscription from (generally a user label) + self::subscriptionEdit($streamNames, $titles, $action, $add, $remove); + } + break; + case 'quickadd': //https://github.com/theoldreader/api + if (isset($_REQUEST['quickadd'])) { + self::quickadd($_REQUEST['quickadd']); + } + break; } - break; - } - } - break; - case 'unread-count': - $output = isset($_GET['output']) ? $_GET['output'] : ''; - if ($output !== 'json') notImplemented(); - unreadCount(); - break; - case 'edit-tag': //http://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3/ - $token = isset($_POST['T']) ? trim($_POST['T']) : ''; - checkToken(FreshRSS_Context::$user_conf, $token); - $a = isset($_POST['a']) ? $_POST['a'] : ''; //Add: user/-/state/com.google/read user/-/state/com.google/starred - $r = isset($_POST['r']) ? $_POST['r'] : ''; //Remove: user/-/state/com.google/read user/-/state/com.google/starred - $e_ids = multiplePosts('i'); //item IDs - editTag($e_ids, $a, $r); - break; - case 'rename-tag': //https://github.com/theoldreader/api - $token = isset($_POST['T']) ? trim($_POST['T']) : ''; - checkToken(FreshRSS_Context::$user_conf, $token); - $s = isset($_POST['s']) ? $_POST['s'] : ''; //user/-/label/Folder - $dest = isset($_POST['dest']) ? $_POST['dest'] : ''; //user/-/label/NewFolder - renameTag($s, $dest); - break; - case 'disable-tag': //https://github.com/theoldreader/api - $token = isset($_POST['T']) ? trim($_POST['T']) : ''; - checkToken(FreshRSS_Context::$user_conf, $token); - $s_s = multiplePosts('s'); - foreach ($s_s as $s) { - disableTag($s); //user/-/label/Folder - } - break; - case 'mark-all-as-read': - $token = isset($_POST['T']) ? trim($_POST['T']) : ''; - checkToken(FreshRSS_Context::$user_conf, $token); - $streamId = $_POST['s'] ?? ''; - $ts = isset($_POST['ts']) ? $_POST['ts'] : '0'; //Older than timestamp in nanoseconds - if (!ctype_digit($ts)) { - badRequest(); + } + break; + case 'unread-count': + $output = isset($_GET['output']) ? $_GET['output'] : ''; + if ($output !== 'json') self::notImplemented(); + self::unreadCount(); + // Always exits + case 'edit-tag': //http://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3/ + $token = isset($_POST['T']) ? trim($_POST['T']) : ''; + self::checkToken(FreshRSS_Context::$user_conf, $token); + $a = isset($_POST['a']) ? $_POST['a'] : ''; //Add: user/-/state/com.google/read user/-/state/com.google/starred + $r = isset($_POST['r']) ? $_POST['r'] : ''; //Remove: user/-/state/com.google/read user/-/state/com.google/starred + $e_ids = multiplePosts('i'); //item IDs + self::editTag($e_ids, $a, $r); + // Always exits + case 'rename-tag': //https://github.com/theoldreader/api + $token = isset($_POST['T']) ? trim($_POST['T']) : ''; + self::checkToken(FreshRSS_Context::$user_conf, $token); + $s = isset($_POST['s']) ? $_POST['s'] : ''; //user/-/label/Folder + $dest = isset($_POST['dest']) ? $_POST['dest'] : ''; //user/-/label/NewFolder + self::renameTag($s, $dest); + // Always exits + case 'disable-tag': //https://github.com/theoldreader/api + $token = isset($_POST['T']) ? trim($_POST['T']) : ''; + self::checkToken(FreshRSS_Context::$user_conf, $token); + $s_s = multiplePosts('s'); + foreach ($s_s as $s) { + self::disableTag($s); //user/-/label/Folder + } + // Always exits + case 'mark-all-as-read': + $token = isset($_POST['T']) ? trim($_POST['T']) : ''; + self::checkToken(FreshRSS_Context::$user_conf, $token); + $streamId = trim($_POST['s'] ?? ''); + $ts = trim($_POST['ts'] ?? '0'); //Older than timestamp in nanoseconds + if (!ctype_digit($ts)) { + self::badRequest(); + } + self::markAllAsRead($streamId, $ts); + // Always exits + case 'token': + self::token(FreshRSS_Context::$user_conf); + // Always exits + case 'user-info': + self::userInfo(); + // Always exits } - markAllAsRead($streamId, $ts); - break; - case 'token': - token(FreshRSS_Context::$user_conf); - break; - case 'user-info': - userInfo(); - break; + } + + self::badRequest(); } } -badRequest(); +GReaderAPI::parse(); diff --git a/p/api/pshb.php b/p/api/pshb.php index 26d1e125b..b3e3f400f 100644 --- a/p/api/pshb.php +++ b/p/api/pshb.php @@ -7,9 +7,13 @@ const MAX_PAYLOAD = 3145728; header('Content-Type: text/plain; charset=UTF-8'); header('X-Content-Type-Options: nosniff'); -$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, MAX_PAYLOAD); +$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, MAX_PAYLOAD) ?: ''; FreshRSS_Context::initSystem(); +if (FreshRSS_Context::$system_conf == null) { + header('HTTP/1.1 500 Internal Server Error'); + die('Invalid system init!'); +} FreshRSS_Context::$system_conf->auth_type = 'none'; // avoid necessity to be logged in (not saved!) //Minz_Log::debug(print_r(array('_SERVER' => $_SERVER, '_GET' => $_GET, '_POST' => $_POST, 'INPUT' => $ORIGINAL_INPUT), true), PSHB_LOG); @@ -41,7 +45,7 @@ if ($hubFile === false) { die('Feed info not found!'); } $hubJson = json_decode($hubFile, true); -if (!$hubJson || empty($hubJson['key']) || $hubJson['key'] !== $key) { +if (!is_array($hubJson) || empty($hubJson['key']) || $hubJson['key'] !== $key) { header('HTTP/1.1 500 Internal Server Error'); Minz_Log::error('Error: Invalid key cross-check!: ' . $key, PSHB_LOG); die('Invalid key cross-check!'); @@ -120,15 +124,12 @@ foreach ($users as $userFilename) { try { FreshRSS_Context::initUser($username); - if (FreshRSS_Context::$user_conf != null) { - Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); - Minz_Translate::reset(FreshRSS_Context::$user_conf->language); - } - - if (!FreshRSS_Context::$user_conf->enabled) { + if (FreshRSS_Context::$user_conf == null || !FreshRSS_Context::$user_conf->enabled) { Minz_Log::warning('FreshRSS skip disabled user ' . $username); continue; } + Minz_ExtensionManager::enableByList(FreshRSS_Context::$user_conf->extensions_enabled); + Minz_Translate::reset(FreshRSS_Context::$user_conf->language); list($updated_feeds, $feed, $nb_new_articles) = FreshRSS_feed_Controller::actualizeFeed(0, $self, false, $simplePie); if ($updated_feeds > 0 || $feed != false) { @@ -13,10 +13,7 @@ const SUPPORTED_TYPES = [ 'svg' => 'image/svg+xml', ]; -/** - * @return string - */ -function get_absolute_filename(string $file_name) { +function get_absolute_filename(string $file_name): string { $core_extension = realpath(CORE_EXTENSIONS_PATH . '/' . $file_name); if (false !== $core_extension) { return $core_extension; @@ -40,9 +37,12 @@ function get_absolute_filename(string $file_name) { return ''; } -function is_valid_path_extension($path, $extensionPath, $isStatic = true) { +function is_valid_path_extension(string $path, string $extensionPath, bool $isStatic = true): bool { // It must be under the extension path. $real_ext_path = realpath($extensionPath); + if ($real_ext_path == false) { + return false; + } //Windows compatibility $real_ext_path = str_replace('\\', '/', $real_ext_path); @@ -60,7 +60,7 @@ function is_valid_path_extension($path, $extensionPath, $isStatic = true) { // Static files to serve must be under a `ext_dir/static/` directory. $path_relative_to_ext = substr($path, strlen($real_ext_path) + 1); - list(,$static,$file) = sscanf($path_relative_to_ext, '%[^/]/%[^/]/%s'); + list(, $static, $file) = sscanf($path_relative_to_ext, '%[^/]/%[^/]/%s') ?? [null, null, null]; if (null === $file || 'static' !== $static) { return false; } @@ -78,16 +78,18 @@ function is_valid_path_extension($path, $extensionPath, $isStatic = true) { * @return bool true if it can be served, false otherwise. * */ -function is_valid_path($path) { +function is_valid_path(string $path): bool { return is_valid_path_extension($path, CORE_EXTENSIONS_PATH) || is_valid_path_extension($path, THIRDPARTY_EXTENSIONS_PATH) || is_valid_path_extension($path, USERS_PATH, false); } +/** @return never */ function sendBadRequestResponse(string $message = null) { header('HTTP/1.1 400 Bad Request'); die($message); } +/** @return never */ function sendNotFoundResponse() { header('HTTP/1.1 404 Not Found'); die(); @@ -4,7 +4,7 @@ require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader require(LIB_PATH . '/favicons.php'); require(LIB_PATH . '/http-conditional.php'); -function show_default_favicon($cacheSeconds = 3600) { +function show_default_favicon(int $cacheSeconds = 3600): void { $default_mtime = @filemtime(DEFAULT_FAVICON); if (!httpConditional($default_mtime, $cacheSeconds, 2)) { header('Content-Type: image/x-icon'); diff --git a/p/i/index.php b/p/i/index.php index 48cedfc92..360a858ca 100755 --- a/p/i/index.php +++ b/p/i/index.php @@ -35,8 +35,8 @@ if (!file_exists($applied_migrations_path)) { require(LIB_PATH . '/http-conditional.php'); $currentUser = Minz_Session::param('currentUser', ''); $dateLastModification = $currentUser === '' ? time() : max( - @filemtime(join_path(USERS_PATH, $currentUser, LOG_FILENAME)), - @filemtime(join_path(DATA_PATH, 'config.php')) + @filemtime(USERS_PATH . '/' . $currentUser . '/' . LOG_FILENAME), + @filemtime(DATA_PATH . '/config.php') ); if (httpConditional($dateLastModification, 0, 0, false, PHP_COMPRESSION, true)) { Minz_Session::init('FreshRSS'); |
