]> git.mxchange.org Git - friendica.git/blobdiff - src/Module/BaseApi.php
Merge pull request #13599 from Raroun/Fix_for_Pull_Request_#13596_missing_a_hidden...
[friendica.git] / src / Module / BaseApi.php
index 3b940e3ae3af14c2df4b92103be3efd7e9ad5fe3..7d21d7a8d48c927a1b725e9d61a067cedcf7c198 100644 (file)
@@ -27,7 +27,6 @@ use Friendica\App\Router;
 use Friendica\BaseModule;
 use Friendica\Core\L10n;
 use Friendica\Core\Logger;
-use Friendica\Core\System;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Contact;
@@ -37,6 +36,7 @@ use Friendica\Model\User;
 use Friendica\Module\Api\ApiResponse;
 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
 use Friendica\Network\HTTPException;
+use Friendica\Object\Api\Mastodon\Error;
 use Friendica\Object\Api\Mastodon\Status;
 use Friendica\Object\Api\Mastodon\TimelineOrderByTypes;
 use Friendica\Security\BasicAuth;
@@ -71,11 +71,15 @@ class BaseApi extends BaseModule
        /** @var ApiResponse */
        protected $response;
 
-       public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
+       /** @var \Friendica\Factory\Api\Mastodon\Error */
+       protected $errorFactory;
+
+       public function __construct(\Friendica\Factory\Api\Mastodon\Error $errorFactory, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
        {
                parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
 
-               $this->app = $app;
+               $this->app          = $app;
+               $this->errorFactory = $errorFactory;
        }
 
        /**
@@ -93,7 +97,7 @@ class BaseApi extends BaseModule
                                case Router::PATCH:
                                case Router::POST:
                                case Router::PUT:
-                                       self::checkAllowedScope(self::SCOPE_WRITE);
+                                       $this->checkAllowedScope(self::SCOPE_WRITE);
 
                                        if (!self::getCurrentUserID()) {
                                                throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
@@ -129,7 +133,18 @@ class BaseApi extends BaseModule
                                $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", intval($request['min_id'])]);
                        }
                } else {
-                       $order_field = $requested_order;
+                       switch ($requested_order) {
+                               case TimelineOrderByTypes::RECEIVED:
+                               case TimelineOrderByTypes::CHANGED:
+                               case TimelineOrderByTypes::EDITED:
+                               case TimelineOrderByTypes::CREATED:
+                               case TimelineOrderByTypes::COMMENTED:
+                                       $order_field = $requested_order;
+                                       break;
+                               default:
+                                       throw new \Exception("Unrecognized request order: $requested_order");
+                       }
+
                        if (!empty($request['max_id'])) {
                                $condition = DBA::mergeConditions($condition, ["`$order_field` < ?", DateTimeFormat::convert($request['max_id'], DateTimeFormat::MYSQL)]);
                        }
@@ -159,19 +174,11 @@ class BaseApi extends BaseModule
                $requested_order = $request['friendica_order'];
                switch ($requested_order) {
                        case TimelineOrderByTypes::CHANGED:
-                               $order_field = 'changed';
-                               break;
                        case TimelineOrderByTypes::CREATED:
-                               $order_field = 'created';
-                               break;
                        case TimelineOrderByTypes::COMMENTED:
-                               $order_field = 'commented';
-                               break;
                        case TimelineOrderByTypes::EDITED:
-                               $order_field = 'edited';
-                               break;
                        case TimelineOrderByTypes::RECEIVED:
-                               $order_field = 'received';
+                               $order_field = $requested_order;
                                break;
                        case TimelineOrderByTypes::ID:
                        default:
@@ -218,8 +225,8 @@ class BaseApi extends BaseModule
                                        }
                                        break;
                                case TimelineOrderByTypes::EDITED:
-                                       if (!empty($status->friendicaExtension()->editedAt())) {
-                                               self::setBoundaries(new DateTime(DateTimeFormat::utc($status->friendicaExtension()->editedAt(), DateTimeFormat::JSON)));
+                                       if (!empty($status->editedAt())) {
+                                               self::setBoundaries(new DateTime(DateTimeFormat::utc($status->editedAt(), DateTimeFormat::JSON)));
                                        }
                                        break;
                                case TimelineOrderByTypes::RECEIVED:
@@ -278,7 +285,7 @@ class BaseApi extends BaseModule
         * Get the "link" header with "next" and "prev" links
         * @return string
         */
-       protected static function getLinkHeader(bool $asDate): string
+       protected static function getLinkHeader(bool $asDate = false): string
        {
                if (empty(self::$boundaries)) {
                        return '';
@@ -369,7 +376,7 @@ class BaseApi extends BaseModule
         */
        public static function appSupportsQuotes(): bool
        {
-               $token = self::getCurrentApplication();
+               $token = OAuth::getCurrentApplicationToken();
                return (!empty($token['name']) && in_array($token['name'], ['Fedilab']));
        }
 
@@ -411,27 +418,27 @@ class BaseApi extends BaseModule
         *
         * @param string $scope the requested scope (read, write, follow, push)
         */
-       public static function checkAllowedScope(string $scope)
+       public function checkAllowedScope(string $scope)
        {
                $token = self::getCurrentApplication();
 
                if (empty($token)) {
-                       Logger::notice('Empty application token');
-                       DI::mstdnError()->Forbidden();
+                       $this->logger->notice('Empty application token');
+                       $this->logAndJsonError(403, $this->errorFactory->Forbidden());
                }
 
                if (!isset($token[$scope])) {
-                       Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
-                       DI::mstdnError()->Forbidden();
+                       $this->logger->warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
+                       $this->logAndJsonError(403, $this->errorFactory->Forbidden());
                }
 
                if (empty($token[$scope])) {
-                       Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
-                       DI::mstdnError()->Forbidden();
+                       $this->logger->warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
+                       $this->logAndJsonError(403, $this->errorFactory->Forbidden());
                }
        }
 
-       public static function checkThrottleLimit()
+       public function checkThrottleLimit()
        {
                $uid = self::getCurrentUserID();
 
@@ -444,11 +451,11 @@ class BaseApi extends BaseModule
                        $posts_day = Post::countThread($condition);
 
                        if ($posts_day > $throttle_day) {
-                               Logger::notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
-                               $error = DI::l10n()->t('Too Many Requests');
-                               $error_description = DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day);
+                               $this->logger->notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
+                               $error = $this->t('Too Many Requests');
+                               $error_description = $this->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day);
                                $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
-                               System::jsonError(429, $errorobj->toArray());
+                               $this->jsonError(429, $errorobj->toArray());
                        }
                }
 
@@ -461,10 +468,10 @@ class BaseApi extends BaseModule
 
                        if ($posts_week > $throttle_week) {
                                Logger::notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
-                               $error = DI::l10n()->t('Too Many Requests');
-                               $error_description = DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week);
+                               $error = $this->t('Too Many Requests');
+                               $error_description = $this->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week);
                                $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
