The path info always starts with a /.
Suppose this request is instantiated from /mysite on localhost:
* http://localhost/mysite returns an empty string
* http://localhost/mysite/about returns '/about'
* http://localhost/mysite/enco%20ded returns '/enco%20ded'
* http://localhost/mysite/about?var=1 returns '/about'
public static getPathInfo ( ) : string | ||
return | string | The raw path (i.e. not urldecoded) |
/** * @covers Phossa\Route\Context\Request::getPathInfo */ public function testGetPathInfo() { $this->assertEquals('/user/list/1234', $this->object->getPathInfo()); // fake stuff $_SERVER['REQUEST_URI'] = '/user/add/12?ddsfd=adfad'; $_SERVER['PATH_INFO'] = '/add/12'; $this->object = new Request('POST', '/user/list/1234?id=phossa'); $this->assertEquals('/list/1234', $this->object->getPathInfo()); }
public function parseParameters(Route $route) { $parameters = $route->parameters(); $parameters['_route'] = $this->request->getPathInfo(); $action = $route->getAction(); // Controller@action if (is_string($action)) { list($parameters['_controller'], $parameters['action']) = explode('@', $action[0]); return $parameters; } else { if (isset($action['controller'])) { list($parameters['_controller'], $parameters['action']) = explode('@', $action['controller']); return $parameters; } else { if (isset($action['uses']) && !empty($action['uses'])) { // Callable if (is_callable($action['uses'])) { $parameters['_controller'] = $action['uses']; $parameters['action'] = $action['uses']; return $parameters; // 'uses' => 'Controller@action' } else { if (is_string($action['uses']) && strpos($action['uses'], '@') !== false) { list($parameters['_controller'], $parameters['action']) = explode('@', $action['uses']); return $parameters; } } } } } throw new \RuntimeException('Unable to parse laravel route parameters'); }
/** * Parses the given request and returns the corresponding route and parameters. * * @param UrlManager $manager the URL manager * @param Request $request the request component * @return array|boolean the parsing result. The route and the parameters are returned as an array. * If false, it means this rule cannot be used to parse this path info. */ public function parseRequest($manager, $request) { $pathInfo = $request->getPathInfo(); $suffix = Yii::$app->getUrlManager()->suffix; if ($suffix !== null) { $pathInfo = substr($pathInfo, 0, -strlen($suffix)); } // this url rule will always have minimum 2 url path segments (separated by a "/") if (strpos($pathInfo, '/') !== false) { // split the current path into segments $segments = explode('/', $pathInfo); $identifier = false; // if the first segment matches the id of this url rule we have a match. // in this case we also know that no menu points directly to the requested page (otherwise this url rule would never get activated) // use the second segment if ($segments[0] === $this->_id) { return ['pages/page/show', ['alias' => $segments[1]]]; } elseif ($segments[0] === $this->_categoryId) { $identifier = $segments[1]; return ['pages/category/pages', ['catid' => $segments[1]]]; } else { // last segment could be our identifier, we need the segment right before that // to check if it matches a menu pointing to a pages category $alias = $segments[count($segments) - 2]; $menu = Yii::$app->big->menuManager->search('alias', $alias); // the menu points to a page category if ($menu && strpos($menu->route, 'pages/category/pages') === 0) { return ['pages/page/show', ['alias' => array_pop($segments)]]; } } } return false; }
/** * @param $dataSource * @param array $config */ public function __construct($dataSource, array $config = []) { $this->dataSource = $dataSource; $this->setConfigOptions($config); if (!isset($this->baseUrl)) { $this->baseUrl = \Request::getPathInfo(); } }
/** * @param $collection * @param array $config * @param array $excludeQueryString */ public function __construct($collection, array $config = [], array $excludeQueryString = ['page']) { if (is_array($collection)) { $collection = new SupportCollection($collection); } $this->paginator = $collection; $this->input = \Input::except($excludeQueryString); $this->setConfigOptions($config); if (!isset($this->baseUrl)) { $this->baseUrl = \Request::getPathInfo(); } }
/** * Setup layout informations */ public function setupLayout() { if (!is_null($this->layout)) { $this->layout = view($this->layout); $method = \Request::getMethod(); $pathInfo = \Request::getPathInfo(); $route = app()->getRoutes()[$method . $pathInfo]; $this->layout->head = new stdClass(); $this->layout->body = new stdClass(); $this->layout->body->class = $route['action']['as']; } }
/** * Get the URI for the current request. * * @return string */ public static function current() { if (!is_null(static::$uri)) { return static::$uri; } // We'll simply get the path info from the Symfony Request instance and then // format to meet our needs in the router. If the URI is root, we'll give // back a single slash, otherwise we'll strip all of the slashes off. $uri = static::format(Request::getPathInfo()); static::segments($uri); return static::$uri = $uri; }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } if (null !== $this->path && !preg_match($this->path, $request->getPathInfo())) { return false; } if (null !== $this->host && !preg_match($this->host, $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($this->host, $request->getClientIp())) { return false; } return true; }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#^' . $pattern . '$#', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('#^' . $this->path . '$#', $request->getPathInfo())) { return false; } if (null !== $this->host && !preg_match('#^' . $this->host . '$#', $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($this->host, $request->getClientIp())) { return false; } return true; }
/** * {@inheritdoc} */ public function getRoute(Request $request) { $badMethod = false; foreach ($this->rules as $rule) { if (preg_match('%^/v' . $this->version . $rule['path'] . '%', $request->getPathInfo(), $matches)) { if (isset($rule['verbs']) && !in_array($request->getVerb(), $rule['verbs'])) { $badMethod = true; continue; } // Determine numeric keys $exclude = array_filter(array_keys($matches), function ($val) { return is_integer($val); }); // Remove numeric keys from matches $params = array_diff_key($matches, array_flip($exclude)); return new Route($rule['controller'], $rule['action'], $params); } } if ($badMethod) { throw new Exception('Method not supported', 415); } throw new Exception('Endpoint not found', 404); }
<?php require_once "../scripts/init.php"; // Normalize environment Environment::disableMagicQuotes(); // Get and normalize request $request = new Request(); $uri = str_replace(array("'", '"', '%'), "", $request->getPathInfo()); $levels = $request->getLevelsPathInfo(); $dispatcher = new Dispatcher($uri, $levels); // http_method , regex_pattern , class , method , [action] , [method_args] # regras para tools $dispatcher->rules('POST', 'tools/mail/(?<slug>.+)?', 'tools', 'mail'); $dispatcher->rules('GET', '(tools).*', 'tools', 'redir', null, array("url" => $page_not_found)); # autenticações/login $dispatcher->rules('POST', '(authenticate)', 'cadastro', 'index'); $dispatcher->rules('GET', '(login)?', 'cadastro', 'login_system'); $dispatcher->rules('GET', '(logout)', 'cadastro', 'logout_system'); $dispatcher->rules('GET', '(redefinir-acesso)?', 'cadastro', 'password_remember'); $dispatcher->rules('POST', '(redefinir-acesso-enviar)?', 'cadastro', 'password_remember'); $dispatcher->rules('GET', '(cadastro|cadastro/)', 'cadastro', 'cadastro_system'); $dispatcher->rules('POST', '(cadastrar-user)', 'cadastro', 'cadastro_system'); $dispatcher->rules('GET', '(ativar-acesso)?', 'cadastro', 'cadastro_active'); $dispatcher->rules('GET', '(meus-dados)', 'cadastro', 'dados_system'); $dispatcher->rules('POST', '(meus-dados-enviar)?', 'cadastro', 'dados_system'); $dispatcher->rules('GET', '(pontos-turisticos)', 'entidade', 'index'); $dispatcher->rules('GET', 'pontos-turisticos/(?P<id_ponto>[0-9]+)(-?(?<slug>.+))?', 'entidade', 'entidade_system'); $dispatcher->rules('GET', '(destino)', 'entidade', 'destino_choose'); $dispatcher->rules('GET', 'destino/(?P<id_ponto>[0-9]+)(-?(?<slug>.+))?', 'entidade', 'destino_system'); $dispatcher->rules('POST', 'tracar-rota', 'entidade', 'rota_system'); if (!$dispatcher->exec()) {
/** * Parses the given request and returns the corresponding route and parameters. * @param \yii\web\UrlManager $manager the URL manager * @param Request $request the request component * @return array|bool the parsing result. The route and the parameters are returned as an array. * @throws ForbiddenHttpException */ public function parseRequest($manager, $request) { $menuMap = $this->menuManager->getMenuMap(); if (!($pathInfo = $request->getPathInfo() or $pathInfo = ($mainMenu = $menuMap->getMainMenu()) ? $mainMenu->path : null)) { return false; } // помечаем как активные все пункты меню которые ссылаются на тотже урл что в запросе $this->menuManager->setActiveMenuIds($menuMap->getMenuIdsByLink($request->getUrl())); // ищем пункт меню, чей путь совпадает с путем в запросе if ($menu = $menuMap->getMenuByPathRecursive($pathInfo)) { // определяем в каком контексте ("Точный" или "Подходящий") рассматривать активное меню $menu->setContext($menu->path === $pathInfo ? MenuItem::CONTEXT_PROPER : MenuItem::CONTEXT_APPLICABLE); // устанавливаем найденный пункт меню в качестве активного $this->menuManager->setActiveMenu($menu); // добавляем данный пункт в список активных пунктов меню $this->menuManager->addActiveMenuId($menu->id); if ($menu->getContext() === MenuItem::CONTEXT_PROPER) { //при "точном" совпадении, метаданные меню перекрывают метаднные контроллера Yii::$app->getView()->on(View::EVENT_BEGIN_PAGE, [$this, 'applyMetaData']); } else { //при "подходящем" устанавливаются по умолчанию $this->applyMetaData(); } } else { return false; } // устанавливаем макет приложению Event::on(Controller::className(), Controller::EVENT_BEFORE_ACTION, [$this, 'applyLayout']); // Проверка на доступ к пунтку меню if (!empty($menu->access_rule) && !Yii::$app->user->can($menu->access_rule)) { if (Yii::$app->user->getIsGuest()) { Yii::$app->user->loginRequired(); } else { throw new ForbiddenHttpException(Yii::t('gromver.platform', 'You have no rights for access to this section of the site.')); } } if ($menu->getContext() === MenuItem::CONTEXT_PROPER) { // при "точном" контексте пункта меню, возвращаем роут на компонент return $menu->parseUrl(); } else { /* * при "подходящем" контексте пункта меню, необходимо на основании оставшейся части пути * и информации из пункта меню маршрутизировать приложение */ $requestRoute = substr($pathInfo, mb_strlen($menu->path) + 1); list($menuRoute, $menuParams) = $menu->parseUrl(); $requestInfo = new MenuRequestInfo(['menuMap' => $menuMap, 'menuRoute' => $menuRoute, 'menuParams' => $menuParams, 'requestRoute' => $requestRoute, 'requestParams' => $request->getQueryParams()]); foreach ($this->_parseUrlRules as $rule) { if ($result = $rule->process($requestInfo, $this)) { return $result; } } return false; } }
/** * Match and process an HTTP request. * * @param Request $req HTTP request. * @param string $prefix URI prefix of the group. * * @return BoundRoute|null When match this returns BoundRoute, else null. * * @SuppressWarnings(PHPMD.StaticAccess) */ public function matchRequest(Request $req, $prefix = '') { if (!in_array($req->getMethod(), $this->methods)) { return; } if ('/' !== substr($this->rawPath, 0, 1) && Dispatcher::isRegex($this->rawPath)) { preg_match('#\\A(.)(.*)(.[imsxeADSUXJu]*)\\z#', $this->rawPath, $matches); $compiledPath = $matches[1] . '\\A(?:' . preg_quote($prefix, $matches[1]) . ')' . $matches[2] . '\\z' . $matches[3]; } else { $compiledPath = (new PathCompiler($prefix . $this->rawPath))->compile(); } if (!preg_match($compiledPath, $req->getPathInfo(), $matches)) { return; } $dp = new Dispatcher($this->c); $bag = new ParameterBag(); $bag->setRequest($req); $bag->addArray(array_reduce($dp->getParameters($this->controller), function ($carry, $param) { if ($param->isDefaultValueAvailable()) { $carry[$param->name] = $param->getDefaultValue(); } return $carry; }, [])); $bag->addArray($matches); $bag->addArray($this->c); $bag->addArray(['matches' => $matches, 'req' => $req, 'request' => $req, 'router' => $this->router]); $dp->setNamedArgs($bag); $dp->setTypedArg('Ranyuen\\Little\\Request', $req); $dp->setTypedArg('Symfony\\Component\\HttpFoundation\\Request', $req); $dp->setTypedArg('Ranyuen\\Little\\Router', $this->router); foreach ($this->conditions as $cond) { if (!$cond->isMatch($bag, $dp)) { return; } } return new BoundRoute($this->facade, $this->router, $req, $dp); }
/** * @param Paginator $paginator * @param array $config * @param array $excludeQueryString */ public function __construct(Paginator $paginator, array $config = [], array $excludeQueryString = ['page']) { $this->paginator = $paginator; $this->input = \Input::except($excludeQueryString); $this->setConfigOptions($config); if (!isset($this->baseUrl)) { $this->baseUrl = \Request::getPathInfo(); } }
</button> {{ Session::get('error') }} </div> @endif @if(Session::has('success')) <div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> {{ Session::get('success') }} </div> @endif <?php $url = \Request::getPathInfo(); ?> <div class="row"> <div class="col-sm-4 col-md-3"> <div class="list-group"> <a href="{{route('admin.page')}}" class="@if($url == '/admin' || strpos($url, 'page') != false) active @endif list-group-item"> <i class="fa fa-file-archive-o"></i> Manage Pages </a> <a href="{{route('admin.image')}}" class="@if(strpos($url, 'image') != false) active @endif list-group-item"> <i class="fa fa-image"></i> Manage Image </a> </div> </div>
/** * Parses the given request and returns the corresponding route and parameters. * * @param UrlManager $manager the URL manager * @param Request $request the request component * @return array|boolean the parsing result. The route and the parameters are returned as an array. * If false, it means this rule cannot be used to parse this path info. */ public function parseRequest($manager, $request) { $pathInfo = $request->getPathInfo(); $suffix = (string) $manager->suffix; if ($suffix !== '' && $pathInfo !== '') { $n = strlen($suffix); if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) { $pathInfo = substr($pathInfo, 0, -$n); if ($pathInfo === '') { // suffix alone is not allowed return false; } } else { return false; } } // search for a menu that matches the request. if (strpos($pathInfo, '/') !== false) { $segments = explode('/', $pathInfo); } else { $segments = [$pathInfo]; } $menuManager = Yii::$app->big->menuManager; $menu = $menuManager->search('alias', array_pop($segments)); // if a menu was found set it as active and use it to parse the request. if ($menu) { // throw exception if menu is not enabled if (!$menu->getIsEnabled()) { throw new NotFoundHttpException(Yii::t('big', 'Page not found')); } $menuManager->setActive($menu); $params = $this->parseInternalUrl($menu->route); $route = $params[0]; unset($params[0]); return [$route, $params]; } elseif (!empty($segments)) { // no menu was found by the first segment. Search remaining segments for // a matching menu. while (!$menu && !empty($segments)) { $menu = $menuManager->search('alias', array_pop($segments)); } // if a menu was found register it as active if ($menu && $menu->getIsEnabled()) { $menuManager->setActive($menu); } } // no menu found. Search module url rules to find a match. $result = false; foreach ($this->getRules() as $rule) { if (($result = $rule->parseRequest($manager, $request)) !== false) { break; } } return $result; }
private function datagridHeader() { $handler = function ($data) { $html = '<div class="panel panel-default">'; $title = isset($data['title']) ? $data['title'] : ''; $html .= '<div class="panel-heading">' . $title . '</div>'; $html .= '<div class="panel-body b-b b-light"><form action="' . \Request::getPathInfo() . '" method="GET">'; $dataKeys = array_keys($data); foreach ($dataKeys as $key) { switch ($key) { case 'new': $html .= '<a href="' . $this->url->current() . '/create" class="btn btn-primary">+ 新增</a>'; break; case 'priceStart': $priceStart = is_bool($data['priceStart']) ? '价格' : $data['priceStart']; $html .= '<div class="col-md-3" style="padding-left:0px;width: 8%"> <input id="priceStartInput" type="text" class="form-control input" name="priceStart" value="' . Input::get('priceStart') . '" placeholder="' . $priceStart . '" /> </div>'; $js = "<script>init.push(function(){\n \$('#priceStartInput').keyup(function(event){\n if(event.keyCode == 13){\n console.log('do search');\n var params = window.location.search.substring(1);\n var paramObject = {};\n var paramArray = params.split('&');\n paramArray.forEach(function(param){\n if(param){\n var arr = param.split('=');\n paramObject[arr[0]] = arr[1];\n }\n });\n var baseUrl = window.location.origin+window.location.pathname;\n if(\$(this).val()){\n if(\$('#priceEndInput').val())\n {\n if(parseFloat(\$('#priceEndInput').val()) >= parseFloat(\$(this).val())){\n paramObject[\$('#priceEndInput').attr('name')] = \$('#priceEndInput').val();\n }else{\n alert('范围有错');\n return;\n }\n }\n paramObject[\$(this).attr('name')] = \$(this).val();\n }else{\n delete paramObject[\$(this).attr('name')];\n }\n window.location.href = \$.param(paramObject) ? baseUrl+'?'+\$.param(paramObject) : baseUrl;\n }\n });\n });</script>"; $html .= $js; break; case 'priceEnd': $priceEnd = is_bool($data['priceEnd']) ? '价格' : $data['priceEnd']; $html .= '<div class="col-md-3" style="padding-left:0px;width: 8%"> <input id="priceEndInput" type="text" class="form-control input" name="priceEnd" value="' . Input::get('priceEnd') . '" placeholder="' . $priceEnd . '" /> </div>'; $js = "<script>init.push(function(){\n \$('#priceEndInput').keyup(function(event){\n if(event.keyCode == 13){\n console.log('do search');\n var params = window.location.search.substring(1);\n var paramObject = {};\n var paramArray = params.split('&');\n paramArray.forEach(function(param){\n if(param){\n var arr = param.split('=');\n paramObject[arr[0]] = arr[1];\n }\n });\n var baseUrl = window.location.origin+window.location.pathname;\n if(\$(this).val()){\n if(\$('#priceStartInput').val())\n {\n if(parseFloat(\$('#priceStartInput').val()) <= parseFloat(\$(this).val())){\n paramObject[\$('#priceStartInput').attr('name')] = \$('#priceStartInput').val();\n }else{\n alert('范围有错');\n return;\n }\n }\n paramObject[\$(this).attr('name')] = \$(this).val();\n }else{\n delete paramObject[\$(this).attr('name')];\n }\n window.location.href = \$.param(paramObject) ? baseUrl+'?'+\$.param(paramObject) : baseUrl;\n }\n });\n });</script>"; $html .= $js; break; case 'timeStart': $timeStart = $data['timeStart']; $placeholder = is_bool($timeStart['placeholder']) ? '开始时间' : $timeStart['placeholder']; $timeFormat = isset($timeStart['timeFormat']) ? $timeStart['timeFormat'] : 'Y-m-d H:i:s'; $html .= '<div class="col-md-2 col-sm-2" style="padding-left:0px;"> <input id="timeStartInput" type="text" class="form-control input" name="timeStart" value="' . Input::get('timeStart') . '" placeholder="' . $placeholder . '" /> </div>'; $js = "<script>init.push(function(){\n jQuery('#timeStartInput').datetimepicker({format:'" . $timeFormat . "'});\n \$('#timeStartInput').keyup(function(event){\n if(event.keyCode == 13){\n console.log('do search');\n var params = window.location.search.substring(1);\n var paramObject = {};\n var paramArray = params.split('&');\n paramArray.forEach(function(param){\n if(param){\n var arr = param.split('=');\n paramObject[arr[0]] = arr[1];\n }\n });\n var baseUrl = window.location.origin+window.location.pathname;\n if(\$(this).val()){\n if(\$('#timeEndInput').val())\n {\n if(\$('#timeEndInput').val() >= \$(this).val()){\n paramObject[\$('#timeEndInput').attr('name')] = \$('#timeEndInput').val();\n }else{\n alert('范围有错');\n return;\n }\n }\n paramObject[\$(this).attr('name')] = \$(this).val();\n }else{\n delete paramObject[\$(this).attr('name')];\n }\n window.location.href = \$.param(paramObject) ? baseUrl+'?'+\$.param(paramObject) : baseUrl;\n }\n });\n });</script>"; $html .= $js; break; case 'timeEnd': $timeEnd = $data['timeEnd']; $placeholder = is_bool($timeEnd['placeholder']) ? '结束时间' : $timeEnd['placeholder']; $timeFormat = isset($timeEnd['timeFormat']) ? $timeEnd['timeFormat'] : 'Y-m-d H:i:s'; $html .= '<div class="col-md-2 col-sm-2" style="padding-left:0px;"> <input id="timeEndInput" type="text" class="form-control input" name="timeEnd" value="' . Input::get('timeEnd') . '" placeholder="' . $placeholder . '" /> </div>'; $js = "<script>init.push(function(){\n jQuery('#timeEndInput').datetimepicker({format:'" . $timeFormat . "'});\n \$('#timeEndInput').keyup(function(event){\n if(event.keyCode == 13){\n console.log('do search');\n var params = window.location.search.substring(1);\n var paramObject = {};\n var paramArray = params.split('&');\n paramArray.forEach(function(param){\n if(param){\n var arr = param.split('=');\n paramObject[arr[0]] = arr[1];\n }\n });\n var baseUrl = window.location.origin+window.location.pathname;\n if(\$(this).val()){\n if(\$('#timeStartInput').val())\n {\n if(\$('#timeStartInput').val() <= \$(this).val()){\n paramObject[\$('#timeStartInput').attr('name')] = \$('#timeStartInput').val();\n }else{\n alert('范围有错');\n return;\n }\n }\n paramObject[\$(this).attr('name')] = \$(this).val();\n }else{\n delete paramObject[\$(this).attr('name')];\n }\n window.location.href = \$.param(paramObject) ? baseUrl+'?'+\$.param(paramObject) : baseUrl;\n }\n });\n });</script>"; $html .= $js; break; case 'filters': foreach ($data['filters'] as $key => $value) { $html .= '<div class="col-md-6 col-sm-6 form-group" style="margin-bottom: 0px;padding-left: 0"> <label class="col-md-3 col-sm-3 text-right" style="line-height: 35px;">' . $value['text'] . '</label> <select class="form-control" style="width: 75%;margin-right: 0;display:inline-block;" name="' . $key . '">'; foreach ($value['select'] as $item) { $value = is_array($item) ? $item['value'] : $item; $label = is_array($item) ? $item['label'] : $item; $selected = ''; $urlValue = Input::get($key); if ($urlValue != null) { $selected = $urlValue == $item['value'] ? 'selected="selected"' : ''; } $html .= '<option ' . $selected . ' value="' . $value . '">' . $label . '</option>'; } $html .= '</select></div>'; } /*$js = "<script>init.push(function(){ $('select').change(function(){ var params = window.location.search.substring(1); var paramObject = {}; var paramArray = params.split('&'); paramArray.forEach(function(param){ if(param){ var arr = param.split('='); paramObject[arr[0]] = arr[1]; } }); var baseUrl = window.location.origin+window.location.pathname; if($(this).val()){ paramObject[$(this).attr('name')] = $(this).val(); }else{ delete paramObject[$(this).attr('name')]; } window.location.href = $.param(paramObject) ? baseUrl+'?'+$.param(paramObject) : baseUrl; }); })</script>"; $html .= $js;*/ break; case 'timePickerGroup': $timePickerGroup = $data['timePickerGroup']; foreach ($timePickerGroup as $index => $item) { $timeFormat = isset($item['timeFormat']) ? $item['timeFormat'] : 'Y-m-d H:i:s'; $placeholder = $item['placeholder']; $html .= ' <div class="col-md-6 col-sm-6" style="padding-left:0px;height: 39px"> <label class="col-md-3 col-sm-3 text-right" style="line-height: 34px;margin-bottom: 0;">' . $item['text'] . '</label> <input id="' . $index . 'Start" name="' . $index . 'Start" type="text" class="form-control" style="width: 36.5%;margin-right: 0;display:inline-block;" value="' . Input::get($index . 'Start') . '" placeholder="' . $placeholder . '开始" /> <span style="display:inline-block;width: 0.3%;">-</span> <input id="' . $index . 'End" name="' . $index . 'End" type="text" class="form-control" style="width: 36.5%;margin-right: 0;display:inline-block;" value="' . Input::get($index . 'End') . '" placeholder="' . $placeholder . '结束" /> </div>'; $js = "<script>\n init.push(function(){\n jQuery('#" . $index . "Start').datetimepicker({format:'" . $timeFormat . "'});\n jQuery('#" . $index . "End').datetimepicker({format:'" . $timeFormat . "'});\n });\n </script>"; $html .= $js; } break; case 'search': $search = is_bool($data['search']) ? '请输入您想检索的信息' : $data['search']; if (is_array($search)) { foreach ($search as $item) { $keyword = $item['key']; $text = $item['text']; $placeholder = isset($item['placeholder']) ? $item['placeholder'] : ''; $html .= '<div class="col-md-6 col-sm-6" style="padding-left:0px;"> <label class="col-md-3 col-sm-3 text-right control-label" style="line-height: 34px;">' . $text . '</label> <input id="keywordsInput" type="text" class="form-control input" style="width: 75%;margin-right: 0;display:inline-block;" name="' . $keyword . '" value="' . Input::get($keyword) . '" placeholder="' . $placeholder . '" /> </div>'; } } else { $html .= '<div class="col-md-2" style="padding-left:0px; width: 17%"> <input id="keywordsInput" type="text" class="form-control input" name="keywords" value="' . Input::get('keywords') . '" placeholder="' . $search . '" /> </div>'; $js = "<script>init.push(function(){\n \$('#keywordsInput').keyup(function(event){\n if(event.keyCode == 13){\n //console.log('do search');\n var params = window.location.search.substring(1);\n var paramObject = {};\n var paramArray = params.split('&');\n paramArray.forEach(function(param){\n if(param){\n var arr = param.split('=');\n paramObject[arr[0]] = arr[1];\n }\n });\n var baseUrl = window.location.origin+window.location.pathname;\n if(\$(this).val()){\n paramObject[\$(this).attr('name')] = \$(this).val();\n }else{\n delete paramObject[\$(this).attr('name')];\n }\n window.location.href = \$.param(paramObject) ? baseUrl+'?'+\$.param(paramObject) : baseUrl;\n }\n });\n });</script>"; $html .= $js; } break; case 'submit': $search = is_bool($data['submit']) ? '搜索' : $data['submit']; $html .= '<div class="col-md-1" style="width: 4%"> <button type="submit" class="btn btn-primary"> ' . $search . '</button> </div>'; break; case 'callback': $search = is_bool($data['callback']) ? '返回' : $data['callback']; if (is_array($search)) { $text = $search['text']; } else { $text = $search; } $url = isset($search['url']) ? $search['url'] : \URL::previous(); $html .= '<div class="col-md-1" style="width: 5%"> <a class="btn btn-primary" href="' . $url . '"> ' . $text . '</a> </div>'; break; case 'button': $button = $data['button']; $url = $button['url']; $text = $button['text']; $html .= '<div class="col-md-1" style="width: 6%"> <a class="btn btn-default" href="' . $url . '">' . $text . '</a> </div>'; break; case 'label': $text = $data['label']; $html .= '<div class="col-md-6 pull-right"> <label class="label label-info" >' . $text . '</label> </div>'; break; } } $html .= '</form></div>'; return $html; }; Html::macro('list_header', $handler); Html::macro('datagrid_header', $handler); }
public function matches(Request $request) { if ($this->schemes && !in_array($request->getScheme(), $this->schemes)) { return false; } if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('{' . $pattern . '}', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('{' . $this->path . '}', rawurldecode($request->getPathInfo()))) { return false; } if (null !== $this->host && !preg_match('{' . $this->host . '}i', $request->getHost())) { return false; } if (IpUtils::checkIp($request->getClientIp(), $this->ips)) { return true; } return count($this->ips) === 0; }
/** * Gathers custom parameters from a URL based on the conditions given by * the Controller. * * @param \Micro\ControllerInterface $controller * @param \Micro\Request $request * @return void */ protected function addParameters(ControllerInterface $controller, Request $request) { $regex = $this->ut->compile($controller->uri(), $controller->conditions()); $params = $this->ut->parameters($regex, $request->getPathInfo()); $request->request->add($params); }
$logFile = 'log-' . php_sapi_name() . '.txt'; Log::useDailyFiles(storage_path() . '/logs/' . $logFile); /* |-------------------------------------------------------------------------- | Application Error Handler |-------------------------------------------------------------------------- | | Here you may handle any errors that occur in your application, including | logging them or displaying custom views for specific errors. You may | even register several error handlers to handle different types of | exceptions. If nothing is returned, the default error view is | shown, which includes a detailed stack trace during debug. | */ App::error(function (Exception $exception, $code) { $pathInfo = Request::getPathInfo(); $message = $exception->getMessage() ?: 'Exception'; Log::error("{$code} - {$message} @ {$pathInfo}\r\n{$exception}"); if (Config::get('app.debug')) { return; } return Response::view('errors/500', array(), 500); }); //404 macro Response::macro('notFound', function ($value = null) { QuizController::_loadQuizes(); return Response::view('errors.404', array('errorMsg' => strtoupper($value)), 404); }); App::missing(function ($exception) { QuizController::_loadQuizes(); return Response::view('errors.404', array('errorMsg' => strtoupper($exception->getMessage())), 404);
/** * Parses the given request and returns the corresponding route and parameters. * @param UrlManager $manager the URL manager * @param Request $request the request component * @return array|boolean the parsing result. The route and the parameters are returned as an array. * If false, it means this rule cannot be used to parse this path info. */ public function parseRequest($manager, $request) { if ($this->mode === self::CREATION_ONLY) { return false; } if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) { return false; } $pathInfo = $request->getPathInfo(); $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix); if ($suffix !== '' && $pathInfo !== '') { $n = strlen($suffix); if (substr_compare($pathInfo, $suffix, -$n) === 0) { $pathInfo = substr($pathInfo, 0, -$n); if ($pathInfo === '') { // suffix alone is not allowed return false; } } else { return false; } } if ($this->host !== null) { $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo); } if (!preg_match($this->pattern, $pathInfo, $matches)) { return false; } foreach ($this->defaults as $name => $value) { if (!isset($matches[$name]) || $matches[$name] === '') { $matches[$name] = $value; } } $params = $this->defaults; $tr = []; foreach ($matches as $name => $value) { if (isset($this->_routeParams[$name])) { $tr[$this->_routeParams[$name]] = $value; unset($params[$name]); } elseif (isset($this->_paramRules[$name])) { $params[$name] = $value; } } if ($this->_routeRule !== null) { $route = strtr($this->route, $tr); } else { $route = $this->route; } foreach ($params as $name => &$value) { if (!$this->setParamValue($name, $value)) { return false; } } Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__); return [$route, $params]; }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#' . str_replace('#', '\\#', $pattern) . '#', $request->attributes->get($key))) { return false; } } if (null !== $this->path) { if (null !== ($session = $request->getSession())) { $path = strtr($this->path, array('{_locale}' => $session->getLocale(), '#' => '\\#')); } else { $path = str_replace('#', '\\#', $this->path); } if (!preg_match('#' . $path . '#', $request->getPathInfo())) { return false; } } if (null !== $this->host && !preg_match('#' . str_replace('#', '\\#', $this->host) . '#', $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($request->getClientIp())) { return false; } return true; }
/** * 初始化 * * @param Container container * @param Request request */ public function __construct(\Container $container, \Request $request) { $this->container = $container; $this->request = $request; $this->setRoute($this->methods, $request->getPathInfo(), $request->getMethod()); }
/** * Adding coverage for the case where PATH_INFO doesn't exist in $_SERVER but * REQUEST_URI does. * * @test */ public function constructorParsesRequestUri() { $server = ['REQUEST_URI' => '/v2/one/two?three=four']; $request = new \Request($this->config, $server); $this->assertEquals('/v2/one/two', $request->getPathInfo()); }
/** * {@inheritdoc} */ public function matches(Request $request) { if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('{' . $pattern . '}', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('{' . $this->path . '}', rawurldecode($request->getPathInfo()))) { return false; } if (null !== $this->host && !preg_match('{' . $this->host . '}i', $request->getHost())) { return false; } if (IpUtils::checkIp($request->getClientIp(), $this->ips)) { return true; } // Note to future implementors: add additional checks above the // foreach above or else your check might not be run! return count($this->ips) === 0; }
<?php $urls = Config::get('moved.urls', []); foreach ($urls as $old => $new) { Route::get($old, function () use($old, $new) { $url = $new; $query = Request::getQueryString(); $question = Request::getBaseUrl() . Request::getPathInfo() == '/' ? '/?' : '?'; if ($query) { $url = $query ? $url . $question . $query : $url; } Event::fire('moved.redirect', array($old, $new)); return Redirect::to($url, 301); }); }
/** * Process the query string */ private function processQueryString() { // store the query string local, so we don't alter it. $queryString = trim($this->request->getPathInfo(), '/'); // split into chunks $chunks = (array) explode('/', $queryString); $hasMultiLanguages = $this->getContainer()->getParameter('site.multilanguage'); // single language if (!$hasMultiLanguages) { // set language id $language = $this->get('fork.settings')->get('Core', 'default_language', SITE_DEFAULT_LANGUAGE); } else { // multiple languages // default value $mustRedirect = false; // get possible languages $possibleLanguages = (array) Language::getActiveLanguages(); $redirectLanguages = (array) Language::getRedirectLanguages(); // the language is present in the URL if (isset($chunks[0]) && in_array($chunks[0], $possibleLanguages)) { // define language $language = (string) $chunks[0]; // try to set a cookie with the language try { // set cookie CommonCookie::set('frontend_language', $language); } catch (\SpoonCookieException $e) { // settings cookies isn't allowed, because this isn't a real problem we ignore the exception } // set sessions \SpoonSession::set('frontend_language', $language); // remove the language part array_shift($chunks); } elseif (CommonCookie::exists('frontend_language') && in_array(CommonCookie::get('frontend_language'), $redirectLanguages)) { // set languageId $language = (string) CommonCookie::get('frontend_language'); // redirect is needed $mustRedirect = true; } else { // default browser language // set languageId & abbreviation $language = Language::getBrowserLanguage(); // try to set a cookie with the language try { // set cookie CommonCookie::set('frontend_language', $language); } catch (\SpoonCookieException $e) { // settings cookies isn't allowed, because this isn't a real problem we ignore the exception } // redirect is needed $mustRedirect = true; } // redirect is required if ($mustRedirect) { // build URL // trim the first / from the query string to prevent double slashes $url = rtrim('/' . $language . '/' . trim($this->getQueryString(), '/'), '/'); // when we are just adding the language to the domain, it's a temporary redirect because // Safari keeps the 301 in cache, so the cookie to switch language doesn't work any more $redirectCode = $url == '/' . $language ? 302 : 301; // set header & redirect throw new RedirectException('Redirect', new RedirectResponse($url, $redirectCode)); } } // define the language defined('FRONTEND_LANGUAGE') || define('FRONTEND_LANGUAGE', $language); defined('LANGUAGE') || define('LANGUAGE', $language); // sets the locale file Language::setLocale($language); // list of pageIds & their full URL $keys = Navigation::getKeys(); // rebuild our URL, but without the language parameter. (it's tripped earlier) $url = implode('/', $chunks); $startURL = $url; // loop until we find the URL in the list of pages while (!in_array($url, $keys)) { // remove the last chunk array_pop($chunks); // redefine the URL $url = implode('/', $chunks); } // remove language from query string if ($hasMultiLanguages) { $queryString = trim(mb_substr($queryString, mb_strlen($language)), '/'); } // if it's the homepage AND parameters were given (not allowed!) if ($url == '' && $queryString != '') { // get 404 URL $url = Navigation::getURL(404); // remove language if ($hasMultiLanguages) { $url = str_replace('/' . $language, '', $url); } } // set pages $url = trim($url, '/'); // currently not in the homepage if ($url != '') { // explode in pages $pages = explode('/', $url); // reset pages $this->setPages($pages); // reset parameters $this->setParameters(array()); } // set parameters $parameters = trim(mb_substr($startURL, mb_strlen($url)), '/'); // has at least one parameter if ($parameters != '') { // parameters will be separated by / $parameters = explode('/', $parameters); // set parameters $this->setParameters($parameters); } // pageId, parentId & depth $pageId = Navigation::getPageId(implode('/', $this->getPages())); $pageInfo = Navigation::getPageInfo($pageId); // invalid page, or parameters but no extra if ($pageInfo === false || !empty($parameters) && !$pageInfo['has_extra']) { // get 404 URL $url = Navigation::getURL(404); // remove language if ($hasMultiLanguages) { $url = str_replace('/' . $language, '', $url); } // remove the first slash $url = trim($url, '/'); // currently not in the homepage if ($url != '') { // explode in pages $pages = explode('/', $url); // reset pages $this->setPages($pages); // reset parameters $this->setParameters(array()); } } // is this an internal redirect? if (isset($pageInfo['redirect_page_id']) && $pageInfo['redirect_page_id'] != '') { // get url for item $newPageURL = Navigation::getURL((int) $pageInfo['redirect_page_id']); $errorURL = Navigation::getURL(404); // not an error? if ($newPageURL != $errorURL) { // redirect throw new RedirectException('Redirect', new RedirectResponse($newPageURL, $pageInfo['redirect_code'])); } } // is this an external redirect? if (isset($pageInfo['redirect_url']) && $pageInfo['redirect_url'] != '') { // redirect throw new RedirectException('Redirect', new RedirectResponse($pageInfo['redirect_url'], $pageInfo['redirect_code'])); } }
public function testGetPathInfo() { $this->assertThat($this->object->getPathInfo(), $this->equalTo('/default/request')); }
/** * {@inheritdoc} * * @api */ public function matches(Request $request) { if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#' . str_replace('#', '\\#', $pattern) . '#', $request->attributes->get($key))) { return false; } } if (null !== $this->path) { $path = str_replace('#', '\\#', $this->path); if (!preg_match('#' . $path . '#', rawurldecode($request->getPathInfo()))) { return false; } } if (null !== $this->host && !preg_match('#' . str_replace('#', '\\#', $this->host) . '#i', $request->getHost())) { return false; } if (null !== $this->ip && !IpUtils::checkIp($request->getClientIp(), $this->ip)) { return false; } return true; }
/** * Parses the user request. * @param Request $request the request component * @return string the route (controllerID/actionID) and perhaps GET parameters in path format. */ public function parseUrl($request) { if ($this->_urlFormat === self::PATH_FORMAT) { $rawPathInfo = $request->getPathInfo(); $pathInfo = $this->removeUrlSuffix($rawPathInfo, $this->urlSuffix); foreach ($this->_rules as $i => $rule) { if (($r = $rule->parseUrl($this, $request, $pathInfo, $rawPathInfo)) !== false) { return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r; } } $par = explode("/", $pathInfo, 4); if (isset($par[3])) { $this->parsePathInfo($par[3]); } return $pathInfo; } else { if (isset($_REQUEST[$this->routeVar])) { return $_REQUEST[$this->routeVar]; } else { return $this->homeRoute; } } }