Example #1
0
 public function resolve(Request $request, Response $response)
 {
     // Then request params
     if (empty($locale)) {
         $locale = $request->meta('locale');
     }
     // User preference
     if (empty($request->user)) {
         $locale = @$request->user['locale'];
     }
     // Accept from HTTP headers
     if (empty($locale)) {
         $locale = Locale::acceptFromHttp($request->header('Accept-Language'));
     }
     // TODO: Use Locale::lookup(); and its fallback mechanism for $this->defaultLocale.
     // TODO: Locale::getPrimaryLanguage() should be useful.
     // Default locale
     if (empty($locale)) {
         $locale = $this->defaultLocale;
     }
     if (!empty($locale)) {
         if ($request->meta('locale') != $locale) {
             $response->cookie('__locale', $locale, FRAMEWORK_COOKIE_EXPIRE_TIME, '/');
         }
         $response->translation(new Translation($locale));
     }
 }
Example #2
0
 function resolve(Request $request, Response $response)
 {
     if ($response->status() != 200) {
         return;
         // only normal response will be processed
     }
     foreach ((array) $request->meta('output') as $outputFilter) {
         // format: func([param1[,param2[,param3 ...]]])
         if (preg_match('/(\\w+)\\(([\\w\\s,]*)\\)/', $outputFilter, $matches)) {
             $func = @$this->funcMap[$matches[1]];
             if (is_callable($func)) {
                 if (@$matches[2]) {
                     $func = call_user_func_array($func, explode(',', $matches[2]));
                 }
                 if (is_callable($func)) {
                     try {
                         $response->send(call_user_func_array($func, array($response->body())));
                     } catch (\Exception $e) {
                         Log::error(sprintf('[InvokerPostProcessor] Error calling %s(): %s @ %s:%d', $matches[1], $e->getMessage(), basename($e->getFile()), $e->getLine()), $e->getTrace());
                         $response->send(array('error' => $e->getMessage(), 'code' => $e->getCode()), 500);
                     }
                 }
             }
         }
     }
 }
Example #3
0
 /**
  * Add appropriate response header for response class to output.
  */
 public function resolve(Request $req, Response $res)
 {
     $callback = $req->param('JSONP_CALLBACK_NAME');
     if (!$callback) {
         $callback = $this->defaultCallback;
     }
     if ($callback && $req->param($callback)) {
         $res->header('X-JSONP-CALLBACK', $req->param($callback));
     }
 }
Example #4
0
 function resolve(Request $request, Response $response)
 {
     $pathname = $this->basePath . $request->uri('path');
     switch (pathinfo($pathname, PATHINFO_EXTENSION)) {
         case 'md':
         case 'mdown':
             break;
         default:
             return;
     }
     if (is_file($pathname)) {
         $text = file_get_contents($pathname);
         $text = (new Parsedown())->text($text);
         $response->send($text, 200);
     }
 }
Example #5
0
 /**
  * Generate response content output using the passed in template
  * and data.
  *
  * @param  string   $template_filepath
  * @param  array    $data
  * @throws TemplateNotFoundException
  * @return Response
  */
 public function render($template_filepath, array $data = [])
 {
     if (!file_exists($template_filepath)) {
         throw new TemplateNotFoundException();
     }
     // Populate current buffer with $data
     extract($data);
     ob_start();
     include $template_filepath;
     $template_content = ob_get_contents();
     ob_end_clean();
     // Build a Response object
     $response = new Response();
     $response->setContent($template_content);
     return $response;
 }
Example #6
0
 public function redirectTest()
 {
     $r = Response::redirect('/index.php', 301);
     $this->assertContains('Location: /index.php', $r->getHeaders());
     $this->assertEquals(301, $r->getCode());
     $r = Response::redirect('/index.php');
     $this->assertEquals(302, $r->getCode());
 }
