/** * Load the active theme. * * This is called at bootstrap time. * We will only ever have one theme active for any given request. * * @uses Kohana::modules */ public static function load_themes() { $config = Config::load('site'); self::$themes = self::available(FALSE); //set admin theme based on path info $path = ltrim(Request::detect_uri(), '/'); Theme::$is_admin = $path == "admin" || !strncmp($path, "admin/", 6); if (Theme::$is_admin) { // Load the admin theme Theme::$active = $config->get('admin_theme', 'cerber'); } else { // Load the site theme Theme::$active = $config->get('theme', 'cerber'); } //Set mobile theme, if enabled and mobile request if (Request::is_mobile() and $config->get('mobile_theme', FALSE)) { // Load the mobile theme Theme::$active = $config->get('mobile_theme', 'cerber'); } // Admins can override the site theme, temporarily. This lets us preview themes. if (User::is_admin() and isset($_GET['theme']) and $override = Text::plain($_GET['theme'])) { Theme::$active = $override; } //Finally set the active theme Theme::set_theme(); }
public function __construct($template = NULL, array $partials = NULL, $alien_call = false) { // Если объект создается сторонним приложением для использования // определенных функция - конструктор надо освободить от выполнения // лишних операций if (!empty($alien_call)) { return; } // Получаем нужные настройки админ.части $this->site_name = $this->get_variable('site_name'); $this->js_path = $this->get_variable('js_path'); $this->css_path = $this->get_variable('css_path'); $this->image_path = $this->get_variable('image_path'); $this->packages_path = $this->get_variable('packages_path'); // Фомируем текущую дату для использования в шаблоне $this->datetime = date('H:i d/m/y'); // Получаем ID из запроса $this->request = new Request(Request::detect_uri()); $this->id = $this->request->param('id'); // Формируем пользователя if (empty($this->auth)) { $this->auth = Auth::instance(); $this->user = $this->auth->get_user(); if (!empty($this->user)) { // Узнаем роль пользователя (помимо роли Login) $roleuser = Sprig::factory('roleuser')->load(DB::select('*')->where('user_id', '=', $this->user->id)->and_where('role_id', '!=', '1'), NULL); // Вытаскиваем роль if (!empty($roleuser[0]->role_id)) { $this->role = Sprig::factory('role', array('id' => $roleuser[0]->role_id))->load(); } } } parent::__construct($template, $partials); }
public static function instance(&$uri = TRUE) { if (!Request::$instance) { if (!empty($_SERVER['HTTPS']) and filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { Request::$protocol = 'https'; } if (isset($_SERVER['REQUEST_METHOD'])) { Request::$method = $_SERVER['REQUEST_METHOD']; } if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') { Request::$is_ajax = TRUE; } Request::$client_ip = self::get_client_ip(); if (Request::$method !== 'GET' and Request::$method !== 'POST') { parse_str(file_get_contents('php://input'), $_POST); } if (isset($_SERVER['HTTP_USER_AGENT'])) { Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_REFERER'])) { Request::$referrer = $_SERVER['HTTP_REFERER']; } if ($uri === TRUE) { $uri = Request::detect_uri(); } $uri = preg_replace('#//+#', '/', $uri); $uri = preg_replace('#\\.[\\s./]*/#', '', $uri); Request::$instance = new Request($uri); } return Request::$instance; }
protected function authenticate() { if (!Auth::instance()->logged_in()) { $this->session->set('redirect', Request::detect_uri()); $this->request->redirect($this->site . "/login"); } else { $this->user = Auth::instance()->get_user(); } }
public function before() { parent::before(); $this->view = new View_Pages_ErrorHandler(); $this->view->set('page', URL::site(rawurldecode(Request::detect_uri()))); // Internal request only! if (Request::$initial !== $this->request) { if ($message = rawurldecode($this->request->param('message'))) { $this->view->set('raw_message', $message); } } else { $this->request->action(404); } $action = $this->request->action(); $this->response->status((int) $action); $this->view->set('code', $action); }
/** * Finds the current language or falls back to default if no available * language found * * @param string $uri the URI * @return string * @uses Request::detect_uri * @uses Lang::available_languages * @uses Lang::find_default() */ public static function find_current($uri = NULL) { if ($uri === NULL) { // Get the URI $uri = Request::detect_uri(); } // Normalize URI $uri = ltrim($uri, '/'); // Set available languages $available_languages = Lang::available_languages(); if (!preg_match('~^(?:' . implode('|', $available_languages) . ')(?=/|$)~i', $uri, $matches)) { // Find the best default language $matches[0] = Lang::find_default(); } // Return the detected language return strtolower($matches[0]); }
public function get_response() { $this->template = View::factory('base'); $config = Kohana::$config->load('main')->site; $base = new Model_Base(); $options = $base->getOptions(); $this->template->styles = $config['styles']; $this->template->styles[] = 'css/menu.css'; $this->template->scripts = $config['scripts']; $this->template->scripts[] = 'js/errors.js'; $this->template->title = 'Ошибка 404 - Страница не найдена'; $this->template->description = $options['description']; $this->template->keywords = $options['keywords']; $this->template->page_title = null; $header = View::factory('header'); $footer = View::factory('footer'); $this->template->header = $header; $this->template->footer = $footer; $this->template->for_cart = null; $this->template->top_menu = array(Request::factory('widgets/menu/index/4')->execute()); $this->template->left_menu = null; $this->template->block_left = null; $this->template->block_right = null; $this->template->pathway = null; $this->message = '<h1>Упс! Ошибка 404.</h1><br><p>Запрашиваемая страница не найдена. Скорее всего она была перемещена или удалена.</p>'; // Remembering that `$this` is an instance of HTTP_Exception_404 //проверка редиректов $gid = 34; $materials = new Model_Material('group'); $redirects = $materials->getMaterials($gid, 1000, 0); $url = Request::detect_uri(); foreach ($redirects as $redirect) { if ($redirect['name'] == Kohana::$base_url . substr($url, 1)) { $fields = $materials->getFields2($redirect['id'], TRUE); $this->redirect = $fields['to']; } } if (Kohana::$environment === Kohana::PRODUCTION) { $view = View::factory('errors/404')->set('message', $this->message)->set('redirect', $this->redirect)->render(); } else { $view = View::factory('errors/404')->set('message', $this->message)->render(); } $this->template->block_center = array($view); $response = Response::factory()->status(404)->body($this->template->render()); return $response; }
/** * Detect current page url * * @param $uri * @return Request */ public static function factory($uri) { // If this is the initial request if (!Request::$initial) { if ($uri === TRUE) { // Attempt to guess the proper URI $uri = Request::detect_uri(); $dir = str_replace('/', '\\/', DIR); $uri = preg_replace('/^' . $dir . '/', '/', $uri); } // Create the instance singleton Request::$initial = $request = new Request($uri); } else { $request = new Request($uri); } return $request; }
public static function delParamFromUrl($param) { $url = Request::detect_uri(); $arr = $_GET; //смотрим, есть ли параметры GET $base = new Model_Base(); $arr = $base->delFromArray($arr, $param); $cnt = count($arr); if ($cnt > 0) { $url .= '?'; foreach ($arr as $key => $value) { $url .= $key . '=' . $value . '&'; } $url = substr($url, 0, -1); } unset($cnt); return $url; }
/** * Extension of the main request factory. If none given, the URI will * be automatically detected. If the URI contains no language segment, the user * will be redirected to the same URI with the default language prepended. * If the URI does contain a language segment, I18n and locale will be set. * Also, a cookie with the current language will be set. Finally, the language * segment is chopped off the URI and normal request processing continues. * * @param string $uri URI of the request * @param Cache $cache * @param array $injected_routes an array of routes to use, for testing * @return Request * @uses Lang::config * @uses Request::detect_uri * @uses Lang::find_current * @uses Lang::$default_prepended * @uses Lang::$default * @uses Request::lang_redirect * @uses Request::$lang * @uses I18n::$lang * @uses Cookie::get * @uses Lang::$cookie * @uses Cookie::set */ public static function factory($uri = TRUE, $client_params = array(), $allow_external = TRUE, $injected_routes = array()) { // Load config $config = Lang::config(); if ($uri === TRUE) { // We need the current URI $uri = Request::detect_uri(); } // Get current language from URI $current_language = Lang::find_current($uri); if (!Lang::$default_prepended and $current_language === Lang::$default and strpos($uri, '/' . Lang::$default) === 0) { // If default is not prepended and current language is the default, // then redirect to the same URI, but with default language removed Request::lang_redirect(NULL, ltrim($uri, '/' . Lang::$default)); } elseif (Lang::$default_prepended and $current_language === Lang::$default and strpos($uri, '/' . Lang::$default) !== 0) { // If the current language is the default which needs to be // prepended, but it's missing, then redirect to same URI but with // language prepended Request::lang_redirect($current_language, $uri); } // Language found in the URI Request::$lang = $current_language; // Store target language in I18n I18n::$lang = $config[Request::$lang]['i18n_code']; // Set locale setlocale(LC_ALL, $config[Request::$lang]['locale']); if (Cookie::get(Lang::$cookie) !== Request::$lang) { // Update language cookie if needed Cookie::set(Lang::$cookie, Request::$lang); } if (Lang::$default_prepended or Request::$lang !== Lang::$default) { // Remove language from URI if default is prepended or the language is not the default $uri = (string) substr($uri, strlen(Request::$lang) + 1); } // Continue normal request processing with the URI without language return parent::factory($uri, $client_params, $allow_external, $injected_routes); }
public function action_index($options = array()) { $breadcrumbs = new Model_Widgets_Breadcrumb(); $paths[] = array("title" => "Главная", "path" => "/"); $uri = Request::detect_uri(); $dirs = explode("/", $uri); array_shift($dirs); foreach ($dirs as $dir) { $path = $breadcrumbs->getPath($dir); if ($path != FALSE) { $paths[] = array("title" => $path["name"], "path" => $path["path"]); } } $cnt = count($paths) - 1; $paths[$cnt]["path"] = ""; // --- Не удалять!!! -------------------------------------------------- $node = $paths[count($paths) - 1]; $paths[0]["path"] = ""; unset($paths[count($paths) - 1]); // --- /Не удалять!!! ------------------------------------------------- $model = array("nodes" => $paths, "node" => $node); PC::debug($model, "breadcrumb"); $this->set_template("/widgets/w_breadcrumb.php", "twig")->render($model)->body(); }
/** * Adds a message to the log * * Replacement values must be passed in to be * replaced using [strtr](http://php.net/strtr). * * Usage: * ~~~ * $log->add(Log::ERROR, 'Could not locate user: :user', array(':user' => $user->name)); * ~~~ * * @param string $level Level of message * @param string $message Message body * @param array $values Values to replace in the message [Optional] * @param array $additional Additional custom parameters to supply to the log writer [Optional] * @return Log * * @uses Date::formatted_time * @uses Date::$timestamp_format * @uses Date::$timezone * @uses Request::current * @uses Request::initial * @uses Request::uri * @uses Request::detect_uri * @uses Request::$client_ip * @uses Request::$user_agent * @uses Text::plain */ public function add($level, $message, array $values = NULL, array $additional = NULL) { if ($values) { // Insert the values into the message $message = strtr($message, $values); } if (isset($additional['exception'])) { $trace = $additional['exception']->getTrace(); } else { // Older PHP version don't have 'DEBUG_BACKTRACE_IGNORE_ARGS', // so manually remove the args from the backtrace if (!defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $trace = array_map(function ($item) { unset($item['args']); return $item; }, array_slice(debug_backtrace(FALSE), 1)); } else { $trace = array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 1); } } is_null($additional) or $additional = array(); $request = Request::current(); $uri = ''; if ($request instanceof Request) { $uri = Request::initial()->uri(); } elseif (!Kohana::$is_cli) { $uri = Request::detect_uri(); } // Create a new message and timestamp it $this->_messages[] = array('time' => Date::formatted_time('now', Date::$timestamp_format, Date::$timezone), 'level' => $level, 'body' => $message, 'trace' => $trace, 'file' => isset($trace[0]['file']) ? $trace[0]['file'] : NULL, 'line' => isset($trace[0]['line']) ? $trace[0]['line'] : NULL, 'class' => isset($trace[0]['class']) ? $trace[0]['class'] : NULL, 'function' => isset($trace[0]['function']) ? $trace[0]['function'] : NULL, 'additional' => $additional, 'hostname' => Request::$client_ip, 'user_agent' => Request::$user_agent, 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', 'url' => Text::plain($uri)); if (Log::$write_on_add) { // Write logs as they are added $this->write(); } return $this; }
$modules = "modules"; $system = "system"; define("EXT", ".php"); define("DOCROOT", realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR); error_reporting(E_ALL | E_NOTICE | E_STRICT); if (!is_dir($application) and is_dir(DOCROOT . $application)) { $application = DOCROOT . $application; } if (!is_dir($modules) and is_dir(DOCROOT . $modules)) { $modules = DOCROOT . $modules; } if (!is_dir($system) and is_dir(DOCROOT . $system)) { $system = DOCROOT . $system; } define("APPPATH", realpath($application) . DIRECTORY_SEPARATOR); define("MODPATH", realpath($modules) . DIRECTORY_SEPARATOR); define("SYSPATH", realpath($system) . DIRECTORY_SEPARATOR); unset($application, $modules, $system); if (!defined("APPLICATION_START_TIME")) { define("APPLICATION_START_TIME", microtime(TRUE)); } if (!defined("APPLICATION_START_MEMORY")) { define("APPLICATION_START_MEMORY", memory_get_usage()); } require APPPATH . "bootstrap" . EXT; //JsonApiApplication::$log->add(Log::EMERGENCY,'The world will end on :time.',[':time'=>time()+60]); try { echo Request::factory(TRUE, array(), FALSE)->query($_GET)->post($_POST)->method($_SERVER["REQUEST_METHOD"])->execute()->send_headers(TRUE)->body(); } catch (Exception $e) { echo "You tried to reach: " . Request::detect_uri(); }
public function before() { // Выполняем функцию родительского класса parent::before(); $base = new Model_Base(); $config = Kohana::$config->load('main')->site; $positions = Kohana::$config->load('main')->positions; $options = $base->getOptions(); $auth = Auth::instance(); if (isset($options['work']) && $options['work'] == 'TRUE' && $auth->logged_in('admin') == 0) { $this->template = View::factory('cap'); } $this->template->title = $options['title']; $this->template->description = $options['description']; $this->template->keywords = $options['keywords']; $this->template->page_title = null; $this->template->links = array(); // $cart = Request::factory("widgets/"); $header = Request::factory('widgets/header/index')->execute(); // ->bind('cart', $cart); $footer = Request::factory('widgets/footer/index')->execute(); foreach ($positions as $key => $value) { $this->template->{$key} = $value; } $this->template->header = $header; $this->template->footer = $footer; if (isset($_GET['login'])) { //активируем пользователя $vData = $_GET; $validation = Validation::factory($vData); $validation->rule('username', 'not_empty'); $validation->rule('username', 'min_length', array(':value', '2')); $validation->rule('username', 'max_length', array(':value', '250')); $validation->rule('password', 'not_empty'); $validation->rule('password', 'min_length', array(':value', '6')); $validation->rule('password', 'max_length', array(':value', '50')); if (!$validation->check()) { $errors[] = $validation->errors('registrationErrors'); } else { $auth = Auth::instance(); $username = Arr::get($_GET, 'username', ''); $password = Arr::get($_GET, 'password', ''); if ($auth->login($username, $password)) { Controller::redirect('/user'); } else { $errors[] = 'Не верный логин или пароль.'; } } } if (isset($_GET['site_version'])) { if ($_GET['site_version'] == 'standart') { Cookie::set('site_version', 'standart'); } else { Cookie::set('site_version', 'adaptive'); } } $site_version = Cookie::get('site_version', 'adaptive'); //проверка редиректов $gid = 46; $materials = new Model_Material('group'); $redirects = $materials->getMaterials($gid, 1000, 0); $url = Request::detect_uri(); foreach ($redirects as $redirect) { if ($redirect['name'] == DIRECTORY_SEPARATOR . substr($url, 1)) { $fields = $materials->getFields2($redirect['id'], TRUE); Controller::redirect(Kohana::$base_url . substr($fields['to'], 1), 301); } } $auth = Request::factory('widgets/auth/')->execute(); $this->template->site_version = $site_version; $this->template->auth = $auth; $this->template->styles = array(); $this->template->scripts = $config['scripts']; }
<?php $url = explode('/', Request::detect_uri()); if (count($url) > 1) { array_shift($url); if (preg_match("/page(.*)/", $url[count($url) - 1])) { unset($url[count($url) - 1]); } $url = implode('/', $url); } else { $url = ''; } if (count($_GET) > 0) { $query = '?'; $i = 0; foreach ($_GET as $key => $value) { ++$i; $query .= $key . '=' . $value; if ($i < count($_GET)) { $query .= '&'; } } } else { $query = ''; } ?> <ul class="pagination pull-right"> <?php if ($first_page !== FALSE) { ?>
/** * Generates the full URL for a certain page. * * @param * integer page number * @return string page URL */ public function url($page = 1) { // Clean the page number $page = max(1, (int) $page); // No page number in URLs to first page if ($page === 1 and !$this->config['first_page_in_url']) { $page = NULL; } switch ($this->config['current_page']['source']) { case 'query_string': return URL::site(Request::current()->uri()) . URL::query(array($this->config['current_page']['key'] => $page)); case 'route': return URL::site(Request::current()->uri(array($this->config['current_page']['key'] => $page))) . URL::query(); case 'mixed': return URL::site(Request::detect_uri()) . URL::query(array($this->config['current_page']['key'] => $page)); } return '#'; }
public static function factory($uri = TRUE, $client_params = array(), $allow_external = TRUE, $injected_routes = array()) { if (!Request::$initial) { $protocol = HTTP::$protocol; if (isset($_SERVER['REQUEST_METHOD'])) { $method = $_SERVER['REQUEST_METHOD']; } else { $method = HTTP_Request::GET; } if (!empty($_SERVER['HTTPS']) and filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN) or isset($_SERVER['HTTP_X_FORWARDED_PROTO']) and $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) { $secure = TRUE; } if (isset($_SERVER['HTTP_REFERER'])) { $referrer = $_SERVER['HTTP_REFERER']; } if (isset($_SERVER['HTTP_USER_AGENT'])) { Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { $requested_with = $_SERVER['HTTP_X_REQUESTED_WITH']; } if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) { $client_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); Request::$client_ip = array_shift($client_ips); unset($client_ips); } elseif (isset($_SERVER['HTTP_CLIENT_IP']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) { $client_ips = explode(',', $_SERVER['HTTP_CLIENT_IP']); Request::$client_ip = array_shift($client_ips); unset($client_ips); } elseif (isset($_SERVER['REMOTE_ADDR'])) { // The remote IP address Request::$client_ip = $_SERVER['REMOTE_ADDR']; } if ($method !== HTTP_Request::GET) { // Ensure the raw body is saved for future use $body = file_get_contents('php://input'); } if ($uri === TRUE) { // Attempt to guess the proper URI $uri = Request::detect_uri(); } $cookies = array(); if ($cookie_keys = array_keys($_COOKIE)) { foreach ($cookie_keys as $key) { $cookies[$key] = Cookie::get($key); } } // Create the instance singleton Request::$initial = $request = new Request($uri, $client_params, $allow_external, $injected_routes); // Store global GET and POST data in the initial request only $request->protocol($protocol)->query($_GET)->post($_POST); if (isset($secure)) { // Set the request security $request->secure($secure); } if (isset($method)) { // Set the request method $request->method($method); } if (isset($referrer)) { // Set the referrer $request->referrer($referrer); } if (isset($requested_with)) { // Apply the requested with variable $request->requested_with($requested_with); } if (isset($body)) { // Set the request body (probably a PUT type) $request->body($body); } if (isset($cookies)) { $request->cookie($cookies); } } else { $request = new Request($uri, $client_params, $allow_external, $injected_routes); } return $request; }
public function before() { // Вызываем метод для определения вида и шаблона parent::before(); // Создаем объект запроса $request = Request::factory(false); $last_url = Request::detect_uri(); //var_dump($last_url); //exit; // Создаем сессию для сохранения запрошенного пути в админку $session = Session::instance(); // Если запрошенный URL не равен странице авторизации if (!preg_match('!^/admin/login!i', $last_url)) { $session->set('last_url', $last_url); } // Проверяем - авторизован ли пользователь как администратор $this->auth = Auth::instance(); // Изначально доступ для данного модуля для роли закрыт $perm_cur_module = false; // Массив ролей, имеющих доступ в админку $roles_access = array('admin', 'manager', 'rop'); if ($this->ajax == 'cron_') { } elseif ($this->auth->logged_in($roles_access)) { $this->user = $this->auth->get_user(); // Вытаскиваем все роли пользователя $roles = Sprig::factory('roleuser')->load(DB::select('*')->where('user_id', '=', $this->user->id), NULL); for ($i = 0; $i < count($roles); $i++) { // Вытаскиваем разрешение на модули для роли пользователя $perm = Sprig::factory('roleperm')->load(DB::select('*')->where('role_id', '=', $roles[$i]->role_id), NULL); // Проходим по всем разрешенным модулям для роли for ($r = 0; $r < count($perm); $r++) { // Если запись для роли есть и она равна 1 - разрешение есть if ($perm[$r]->permission == 1) { // Вытаскиваем название модуля $module = Sprig::factory('module', array('mid' => $perm[$r]->module_id))->load(); // Если запрашиваемый модуль входит в список разрешенных для данной роли - ставим метку if ($module->loaded() && $this->controller_name == $module->name) { $perm_cur_module = true; } // Добавляем модуль в список разрешенных $this->access_modules[$module->mid] = $module->name; } } } // Если доступа к запрашиваемому модулю нет - редиректим на главную станицу админки if (empty($perm_cur_module) and $last_url != '/admin') { $request->redirect('/admin'); } // Регистрируем список разрешенных модулей в виде $this->view->access_modules = $this->access_modules; } elseif ($last_url != '/admin/subscribe/ajax/send') { // Если была засабмичена форма авторизации if (!empty($_POST['login']) && !empty($_POST['password'])) { // Пробуем авторизоваться по введенным данным if ($this->auth->login($_POST['login'], $_POST['password'])) { // Вытаскиваем запрошенный URL админки из сессии auth_path $path = $session->get('last_url'); if (!empty($path)) { $request->redirect($path); } else { $request->redirect('/admin'); } } } // Если пользователь не авторизован и не находится на странице // авторизации, редиректим его на страницу авторизации if (!preg_match('!^/admin/login!i', $last_url)) { $request->redirect('/admin/login'); } } //$this->auth->logout(); }
/** * Creates a new request object for the given URI. New requests should be * created using the [Request::instance] or [Request::factory] methods. * * $request = Request::factory($uri); * * If $cache parameter is set, the response for the request will attempt to * be retrieved from the cache. * * @param string $uri URI of the request * @param Cache $cache * @param array $injected_routes an array of routes to use, for testing * @return void * @throws Request_Exception * @uses Route::all * @uses Route::matches */ public static function factory($uri = TRUE, HTTP_Cache $cache = NULL, $injected_routes = array()) { // If this is the initial request if (!Request::$initial) { if (Kohana::$is_cli) { // Default protocol for command line is cli:// $protocol = 'cli'; // Get the command line options $options = CLI::options('uri', 'method', 'get', 'post', 'referrer'); if (isset($options['uri'])) { // Use the specified URI $uri = $options['uri']; } elseif ($uri === TRUE) { $uri = ''; } if (isset($options['method'])) { // Use the specified method $method = strtoupper($options['method']); } else { // Default to GET requests $method = HTTP_Request::GET; } if (isset($options['get'])) { // Overload the global GET data parse_str($options['get'], $_GET); } if (isset($options['post'])) { // Overload the global POST data parse_str($options['post'], $_POST); } if (isset($options['referrer'])) { $referrer = $options['referrer']; } } else { if (isset($_SERVER['SERVER_PROTOCOL'])) { $protocol = $_SERVER['SERVER_PROTOCOL']; } else { $protocol = HTTP::$protocol; } if (isset($_SERVER['REQUEST_METHOD'])) { // Use the server request method $method = $_SERVER['REQUEST_METHOD']; } else { // Default to GET requests $method = HTTP_Request::GET; } if (!empty($_SERVER['HTTPS']) and filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { // This request is secure $secure = TRUE; } if (isset($_SERVER['HTTP_REFERER'])) { // There is a referrer for this request $referrer = $_SERVER['HTTP_REFERER']; } if (isset($_SERVER['HTTP_USER_AGENT'])) { // Browser type Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { // Typically used to denote AJAX requests $requested_with = $_SERVER['HTTP_X_REQUESTED_WITH']; } if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) { // Use the forwarded IP address, typically set when the // client is using a proxy server. // Format: "X-Forwarded-For: client1, proxy1, proxy2" $client_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); Request::$client_ip = array_shift($client_ips); unset($client_ips); } elseif (isset($_SERVER['HTTP_CLIENT_IP']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) { // Use the forwarded IP address, typically set when the // client is using a proxy server. $client_ips = explode(',', $_SERVER['HTTP_CLIENT_IP']); Request::$client_ip = array_shift($client_ips); unset($client_ips); } elseif (isset($_SERVER['REMOTE_ADDR'])) { // The remote IP address Request::$client_ip = $_SERVER['REMOTE_ADDR']; } if ($method !== HTTP_Request::GET) { // Ensure the raw body is saved for future use $body = file_get_contents('php://input'); } if ($uri === TRUE) { // Attempt to guess the proper URI $uri = Request::detect_uri(); } } // Create the instance singleton Request::$initial = $request = new Request($uri, $cache); // Store global GET and POST data in the initial request only $request->protocol($protocol)->query($_GET)->post($_POST); if (isset($secure)) { // Set the request security $request->secure($secure); } if (isset($method)) { // Set the request method $request->method($method); } if (isset($referrer)) { // Set the referrer $request->referrer($referrer); } if (isset($requested_with)) { // Apply the requested with variable $request->requested_with($requested_with); } if (isset($body)) { // Set the request body (probably a PUT type) $request->body($body); } } else { $request = new Request($uri, $cache, $injected_routes); } return $request; }
/** * Detect language based on the url. * * ex: example.com/fr/ * $lang = I18n::urlLocale(); * * @return string */ public static function urlLocale() { $uri = Request::detect_uri(); if (preg_match('/^\\/(' . join('|', array_keys(self::$_languages)) . ')\\/?$/', $uri, $matches)) { //'~^(?:' . implode('|', array_keys($installed_locales)) . ')(?=/|$)~i' // matched /lang or /lang/ return $matches[1]; } return FALSE; }
/** * Main request singleton instance. If no URI is provided, the URI will * be automatically detected. * * $request = Request::instance(); * * @param string URI of the request * @return Request * @uses Request::detect_uri */ public static function instance( & $uri = TRUE) { if ( ! Request::$instance) { if (Kohana::$is_cli) { // Default protocol for command line is cli:// Request::$protocol = 'cli'; // Get the command line options $options = CLI::options('uri', 'method', 'get', 'post'); if (isset($options['uri'])) { // Use the specified URI $uri = $options['uri']; } if (isset($options['method'])) { // Use the specified method Request::$method = strtoupper($options['method']); } if (isset($options['get'])) { // Overload the global GET data parse_str($options['get'], $_GET); } if (isset($options['post'])) { // Overload the global POST data parse_str($options['post'], $_POST); } } else { if (isset($_SERVER['REQUEST_METHOD'])) { // Use the server request method Request::$method = $_SERVER['REQUEST_METHOD']; } if ( ! empty($_SERVER['HTTPS']) AND filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { // This request is secure Request::$protocol = 'https'; } if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') { // This request is an AJAX request Request::$is_ajax = TRUE; } if (isset($_SERVER['HTTP_REFERER'])) { // There is a referrer for this request Request::$referrer = $_SERVER['HTTP_REFERER']; } if (isset($_SERVER['HTTP_USER_AGENT'])) { // Set the client user agent Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Use the forwarded IP address, typically set when the // client is using a proxy server. Request::$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { // Use the forwarded IP address, typically set when the // client is using a proxy server. Request::$client_ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { // The remote IP address Request::$client_ip = $_SERVER['REMOTE_ADDR']; } if (Request::$method !== 'GET' AND Request::$method !== 'POST') { // Methods besides GET and POST do not properly parse the form-encoded // query string into the $_POST array, so we overload it manually. parse_str(file_get_contents('php://input'), $_POST); } if ($uri === TRUE) { $uri = Request::detect_uri(); } } // Reduce multiple slashes to a single slash $uri = preg_replace('#//+#', '/', $uri); // Remove all dot-paths from the URI, they are not valid $uri = preg_replace('#\.[\s./]*/#', '', $uri); // Create the instance singleton Request::$instance = Request::$current = new Request($uri); // Add the default Content-Type header Request::$instance->headers['Content-Type'] = 'text/html; charset='.Kohana::$charset; } return Request::$instance; }
} if (!defined('PLUGINS_URL')) { define('PLUGINS_URL', BASE_URL . 'cms/plugins/'); } if (!defined('IS_BACKEND')) { define('IS_BACKEND', FALSE); } /** * Set the default cookie salt */ Cookie::$salt = 'install_system'; /** * Disable kohana caching */ Kohana::$caching = FALSE; /** * Enable modules. Modules are referenced by a relative or absolute path. */ Kohana::modules(array('api' => MODPATH . 'api', 'users' => MODPATH . 'users', 'kodicms' => MODPATH . 'kodicms', 'assets' => MODPATH . 'assets', 'cache' => MODPATH . 'cache', 'database' => MODPATH . 'database', 'auth' => MODPATH . 'auth', 'orm' => MODPATH . 'orm', 'minion' => MODPATH . 'minion', 'filesystem' => MODPATH . 'filesystem', 'breadcrumbs' => MODPATH . 'breadcrumbs', 'widget' => MODPATH . 'widget', 'email' => MODPATH . 'email', 'plugins' => MODPATH . 'plugins', 'installer' => MODPATH . 'installer')); Observer::notify('modules::after_load'); /** * Проверка на существование модуля `installer` */ if (array_key_exists('installer', Kohana::modules()) === FALSE) { throw HTTP_Exception::factory(404, __('System not installed. Installer not found.')); } if (PHP_SAPI != 'cli') { if (!URL::match('install', Request::detect_uri()) and !URL::match('cms/media/', Request::detect_uri())) { $uri = Route::get('install')->uri(); } }
/** * The current request is a backend request? * * @return bool * @throws Kohana_Exception */ public function is_backend() { return is_string(BACKEND_DIR_NAME) ? URL::match(BACKEND_DIR_NAME, Request::detect_uri()) : false; }
public function action_sidebar() { $this->setopt(array("name" => "parent_id", "description" => "Ид каталога", "default" => 6)); $parent_id = $this->getopt("parent_id"); $uri = Request::detect_uri(); $page_uri = explode('/', $uri); $GLOBALS['uri'] = $page_uri; $uri = isset($page_uri[1]) ? $page_uri[1] : ''; $uri2 = isset($page_uri[2]) ? $page_uri[2] : ''; $model_tree = new Model_Widgets_Menu('tree'); $items = $model_tree->menuItems($parent_id, 3); $model = array("items" => array()); foreach ($items as $item) { $item_model = array("href" => "/" . Arr::get($item, "parent") . "/" . $item["url"], "name" => $item["name"]); if ($item["url"] == $uri2) { $item_model["active"] = " class='active'"; } $model["items"][] = $item_model; } $this->set_template("widgets/menu/sidebar.php", "twig")->render($model)->body(); }
public static function factory($uri = TRUE, Cache $cache = NULL) { // If this is the initial request if (!Request::$initial) { if (Kohana::$is_cli) { // Default protocol for command line is cli:// $protocol = 'cli'; // Get the command line options $options = CLI::options('uri', 'method', 'get', 'post', 'referrer'); if (isset($options['uri'])) { // Use the specified URI $uri = $options['uri']; } if (isset($options['method'])) { // Use the specified method $method = strtoupper($options['method']); } else { $method = 'GET'; } if (isset($options['get'])) { // Overload the global GET data parse_str($options['get'], $_GET); } if (isset($options['post'])) { // Overload the global POST data parse_str($options['post'], $_POST); } if (isset($options['referrer'])) { $referrer = $options['referrer']; } else { $referrer = NULL; } } else { if (isset($_SERVER['REQUEST_METHOD'])) { // Use the server request method $method = $_SERVER['REQUEST_METHOD']; } else { // Default to GET $method = Http_Request::GET; } if (!empty($_SERVER['HTTPS']) and filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { // This request is secure $protocol = 'https'; } else { $protocol = 'http'; } if (isset($_SERVER['HTTP_REFERER'])) { // There is a referrer for this request $referrer = $_SERVER['HTTP_REFERER']; } else { $referrer = NULL; } if (isset($_SERVER['HTTP_USER_AGENT'])) { // Set the client user agent Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { $requested_with = $_SERVER['HTTP_X_REQUESTED_WITH']; } if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Use the forwarded IP address, typically set when the // client is using a proxy server. Request::$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { // Use the forwarded IP address, typically set when the // client is using a proxy server. Request::$client_ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { // The remote IP address Request::$client_ip = $_SERVER['REMOTE_ADDR']; } if ($method !== 'GET') { // Ensure the raw body is saved for future use $body = file_get_contents('php://input'); } if ($uri === TRUE) { $uri = Request::detect_uri(); } } // Create the instance singleton $request = new Request($uri, $cache); $request->protocol($protocol)->method($method)->referrer($referrer); // Apply the requested with variable isset($requested_with) and $request->requested_with($requested_with); // If there is a body, set it to the model isset($body) and $request->body($body); } else { $request = new Request($uri, $cache); } // Create the initial request if it does not exist if (!Request::$initial) { Request::$initial = $request; $request->query($_GET)->post($_POST); } return $request; }
echo $body; ?> </div> <!--/content-wrapper--> <?php echo $scripts; ?> <script type="text/javascript"> var global = { 'base_url' : '<?php echo URL::base(); ?> ', 'current_url' : '<?php echo str_replace('/', '', substr(Request::detect_uri(), 1)); ?> ', 'theme' : '<?php echo $config['theme']; ?> ' } var messages = <?php echo $javascript_messages; ?> </script> </body> </html>
<?php defined('SYSPATH') or die('No direct access allowed.'); if (PHP_SAPI != 'cli') { define('IS_BACKEND', URL::match(ADMIN_DIR_NAME, Request::detect_uri())); } if (!defined('IS_BACKEND')) { define('IS_BACKEND', FALSE); } if (!defined('SESSION_TYPE')) { define('SESSION_TYPE', 'native'); } // CMS defaults define('ADMIN_URL', BASE_URL . ADMIN_DIR_NAME . '/'); define('PLUGINS_URL', BASE_URL . 'cms/plugins/'); define('PUBLIC_URL', BASE_URL . 'public/'); /** * Set the default time zone. * * @see http://kohanaframework.org/guide/using.configuration * @see http://php.net/timezones */ date_default_timezone_set(DEFAULT_TIMEZONE); /** * Cookie Salt * @see http://kohanaframework.org/3.3/guide/kohana/cookies * * If you have not defined a cookie salt in your Cookie class then * uncomment the line below and define a preferrably long salt. */ Cookie::$salt = COOKIE_SALT;
/** * Generates the full URL for a certain page. * * @param integer page number * @return string page URL */ public function url($page = 1) { // Clean the page number $page = max(1, (int) $page); // No page number in URLs to first page if ($page === 1 && !$this->config['first_page_in_url']) { $page = ''; } switch ($this->config['current_page']['source']) { case 'query_string': return URL::site(Request::current()->uri(), NULL, $this->config['show_index']) . URL::query(array($this->config['current_page']['key'] => $page)); case 'route': if (Request::current()->param('user_id')) { return URL::site(Request::current()->route()->uri(array('user_id' => Request::current()->param('user_id'), $this->config['current_page']['key'] => $page)), NULL, $this->config['show_index']) . URL::query(); } elseif (Request::current()->param('lang')) { return URL::site(Request::current()->route()->uri(array('lang' => Request::current()->param('lang'), $this->config['current_page']['key'] => $page)), NULL, $this->config['show_index']) . URL::query(); } else { return URL::site(Request::current()->route()->uri(array($this->config['current_page']['key'] => $page)), NULL, $this->config['show_index']) . URL::query(); } case 'mixed': return URL::site(Request::detect_uri(), NULL, $this->config['show_index']) . URL::query(array($this->config['current_page']['key'] => $page)); } return '#'; }
<?php $uri = Request::detect_uri(); $page_uri = explode('/', $uri); $GLOBALS['uri'] = $page_uri; $uri = isset($page_uri[1]) ? $page_uri[1] : ''; $uri2 = isset($page_uri[2]) ? $page_uri[2] : ''; require_once APPPATH . 'classes/Templater/phpQuery.php'; $template = file_get_contents(APPPATH . 'views/widgets/w_menu.html'); $template = phpQuery::newDocument($template); if ($uri == '') { $template->find('.index_link')->addClass('active'); } $dropdown = null; $mitem_el = null; $endkey = null; $mitem_id = null; foreach ($menu as $key => $mitem) { $mitem_template = $template->find('.mitem_template'); $dropdown_menu_template = $template->find('.dropdown_menu_template'); $dropdown_item_template = $template->find('.dropdown_item_template'); if ($mitem['level'] == 2) { $mitem_el = $mitem_template->clone(); $mitem_id = $mitem['id']; $mitem_el->attr('id', 'mitem_' . $mitem['id']); $mitem_a = $mitem_el->find('a'); $mitem_a->attr('href', '/' . $mitem['url'])->attr('id', $mitem['id'])->html($mitem['name']); if ($mitem['url'] == $uri) { $mitem_el->addClass('active'); } $mitem_el->removeClass('mitem_template');
/** * Top buttons * * @param array $links * * @return string */ public static function btns_top(array $links = []) { $class = ['class' => 'btn btn-default btn-sm']; $html = PHP_EOL; foreach ($links as $url => $title) { if (!$title) { continue; } $action = explode('/', $url); $count = count($action) - 1; if (Valid::digit($action[$count])) { $action = $action[$count - 1]; } else { $action = end($action); } switch ($action) { case 'add': $html .= HTML::anchor($url, '<i class="fa fa-plus fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'edit': $html .= HTML::anchor($url, '<i class="fa fa-edit fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'password': $html .= HTML::anchor($url, '<i class="fa fa-key fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'profile': $html .= HTML::anchor($url, '<i class="fa fa-user fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'filter': if (Request::current()->action() == 'filter') { $html .= HTML::anchor($url, '<i class="fa fa-filter fa-fw"></i> ' . $title, $class) . PHP_EOL; } break; case 'order': $html .= HTML::anchor($url, '<i class="fa fa-sort fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'npupdate': $html .= HTML::anchor($url, '<i class="fa fa-refresh fa-fw"></i> ' . $title, $class) . PHP_EOL; break; case 'list': if (Request::current()->query('colunm') and Request::current()->query('order')) { $html .= HTML::anchor(Request::detect_uri(), '<i class="fa fa-angle-right fa-fw"></i> ' . $title, $class) . PHP_EOL; } elseif (Request::current()->action() == 'deleted') { $html .= HTML::anchor($url, '<i class="fa fa-list-ul fa-fw"></i> ' . $title, $class) . PHP_EOL; } break; } } return '<div class="btn-group">' . $html . '</div>'; }