-                               System::jsonError(429, $errorobj->toArray());
+                               $this->jsonError(429, $errorobj->toArray());
                        }
                }
 
@@ -477,10 +484,10 @@ class BaseApi extends BaseModule
 
                        if ($posts_month > $throttle_month) {
                                Logger::notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
-                               $error = DI::l10n()->t('Too Many Requests');
-                               $error_description = DI::l10n()->tt('Monthly posting limit of %d post reached. The post was rejected.', 'Monthly posting limit of %d posts reached. The post was rejected.', $throttle_month);
+                               $error = $this->t('Too Many Requests');
+                               $error_description = $this->tt('Monthly posting limit of %d post reached. The post was rejected.', 'Monthly posting limit of %d posts reached. The post was rejected.', $throttle_month);
                                $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
-                               System::jsonError(429, $errorobj->toArray());
+                               $this->jsonError(429, $errorobj->toArray());
                        }
                }
        }
@@ -512,4 +519,16 @@ class BaseApi extends BaseModule
 
                return null;
        }
+
+       /**
+        * @param int   $errorno
+        * @param Error $error
+        * @return void
+        * @throws HTTPException\InternalServerErrorException
+        */
+       protected function logAndJsonError(int $errorno, Error $error)
+       {
+               $this->logger->info('API Error', ['no' => $errorno, 'error' => $error->toArray(), 'method' => $this->args->getMethod(), 'command' => $this->args->getQueryString(), 'user-agent' => $this->server['HTTP_USER_AGENT'] ?? '']);
+               $this->jsonError(403, $error->toArray());
+       }
 }