Example #7
0
 public function resolve(Request $req, Response $res)
 {
     $req->user = new User();
     // User from CLI
     switch ($req->client('type')) {
         case 'cli':
             // Retrieve user context from process data, then CLI argument.
             $userId = (int) Process::get('type');
             if (!$userId) {
                 $req->cli()->options('u', array('alias' => 'user', 'type' => 'integer', 'describe' => 'Idenitfier of target context user.'));
                 $userId = (int) $req->meta('user');
             }
             if ($userId) {
                 $req->user->load($userId);
             }
             unset($userId);
             break;
         default:
             // Session ID provided, validate it.
             $sid = $req->meta('sid');
             if ($sid) {
                 $ret = Session::ensure($sid, $req->meta('token'), $req->fingerprint());
                 // Session doesn't exist, delete the cookie.
                 if ($ret === false || $ret === Session::ERR_EXPIRED) {
                     $res->cookie('__sid', '', time() - 3600);
                 } else {
                     if (is_integer($ret)) {
                         switch ($ret) {
                             // note: System should treat as public user.
                             case Session::ERR_INVALID:
                                 break;
                         }
                     } else {
                         // Success, proceed.
                         $req->user->load(Session::current('username'));
                         unset($req->user->password);
                     }
                 }
             } else {
                 if ($this->setupSession && !@\core\Node::get('User')) {
                     $req->user->data(['id' => 0, 'groups' => ['Administrators'], 'username' => '__default']);
                 }
             }
             break;
     }
 }
 public function resolve(Request $request, Response $response)
 {
     // No more successful resolve should occur at this point.
     if (!$response->status()) {
         $response->status(404);
     }
     if ($response->body() || is_array($response->body())) {
         return;
     }
     // Check if docment of target status and mime type exists.
     switch ($response->header('Content-Type')) {
         case 'application/xhtml+xml':
         case 'text/html':
         default:
             $ext = 'html';
             break;
         case 'application/json':
             $ext = 'json';
             break;
         case 'application/xml':
         case 'text/xml':
             $ext = 'xml';
             break;
     }
     $basename = $this->pathPrefix() . '/' . $response->status();
     if (isset($ext) && file_exists("{$basename}.{$ext}")) {
         readfile("{$basename}.{$ext}");
     } else {
         if (file_exists("{$basename}.php")) {
             $context = array('request' => $request, 'response' => $response);
             (new IncludeRenderer($context))->render("{$basename}.php");
         } else {
             if ($ext != 'html' && file_exists("{$basename}.html")) {
                 readfile("{$basename}.html");
             }
         }
     }
 }
