/** * Maps HTTP request to a Request object. * @param IHttpRequest * @return NPresenterRequest|NULL */ public function match(IHttpRequest $httpRequest) { if ($httpRequest->getUrl()->getPathInfo() !== '') { return NULL; } // combine with precedence: get, (post,) defaults $params = $httpRequest->getQuery(); $params += $this->defaults; if (!isset($params[self::PRESENTER_KEY])) { throw new InvalidStateException('Missing presenter.'); } $presenter = $this->module . $params[self::PRESENTER_KEY]; unset($params[self::PRESENTER_KEY]); return new NPresenterRequest( $presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(NPresenterRequest::SECURED => $httpRequest->isSecured()) ); }
/** * Constructs absolute URL from PresenterRequest object. * @param IHttpRequest * @param PresenterRequest * @return string|NULL */ public function constructUrl(PresenterRequest $appRequest, IHttpRequest $httpRequest) { $params = $appRequest->getParams(); // presenter name $presenter = $appRequest->getPresenterName(); if (strncasecmp($presenter, $this->module, strlen($this->module)) === 0) { $params[self::PRESENTER_KEY] = substr($presenter, strlen($this->module)); } else { return NULL; } // remove default values; NULL values are retain foreach ($this->defaults as $key => $value) { if (isset($params[$key]) && $params[$key] == $value) { // intentionally == unset($params[$key]); } } $uri = $httpRequest->getUri(); $uri = ($this->flags & self::SECURED ? 'https://' : 'http://') . $uri->getAuthority() . $uri->getScriptPath(); $sep = ini_get('arg_separator.input'); $query = http_build_query($params, '', $sep ? $sep[0] : '&'); if ($query != '') { // intentionally == $uri .= '?' . $query; } return $uri; }
/** * Maps HTTP request to a PresenterRequest object. * @param Nette\Web\IHttpRequest * @return PresenterRequest|NULL */ public function match(IHttpRequest $context) { if (!preg_match('#^/([a-z0-9]{1,3})/(.*?)/?$#', $context->getUri()->path, $matches)) { return NULL; } $lang = $matches[1]; $categories = $matches[2]; $pom = explode("/", $categories); $last = end($pom); if (dibi::fetchSingle("\n\t\t\tSELECT\n\t\t\t COUNT(*)\n\t\t\tFROM\n\t\t\t category\n\t\t\t JOIN category_lang USING(id_category)\n\t\t\t JOIN [lang] USING(id_lang)\n\t\t\tWHERE iso=%s", $lang, "AND link_rewrite = %s", $last)) { $presenter = 'Front:Eshop'; } elseif (dibi::fetchSingle("SELECT COUNT(*) FROM menu_item WHERE lang = %s", $lang, "AND url_identifier=%s", $last)) { $presenter = 'Front:List'; } else { return NULL; } // alternativa: použít jednu tabulku s páry URL -> jméno Presenteru // výhoda: jeden lookup místo (až) tří, neměřitelně vyšší rychlost ;) // nevýhoda: nutnost ji udržovat :-( // alternativa č.2: místo COUNT(*) načíst z DB celý záznam a předat v parametru presenteru // výhoda: stejně jej bude potřebovat // nevýhoda: nadstandardní závislost mezi routerem a presenterem $params = $context->getQuery(); // $params['link_rewrite'] = $last; $params['lang'] = $lang; return new NPresenterRequest($presenter, $context->getMethod(), $params, $context->getPost(), $context->getFiles(), array('secured' => $context->isSecured())); }
function BasicAuthenticator($name, $pattern, &$request, &$response) { $this->realm_name = $name; $this->pattern = $pattern; if (IHttpRequest::validClass($request) && IHttpResponse::validClass($response)) { $this->request =& $request; $this->response =& $response; } }
function match(IHttpRequest $httpRequest) { $url = $httpRequest->getUrl(); $lang = $this->getDefaultLang(); $langs = Environment::getVariable("langs"); $langDomains = Environment::getVariable("langDomains"); //domains for languages or just directory prefix? if (count($langDomains)) { $path = '//' . $url->getHost() . $url->getPath(); foreach ($langDomains as $lang => $pattern) { $pattern = preg_quote($pattern, '~'); $pattern = preg_replace('~^//(www\\.)?~', '//(www\\.)?', $pattern); //www not mandatory if (preg_match("~^{$pattern}~", $path, $m)) { //matching absolute path $seoname = substr($path, strlen($m[0])); //what follows break; } } } else { //just language prefixes $path = $url->pathInfo; foreach ($langs as $lang => $txt) { if (preg_match("~^{$lang}/~", $path, $m)) { //matching relative path $seoname = substr($path, strlen($m[0])); //what follows break; } } } if (!isset($seoname)) { //default language possible without prefix $keys = array_keys($langs); $lang = array_shift($keys); $seoname = $url->pathInfo; } if (substr($seoname, -1) == '/') { $seoname = substr($seoname, 0, -1); } $page = PagesModel::getPageBySeoname('/' . $seoname, $lang); //just one level if (!$page) { if (preg_match('~^p([0-9]+)(-|$)~', $seoname, $matches)) { $page = PagesModel::getPageById($matches[1], $lang); if (!$page) { return NULL; } } else { return NULL; } } $params = array(); $params += $httpRequest->getQuery(); $params['id_page'] = $page['id_page']; $params['lang'] = $lang; return new PresenterRequest(self::PRESENTER, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(PresenterRequest::SECURED => $httpRequest->isSecured())); }
/** * Attempts to cache the sent entity by its last modification date. * @param string|int|DateTime last modified time * @param string strong entity tag validator * @return bool */ public function isModified($lastModified = NULL, $etag = NULL) { if ($lastModified) { $this->response->setHeader('Last-Modified', $this->response->date($lastModified)); } if ($etag) { $this->response->setHeader('ETag', '"' . addslashes($etag) . '"'); } $ifNoneMatch = $this->request->getHeader('If-None-Match'); if ($ifNoneMatch === '*') { $match = TRUE; // match, check if-modified-since } elseif ($ifNoneMatch !== NULL) { $etag = $this->response->getHeader('ETag'); if ($etag == NULL || strpos(' ' . strtr($ifNoneMatch, ",\t", ' '), ' ' . $etag) === FALSE) { return TRUE; } else { $match = TRUE; // match, check if-modified-since } } $ifModifiedSince = $this->request->getHeader('If-Modified-Since'); if ($ifModifiedSince !== NULL) { $lastModified = $this->response->getHeader('Last-Modified'); if ($lastModified != NULL && strtotime($lastModified) <= strtotime($ifModifiedSince)) { $match = TRUE; } else { return TRUE; } } if (empty($match)) { return TRUE; } $this->response->setCode(IHttpResponse::S304_NOT_MODIFIED); return FALSE; }
/** * Constructs URL path from PresenterRequest object. * @param Nette\Web\IHttpRequest * @param PresenterRequest * @return string|NULL */ public function constructUrl(PresenterRequest $request, IHttpRequest $context) { \Nette\Diagnostics\FireLogger::log('oooooooooooooo'); return NULL; // overime ze presenter je jeden ze podporovanych a existuje parameter 'id' static $presenters = array('Front:Spot' => TRUE, 'Front:Category' => TRUE, 'Front:Product' => TRUE); if (!isset($presenters[$request->getPresenterName()])) { return NULL; } $params = $request->getParams(); if (!isset($params['id'])) { return NULL; } // vse ok, generuj URL $uri = $context->getUri()->basePath . rawurlencode($params['id']); unset($params['id'], $params['action']); $query = http_build_query($params, '', '&'); if ($query !== '') { $uri .= '?' . $query; } return $uri; }
/** * Sends response to output. * @return void */ public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse) { $httpResponse->setContentType($this->contentType); $httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"'); $filesize = $length = filesize($this->file); $handle = fopen($this->file, 'r'); if ($this->resuming) { $httpResponse->setHeader('Accept-Ranges', 'bytes'); if (preg_match('#^bytes=(\\d*)-(\\d*)$#', $httpRequest->getHeader('Range'), $matches)) { list(, $start, $end) = $matches; if ($start === '') { $start = max(0, $filesize - $end); $end = $filesize - 1; } elseif ($end === '' || $end > $filesize - 1) { $end = $filesize - 1; } if ($end < $start) { $httpResponse->setCode(416); // requested range not satisfiable return; } $httpResponse->setCode(206); $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize); $length = $end - $start + 1; fseek($handle, $start); } else { $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize); } } $httpResponse->setHeader('Content-Length', $length); while (!feof($handle) && $length > 0) { echo $s = fread($handle, min(4000000.0, $length)); $length -= strlen($s); } fclose($handle); }
function match(IHttpRequest $httpRequest) { $path = $httpRequest->getUrl()->getPath(); //look for redirect record $newurl = RedirectModel::getByOldUrl($path); //fix pathinfo bug - strip "/index.php/" from url if (!$newurl and preg_match('~^/index\\.php~', $path)) { $newurl = preg_replace('~^/index\\.php~', '', $path); } if ($newurl) { RedirectModel::hit($path); if ($p = RedirectModel::parseHashIdLang($newurl)) { $newurl = Environment::getLinkHelper()->pageLink($p[0], $p[1]); if ($newurl == NULL) { return NULL; } } header("Location: {$newurl}", true, 301); //TODO (ask) if comented, output twice :/ better? echo "Moved permanetly to <a href='{$newurl}'>{$newurl}</a>"; exit; } return NULL; }
/** * Maps HTTP request to a Request object. * @param IHttpRequest * @return NPresenterRequest|NULL */ public function match(IHttpRequest $httpRequest) { // combine with precedence: mask (params in URL-path), fixity, query, (post,) defaults // 1) URL MASK $url = $httpRequest->getUrl(); if ($this->type === self::HOST) { $path = '//' . $url->getHost() . $url->getPath(); } elseif ($this->type === self::RELATIVE) { $basePath = $url->getBasePath(); if (strncmp($url->getPath(), $basePath, strlen($basePath)) !== 0) { return NULL; } $path = (string) substr($url->getPath(), strlen($basePath)); } else { $path = $url->getPath(); } if ($path !== '') { $path = rtrim($path, '/') . '/'; } if (!$matches = NStrings::match($path, $this->re)) { // stop, not matched return NULL; } // deletes numeric keys, restore '-' chars $params = array(); foreach ($matches as $k => $v) { if (is_string($k) && $v !== '') { $params[str_replace('___', '-', $k)] = $v; // trick } } // 2) CONSTANT FIXITY foreach ($this->metadata as $name => $meta) { if (isset($params[$name])) { //$params[$name] = $this->flags & self::CASE_SENSITIVE === 0 ? strtolower($params[$name]) : */$params[$name]; // strtolower damages UTF-8 } elseif (isset($meta['fixity']) && $meta['fixity'] !== self::OPTIONAL) { $params[$name] = NULL; // cannot be overwriten in 3) and detected by isset() in 4) } } // 3) QUERY if ($this->xlat) { $params += self::renameKeys($httpRequest->getQuery(), array_flip($this->xlat)); } else { $params += $httpRequest->getQuery(); } // 4) APPLY FILTERS & FIXITY foreach ($this->metadata as $name => $meta) { if (isset($params[$name])) { if (!is_scalar($params[$name])) { } elseif (isset($meta[self::FILTER_TABLE][$params[$name]])) { // applies filterTable only to scalar parameters $params[$name] = $meta[self::FILTER_TABLE][$params[$name]]; } elseif (isset($meta[self::FILTER_TABLE]) && !empty($meta[self::FILTER_STRICT])) { return NULL; // rejected by filterTable } elseif (isset($meta[self::FILTER_IN])) { // applies filterIn only to scalar parameters $params[$name] = call_user_func($meta[self::FILTER_IN], (string) $params[$name]); if ($params[$name] === NULL && !isset($meta['fixity'])) { return NULL; // rejected by filter } } } elseif (isset($meta['fixity'])) { $params[$name] = $meta[self::VALUE]; } } // 5) BUILD Request if (!isset($params[self::PRESENTER_KEY])) { throw new InvalidStateException('Missing presenter in route definition.'); } if (isset($this->metadata[self::MODULE_KEY])) { if (!isset($params[self::MODULE_KEY])) { throw new InvalidStateException('Missing module in route definition.'); } $presenter = $params[self::MODULE_KEY] . ':' . $params[self::PRESENTER_KEY]; unset($params[self::MODULE_KEY], $params[self::PRESENTER_KEY]); } else { $presenter = $params[self::PRESENTER_KEY]; unset($params[self::PRESENTER_KEY]); } return new NPresenterRequest( $presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(NPresenterRequest::SECURED => $httpRequest->isSecured()) ); }
/** * Constructs absolute URL from PresenterRequest object. * @param IHttpRequest * @param PresenterRequest * @return string|NULL */ public function constructUrl(PresenterRequest $appRequest, IHttpRequest $httpRequest) { if ($this->flags & self::ONE_WAY) { return NULL; } $params = $appRequest->getParams(); $metadata = $this->metadata; $presenter = $appRequest->getPresenterName(); $params[self::PRESENTER_KEY] = $presenter; if (isset($metadata[self::MODULE_KEY])) { // try split into module and [submodule:]presenter parts $module = $metadata[self::MODULE_KEY]; if (isset($module['fixity']) && strncasecmp($presenter, $module[self::VALUE] . ':', strlen($module[self::VALUE]) + 1) === 0) { $a = strlen($module[self::VALUE]); } else { $a = strrpos($presenter, ':'); } if ($a === FALSE) { $params[self::MODULE_KEY] = ''; } else { $params[self::MODULE_KEY] = substr($presenter, 0, $a); $params[self::PRESENTER_KEY] = substr($presenter, $a + 1); } } foreach ($metadata as $name => $meta) { if (!isset($params[$name])) { continue; } // retains NULL values if (isset($meta['fixity'])) { if (is_scalar($params[$name]) && strcasecmp($params[$name], $meta[self::VALUE]) === 0) { // remove default values; NULL values are retain unset($params[$name]); continue; } elseif ($meta['fixity'] === self::CONSTANT) { return NULL; // missing or wrong parameter '$name' } } if (!is_scalar($params[$name])) { } elseif (isset($meta['filterTable2'][$params[$name]])) { $params[$name] = $meta['filterTable2'][$params[$name]]; } elseif (isset($meta[self::FILTER_OUT])) { $params[$name] = call_user_func($meta[self::FILTER_OUT], $params[$name]); } if (isset($meta[self::PATTERN]) && !preg_match($meta[self::PATTERN], rawurldecode($params[$name]))) { return NULL; // pattern not match } } // compositing path $sequence = $this->sequence; $brackets = array(); $required = 0; $uri = ''; $i = count($sequence) - 1; do { $uri = $sequence[$i] . $uri; if ($i === 0) { break; } $i--; $name = $sequence[$i]; $i--; // parameter name if ($name === ']') { // opening optional part $brackets[] = $uri; } elseif ($name[0] === '[') { // closing optional part $tmp = array_pop($brackets); if ($required < count($brackets) + 1) { // is this level optional? if ($name !== '[!') { // and not "required"-optional $uri = $tmp; } } else { $required = count($brackets); } } elseif ($name[0] === '?') { // "foo" parameter continue; } elseif (isset($params[$name]) && $params[$name] != '') { // intentionally == $required = count($brackets); // make this level required $uri = $params[$name] . $uri; unset($params[$name]); } elseif (isset($metadata[$name]['fixity'])) { // has default value? $uri = $metadata[$name]['defOut'] . $uri; } else { return NULL; // missing parameter '$name' } } while (TRUE); // build query string if ($this->xlat) { $params = self::renameKeys($params, $this->xlat); } $sep = ini_get('arg_separator.input'); $query = http_build_query($params, '', $sep ? $sep[0] : '&'); if ($query != '') { $uri .= '?' . $query; } // intentionally == // absolutize path if ($this->type === self::RELATIVE) { $uri = '//' . $httpRequest->getUri()->getAuthority() . $httpRequest->getUri()->getBasePath() . $uri; } elseif ($this->type === self::PATH) { $uri = '//' . $httpRequest->getUri()->getAuthority() . $uri; } if (strpos($uri, '//', 2) !== FALSE) { return NULL; // TODO: implement counterpart in match() ? } $uri = ($this->flags & self::SECURED ? 'https:' : 'http:') . $uri; return $uri; }
/** * Sends response to output. * @return void */ public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse) { $httpResponse->setContentType($this->contentType); $httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"'); $filesize = $length = filesize($this->file); $handle = fopen($this->file, 'r'); if ($this->resuming) { $httpResponse->setHeader('Accept-Ranges', 'bytes'); $range = $httpRequest->getHeader('Range'); if ($range !== NULL) { $range = substr($range, 6); // 6 == strlen('bytes=') list($start, $end) = explode('-', $range); if ($start == NULL) { $start = 0; } if ($end == NULL) { $end = $filesize - 1; } if ($start < 0 || $end <= $start || $end > $filesize -1) { $httpResponse->setCode(416); // requested range not satisfiable return; } $httpResponse->setCode(206); $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize); $length = $end - $start + 1; fseek($handle, $start); } else { $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize); } } $httpResponse->setHeader('Content-Length', $length); while (!feof($handle)) { echo fread($handle, 4e6); } fclose($handle); }
/** * Constructs absolute URL from PresenterRequest object. * @param Nette\Web\IHttpRequest * @param PresenterRequest * @return string|NULL */ public function constructUrl(PresenterRequest $appRequest, IHttpRequest $httpRequest) { if ($this->flags & self::ONE_WAY) { return NULL; } $params = $appRequest->getParams(); $metadata = $this->metadata; $presenter = $appRequest->getPresenterName(); if (isset($metadata[self::MODULE_KEY])) { if (isset($metadata[self::MODULE_KEY]['fixity'])) { $a = strlen($metadata[self::MODULE_KEY]['default']); if (substr($presenter, $a, 1) !== ':') { return NULL; // module not match } } else { $a = strrpos($presenter, ':'); } $params[self::MODULE_KEY] = substr($presenter, 0, $a); $params[self::PRESENTER_KEY] = substr($presenter, $a + 1); } else { $params[self::PRESENTER_KEY] = $presenter; } foreach ($metadata as $name => $meta) { if (!isset($params[$name])) { continue; } // retains NULL values if (isset($meta['fixity'])) { if (is_scalar($params[$name]) && strcasecmp($params[$name], $meta['default']) === 0) { // remove default values; NULL values are retain unset($params[$name]); continue; } elseif ($meta['fixity'] === self::CONSTANT) { return NULL; // missing or wrong parameter '$name' } } if (!is_scalar($params[$name])) { } elseif (isset($meta['filterTable2'][$params[$name]])) { $params[$name] = $meta['filterTable2'][$params[$name]]; } elseif (isset($meta[self::FILTER_OUT])) { $params[$name] = call_user_func($meta[self::FILTER_OUT], $params[$name]); } if (isset($meta[self::PATTERN]) && !preg_match($meta[self::PATTERN], $params[$name])) { return NULL; // pattern not match } } // compositing path $sequence = $this->sequence; $optional = TRUE; $uri = ''; $i = count($sequence) - 1; do { $uri = $sequence[$i] . $uri; if ($i === 0) { break; } $i--; $name = $sequence[$i]; $i--; // parameter name if ($name[0] === '?') { // "foo" parameter continue; } elseif (isset($params[$name]) && $params[$name] != '') { // intentionally == $optional = FALSE; $uri = $params[$name] . $uri; unset($params[$name]); } elseif (isset($metadata[$name]['fixity'])) { // has default value? if ($optional) { $uri = ''; } elseif ($metadata[$name]['default'] == '') { // intentionally == if ($uri[0] === '/' && substr($sequence[$i], -1) === '/') { return NULL; // default value is empty but is required } } else { $uri = $metadata[$name]['defOut'] . $uri; } } else { return NULL; // missing parameter '$name' } } while (TRUE); // build query string if ($this->xlat) { $params = self::renameKeys($params, $this->xlat); } $sep = ini_get('arg_separator.input'); $query = http_build_query($params, '', $sep ? $sep[0] : '&'); if ($query != '') { $uri .= '?' . $query; } // intentionally == // absolutize path if ($this->type === self::RELATIVE) { $uri = '//' . $httpRequest->getUri()->getAuthority() . $httpRequest->getUri()->getBasePath() . $uri; } elseif ($this->type === self::PATH) { $uri = '//' . $httpRequest->getUri()->getAuthority() . $uri; } $uri = ($this->flags & self::SECURED ? 'https:' : 'http:') . $uri; return $uri; }
/** * Does session exists for the current request? * @return bool */ public function exists() { return self::$started || $this->request->getCookie(session_name()) !== NULL; }
function initRequest() { $class = trim($this->config->getRequestManager()); if ($class === '') { $class = $this->default_request_manager; } $this->request = JPHP::loadClass($class, array(&$this)); if (IHttpRequest::validClass($this->request)) { $names = $this->config->getRequestManagerPropertyNames(); while ($names->hasMoreElements()) { $name = $names->nextElement(); $value = $this->config->getRequestManagerProperty($name); eval('$this->request->set' . ucfirst($name) . '("' . $value . '");'); } } }