scheme user password host port basePath relativeUrl | | | | | | | --\ /--\ /------\ /-------\ /--\/--\/----------------------------\ http://john:x0y17575@nette.org:8042/en/manual.php?name=param#fragment <-- absoluteUrl \__________________________/\____________/^\________/^\______/ | | | | authority path query fragment- authority: [user[:password]@]host[:port] - hostUrl: http://user:password@nette.org:8042 - basePath: /en/ (everything before relative URI not including the script name) - baseUrl: http://user:password@nette.org:8042/en/ - relativeUrl: manual.php
public function render($rowData) { if ($this->_renderer) { return call_user_func($this->_renderer, $this); } // Direct URL if ($this->_url !== NULL) { // URL callback if (is_callable($this->_url)) { $url = call_user_func($this->_url, $rowData); } else { $url = new Nette\Http\Url($this->_url); foreach ($this->_table->getIdColumns() as $key) { $url->appendQuery(array('record' . ucfirst($key) => isset($rowData->{$key}) ? $rowData->{$key} : NULL)); } } $this->element->href((string) $url); // Standard action's URL } else { $this->element->href($this->_table->createActionLink($this->getName(), $rowData)); } // Class if (($class = $this->getClass($rowData)) !== NULL) { $this->element->class .= " {$class}"; } return (string) $this->element; }
public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return null; } $params = $appRequest->getParameters(); $urlStack = []; // Module prefix $moduleFrags = explode(":", Strings::lower($appRequest->getPresenterName())); $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; // Resource $urlStack[] = Strings::lower($resourceName); // Id if (isset($params['id']) && is_scalar($params['id'])) { $urlStack[] = $params['id']; unset($params['id']); } // Set custom action if (isset($params['action']) && $this->_isApiAction($params['action'])) { unset($params['action']); } $url = $refUrl->getBaseUrl() . implode('/', $urlStack); // Add query parameters if (!empty($params)) { $url .= "?" . http_build_query($params); } return $url; }
/** * @param Payment $payment * @return Payment */ public static function addTrackingParameters(Payment $payment) { $resURL = $payment->getResURL(); $url = new Url($resURL); $url->setQueryParameter('utm_nooverride', 1); $payment->setResURL($url->getAbsoluteUrl()); return $payment; }
public static function addTrackingParameters(Payment $payment) { $redirectUrls = $payment->getRedirectUrls(); $url = new Url($redirectUrls->getReturnUrl()); $url->setQueryParameter('utm_nooverride', 1); $redirectUrls->setReturnUrl($url->getAbsoluteUrl()); $payment->setRedirectUrls($redirectUrls); return $payment; }
/** * Fetches video data by youtube url * @param string $videoUrl YouTube url * @return Video */ public function getVideoByUrl($videoUrl) { $url = new Nette\Http\Url($videoUrl); if (stripos($url->host, 'youtu.be') !== false) { return $this->getVideo(trim($url->getPath(), '/')); } $videoId = $url->getQueryParameter('v'); if (stripos($url->host, 'youtube.com') === false || $videoId === null) { throw new Nette\InvalidArgumentException('videoUrl must be valid youtube url.'); } return $this->getVideo($videoId); }
/** * Restores request from session. * @param string $key */ public function redirectToRequest($key) { $request = $this->requestStorage->loadRequest($key); if (!$request) { return; } $parameters = $request->getParameters(); $parameters[Presenter::FLASH_KEY] = $this->getParameter(Presenter::FLASH_KEY); $parameters[RequestStorage::REQUEST_KEY] = $key; $request->setParameters($parameters); $refUrl = new Url($this->httpRequest->getUrl()); $refUrl->setPath($this->httpRequest->getUrl()->getScriptPath()); $url = $this->router->constructUrl($request, $refUrl); $this->redirectUrl($url); }
/** * Constructs absolute URL from Request object. * * @param Nette\Application\Request * @param Nette\Http\Url * * @return string|NULL */ public function constructUrl(Application\Request $appRequest, Nette\Http\Url $refUrl) { if ($this->flags & self::ONE_WAY) { return null; } $params = $appRequest->getParameters(); // 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]); } } $url = ($this->flags & self::SECURED ? 'https://' : 'http://') . $refUrl->getAuthority() . $refUrl->getPath(); $sep = ini_get('arg_separator.input'); $query = http_build_query($params, '', $sep ? $sep[0] : '&'); if ($query != '') { // intentionally == $url .= '?' . $query; } return $url; }
/** * @return bool */ public function validateRecaptcha() { $httpData = $this->getForm()->getHttpData(); if (!isset($httpData['g-recaptcha-response'])) { $this->addError($this->getFilledMessage()); return TRUE; } $this->validateKeys(); $url = new Url(); $url->setHost('www.google.com')->setScheme('https')->setPath('recaptcha/api/siteverify')->setQueryParameter('secret', $this->secretKey)->setQueryParameter('response', $httpData['g-recaptcha-response']); $data = json_decode(file_get_contents((string) $url)); if (!isset($data->success) || $data->success !== TRUE) { $this->addError($this->getValidMessage()); } return TRUE; }
/** * Calls remote API. * * @param string * @return mixed json-decoded result * @throws \NetteAddons\IOException */ protected function exec($path) { try { $url = new Url($this->baseUrl . '/' . ltrim($path, '/')); if ($this->clientId && $this->clientSecret) { $url->appendQuery(array('client_id' => $this->clientId, 'client_secret' => $this->clientSecret)); } $request = $this->requestFactory->create($url); $request->addHeader('Accept', "application/vnd.github.{$this->apiVersion}+json"); return \Nette\Utils\Json::decode($request->execute()); } catch (\NetteAddons\Utils\StreamException $e) { throw new \NetteAddons\IOException('Request execution failed.', NULL, $e); } catch (\Nette\Utils\JsonException $e) { throw new \NetteAddons\IOException('GitHub API returned invalid JSON.', NULL, $e); } }
private function process($url, string $directory, string $parameter, array &$dependencies = []) : string { $url = new Nette\Http\Url($url); $time = NULL; if ($url->getHost() && (!$this->request || $url->getHost() !== $this->request->getUrl()->getHost())) { $headers = @get_headers($url, TRUE); if (is_array($headers) && isset($headers['Last-Modified'])) { $time = (new DateTime($headers['Last-Modified']))->getTimestamp(); } } elseif (is_file($filename = implode(DIRECTORY_SEPARATOR, [rtrim($directory, '\\/'), ltrim($url->getPath(), '\\/')]))) { $time = filemtime($filename); unset($dependencies[Nette\Caching\Cache::EXPIRE]); $dependencies[Nette\Caching\Cache::FILES] = $filename; } $url->setQueryParameter($parameter, $time ?: ($this->time ?: ($this->time = time()))); return preg_replace($pattern = '#^(\\+|/+)#', preg_match($pattern, $url->getPath()) ? DIRECTORY_SEPARATOR : NULL, $url); }
public function validateRecaptcha() { $httpData = $this->getForm()->getHttpData(); if (!isset($httpData['g-recaptcha-response'])) { $this->addError('Please fill antispam.'); return TRUE; } $url = new Url(); $url->setHost('www.google.com')->setScheme('https')->setPath('recaptcha/api/siteverify')->setQueryParameter('secret', $this->secretKey)->setQueryParameter('response', $httpData['g-recaptcha-response']); $data = json_decode(file_get_contents((string) $url)); if (isset($data->success) && $data->success === TRUE) { return TRUE; } else { $this->addError('Antispam detection wasn\'t success.'); return TRUE; } }
/** * Funkce pro odeslání GET požadavku bez čekání na získání odpovědi * @param string $url * @throws \Exception */ public static function sendBackgroundGetRequest($url) { $url = new Url($url); $host = $url->getHost(); if (empty($host)) { $host = 'localhost'; } #region parametry připojení switch ($url->getScheme()) { case 'https': $scheme = 'ssl://'; $port = 443; break; case 'http': default: $scheme = ''; $port = 80; } $urlPort = $url->getPort(); if (!empty($urlPort)) { $port = $urlPort; } #endregion $fp = @fsockopen($scheme . $host, $port, $errno, $errstr, self::REQUEST_TIMEOUT); if (!$fp) { Debugger::log($errstr, ILogger::ERROR); throw new \Exception($errstr, $errno); } $path = $url->getPath() . ($url->getQuery() != "" ? '?' . $url->getQuery() : ''); fputs($fp, "GET " . $path . " HTTP/1.0\r\nHost: " . $host . "\r\n\r\n"); fputs($fp, "Connection: close\r\n"); fputs($fp, "\r\n"); }
public function createComponentPlayer() { $host = explode(".", $this->playUrl->getHost()); $provider = Nette\Utils\Strings::lower($host[count($host) - 2]); $handler = "\\App\\Controls\\" . ucfirst($provider) . "Player"; if (class_exists($handler)) { $player = new $handler($this->playUrl); } else { $player = new \App\Controls\NoPlayer($this->playUrl); } return $player; }
/** * Constructs absolute URL from Request object. * @return string|NULL */ public function constructUrl(array $params, Nette\Http\Url $refUrl) { if ($this->flags & self::ONE_WAY) { 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]); } } $url = ($this->flags & self::SECURED ? 'https://' : $refUrl->getScheme() . '://') . $refUrl->getAuthority() . $refUrl->getPath(); $sep = ini_get('arg_separator.input'); $query = http_build_query($params, '', $sep ? $sep[0] : '&'); if ($query != '') { // intentionally == $url .= '?' . $query; } return $url; }
/** * Constructs absolute URL from Request object. * * @return string|NULL */ public function constructUrl(AppRequest $appRequest, Url $refUrl) { if ($this->flags & self::ONE_WAY) { return NULL; } $params = $appRequest->getParameters(); if (!isset($params['action']) || !is_string($params['action'])) { return NULL; } $key = $appRequest->getPresenterName() . ':' . $params['action']; if (!isset($this->tableOut[$key])) { return NULL; } if ($this->lastRefUrl !== $refUrl) { $this->lastBaseUrl = $refUrl->getBaseUrl(); $this->lastRefUrl = $refUrl; } unset($params['action']); $slug = $this->tableOut[$key]; $query = ($tmp = http_build_query($params)) ? '?' . $tmp : ''; $url = $this->lastBaseUrl . $slug . $query; return $url; }
/** * Funkce pro doplnění základních parametrů do API * @param string $jsonString * @return string */ private function replaceJsonVariables($jsonString) { $link = $this->link('//Default:default'); $url = new Url($link); if (empty($url->host)) { $url = $this->getHttpRequest()->getUrl()->hostUrl; if (Strings::endsWith($url, '/')) { rtrim($url, '/'); } $url .= $link; $url = new Url($url); } $hostUrl = Strings::endsWith($url->getHost(), '/') ? rtrim($url->getHost(), '/') : $url->getHost(); $basePath = rtrim($url->getBasePath(), '/'); $paramsArr = ['%VERSION%' => $this->getInstallVersion(), '%BASE_PATH%' => $basePath, '%HOST%' => $hostUrl]; $arrSearch = []; $arrReplace = []; foreach ($paramsArr as $key => $value) { $arrSearch[] = $key; $arrReplace[] = $value; } return str_replace($arrSearch, $arrReplace, $jsonString); }
protected function setupCallbackUrl() { //Create and setup callback URL $this->callback_url = new Url(); $this->callback_url->setScheme('http'); $this->callback_url->setHost('ws.audioscrobbler.com'); $this->callback_url->setPath('/2.0/'); //2.0 - API version $this->callback_url->appendQuery("api_key={$this->key}"); if ($this->data_format == self::DATA_JSON) { $this->callback_url->appendQuery('format=json'); } //JSON result }
/** * Sign current request * * @param Signature\SignatureMethod $method * * @return $this */ public function signRequest(Signature\SignatureMethod $method) { $this->url->setQueryParameter('oauth_signature_method', $method->getName()); $signature = $method->buildSignature($this->getSignatureBaseString(), $this->consumer, $this->token); $this->url->setQueryParameter('oauth_signature', $signature); $parameters = $this->getParameters(); ksort($parameters, SORT_STRING); $authHeader = NULL; foreach ($parameters as $key => $value) { if (in_array($key, $this->oauthHeader)) { $authHeader .= ' ' . $key . '="' . OAuth\Utils\Url::urlEncodeRFC3986($value) . '",'; // Remove oauth from query parameter $this->url->setQueryParameter($key, NULL); } } if ($authHeader !== NULL) { $this->headers['Authorization'] = 'OAuth ' . trim(rtrim($authHeader, ',')); } return $this; }
/** * Pro zadane URL vytvori URL na minimalizacni skript * @param string $url * @param int $width [optional] * @param int $height [optional] * @return string */ public function min($url, $width = NULL, $height = NULL, $topcut = FALSE) { $min = new Url($this->scriptUrl); $min->setQueryParameter('file', $url); if ($width) { $min->setQueryParameter('w', $width); } if ($height) { $min->setQueryParameter('h', $height); } if ($width && $height) { $min->setQueryParameter('exact', TRUE); if ($topcut) { $min->setQueryParameter('topcut', TRUE); } } $minUrl = "/" . $min->getRelativeUrl(); return $minUrl; }
/** * Request/URL factory. * @param PresenterComponent base * @param string destination in format "[[module:]presenter:]action" or "signal!" or "this" * @param array array of arguments * @param string forward|redirect|link * @return string URL * @throws InvalidLinkException * @internal */ protected function createRequest($component, $destination, array $args, $mode) { // note: createRequest supposes that saveState(), run() & tryCall() behaviour is final // cached services for better performance static $presenterFactory, $router, $refUrl; if ($presenterFactory === NULL) { $presenterFactory = $this->application->getPresenterFactory(); $router = $this->application->getRouter(); $refUrl = new Http\Url($this->httpRequest->getUrl()); $refUrl->setPath($this->httpRequest->getUrl()->getScriptPath()); } $this->lastCreatedRequest = $this->lastCreatedRequestFlag = NULL; // PARSE DESTINATION // 1) fragment $a = strpos($destination, '#'); if ($a === FALSE) { $fragment = ''; } else { $fragment = substr($destination, $a); $destination = substr($destination, 0, $a); } // 2) ?query syntax $a = strpos($destination, '?'); if ($a !== FALSE) { parse_str(substr($destination, $a + 1), $args); // requires disabled magic quotes $destination = substr($destination, 0, $a); } // 3) URL scheme $a = strpos($destination, '//'); if ($a === FALSE) { $scheme = FALSE; } else { $scheme = substr($destination, 0, $a); $destination = substr($destination, $a + 2); } // 4) signal or empty if (!$component instanceof Presenter || substr($destination, -1) === '!') { $signal = rtrim($destination, '!'); $a = strrpos($signal, ':'); if ($a !== FALSE) { $component = $component->getComponent(strtr(substr($signal, 0, $a), ':', '-')); $signal = (string) substr($signal, $a + 1); } if ($signal == NULL) { // intentionally == throw new InvalidLinkException("Signal must be non-empty string."); } $destination = 'this'; } if ($destination == NULL) { // intentionally == throw new InvalidLinkException("Destination must be non-empty string."); } // 5) presenter: action $current = FALSE; $a = strrpos($destination, ':'); if ($a === FALSE) { $action = $destination === 'this' ? $this->action : $destination; $presenter = $this->getName(); $presenterClass = get_class($this); } else { $action = (string) substr($destination, $a + 1); if ($destination[0] === ':') { // absolute if ($a < 2) { throw new InvalidLinkException("Missing presenter name in '{$destination}'."); } $presenter = substr($destination, 1, $a - 1); } else { // relative $presenter = $this->getName(); $b = strrpos($presenter, ':'); if ($b === FALSE) { // no module $presenter = substr($destination, 0, $a); } else { // with module $presenter = substr($presenter, 0, $b + 1) . substr($destination, 0, $a); } } try { $presenterClass = $presenterFactory->getPresenterClass($presenter); } catch (Application\InvalidPresenterException $e) { throw new InvalidLinkException($e->getMessage(), NULL, $e); } } // PROCESS SIGNAL ARGUMENTS if (isset($signal)) { // $component must be IStatePersistent $reflection = new PresenterComponentReflection(get_class($component)); if ($signal === 'this') { // means "no signal" $signal = ''; if (array_key_exists(0, $args)) { throw new InvalidLinkException("Unable to pass parameters to 'this!' signal."); } } elseif (strpos($signal, self::NAME_SEPARATOR) === FALSE) { // counterpart of signalReceived() & tryCall() $method = $component->formatSignalMethod($signal); if (!$reflection->hasCallableMethod($method)) { throw new InvalidLinkException("Unknown signal '{$signal}', missing handler {$reflection->name}::{$method}()"); } if ($args) { // convert indexed parameters to named self::argsToParams(get_class($component), $method, $args); } } // counterpart of IStatePersistent if ($args && array_intersect_key($args, $reflection->getPersistentParams())) { $component->saveState($args); } if ($args && $component !== $this) { $prefix = $component->getUniqueId() . self::NAME_SEPARATOR; foreach ($args as $key => $val) { unset($args[$key]); $args[$prefix . $key] = $val; } } } // PROCESS ARGUMENTS if (is_subclass_of($presenterClass, __CLASS__)) { if ($action === '') { $action = self::DEFAULT_ACTION; } $current = ($action === '*' || strcasecmp($action, $this->action) === 0) && $presenterClass === get_class($this); $reflection = new PresenterComponentReflection($presenterClass); if ($args || $destination === 'this') { // counterpart of run() & tryCall() $method = $presenterClass::formatActionMethod($action); if (!$reflection->hasCallableMethod($method)) { $method = $presenterClass::formatRenderMethod($action); if (!$reflection->hasCallableMethod($method)) { $method = NULL; } } // convert indexed parameters to named if ($method === NULL) { if (array_key_exists(0, $args)) { throw new InvalidLinkException("Unable to pass parameters to action '{$presenter}:{$action}', missing corresponding method."); } } elseif ($destination === 'this') { self::argsToParams($presenterClass, $method, $args, $this->params); } else { self::argsToParams($presenterClass, $method, $args); } } // counterpart of IStatePersistent if ($args && array_intersect_key($args, $reflection->getPersistentParams())) { $this->saveState($args, $reflection); } if ($mode === 'redirect') { $this->saveGlobalState(); } $globalState = $this->getGlobalState($destination === 'this' ? NULL : $presenterClass); if ($current && $args) { $tmp = $globalState + $this->params; foreach ($args as $key => $val) { if (http_build_query(array($val)) !== (isset($tmp[$key]) ? http_build_query(array($tmp[$key])) : '')) { $current = FALSE; break; } } } $args += $globalState; } // ADD ACTION & SIGNAL & FLASH if ($action) { $args[self::ACTION_KEY] = $action; } if (!empty($signal)) { $args[self::SIGNAL_KEY] = $component->getParameterId($signal); $current = $current && $args[self::SIGNAL_KEY] === $this->getParameter(self::SIGNAL_KEY); } if (($mode === 'redirect' || $mode === 'forward') && $this->hasFlashSession()) { $args[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY); } $this->lastCreatedRequest = new Application\Request($presenter, Application\Request::FORWARD, $args, array(), array()); $this->lastCreatedRequestFlag = array('current' => $current); if ($mode === 'forward' || $mode === 'test') { return; } // CONSTRUCT URL $url = $router->constructUrl($this->lastCreatedRequest, $refUrl); if ($url === NULL) { unset($args[self::ACTION_KEY]); $params = urldecode(http_build_query($args, NULL, ', ')); throw new InvalidLinkException("No route for {$presenter}:{$action}({$params})"); } // make URL relative if possible if ($mode === 'link' && $scheme === FALSE && !$this->absoluteUrls) { $hostUrl = $refUrl->getHostUrl() . '/'; if (strncmp($url, $hostUrl, strlen($hostUrl)) === 0) { $url = substr($url, strlen($hostUrl) - 1); } } return $url . $fragment; }
/** * Constructs absolute URL from Request object. * @return string|NULL */ public function constructUrl(Application\Request $appRequest, Nette\Http\Url $refUrl) { if ($this->flags & self::ONE_WAY) { return NULL; } $params = $appRequest->getParameters(); $metadata = $this->metadata; $presenter = $appRequest->getPresenterName(); $params[self::PRESENTER_KEY] = $presenter; if (isset($metadata[NULL][self::FILTER_OUT])) { $params = call_user_func($metadata[NULL][self::FILTER_OUT], $params); if ($params === NULL) { return NULL; } } 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 ($params[$name] === FALSE) { $params[$name] = '0'; } if (is_scalar($params[$name]) ? strcasecmp($params[$name], $meta[self::VALUE]) === 0 : $params[$name] === $meta[self::VALUE]) { // 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]) && isset($meta['filterTable2'][$params[$name]])) { $params[$name] = $meta['filterTable2'][$params[$name]]; } elseif (isset($meta['filterTable2']) && !empty($meta[self::FILTER_STRICT])) { return NULL; } 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 = NULL; // NULL for auto-optional $url = ''; $i = count($sequence) - 1; do { $url = $sequence[$i] . $url; if ($i === 0) { break; } $i--; $name = $sequence[$i]; $i--; // parameter name if ($name === ']') { // opening optional part $brackets[] = $url; } 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 $url = $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 $url = $params[$name] . $url; unset($params[$name]); } elseif (isset($metadata[$name]['fixity'])) { // has default value? if ($required === NULL && !$brackets) { // auto-optional $url = ''; } else { $url = $metadata[$name]['defOut'] . $url; } } else { return NULL; // missing parameter '$name' } } while (TRUE); // absolutize path if ($this->type === self::RELATIVE) { $url = '//' . $refUrl->getAuthority() . $refUrl->getBasePath() . $url; } elseif ($this->type === self::PATH) { $url = '//' . $refUrl->getAuthority() . $url; } else { $host = $refUrl->getHost(); $host = ip2long($host) ? array($host) : array_reverse(explode('.', $host)); $url = strtr($url, array('/%basePath%/' => $refUrl->getBasePath(), '%tld%' => $host[0], '%domain%' => isset($host[1]) ? "{$host['1']}.{$host['0']}" : $host[0])); } if (strpos($url, '//', 2) !== FALSE) { return NULL; } $url = ($this->flags & self::SECURED ? 'https:' : 'http:') . $url; // 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 != '') { // intentionally == $url .= '?' . $query; } return $url; }
private function createFileRoute(array $route) { $web = $route['metadata']['web'][Nette\Application\Routers\Route::VALUE]; unset($route['metadata']['web']); return new Nette\Application\Routers\Route(...array_values(array_merge_recursive(['mask' => self::FILE_MASK] + $route, ['metadata' => ['file' => [Nette\Application\Routers\Route::PATTERN => '[a-z0-9.-/]+'], NULL => [Nette\Application\Routers\Route::FILTER_IN => function (array $params) { $webDir = implode(DIRECTORY_SEPARATOR, [$this->wwwDir, 'web', $params['web']]); $domainDir = implode(DIRECTORY_SEPARATOR, [$webDir, 'domain', $domain = $params['domain']]); $webFile = implode(DIRECTORY_SEPARATOR, [$webDir, $file = $params['file']]); $domainFile = implode(DIRECTORY_SEPARATOR, [$domainDir, $file]); if (is_file($domainFile)) { $params['webDomain'] = $domain; } elseif (!is_file($webFile)) { return NULL; } return $params; }, Nette\Application\Routers\Route::FILTER_OUT => function (array $params) use($web) { if (!isset($params['file']) || !($file = $params['file'])) { return NULL; } $webDir = implode(DIRECTORY_SEPARATOR, [$this->wwwDir, 'web', $params['web'] = $web]); $webFile = implode(DIRECTORY_SEPARATOR, [$webDir, $file]); $domainDir = implode(DIRECTORY_SEPARATOR, [$webDir, 'domain', $domain = $params['domain']]); $domainFile = implode(DIRECTORY_SEPARATOR, [$domainDir, $file]); $directory = NULL; if (is_file($domainFile)) { $params['webDomain'] = $domain; $directory = $domainDir; } elseif (is_file($webFile)) { $directory = $webDir; } else { unset($params['web']); $directory = $this->wwwDir; } if ((!isset($params['version']) || $params['version']) && $directory) { $url = new Nette\Http\Url(call_user_func($this->versionFilter, $file, $directory, $parameter = is_string($params['version'] ?? NULL) ? $params['version'] : 'version')); $params['version'] = $url->getQueryParameter($parameter); } else { unset($params['version']); } return array_intersect_key($params, array_flip(['domain', 'web', 'webDomain', 'file', 'version'])); }]]]))); }
/** * Generates URL to PayPal for redirection. * @return Nette\Http\Url */ public function getUrl() { $url = new Url($this->sandbox ? self::SANDBOX_PAYPAL_URL : self::PAYPAL_URL); $query = array('cmd' => '_express-checkout', 'token' => $this->token); $url->setQuery($query); return $url; }
/** * Send OAuth response * @param array|\Traversable $data * @param string|null $redirectUrl * @param int $code */ public function oauthResponse($data, $redirectUrl = NULL, $code = 200) { if ($data instanceof \Traversable) { $data = iterator_to_array($data); } $data = (array) $data; // Redirect, if there is URL if ($redirectUrl !== NULL) { $url = new Url($redirectUrl); if ($this->getParameter('response_type') == 'token') { $url->setFragment(http_build_query($data)); } else { $url->appendQuery($data); } $this->redirectUrl($url); } // else send JSON response foreach ($data as $key => $value) { $this->payload->{$key} = $value; } $this->getHttpResponse()->setCode($code); $this->sendResponse(new JsonResponse($this->payload)); }
/** * Constructs absolute URL from Request object. * @param \Nette\Application\Request $appRequest * @param \Nette\Http\Url $refUrl * @throws \Nette\InvalidStateException * @return string|NULL */ public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return NULL; } $parameters = $appRequest->getParameters(); $url = $refUrl->getBaseUrl(); $urlStack = array(); // Module prefix. $moduleFrags = explode(":", Strings::lower($appRequest->getPresenterName())); $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; // Associations. if (isset($parameters['associations']) && Validators::is($parameters['associations'], 'array')) { $associations =& $parameters['associations']; if (count($associations) % 2 !== 0) { throw new InvalidStateException("Number of associations is not even"); } foreach ($associations as $key => $value) { $urlStack[] = $key; $urlStack[] = $value; } } // Resource. $urlStack[] = Strings::lower($resourceName); // Id. if (isset($parameters['id']) && Validators::is($parameters['id'], 'scalar')) { $urlStack[] = $parameters['id']; } return $url . implode('/', $urlStack); }
public function setParam($key, $value) { $this->queryArray[$key] = $value; parent::setQuery(\http_build_query($this->queryArray)); }
/** * Constructs absolute URL from Request object. * * @param \Nette\Application\Request $appRequest * @param \Nette\Http\Url $refUrl * @throws \Nette\InvalidStateException * @return string|NULL */ public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return null; } $parameters = $appRequest->getParameters(); $urlStack = array(); // Module prefix. $moduleFrags = explode(":", $appRequest->getPresenterName()); if (count($moduleFrags)) { foreach ($moduleFrags as &$fragment) { $fragment = $this->presenter2path($fragment); } } $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; if (isset($parameters['associations']) && is_array($parameters['associations'])) { $associations =& $parameters['associations']; foreach ($associations as $key => $value) { $urlStack[] = $key; $urlStack[] = $value; } } $urlStack[] = $resourceName; if (isset($parameters['specific_action']) && $parameters['specific_action']) { $urlStack[] = $this->action2path($parameters['specific_action']); } if (isset($parameters['id']) && is_scalar($parameters['id'])) { $urlStack[] = $parameters['id']; } $url = $q = $refUrl->getBaseUrl() . implode('/', $urlStack); if (isset($parameters['query']) && count($parameters['query'])) { $sep = ini_get('arg_separator.input'); $query = http_build_query($parameters['query'], '', $sep ? $sep[0] : '&'); $url .= '?' . $query; } return $url; }
/** * Constructs absolute URL from Request object. * @param \Nette\Application\Request $appRequest * @param \Nette\Http\Url $refUrl * @throws \Nette\InvalidStateException * @return string|NULL */ public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return NULL; } $parameters = $appRequest->getParameters(); $url = $refUrl->getBaseUrl(); $urlStack = []; // Module prefix. $moduleFrags = explode(":", $appRequest->getPresenterName()); $moduleFrags = array_map('\\AdamStipak\\Support\\Inflector::spinalCase', $moduleFrags); $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; // Associations. if (isset($parameters['associations']) && Validators::is($parameters['associations'], 'array')) { $associations = $parameters['associations']; unset($parameters['associations']); foreach ($associations as $key => $value) { $urlStack[] = $key; $urlStack[] = $value; } } // Resource. $urlStack[] = $resourceName; // Id. if (isset($parameters['id']) && Validators::is($parameters['id'], 'scalar')) { $urlStack[] = $parameters['id']; unset($parameters['id']); } $url = $url . implode('/', $urlStack); $sep = ini_get('arg_separator.input'); if (isset($parameters['query'])) { $query = http_build_query($parameters['query'], '', $sep ? $sep[0] : '&'); if ($query != '') { $url .= '?' . $query; } } return $url; }
/** * Generates URL to PayPal for redirection. * * @param bool $commit determines whether buyers complete their purchases on PayPal or on your website * * @return Nette\Http\Url */ public function getUrl($commit = false) { $url = new Url($this->sandbox ? self::SANDBOX_PAYPAL_URL : self::PAYPAL_URL); $query = array('cmd' => '_express-checkout', 'token' => $this->token); if ($commit) { $query['useraction'] = 'commit'; } $url->setQuery($query); return $url; }
/** * Creates current HttpRequest object. * @return Request */ public function createHttpRequest() { // DETECTS URI, base path and script path of the request. $url = new UrlScript(); $url->setScheme(!empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https' : 'http'); $url->setUser(isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : ''); $url->setPassword(isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''); // host & port if ((isset($_SERVER[$tmp = 'HTTP_HOST']) || isset($_SERVER[$tmp = 'SERVER_NAME'])) && preg_match('#^([a-z0-9_.-]+|\\[[a-f0-9:]+\\])(:\\d+)?\\z#i', $_SERVER[$tmp], $pair)) { $url->setHost(strtolower($pair[1])); if (isset($pair[2])) { $url->setPort(substr($pair[2], 1)); } elseif (isset($_SERVER['SERVER_PORT'])) { $url->setPort($_SERVER['SERVER_PORT']); } } // path & query $requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; $requestUrl = Strings::replace($requestUrl, $this->urlFilters['url']); $tmp = explode('?', $requestUrl, 2); $path = Url::unescape($tmp[0], '%/?#'); $path = Strings::fixEncoding(Strings::replace($path, $this->urlFilters['path'])); $url->setPath($path); $url->setQuery(isset($tmp[1]) ? $tmp[1] : ''); // detect script path $lpath = strtolower($path); $script = isset($_SERVER['SCRIPT_NAME']) ? strtolower($_SERVER['SCRIPT_NAME']) : ''; if ($lpath !== $script) { $max = min(strlen($lpath), strlen($script)); for ($i = 0; $i < $max && $lpath[$i] === $script[$i]; $i++) { } $path = $i ? substr($path, 0, strrpos($path, '/', $i - strlen($path) - 1) + 1) : '/'; } $url->setScriptPath($path); // GET, POST, COOKIE $useFilter = !in_array(ini_get('filter.default'), array('', 'unsafe_raw')) || ini_get('filter.default_flags'); $query = $url->getQueryParameters(); $post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? array() : $_POST); $cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? array() : $_COOKIE); if (get_magic_quotes_gpc()) { $post = Helpers::stripslashes($post, $useFilter); $cookies = Helpers::stripslashes($cookies, $useFilter); } // remove invalid characters $reChars = '#^[' . self::CHARS . ']*+\\z#u'; if (!$this->binary) { $list = array(&$query, &$post, &$cookies); while (list($key, $val) = each($list)) { foreach ($val as $k => $v) { if (is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) { unset($list[$key][$k]); } elseif (is_array($v)) { $list[$key][$k] = $v; $list[] =& $list[$key][$k]; } else { $list[$key][$k] = (string) preg_replace('#[^' . self::CHARS . ']+#u', '', $v); } } } unset($list, $key, $val, $k, $v); } $url->setQuery($query); // FILES and create FileUpload objects $files = array(); $list = array(); if (!empty($_FILES)) { foreach ($_FILES as $k => $v) { if (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) { continue; } $v['@'] =& $files[$k]; $list[] = $v; } } while (list(, $v) = each($list)) { if (!isset($v['name'])) { continue; } elseif (!is_array($v['name'])) { if (get_magic_quotes_gpc()) { $v['name'] = stripSlashes($v['name']); } if (!$this->binary && (!preg_match($reChars, $v['name']) || preg_last_error())) { $v['name'] = ''; } if ($v['error'] !== UPLOAD_ERR_NO_FILE) { $v['@'] = new FileUpload($v); } continue; } foreach ($v['name'] as $k => $foo) { if (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) { continue; } $list[] = array('name' => $v['name'][$k], 'type' => $v['type'][$k], 'size' => $v['size'][$k], 'tmp_name' => $v['tmp_name'][$k], 'error' => $v['error'][$k], '@' => &$v['@'][$k]); } } // HEADERS if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); } else { $headers = array(); foreach ($_SERVER as $k => $v) { if (strncmp($k, 'HTTP_', 5) == 0) { $k = substr($k, 5); } elseif (strncmp($k, 'CONTENT_', 8)) { continue; } $headers[strtr($k, '_', '-')] = $v; } } $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL; $remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : NULL; // proxy foreach ($this->proxies as $proxy) { if (Helpers::ipMatch($remoteAddr, $proxy)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $remoteAddr = trim(current(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))); } if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $remoteHost = trim(current(explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']))); } break; } } $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : NULL; if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) && preg_match('#^[A-Z]+\\z#', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; } // raw body $rawBodyCallback = function () { static $rawBody; if (PHP_VERSION_ID >= 50600) { return file_get_contents('php://input'); } elseif ($rawBody === NULL) { // can be read only once in PHP < 5.6 $rawBody = (string) file_get_contents('php://input'); } return $rawBody; }; return new Request($url, NULL, $post, $files, $cookies, $headers, $method, $remoteAddr, $remoteHost, $rawBodyCallback); }