Example #9
0
 public function resolve(Request $request, Response $response)
 {
     $path = $this->srcPath . $request->uri('path') . '.url';
     // Check if target file is a proxy.
     if (!is_file($path)) {
         return;
     }
     $cacheTarget = parse_ini_file($path);
     $cacheTarget = @$cacheTarget['URL'];
     unset($path);
     if (!$cacheTarget) {
         Log::warning('Proxy file has not URL parameter.', array('requestUri' => $request->uri(), 'proxyFile' => $request->uri('path') . '.uri'));
         $response->status(502);
         // Bad Gateway
         return;
     }
     /*! Cache Header Notes
      *
      *  # Cache-Control
      *  [public | private] Cacheable when public, otherwise the client is responsible for caching.
      *  [no-cache( \w+)?]  When no fields are specified, the whole thing must revalidate everytime,
      *                     otherwise cache it except specified fields.
      *  [no-store] 				 Ignore caching and pipe into output.
      *  [max-age=\d+] 		 Seconds before this cache is meant to expire, this overrides Expires header.
      *  [s-maxage=\d+] 		 Overrides max-age and Expires header, behaves just like max-age.
      *                 	   (This is for CDN and we are using it.)
      *  [must-revalidate]  Tells those CDNs which are intended to serve stale contents to revalidate every time.
      *  [proxy-revalidate] Like the "s-" version of max-age, a "must-revalidate" override only for CDN.
      *  [no-transform]     Some CDNs will optimize images and other formats, this "opt-out" of it.
      *
      *  # Expires
      *  RFC timestamp for an absolute cache expiration, overridden by Cache-Control header.
      *
      *  # ETag
      *  Hash of anything, weak ETags is not supported at this moment.
      *
      *  # vary
      *  Too much fun inside and we are too serious about caching, ignore this.
      *
      *  # pragma
      *  This guy is too old to recognize.
      *  [no-cache] Only this is known nowadays and is already succeed by Cache-Control: no-cache.
      *
      */
     // note; Use "cache-meta://" scheme for header and cache meta info, for performance.
     // 1. Check if cache exists.
     $cache = (array) Cache::get("cache-meta://{$cacheTarget}");
     // Cache expiration, in seconds.
     // expires = ( s-maxage || max-age || Expires );
     if (@$cache['expires'] && time() > $cache['expires']) {
         Cache::delete("cache-meta://{$cacheTarget}");
         Cache::delete("cache://{$cacheTarget}");
         $cache = null;
     }
     // - If not exists, make normal request to remote server.
     // - If exists, make conditional request to remote server.
     //   - Revalidation, we can skip this request and serve the content if false.
     //     revalidates = ( Cache-Control:proxy-revalidate || Cache-Control:must-revalidate )
     if (!$cache || @$cache['revalidates']) {
         $_request = array('uri' => $cacheTarget);
         if ($cache) {
             // Last-Modified
             if (@$cache['headers']['Last-Modified']) {
                 $_request['headers']['If-Modified-Since'] = $cache['Last-Modified'];
             }
             // Entity-Tag
             if (@$cache['headers']['ETag'] && strpos($cache['headers']['ETag'], 'W\\') !== 0) {
                 $_request['headers']['If-None-Match'] = $cache['ETag'];
             }
         } else {
             $cache = array();
         }
         // Make the request
         $_response = new Response(array('autoOutput' => false));
         (new Request($_request))->send(null, $_response);
         unset($_request);
         // parse headers into cache settings.
         if (in_array($_response->status(), array(200, 304))) {
             $res = preg_split('/\\s*,\\s*/', util::unwrapAssoc($_response->header('Cache-Control')));
             $res = array_reduce($res, function ($res, $value) {
                 // todo; Take care of no-cache with field name.
                 if (strpos($value, '=') > 0) {
                     $value = explode('=', $value);
                     $res[$value[0]] = $value[1];
                 } else {
                     $res[$value] = true;
                 }
                 return $res;
             }, array());
             // private, no-store, no-cache
             if (@$res['private'] || @$res['no-store'] || @$res['no-cache']) {
                 // note; in case the upstream server change this to uncacheable
                 Cache::delete("cache-meta://{$cacheTarget}");
                 Cache::delete("cache://{$cacheTarget}");
                 $_response->clearBody();
             }
             if ($_response->status() == 200 && $_response->body()) {
                 $cache['contents'] = $_response->body();
             }
             // expires = ( s-maxage || max-age || Expires );
             if (@$res['s-maxage']) {
                 $cache['expires'] = time() + $res['s-maxage'];
             } elseif (@$res['max-age']) {
                 $cache['expires'] = time() + $res['max-age'];
             } else {
                 $res = util::unwrapAssoc($_response->header('Expires'));
                 if ($res) {
                     $cache['expires'] = strtotime($res);
                 }
             }
             // revalidates = ( Cache-Control:proxy-revalidate || Cache-Control:must-revalidate )
             if (@$res['proxy-revalidate'] || @$res['must-revalidate']) {
                 $cache['revalidates'] = true;
             }
             unset($res);
         }
         $cache['headers'] = array_map('core\\Utility::unwrapAssoc', $_response->header());
         // PHP does not support chunked, skip this one.
         unset($cache['headers']['Transfer-Encoding']);
         // note; If cache is to be ignored, the $cacheTarget variable will be already unset().
         if (isset($cacheTarget)) {
             if (@$cache['contents']) {
                 Cache::set("cache://{$cacheTarget}", $cache['contents']);
             }
             Cache::set("cache-meta://{$cacheTarget}", array_filter_keys($cache, isNot('contents')));
         }
         unset($_response);
     }
     // note; Send cache headers regardless of the request condition.
     if (@$cache['headers']) {
         $response->clearHeaders();
         foreach ($cache['headers'] as $name => $value) {
             $response->header($name, $value, true);
         }
         unset($name, $value);
     }
     // note; Handles conditional request
     $ch = array_map('core\\Utility::unwrapAssoc', (array) @$cache['headers']);
     $mtime = @$ch['Last-Modified'] ? strtotime($ch['Last-Modified']) : false;
     // Request headr: If-Modified-Since
     if (@$ch['Last-Modified'] && $mtime) {
         if (strtotime($request->header('If-Modified-Since')) >= $mtime) {
             return $response->status(304);
         }
     }
     // Request header: If-Range
     if ($request->header('If-Range')) {
         // Entity tag
         if (strpos(substr($request->header('If-Range'), 0, 2), '"') !== false && @$ch['ETag']) {
             if ($this->compareETags(@$ch['ETag'], $request->header('If-Range'))) {
                 return $this->response()->status(304);
             }
         } elseif (strtotime($request->header('If-Range')) === $mtime) {
             return $this->response()->status(304);
         }
     }
     unset($mtime);
     // Request header: If-None-Match
     if (!$request->header('If-Modified-Since') && $request->header('If-None-Match')) {
         // Exists but not GET or HEAD
         switch ($request->method()) {
             case 'get':
             case 'head':
                 break;
             default:
                 return $this->response()->status(412);
         }
         /*! Note by Vicary @ 24 Jan, 2013
          *  If-None-Match means 304 when target resources exists.
          */
         if ($request->header('If-None-Match') === '*' && @$ch['ETag']) {
             return $this->response()->status(304);
         }
         if ($this->compareETags(@$ch['ETag'], preg_split('/\\s*,\\s*/', $request->header('If-None-Match')))) {
             return $this->response()->status(304);
         }
     }
     // Request header: If-Match
     if (!$request->header('If-Modified-Since') && $request->header('If-Match')) {
         // Exists but not GET or HEAD
         switch ($request->method()) {
             case 'get':
             case 'head':
                 break;
             default:
                 return $this->response()->status(412);
         }
         if ($request->header('If-Match') === '*' && !@$ch['ETag']) {
             return $this->response()->status(412);
         }
         preg_match_all('/(?:^\\*$|(:?"([^\\*"]+)")(?:\\s*,\\s*(:?"([^\\*"]+)")))$/', $request->header('If-Match'), $eTags);
         // 412 Precondition Failed when nothing matches.
         if (@$eTags[1] && !in_array($eTag, (array) $eTags[1])) {
             return $this->response()->status(412);
         }
     }
     if ($cacheTarget && empty($cache['contents'])) {
         $cache['contents'] = Cache::get("cache://{$cacheTarget}");
     }
     // Output the cahce content
     $response->send($cache['contents'], 200);
 }
