Beispiel #1
0
 /**
  * @param SlimBootstrap\Exception $exception
  *
  * @throws Slim\Exception\Stop
  */
 private function _handleError(SlimBootstrap\Exception $exception)
 {
     $this->_app->getLog()->log($exception->getLogLevel(), $exception->getCode() . ' - ' . $exception->getMessage());
     $this->_app->response->setStatus($exception->getCode());
     $this->_app->response->setBody($exception->getMessage());
     $this->_app->stop();
 }
Beispiel #2
0
 /**
  * @return $this
  */
 private function instantiateRoutes()
 {
     foreach ($this->routes as $routeParams) {
         $route = new Route($routeParams);
         $method = $route->method;
         $this->app->{$method}($route->path, function () use($route) {
             $arguments = func_get_args();
             call_user_func_array([$route->controller, $route->action], $arguments);
             $this->app->stop();
         });
     }
     return $this;
 }
Beispiel #3
0
 /**
  * @param Route $route
  * @throws \Slim\Exception\Stop
  */
 private function checkAuth(Route $route)
 {
     $request = OAuth2\Request::createFromGlobals();
     $scopeRequired = [];
     if ($route->isSecure()) {
         $scopeRequired = 'admin';
     }
     if (!$this->oauth->verifyResourceRequest($request, NULL, $scopeRequired)) {
         $response = $this->oauth->getResponse();
         $this->app->response()->status($response->getStatusCode());
         $response->send();
         $this->app->stop();
     }
 }
Beispiel #4
0
 /**
  * @param object $endpoint
  * @param string $type
  * @param array  $params
  *
  * @throws Slim\Exception\Stop
  */
 private function _handleEndpointCall($endpoint, $type, array $params)
 {
     if ($endpoint instanceof SlimBootstrap\Endpoint\InjectClientId) {
         $endpoint->setClientId($this->_app->router()->getCurrentRoute()->getParam('clientId'));
     }
     try {
         $outputWriter =& $this->_hook->getResponseOutputWriter();
         if ($endpoint instanceof SlimBootstrap\Endpoint\ForceDefaultMimeType) {
             $csvConfig = array();
             if (true === \array_key_exists('csv', $this->_applicationConfig) && true === \is_array($this->_applicationConfig['csv'])) {
                 $csvConfig = $this->_applicationConfig['csv'];
             }
             // create output writer
             $responseOutputWriterFactory = new SlimBootstrap\ResponseOutputWriter\Factory($this->_app->request, $this->_app->response, $this->_app->response->headers, $this->_applicationConfig['shortName'], $csvConfig);
             $outputWriter = $responseOutputWriterFactory->create($endpoint->getDefaultMimeType());
         }
         if ($endpoint instanceof SlimBootstrap\Endpoint\Streamable) {
             if ($outputWriter instanceof SlimBootstrap\ResponseOutputWriterStreamable) {
                 $endpoint->setOutputWriter($outputWriter);
                 \ob_start();
                 $endpoint->{$type}($params, $this->_app->request->{$type}());
                 \ob_end_clean();
             } else {
                 throw new SlimBootstrap\Exception('media type does not support streaming', 406, Slim\Log::WARN);
             }
         } else {
             $data = $endpoint->{$type}($params, $this->_app->request->{$type}());
             if ($endpoint instanceof SlimBootstrap\Endpoint\PlainData) {
                 if ($outputWriter instanceof SlimBootstrap\ResponseOutputWriterPlainData) {
                     $outputWriter->writePlain($data);
                 } else {
                     throw new SlimBootstrap\Exception('media type does not support plain data writing', 406, Slim\Log::WARN);
                 }
             } else {
                 $outputWriter->write($data);
             }
         }
     } catch (SlimBootstrap\Exception $e) {
         $this->_app->getLog()->log($e->getLogLevel(), $e->getCode() . ' - ' . $e->getMessage());
         $this->_app->response->setStatus($e->getCode());
         $this->_app->response->setBody($e->getMessage());
         $this->_app->stop();
     }
 }
