Example #1
0
 /**
  * Execute the API
  * @throws \Phramework\Exceptions\PermissionException
  * @throws \Phramework\Exceptions\NotFoundException
  * @throws \Phramework\Exceptions\IncorrectParametersException
  * @throws \Phramework\Exceptions\RequestException
  * @todo change default timezone
  * @todo change default language
  * @todo initialize database if set
  * @todo @security deny access to any else referals
  */
 public function invoke()
 {
     $params = new \stdClass();
     $method = self::METHOD_GET;
     $headers = [];
     try {
         date_default_timezone_set('Europe/Athens');
         if (self::getSetting('debug')) {
             error_reporting(E_ALL);
             ini_set('display_errors', '1');
         }
         if (self::getSetting('errorlog_path')) {
             ini_set('error_log', self::getSetting('errorlog_path'));
         }
         //Check if callback is set (JSONP)
         if (isset($_GET['callback'])) {
             if (!\Phramework\Validate\Validate::isValidJsonpCallback($_GET['callback'])) {
                 throw new \Phramework\Exceptions\IncorrectParametersException(['callback']);
             }
             self::$callback = $_GET['callback'];
             unset($_GET['callback']);
         }
         /*
         //Initialize Database connection if required or db set
         if (self::getSetting('require_db') || self::getSetting('db')) {
             \Phramework\Models\Database::requireDatabase(self::getSetting('db'));
         }
         
         //Unset from memory Database connection information
         unset(self::$settings['db']);
         */
         //Get method from the request (HTTP) method
         $method = self::$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : self::METHOD_GET;
         //Check if the requested HTTP method method is allowed
         // @todo check error code
         if (!in_array($method, self::$methodWhitelist)) {
             throw new \Phramework\Exceptions\RequestException('Method not allowed');
         }
         //Default value of response's header origin
         $origin = '*';
         //Get request headers
         $headers = Models\Request::headers();
         //Check origin header
         if (isset($headers['Origin'])) {
             $originHost = parse_url($headers['Origin'], PHP_URL_HOST);
             //Check if origin host is allowed
             if ($originHost && self::getSetting('allowed_referer') && in_array($originHost, self::getSetting('allowed_referer'))) {
                 $origin = $headers['Origin'];
             }
             //@TODO @security else deny access
         } elseif (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
             $origin = '*';
             //TODO Exctract origin from request url
         }
         //Send access control headers
         if (!headers_sent()) {
             header('Access-Control-Allow-Credentials: true');
             header('Access-Control-Allow-Origin: ' . $origin);
             header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, HEAD, DELETE, OPTIONS');
             header('Access-Control-Allow-Headers: ' . 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Content-Encoding');
         }
         //Catch OPTIONS request and kill it
         if ($method == self::METHOD_OPTIONS) {
             header('HTTP/1.1 200 OK');
             exit;
         }
         //Merge all REQUEST parameters into $params array
         $params = (object) array_merge($_GET, $_POST, $_FILES);
         //TODO $_FILES only if POST OR PUT
         //Parse request body
         //@Todo add allowed content-types
         if (in_array($method, [self::METHOD_POST, self::METHOD_PATCH, self::METHOD_PUT, self::METHOD_DELETE])) {
             $CONTENT_TYPE = null;
             if (isset($headers[Request::HEADER_CONTENT_TYPE])) {
                 $CONTENT_TYPE = explode(';', $headers[Request::HEADER_CONTENT_TYPE]);
                 $CONTENT_TYPE = $CONTENT_TYPE[0];
             }
             if ($CONTENT_TYPE === 'application/x-www-form-urlencoded') {
                 //Decode and merge params
                 parse_str(file_get_contents('php://input'), $input);
                 if ($input && !empty($input)) {
                     $params = (object) array_merge((array) $params, (array) $input);
                 }
             } elseif (in_array($CONTENT_TYPE, ['application/json', 'application/vnd.api+json'], true)) {
                 $input = trim(file_get_contents('php://input'));
                 if (!empty($input)) {
                     //note if input length is >0 and decode returns null then its bad data
                     //json_last_error()
                     $inputObject = json_decode($input);
                     if (json_last_error() !== JSON_ERROR_NONE) {
                         throw new \Phramework\Exceptions\RequestException('JSON parse error: ' . json_last_error_msg());
                     }
                     if ($inputObject && !empty($inputObject)) {
                         $params = (object) array_merge((array) $params, (array) $inputObject);
                     }
                 }
             }
         }
         //STEP_AFTER_AUTHENTICATION_CHECK
         self::$stepCallback->call(StepCallback::STEP_BEFORE_AUTHENTICATION_CHECK, $params, $method, $headers);
         //Authenticate request (check authentication)
         self::$user = \Phramework\Authentication\Manager::check($params, $method, $headers);
         //In case of array returned force type to be object
         if (is_array(self::$user)) {
             self::$user = (object) self::$user;
         }
         //STEP_AFTER_AUTHENTICATION_CHECK
         self::$stepCallback->call(StepCallback::STEP_AFTER_AUTHENTICATION_CHECK, $params, $method, $headers, [self::$user]);
         //Default language value
         $language = self::getSetting('language');
         //Select request's language
         if (isset($_GET['this_language']) && self::getSetting('languages') && in_array($_GET['this_language'], self::getSetting('languages'))) {
             //Force requested language
             if ($_GET['this_language'] != $language) {
                 $language = $_GET['this_language'];
             }
             unset($_GET['this_language']);
         } elseif (self::$user && property_exists(self::$user, 'language_code')) {
             // Use user's langugae
             $language = self::$user->language_code;
         } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && self::getSetting('languages')) {
             // Use Accept languge if provided
             $a = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
             if (in_array($a, self::getSetting('languages'))) {
                 $language = $a;
             }
         }
         //Set language variable
         self::$language = $language;
         //self::$translation->setLanguageCode($language);
         //STEP_BEFORE_CALL_URISTRATEGY
         self::$stepCallback->call(StepCallback::STEP_BEFORE_CALL_URISTRATEGY, $params, $method, $headers);
         //Call controller's method
         list($invokedController, $invokedMethod) = self::$URIStrategy->invoke($params, $method, $headers, self::$user);
         self::$stepCallback->call(StepCallback::STEP_AFTER_CALL_URISTRATEGY, $params, $method, $headers, [$invokedController, $invokedMethod]);
         //STEP_BEFORE_CLOSE
         self::$stepCallback->call(StepCallback::STEP_BEFORE_CLOSE, $params, $method, $headers);
     } catch (\Phramework\Exceptions\NotFoundException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\RequestException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\PermissionException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\UnauthorizedException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\MissingParametersException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['missing' => $exception->getParameters()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\IncorrectParametersException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['incorrect' => $exception->getParameters()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\MethodNotAllowedException $exception) {
         //Write allow header if AllowedMethods is set
         if (!headers_sent() && $exception->getAllowedMethods()) {
             header('Allow: ' . implode(', ', $exception->getAllowedMethods()));
         }
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['allow' => $exception->getAllowedMethods()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\RequestException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => 'Request Error']], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Exception $exception) {
         self::errorView([(object) ['status' => 400, 'detail' => $exception->getMessage(), 'title' => 'Error']], 400, $params, $method, $headers, $exception);
     } finally {
         self::$stepCallback->call(StepCallback::STEP_FINALLY, $params, $method, $headers);
         //Unset all
         unset($params);
         //Try to close the databse
         \Phramework\Database\Database::close();
     }
 }