Example #10
0
 function display()
 {
     $this->setCode(200)->setContentType('text/html')->setContent($this->get());
     parent::display();
 }
Example #11
0
 /**
  * This function will be resolved from the above test.
  */
 public function shouldBeResolvedAction()
 {
     $response = new Response();
     $response->setContent('Hello World!');
     return $response;
 }
Example #12
0
 public function resolve(Request $request, Response $response)
 {
     // Stop processing when previous resolvers has done something and given a response status code.
     if ($response->status()) {
         return;
     }
     $path = $request->uri('path');
     // note; decode escaped URI characters into escaped shell path
     $path = preg_replace_callback('/%([\\dA-F]{2,2})/i', function ($matches) {
         return '\\' . chr(hexdec($matches[1]));
     }, $path);
     // Store original request
     if (empty($request->__directoryIndex)) {
         $request->__uri = $request->uri();
     }
     if (stripos($path, $this->pathPrefix) === 0) {
         $path = substr($path, strlen($this->pathPrefix));
     }
     if (strpos($path, '?') !== false) {
         $path = strstr($path, '?', true);
     }
     $path = urldecode($path);
     if (!$path) {
         $path = './';
     }
     //------------------------------
     //  Emulate DirectoryIndex
     //------------------------------
     if (is_dir($path)) {
         if (!is_file($path) && !isset($request->__directoryIndex)) {
             // Prevent redirection loop
             $request->__directoryIndex = true;
             foreach ($this->directoryIndex() as $file) {
                 $request->setUri(preg_replace('/^\\.\\//', '', $path) . $file);
                 // Exit whenever an index is handled successfully, this will exit.
                 if ($this->resolve($request, $response)) {
                     return;
                 }
             }
             unset($request->__directoryIndex);
             // Nothing works, going down.
             if (isset($request->__uri)) {
                 $request->setUri($request->__uri);
             }
         }
     } else {
         if (empty($request->__directoryIndex)) {
             $dirname = dirname($path);
             if ($dirname == '.') {
                 $dirname = '/';
             }
             if (in_array(pathinfo($path, PATHINFO_FILENAME), $this->directoryIndex())) {
                 // extension-less
                 if (!pathinfo($path, PATHINFO_EXTENSION) || is_file($path)) {
                     $response->redirect($dirname);
                     return true;
                 }
             }
             unset($dirname);
         }
     }
     //------------------------------
     //  Virtual file handling
     //------------------------------
     $this->createVirtualFile($path);
     if (is_file($path)) {
         try {
             $this->handle($path, $request, $response);
         } catch (ResolverException $e) {
             $response->status($e->statusCode());
         }
         if (!$response->status()) {
             $response->status(200);
         }
         return true;
     }
 }