Beispiel #5
0
 /**
  * Output tabular data, in the most appropriate MIME type
  *
  * @param array $data    The rows to output
  * @param array $headers Column headers
  *
  * @throws \SameAsLite\Exception\ContentTypeException An exception may be thrown if the requested MIME type
  * is not supported
  */
 protected function outputTable(array $data, array $headers = array())
 {
     // pagination check
     if (empty($data)) {
         $this->app->view()->set('pagination', false);
     } elseif ($this->stores[$this->store]->isPaginated()) {
         $current_page = $this->stores[$this->store]->getCurrentPage();
         // add pagination buttons to the template
         $this->app->view()->set('currentPage', $current_page);
         // $this->app->view()->set('numResults', count($data));
         $max_page_num = (int) ceil($this->stores[$this->store]->getMaxResults() / $this->appOptions['num_per_page']);
         $this->app->view()->set('maxPageNum', $max_page_num);
         // // build pages array
         $pages = [];
         if (!isset($this->appOptions['num_page_links'])) {
             $num_page_links = 5;
         } else {
             $num_page_links = intval($this->appOptions['num_page_links']);
         }
         $pcounter = 0;
         $p = $current_page;
         while ($pcounter < $num_page_links) {
             $page = $p - ceil($num_page_links / 2);
             if ($page > 0) {
                 $pages[] = $page;
                 $pcounter++;
             }
             $p++;
             if ($page >= $max_page_num) {
                 break;
             }
         }
         $this->app->view()->set('pages', $pages);
     }
     switch ($this->mimeBest) {
         case 'text/csv':
         case 'text/tab-separated-values':
             if ($this->mimeBest === 'text/tab-separated-values') {
                 $delimiter = "\t";
             } else {
                 $delimiter = ",";
             }
             ob_start();
             $out = fopen('php://output', 'w');
             fputcsv($out, $headers, $delimiter);
             foreach ($data as $i) {
                 fputcsv($out, $i, $delimiter);
             }
             fclose($out);
             $out = ob_get_contents();
             ob_end_clean();
             $this->app->response->setBody($out);
             break;
         case 'text/plain':
             ob_start();
             $out = fopen('php://output', 'w');
             // fwrite($out, implode(' => ', $headers) . PHP_EOL);
             foreach ($data as $i) {
                 fwrite($out, implode(' => ', $i) . PHP_EOL);
             }
             fclose($out);
             $out = ob_get_contents();
             ob_end_clean();
             $this->app->response->setBody($out);
             break;
         case 'application/rdf+xml':
         case 'text/turtle':
         case 'application/x-turtle':
             $this->outputRDF(array_merge([$headers], $data), 'table', 'eg:predicate');
             // TODO
             break;
         case 'application/json':
             $op = array();
             foreach ($data as $row) {
                 $op[] = array_combine($headers, $row);
             }
             $this->app->response->setBody(json_encode($op, JSON_PRETTY_PRINT));
             // PHP 5.4+
             break;
             // full webpage output
         // full webpage output
         case 'text/html':
         case 'application/xhtml+xml':
             // add the alternate formats for ajax query and pagination buttons
             $this->prepareWebResultView();
             // escaping for output
             array_walk($headers, '\\SameAsLite\\Helper::escapeInputArray');
             array_walk($data, '\\SameAsLite\\Helper::escapeInputArray');
             $tables = array();
             // no headers were given
             // turn the array keys into table headlines
             // use the sub-keys in the first column
             // and the array values in the second column
             if (!$headers && \SameAsLite\Helper::countdim($data) === 2) {
                 foreach ($data as $hdr => $dat) {
                     // reset the table
                     $subtabledata = array();
                     if (is_array($dat)) {
                         foreach ($dat as $k => $v) {
                             if (is_array($v)) {
                                 $hdr = $k;
                                 // TODO
                                 //add a new data row with key and value
                                 foreach ($v as $uk => $uv) {
                                     $subtabledata[] = array($uk, $uv);
                                 }
                             } else {
                                 //add a new data row with key and value
                                 $subtabledata[] = array($k, $v);
                             }
                         }
                     } else {
                         $subtabledata[] = array($hdr, $dat);
                     }
                     $tables[] = array('title' => $hdr, 'headers' => array(), "data" => $subtabledata);
                 }
                 // var_dump($tables);die;
             } else {
                 $tables[] = array('headers' => $headers, "data" => $data);
                 foreach ($data as &$d) {
                     if (!is_array($d)) {
                         $d = array_map('\\SameAsLite\\Helper::linkify', $d);
                         // $d = \SameAsLite\Helper::linkify($d);
                     }
                 }
             }
             $this->app->render('page/table.twig', array('tables' => $tables));
             break;
         default:
             throw new Exception\ContentTypeException('Could not render tabular output as ' . $this->mimeBest);
     }
     $this->app->stop();
 }
Beispiel #6
0
$app->view->parserExtensions = array(new \Slim\Views\TwigExtension());
//route middleware
$authenticator = function () use($app) {
    $response = $app->response();
    $response->header("Content-type", "application/json");
    //determine if the user has authorization.
    $authorization = $app->request->headers->get('Authorization');
    if (!is_null($authorization)) {
        //check token expiry
        $manager = new UserManager();
        try {
            $user = $manager->where('token', '=', $authorization);
            if ($user['token_expire'] < date('Y-m-d H:i:s')) {
                $response->body(json_encode(['status' => 401, 'message' => 'You have no authorization']));
                $response->status(401);
                $app->stop();
                return $response;
            }
            $app->response->header('Authorization', $authorization);
        } catch (RecordNotFoundException $e) {
            $response->body(json_encode(['status' => 401, 'message' => 'You have no authorization']));
            $response->status(401);
            $app->stop();
            return $response;
        }
    } else {
        $response->body(json_encode(['status' => 401, 'message' => 'You have no authorization']));
        $response->status(401);
        $app->stop();
        return $response;
    }