Example #13
0
 /**
  * Fire this request object as a request.
  *
  * @param {?Resolver} $resolver If provided, this request will be resolved by
  *                              it instead of creating a real HTTP request.
  *                              A real CURL request will be made upon omission.
  * @param {?Response} $response Response object for the request, a new response
  *                              object will be created if omitted.
  *
  * @return {Response} The response object after resolution.
  */
 public function send(Resolver $resolver = null, Response $response = null)
 {
     if ($this->resolver) {
         trigger_error('Active request cannot be fired again.', E_USER_WARNING);
         return;
     }
     if ($resolver) {
         $this->resolver = $resolver;
         $resolver->run($this, $response);
         return $resolver->response();
     }
     // TODO: Handle file uploads?
     // Creates a CURL request upon current request context.
     Net::httpRequest(array('url' => http_build_url($this->uri()), 'data' => array_replace_recursive((array) $this->param(), (array) $this->file()), 'type' => $this->method(), 'headers' => $this->header(), 'success' => function ($responseText, $options) use(&$response) {
         if ($response === null) {
             $response = new Response();
         }
         foreach (array_filter(preg_split('/\\r?\\n/', @$options['response']['headers'])) as $value) {
             $response->header($value);
         }
         $response->send($responseText, (int) @$options['status']);
     }, 'failure' => function ($errNum, $errMsg, $options) {
         throw new FrameworkException($errMsg, $errNum);
     }));
     return $response;
 }
Example #14
0
 public function resolve(Request $req, Response $res)
 {
     $auth = $this->paths;
     $pathNodes = trim($req->uri('path'), '/');
     if ($pathNodes) {
         $pathNodes = explode('/', $pathNodes);
     } else {
         $pathNodes = ['/'];
     }
     $lastWildcard = @$auth['*'];
     foreach ($pathNodes as $index => $pathNode) {
         if (!util::isAssoc($auth)) {
             break;
             // No more definitions, break out.
         }
         if (isset($auth['*'])) {
             $lastWildcard = $auth['*'];
         }
         if (isset($auth[$pathNode])) {
             $auth = $auth[$pathNode];
         } else {
             unset($auth);
             break;
         }
     }
     if (!isset($auth) || !is_bool($auth) && (!is_array($auth) || util::isAssoc($auth))) {
         if (empty($lastWildcard)) {
             throw new FrameworkException('Unable to resolve authentication chain from request URI.');
         } else {
             $auth = $lastWildcard;
         }
     }
     unset($pathNodes, $lastWildcard);
     // Numeric array
     if (is_array($auth) && !util::isAssoc($auth)) {
         $auth = array_reduce($auth, function ($result, $auth) use($req) {
             if (!$result) {
                 return $result;
             }
             if (is_callable($auth)) {
                 $auth = $auth($req);
             } else {
                 if (is_string($auth)) {
                     if (strpos($auth, '/') === false) {
                         $auth = "authenticators\\{$auth}";
                     }
                     if (is_a($auth, 'framework\\interfaces\\IAuthenticator', true)) {
                         $result = $result && $auth::authenticate($req);
                     } else {
                         throw new FrameworkException('Unknown authenticator type, must be ' . 'instance of IAuthenticator or callable.');
                     }
                 } else {
                     throw new FrameworkException('Unknown authenticator type, must be ' . 'instance of IAuthenticator or callable.');
                 }
             }
             return $result && $auth;
         }, true);
     }
     // Boolean
     if (is_bool($auth) && !$auth) {
         $res->status($this->statusCode);
     }
     // TODO: Mark allowed or denied according to the new resolver mechanism.
 }
Example #15
0
 static function action($method, $path, $function)
 {
     $restInput = array();
     $me = self::getInstance();
     if (Input::has('__request_method')) {
         $request_method = Input::get('__request_method');
     } else {
         $request_method = $_SERVER['REQUEST_METHOD'];
     }
     if ($me->is_called == true) {
         return IgnoreProcessor::getInstance();
     }
     if ($method != 'otherwise') {
         if ($method != $request_method) {
             return IgnoreProcessor::getInstance();
         }
         $path_array = preg_split("/\\//", $path);
         foreach ($path_array as $key => $path_element) {
             if (strlen(trim($path_element)) == 0) {
                 unset($path_array[$key]);
             }
         }
         $path_array = array_values($path_array);
         if (count($path_array) != count($me->path)) {
             return $me->getPostProcessor();
         }
         foreach ($path_array as $key => $path_element) {
             if (preg_match("/^\\:(.*)\$/", $path_element, $match) || preg_match("/^\\{(.*)\\}\$/", $path_element, $match)) {
                 Input::set($match[1], $me->path[$key]);
                 $restInput[] = $me->path[$key];
             } else {
                 if (!isset($me->path[$key]) || $me->path[$key] != $path_element) {
                     return IgnoreProcessor::getInstance();
                 }
             }
         }
     }
     if ($me->skip) {
         return $me->getPostProcessor();
     }
     try {
         if (is_callable($function)) {
             $response = $function();
         } else {
             $function_array = preg_split("/@/", $function);
             if (!isset($function_array[1])) {
                 throw FrameworkException::internalError('Routing Error');
             }
             $controller_namespace = Config::get("app.controller_namespace", "App\\Controller\\");
             $class_name = $controller_namespace . $function_array[0];
             $method_name = $function_array[1];
             //$response = $class_name::$method_name();
             // Initialization controller object
             $controller = new $class_name();
             $response = call_user_func_array(array($controller, $method_name), $restInput);
             //$response = $controller->$method_name();
         }
         if ($response instanceof Response) {
             $response->display();
         } else {
             $rs = new Response();
             $rs->setContentType('text/html')->setContent($response)->display();
         }
         $me->is_called = true;
     } catch (FrameworkException $e) {
         $me->handleError($e);
         $me->is_called = true;
         return IgnoreProcessor::getInstance();
     } catch (Exception $e) {
         $exception = FrameworkException::internalError('Internal Error: ' . $e->getMessage());
         $me->handleError($exception);
         $me->is_called = true;
         return IgnoreProcessor::getInstance();
     }
     return $me->getPostProcessor();
 }