fullUrl() public static method

Get the full URL for the request.
public static fullUrl ( ) : string
return string
Beispiel #1
0
 public function apply(Transformable $transformable)
 {
     $file = \File::get(public_path('assets/img/borders.png'));
     $img = base64_encode($file);
     $data = str_ireplace(["\r", "\n"], '', $transformable->getContents());
     $data = preg_replace("~<(/?(br|p|dd))[^>]*?>~i", '<\\1>', $data);
     $data = preg_replace("~</(p|dd)>~i", '', $data);
     $data = preg_replace("~<(br|p|dd)>~i", static::LINEBREAK, $data);
     $data = preg_replace('/[ ]{2,}/', ' ', $data);
     $data = preg_replace("/" . static::LINEBREAK . "[ ]+/s", static::LINEBREAK . "    ", $data);
     $data = str_replace(static::LINEBREAK, '<p>', $data);
     $page = $transformable->page;
     $author = $page->author;
     $charset = $transformable->charset ?: 'utf-8';
     $title = $author->fio . " - " . $page->title;
     $link = \HTML::link(path_join("http://samlib.ru", $author->absoluteLink()), $author->fio) . " - " . \HTML::link(path_join("http://samlib.ru", $page->absoluteLink()), $page->title);
     $annotation = $page->annotation;
     $contents = $data;
     $downloaded = \Lang::get('pages.pages.downloaded', ['url' => \Request::fullUrl()]);
     if ($charset != 'utf-8') {
         $e = app('charset-encoder');
         $c = $e->remap($charset, true);
         $title = $e->transform($title, 'utf-8', $c);
         $link = $e->transform($link, 'utf-8', $c);
         $annotation = $e->transform($annotation, 'utf-8', $c);
         $downloaded = $e->transform($downloaded, 'utf-8', $c);
     }
     $view = view('pages.html-download', compact('img', 'charset', 'title', 'link', 'annotation', 'contents', 'downloaded'));
     $transformable->setContents((string) $view);
     $transformable->setType(static::EXTENSION);
     return $transformable;
 }
Beispiel #2
0
 /**
  * Share common view variables
  */
 protected function setSharedVariables()
 {
     view()->share('currentLocale', app()->getLocale());
     view()->share('currentUser', auth()->user());
     view()->share('currentRouteName', \Route::currentRouteName());
     view()->share('currentUrl', \Request::fullUrl());
 }
 public function onFinish()
 {
     if ($this->_queriesCount < $this->_limit) {
         return;
     }
     $filename = storage_path('/logs/query.' . date('d.m.y') . '.request.log');
     $string = '[' . date('H:i:s') . '] ' . \Request::fullUrl() . ': ' . $this->_queriesCount . ' queries in ' . $this->_totalTime . 'ms.' . PHP_EOL;
     \File::append($filename, $string);
 }
Beispiel #4
0
 public function set($key = '', $current_url = '')
 {
     if (empty($key)) {
         $key = \Request::route()->getName();
     }
     if (empty($current_url)) {
         $current_url = \Request::fullUrl();
     }
     $session_key = $this->session_key($key);
     \Session::put($session_key, $current_url);
 }
/**
 * Array View Helper
 * 
 * @param  array  $items
 * @return array
 */
function helper_links($items = [])
{
    $hrefSelf = Request::fullUrl();
    $links = ['self' => ['href' => $hrefSelf, 'type' => 'application/json; version=1.0']];
    if (count($items)) {
        $last = $items[count($items) - 1];
        $currentRoute = Route::current();
        $queries = Input::all();
        $queries = array_merge($queries, ['cursor' => $last->id]);
        $hrefNext = url($currentRoute->getPath()) . '?' . http_build_query($queries);
        $links['next'] = ['href' => $hrefNext, 'type' => 'application/json; version=1.0'];
    }
    return $links;
}
Beispiel #6
0
 /**
  * 获得微信jsapi的配置信息
  * @return stdClass
  */
 public function getJsapiConfig()
 {
     $mq = new MQ();
     $jsapiTicket = $mq->getWeixinJsapiTicketByName('buyer');
     $url = \Request::fullUrl();
     $noncestr = Tool::getRandChar(16);
     $timestamp = time();
     $weixinClient = new WeixinClient();
     $signature = $weixinClient->getSignature($jsapiTicket, $url, $noncestr, $timestamp);
     $config = new \stdClass();
     $config->jsapiTicket = $jsapiTicket;
     $config->url = $url;
     $config->noncestr = $noncestr;
     $config->timestamp = $timestamp;
     $config->signature = $signature;
     $config->appid = \Config::get('weixin.buyer.appid');
     return $config;
 }
Beispiel #7
0
 public static function enviarError(Exception $exception, $code)
 {
     $arr = explode('\\', get_class($exception));
     $stackFinal = $exception->getTraceAsString();
     $stackFinal .= "<br>Linea: " . $exception->getLine();
     $stackFinal .= "<br>Archivo: " . $exception->getFile();
     $stackFinal .= "<br>Mensaje: " . $exception->getMessage();
     $stackFinal .= "<br>Código: " . $code;
     $data = array('EXCEPCION' => $arr[count($arr) - 1], 'STACK' => $stackFinal, 'URL' => Request::fullUrl() . ' (' . Request::method() . ')', 'PARAMETROS' => json_encode(Input::all()));
     $url = Configuracion::get('urlactualizacion') . 'error?CLAVEPROYECTO=' . Configuracion::get('claveproyecto') . '&AMBIENTE=' . Configuracion::get('ambiente') . '&VERSION=' . Configuracion::get('version');
     $ch = curl_init();
     $optArray = array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_NOBODY => false, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data);
     curl_setopt_array($ch, $optArray);
     $curl = new AyudanteCurl();
     $curl->respuesta = substr(curl_exec($ch), curl_getinfo($ch, CURLINFO_HEADER_SIZE));
     $curl->codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     $curl->respuestaObj = json_decode($curl->respuesta);
     if ($curl->codigoRespuesta != 200) {
         throw new CurlException($curl);
     }
     curl_close($ch);
     return $curl->respuestaObj->mensaje;
 }
 public function index()
 {
     // Get the base url. We do it this way cause Request::getBaseUrl()
     // doesn't seem to work in all cases.
     $fullUrl = Request::fullUrl();
     $url = substr($fullUrl, 0, strpos($fullUrl, '/install'));
     $local = true;
     if (!isUsingLocalStorage()) {
         $local = false;
         $keys = ['database_database', 'database_default', 'database_host', 'database_username', 'database_password', 'app_key', 'app_url', 'services_phaxio_public', 'services_phaxio_secret', 'mail_driver', 'mail_from_address', 'mail_from_name', 'mail_host', 'mail_port', 'mail_username', 'mail_password', 'services_mailgun_domain', 'services_mailgun_secret'];
         $envErrors = [];
         foreach ($keys as $key) {
             if (!isset($_ENV[$key])) {
                 $envErrors[] = "The key <strong>{$key}</strong> must be set in your environment variables";
             } else {
                 $env[$key] = $_ENV[$key];
             }
         }
         if ($envErrors) {
             return View::make('install.envErrors', compact('envErrors'));
         }
     }
     return View::make('install.index', compact('url', 'env', 'local'));
 }
 private static function ajaxRedirect($object = false, $action = false, $quickEdit = false)
 {
     $data = array('success' => true, 'returnToParent' => false, 'quickEdit' => $quickEdit, 'objectRow' => false, 'objectId' => false);
     if (!self::$modelConfig->relatedModels) {
         $data['returnToParent'] = true;
     }
     if (config('gtcms.preventRedirectOnSave') || $quickEdit) {
         $data['returnToParent'] = false;
     }
     /** @var \App\BaseModel $object */
     if (config('gtcms.premium') && $quickEdit) {
         GtcmsPremium::setQuickEditReturnData($data, $object, self::$modelConfig);
     }
     // If object has just been successfully added
     if ($action == 'add' && !$data['returnToParent'] && self::$modelConfig->name != "GtcmsSetting") {
         $printProperty = self::$modelConfig->printProperty;
         $data['replaceCurrentHistory'] = array('modelName' => self::$modelConfig->hrName, 'objectName' => $printProperty ? $object->{$printProperty} : false);
         $fullUrl = str_replace("/edit/new", "/edit/" . $object->id, \Request::fullUrl());
         $data['replaceUrl'] = $fullUrl;
         $data['objectId'] = $object->id;
         AdminHistoryManager::replaceAddLink($fullUrl, self::$modelConfig->name);
     }
     return \Response::json($data);
 }
 /**
  * Attempt to authenticate. True on success, also sets $this->user to authenticated user
  * @return bool whether user authentication was successful
  */
 private function attemptAuth()
 {
     $guid = Request::segment(2);
     $method = Request::segment(3, 'empty');
     $ip_address = Request::ip();
     $fullUrl = Request::fullUrl();
     // if request fails, only then log the full query string
     if (Input::get('cryptotype')) {
         $this->crypto_type_id = Input::get('cryptotype');
     }
     $error = $this->checkQueryRequiredArgs();
     if ($error) {
         Log::error("Query arguments not correct. Error: {$error}. Arguments - GUID: {$guid}, method: {$method}, ipAddress: {$ip_address}. Full URL: {$fullUrl}");
         return false;
     }
     $user_valid = $this->validateUser($guid);
     // error is printed inside #validateUser function
     if ($user_valid['status'] == 'error') {
         Log::error('User not validated. Error: ' . $user_valid['message'] . ". Arguments - GUID: {$guid}, method: {$method}, ipAddress: {$ip_address}. Full URL: {$fullUrl}");
         return false;
     }
     return true;
 }
 /** @test */
 public function it_redirect_to_login_page_without_login()
 {
     $this->visit(route('home'))->seePageIs(\Request::fullUrl());
 }
Beispiel #12
0
<?php

/**
 * Array View Helper
 * 
 * @param  array  $items
 * @return array
 */
return function ($items = []) {
    $hrefSelf = Request::fullUrl();
    $links = ['self' => ['href' => $hrefSelf, 'type' => 'application/json; version=1.0']];
    if (count($items)) {
        $last = $items[count($items) - 1];
        $queries = Input::all();
        $queries = array_merge($queries, ['cursor' => $last->id]);
        $hrefNext = url(Request::url()) . '?' . http_build_query($queries);
        $links['next'] = ['href' => $hrefNext, 'type' => 'application/json; version=1.0'];
    }
    return $links;
};
Beispiel #13
0
    /**
     *	return function that return html to the list of categories in wpanel.
     *
     *	@param array|collection $categories All Categories
     *
     *	@return function
     */
    public static function printCategory($categories = [])
    {
        $url = \Request::fullUrl();
        $printCategory = function ($row) use(&$printCategory, $categories, $url) {
            if (count($categories) > 0 && $row['category_id']) {
                foreach ($categories as $category) {
                    if ($row['category_id'] == $category['id']) {
                        $father = '<a href="' . $url . '#category' . $category['id'] . '">' . $category['name'] . '</a>';
                        break;
                    }
                }
            } else {
                $father = '';
                //trans('globals.action')
            }
            echo '<li class="list-group-item" ng-init="str' . $row['id'] . '=\'' . $row['name'] . '\'" ng-show="(search==\'\'||(str' . $row['id'] . '.toLowerCase().indexOf(search.toLowerCase())>-1))?true:false">
						<div class="row">
							<div class="col-md-1"><span class="label label-default visible-xs-inline">#ID:</span>  ' . $row['id'] . '</div>
		                    <div class="col-md-3"><span class="label label-default visible-xs-inline">' . trans('product.inputs_view.name') . ':</span>  <a name="category' . $row['id'] . '">' . $row['name'] . '</a></div>
		                    <div class="col-md-2"><span class="label label-default visible-xs-inline">' . trans('globals.status') . ':</span>  ' . ($row['status'] == 1 ? '<span class="label label-success">' . trans('globals.active') . '</span>' : '<span class="label label-danger">' . trans('globals.inactive') . '</span>') . '</div>
		                    <div class="col-md-2"><span class="label label-default visible-xs-inline">' . trans('store.father') . ':</span>  ' . $father . '</div>
		                    <div class="col-md-2"><span class="label label-default visible-xs-inline">' . trans('globals.type') . ':</span>  ' . $row['type'] . '</div>
		                    <div class="col-md-2"><a href="' . route('wpanel.category.edit', $row['id']) . '">Edit</a></div>
		                </div>
					</li>';
            if (isset($row['sub']) && count($row['sub']) > 0) {
                foreach ($row['sub'] as $subRow) {
                    $printCategory($subRow);
                }
            }
        };
        return $printCategory;
    }
 function obtainAuthCodeGrant(ApiTester $I)
 {
     $user = factory(App\Models\User::class, 1)->create();
     $user->password = '******';
     $user->save();
     $I->amLoggedAs($user);
     $client = factory(App\Models\OAuthClient::class, 1)->create();
     $grant = \App\Models\OAuthGrant::find('authorization_code');
     $client->oauth_grants()->attach($grant);
     $scope = \App\Models\OAuthScope::find('user_read');
     $client->oauth_scopes()->attach($scope);
     $endpoint = factory(App\Models\OAuthClientEndpoint::class, 1)->make();
     $endpoint->oauth_client()->associate($client);
     $endpoint->save();
     $I->wantTo('Perform a full 3rd party authorisation flow and get an access token');
     $I->amOnPage('authorize?client_id=' . $client->id . '&redirect_uri=' . $endpoint->redirect_uri . '&response_type=code&scope=user_read');
     $I->click('approve');
     $I->seeInCurrentUrl('code=');
     $url = Request::fullUrl();
     $parts = parse_url($url);
     parse_str($parts['query'], $query);
     $code = $query['code'];
     $I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
     $I->sendPOST('oauth/access_token', ['grant_type' => 'authorization_code', 'client_id' => $client->id, 'client_secret' => $client->secret, 'redirect_uri' => $endpoint->redirect_uri, 'code' => $code]);
     $I->seeResponseCodeIs(200);
     $I->seeResponseIsJson();
     $I->seeResponseMatchesJsonType(['access_token' => 'string']);
 }
Beispiel #15
0
 public function rememberDesiredUrl()
 {
     $desiredUrl = \Request::fullUrl();
     \Session::flash('url.intended', $desiredUrl);
 }
Beispiel #16
0
 /**
  * Build current url string, without return param.
  *
  * @return string
  */
 function current_url()
 {
     if (!Request::has('return')) {
         return Request::fullUrl();
     }
     return sprintf('%s?%s', Request::url(), http_build_query(Request::except('return')));
 }
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function () {
    if (Auth::check()) {
        return Redirect::to('/');
    }
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function () {
    if (Session::token() !== Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException();
    }
});
Route::filter('wechat-login', function () {
    if (!Session::has('openid')) {
        Session::put('wechat-login-before-url', Request::fullUrl());
        return Redirect::route('wechat.login', ['openid' => Input::get('openid')]);
    }
});
Beispiel #18
0
    foreach ($menulinks as $link) {
        $attributes = $link;
        unset($attributes['title']);
        unset($attributes['href']);
        $active = Request::is($link['href']) ? 'class="active"' : '';
        $html .= '<li ' . $active . '>' . HTML::link($link['href'], $link['title'], $attributes, $secure = null);
    }
    $html .= '</ul>';
    return $html;
});
HTML::macro('page_header', function ($header, $subtitle = false) {
    return View::make('macros/html_page_header', array('header' => $header, 'subtitle' => $subtitle));
});
HTML::macro('icon', function ($icon) {
    return "<span class=\"glyphicon glyphicon-{$icon}\"></span>";
});
HTML::macro('order_by', function ($field, $title) {
    $url = new \Purl\Url(Request::fullUrl());
    $url->query->set('orderBy', $field);
    $dir = 'asc';
    if (Input::get('orderBy') == $field) {
        if (Input::get('orderDir', 'asc') == 'asc') {
            $dir = 'desc';
        }
    }
    $url->query->set('orderDir', $dir);
    return View::make('macros/html_order_by', array('field' => $field, 'title' => $title, 'url' => $url));
});
HTML::macro('pr', function ($var) {
    return View::make('macros/html_pr', array('var' => $var));
});
 /**
  * Pagination
  * Creates the pagination links:
  * 
  * $page = the current page number
  * $total = total number of listings returned
  * $perPage = number of listings to show per page
  * 
  * @param  array $pages
  * @return string Html to create pagination links
  */
 public function paginationLinks($pages)
 {
     // if the pages is empty, doesn't exist, etc.
     if (!$pages) {
         return '';
     }
     // extract array vars
     extract($pages);
     // if we didn't get a base url
     if (!isset($base_url)) {
         $base_url = \Request::fullUrl();
     }
     // remove any current page parameter from query string
     $base_url = $this->removeUrlQueryParam($base_url, 'p');
     // set the concatenator
     $concatenator = !isset($_SERVER['QUERY_STRING']) ? '?' : '&';
     // set next and previous page numbers
     $nextPageNumber = $page + 1;
     $previousPageNumber = $page - 1 > 0 ? $page - 1 : 0;
     // calculate total pages
     $total_pages = ceil($total / $perPage);
     // set the previous page link and empty link
     $previousLabel = 'Previous Page';
     $previousPageLink = '<a href="' . $base_url . $concatenator . 'p=' . $previousPageNumber . '">' . $previousLabel . '</a>';
     // set the next page link and empty link
     $nextLabel = "Next Page";
     $nextPageLink = '<a href="' . $base_url . $concatenator . 'p=' . $nextPageNumber . '">' . $nextLabel . '</a>';
     // set the links
     $nextPage = $page < $total_pages ? $nextPageLink : $nextLabel;
     $previousPage = $page > 1 ? $previousPageLink : $previousLabel;
     return $total . ' Total Listings &nbsp; &nbsp; Page ' . $page . ' of ' . $total_pages . ' &nbsp; &nbsp; ' . $previousPage . ' &nbsp; &nbsp; ' . $nextPage;
 }
Beispiel #20
0
<?php

Html::macro('is_active', function ($route) {
    if (Request::is($route . '/*') or Request::is($route)) {
        return "active";
    }
});
Html::macro('is_active_lesson', function ($route) {
    if (Request::fullUrl() == $route) {
        return "active";
    }
});
 public function logRequestToGa()
 {
     //api key
     $clientId = Input::get('api_key');
     //ga
     $gamp = \GAMP::setClientId($clientId);
     $fullUrl = \Request::fullUrl();
     $root = \Request::root();
     $url = str_replace($root, '', $fullUrl);
     $gamp->setDocumentPath($url);
     $gamp->sendPageview();
 }
 /**
  * Build payload array based on given Exception object.
  *
  * @param \Exception $e
  * @return array
  */
 protected function buildPayload(\Exception $e)
 {
     return ['username' => auth()->check() ? auth()->user()->email : 'Unknown', 'route' => \Route::currentRouteName(), 'localtime' => \Carbon\Carbon::now('Asia/Seoul')->toDateTimeString(), 'exception' => ['class' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'trace' => $e->getTraceAsString(), 'ip' => \Request::ip(), 'method' => \Request::method(), 'url' => \Request::fullUrl(), 'content' => \Request::instance()->getContent() ?: json_encode(\Request::all()), 'headers' => \Request::header()]];
 }
Beispiel #23
0
function handleHttpError($httpStatusCode, $options = [])
{
    switch ($httpStatusCode) {
        case 400:
            $httpStatusName = 'Bad request';
            $httpDescription = 'The server cannot or will not process the request due to a client error.';
            $level = 'notice';
            break;
        case 401:
            $httpStatusName = 'Unauthorized';
            $httpDescription = 'The request has not been applied because it lacks valid authentication credentials for the target resource.';
            $level = 'notice';
            break;
        case 403:
            $httpStatusName = 'Forbidden';
            $httpDescription = 'The server understood the request but refuses to authorize it.';
            $level = 'notice';
            break;
        case 404:
            $httpStatusName = 'Not found';
            $httpDescription = 'The server did not find a current representation for the target resource.';
            $level = 'notice';
            break;
        case 405:
            $httpStatusName = 'Method not allowed';
            $httpDescription = 'The method received in the request is known by the server but not supported by the target resource.';
            $level = 'notice';
            break;
        case 422:
            $httpStatusName = 'Unprocessable entity';
            $httpDescription = 'The request was well-formed but was unable to be followed due to semantic errors.';
            $level = 'notice';
            break;
        case 500:
            $httpStatusName = 'Internal Server Error';
            $httpDescription = 'The server encountered an unexpected condition which prevented it from fulfilling the request.';
            $level = 'error';
            break;
        default:
            $httpStatusName = $httpStatusCode;
            $httpDescription = $httpStatusCode;
            $level = 'error';
    }
    $description = isset($options['description']) ? $options['description'] : $httpDescription;
    if (!isset($options['log']) or $options['log'] == true) {
        Log::$level($httpStatusCode . ' ' . $httpStatusName . ': ' . Request::fullUrl(), ['description' => $description, 'url' => Request::fullUrl(), 'headers' => Request::header(), 'ips' => Request::ips()]);
    }
    if (!isset($options['source']) or $options['source'] == 'gui') {
        return Response::view('errors.default', ['title' => $httpStatusCode . ' ' . $httpStatusName, 'description' => $description], $httpStatusCode);
    } elseif (isset($options['source']) && $options['source'] == 'api') {
        $response = Response::make(['message' => $description], $httpStatusCode);
        if ($httpStatusCode == 401) {
            $response->header('WWW-Authenticate', 'Lanager');
        }
        return $response;
    }
}
 public function display_error($id)
 {
     return Response::json(array("code" => ApiResponse::URL_NOT_EXIST, "data" => array("message" => ApiResponse::getErrorContent(ApiResponse::URL_NOT_EXIST), "url" => Request::fullUrl())));
 }
Beispiel #25
0
| 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) {
    Log::error($exception);
    //return Redirect::to('errorExceptionPage');
});
App::missing(function ($e) {
    $url = Request::fullUrl();
    Log::warning("404 for URL: {$url}");
    return Response::view('errors.notFound', array(), 404);
});
/*
|--------------------------------------------------------------------------
| Maintenance Mode Handler
|--------------------------------------------------------------------------
|
| The "down" Artisan command gives you the ability to put an application
| into maintenance mode. Here, you will define what is displayed back
| to the user if maintenance mode is in effect for the application.
|
*/
App::down(function () {
    return Response::make("Be right back!", 503);
Beispiel #26
0
 /**
  * Constructor
  *
  * @param string $url
  * @param string $method
  */
 public function __construct($url = null, $method = null)
 {
     /*
      * Configure polliwog
      */
     $c = configurator();
     $class = $c->get('form.renderer.class');
     $this->setRenderer(new $class());
     $class = $c->get('form.validator.class');
     $this->setValidator(new $class());
     $class = $c->get('form.filterer.class');
     $this->setFilterer(new $class());
     $this->has_csrfToken = $c->get('form.default.has_csrfToken', true);
     //default configuration
     $this->addAttribute('id', 'form-' . rand());
     // if method "init" exist, we call it.
     if (method_exists($this, 'init')) {
         $this->setMethod($c->get('form.default.method', 'POST'));
         call_user_func_array([$this, 'init'], func_get_args());
     } else {
         $this->setUrl($url);
         $this->setMethod(is_null($method) ? $c->get('form.default.method', 'POST') : $method);
     }
     // default url
     if (empty($this->getUrl())) {
         $this->setUrl(\Request::fullUrl());
     }
 }
    /**
     * Возвращаем пометку об активности текущего пункта меню
     *
     * @param $element
     * @return bool
     */
    private function get_active($element) {
        #return false;

        #Helper::tad($element);

        $is_active = false;

        /**
         * Собственное правило для определения активности пункта меню
         * Проверка текущего URL на соответствие шаблону регулярного выражения
         */
        if (isset($element) && is_array($element)) {

            if (
                (@$element['use_active_regexp'] && @$element['active_regexp'])
            ) {

                #Helper::ta($element);

                if (@$element['use_active_regexp'] && @$element['active_regexp']) {

                    /**
                     * Сделаем замену в регулярке, если у нас обычная страница
                     */
                    if (isset($element['type']) && $element['type'] == 'page') {
                        $page = isset($this->pages[$element['page_id']]) ? $this->pages[$element['page_id']] : NULL;
                        if ($page && is_object($page) && $page->slug) {
                            $element['active_regexp'] = strtr($element['active_regexp'], [
                                '%slug%' => $page->slug, '%url%' => $page->slug,
                            ]);
                        }
                        #var_dump($element['active_regexp']);
                    }

                    try {
                        $element['active_regexp'] = $this->replaces($element['active_regexp']);
                    } catch (Exception $e) {
                        echo 'Error: ', $e->getMessage(), "\n";
                        Helper::tad($element);
                        #die;
                    }

                    /**
                     * Замена конструкций вида %_page_sysname_>url%
                     */
                    preg_match_all('~\%([A-Za-z0-9\-\_]+)\>url\%~is', $element['active_regexp'], $matches);

                    if (isset($matches[1]) && count($matches[1])) {

                        #var_dump($matches);
                        #Helper::ta($this->pages_by_sysname);
                        $pages = new Collection();
                        $page_sysnames = [];
                        ## Все найденные конструкции
                        foreach ($matches[1] as $page_sysname) {
                            if (isset($this->pages_by_sysname[$page_sysname])) {
                                ## Ищем текущую страницу среди страниц текущего меню
                                $pages[$page_sysname] = $this->pages_by_sysname[$page_sysname];
                            } elseif (NULL !== Config::get('pages.preload_pages_limit') && NULL !== ($tmp = Page::by_sysname($page_sysname))) {
                                ## Ищем текущую страницу в кеше страниц
                                $pages[$page_sysname] = $tmp;
                            } else {
                                ## Если страница уж совсем нигде не нашлась - придется ее подгружать из БД. Делать это будем позже одним запросом.
                                $page_sysnames[] = $page_sysname;
                            }
                        }
                        ## Если есть список страниц для их подгрузки из БД - сделаем это!
                        if (count($page_sysnames)) {
                            $temp = Page::whereIn('sysname', $page_sysnames)->where('version_of', NULL)->get();
                            if (count($temp)) {
                                ## Если что-то нашлось - разложим по sysname
                                $pages_by_sysnames = new Collection();
                                foreach ($temp as $tmp) {
                                    if (!$tmp->sysname)
                                        continue;
                                    $pages_by_sysnames[$tmp->sysname] = $tmp;
                                }
                                if (count($pages_by_sysnames)) {
                                    ## Найдем недостающие страницы и добавим их в список
                                    foreach ($page_sysnames as $psn) {
                                        if (isset($pages_by_sysnames[$psn]))
                                            $pages[$psn] = $pages_by_sysnames[$psn];
                                    }
                                }
                            }
                            unset($temp, $tmp);
                        }
                        #Helper::tad($pages_by_sysnames);
                        #Helper::tad($pages);

                        $replaces = [];
                        ## Еще раз пройдемся по списку найденных паттернов и сгенерируем список для замены
                        foreach ($matches[1] as $page_sysname) {
                            if (isset($pages[$page_sysname]) && NULL !== ($page = $pages[$page_sysname])) {
                                $replaces['%' . $page->sysname . '>url%'] = $page->slug;
                            }
                        }
                        #dd($replaces);

                        ## Производим замену паттернов
                        $element['active_regexp'] = strtr($element['active_regexp'], $replaces);
                        ## Если остались ненайденные паттерны - удалим их
                        $element['active_regexp'] = preg_replace('~\%([A-Za-z0-9\-\_]+)\>url\%~is', '', $element['active_regexp']);
                    }

                    #Helper::dd(Request::path());
                    #Helper::dd($element['active_regexp']);
                    #Helper::dd(preg_match($element['active_regexp'], Request::path()));

                    $is_active = @(bool)preg_match($element['active_regexp'], Request::path());
                    #return $is_active;
                }

                if ($is_active)
                    return true;
            }
        }

        /**
         * Возвращаем пометку об активности ссылки, в зависимости от типа элемента меню
         */
        switch(@$element['type']) {

            case 'page':
                #Helper::ta($this->pages);
                #Helper::ta($this->pages[$element['page_id']]);
                $page = isset($this->pages[$element['page_id']]) ? $this->pages[$element['page_id']] : NULL;
                #Helper::ta($page);
                if (!$page)
                    return NULL;

                #$return = $this->isRoute('page', ['url' => $page->slug]);
                #$return = $this->isRoute('page', $page->slug);

                $is_active = $this->isRoute($page->start_page ? 'mainpage' : 'page', ['url' => $page->slug]);
                #Helper::tad($is_active);

                if ($is_active)
                    return $is_active;

                ## Если активна опция определения активности по дочерним страницам (из структуры страниц)
                if (@$element['use_active_hierarchy']) {

                    #Helper::ta($element);
                    #Helper::ta($page);

                    ## Получим структуру страниц из Storage
                    $current_hierarchy = Storage::where('module', 'pages')->where('name', 'hierarchy')->pluck('value');
                    $elements = json_decode($current_hierarchy, false);
                    #Helper::d($elements);
                    #Helper::d($elements[$page->id]);

                    ## Сформируем id_left_right
                    $id_left_right = [];
                    if (count($elements)) {

                        foreach($elements as $element_id => $element) {
                            #dd($element);
                            $id_left_right[$element_id] = array();
                            $id_left_right[$element_id]['left'] = $element->left;
                            $id_left_right[$element_id]['right'] = $element->right;
                        }
                    }
                    #Helper::tad($id_left_right);

                    ## Получим IDs страниц, для которых текущая страница (пункт меню) является родителем
                    $pages_ids = (new NestedSetModel())->get_children_ids_by_id_from_id_left_right($id_left_right, $page->id);
                    #Helper::ta('PAGES IDS:');
                    #Helper::ta($pages_ids);

                    ## Если у текущей страницы (пункта меню) в иерархии есть потомки
                    if (isset($pages_ids) && is_array($pages_ids) && count($pages_ids)) {

                        ## Получение страниц-потомков по их IDs
                        ## Как будем искать страницы - в кеше или в БД?
                        if (Config::get('pages.not_cached')) {

                            #Helper::tad('PAGES CACHE DISABLED! MenuConstructor:709');
                            ## Кеширование отключено (или не найдено ни одной страницы) - ищем в БД
                            $pages = (new Page())
                                ->where('publication', 1)
                                ->where('version_of', NULL)
                                ->whereIn('id', $pages_ids)
                                ->get()
                            ;

                        } else {

                            ## Если страницы есть в кеше
                            if (count(Page::all_by_id())) {

                                ## Ищем все нужные страницы в кеше по их IDs
                                foreach ($pages_ids as $page_id) {

                                    $pages[] = Page::by_id($page_id);
                                }
                            }
                        }

                        ## Если получены объекты страниц
                        if (isset($pages) && count($pages)) {

                            #Helper::dd($pages);

                            ## Перебираем их
                            foreach ($pages as $page) {

                                if (!is_object($page)) {
                                    #dd($page);
                                    continue;
                                }

                                ## Проверка на активность
                                $is_active = $this->isRoute($page->start_page ? 'mainpage' : 'page', ['url' => $page->slug]);
                                if ($is_active)
                                    return true;
                            }
                        }

                    }

                    $is_active = false;
                }

                return $is_active;

                break;

            case 'link':
                return (bool)preg_match('~' . $element['url'] . '$~s', Request::fullUrl());
                break;

            case 'route':
                $route_params = array();
                if ('' != ($element['route_params'] = trim($element['route_params']))) {
                    $temp = explode("\n", $element['route_params']);
                    if (@count($temp)) {
                        foreach ($temp as $tmp) {
                            $tmp = trim($tmp);
                            if (!$tmp) {
                                continue;
                            }
                            if (strpos($tmp, '=')) {
                                $tmp_params = explode('=', $tmp, 2);
                                $route_params[trim($tmp_params[0])] = trim($tmp_params[1]);
                            } else {
                                $route_params[] = $tmp;
                            }
                        }
                    }
                }
                return $this->isRoute($element['route_name'], $route_params);
                break;

            case 'function':
                #Helper::dd($element);
                $function = Config::get('menu.functions.' . $element['function_name']);
                if (isset($function) && is_callable($function)) {
                    $result = $function();
                    #return $result['url'];


                    /**
                     * Одиночная ссылка
                     */
                    #return (bool)preg_match('~' . $result['url'] . '$~s', Request::fullUrl());
                    if (isset($result['url']))
                        $result = array($result);

                    /**
                     * Перебираем весь массив ссылок
                     */
                    foreach ($result as $res)
                        if (isset($res['url']) && (bool)preg_match('~' . $res['url'] . '$~s', Request::fullUrl()) == true)
                            return true;

                }
                return false;
                break;

            default:
                return false;
                break;
        }
    }
Beispiel #28
0
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function () {
    if (Session::token() != Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException();
    }
});
Route::filter('checkIsSetup', function () {
    if (!Setting::isSetup()) {
        return Redirect::to('setup');
    }
});
Route::filter('checkIsAdmin', function () {
    $admin = Sentry::findGroupByName('Administrator');
    if (!Sentry::getUser()->inGroup($admin)) {
        return Redirect::back();
    }
});
Route::filter('checkLoggedIn', function () {
    if (!Sentry::check()) {
        Session::put('originalRequest', Request::fullUrl());
        return Redirect::to('dashboard/login');
    }
});
Route::filter('redirectIfLoggedIn', function () {
    if (Sentry::check()) {
        return Redirect::to('dashboard');
    }
});
Beispiel #29
0
 private function loadCurrentUrl()
 {
     $this->url = \Request::fullUrl();
 }
Beispiel #30
0
 /**
  * Perform the SPECTQL query.
  */
 private function performQuery($uri)
 {
     SPECTQLController::$TMP_DIR = __DIR__ . "/../tmp/";
     // Fetch the original uri, which is a hassle since our spectql format allows for a ? - character
     // identify the start of a filter, the Request class sees this is the start of query string parameters
     // and fails to parse them as they only contain keys, but never values ( our spectql filter syntax is nowhere near
     // the same as a query string parameter sequence). Therefore, we need to build our spectql uri manually.
     // Furthermore, after the ? - character dots are replaced with underscores by PHP itself. http://ca.php.net/variables.external
     // This is another reason why we build the query string to be passed to the parser ourselves.
     // The Request class also seems to have an issue with evaluating a semi-colon in the query string
     // It puts the semi-colon and what follows next to the first query string parameter, IF there are multiple
     // query string parameters (lon>5&lon<10), since this isn't really supported by PHP, Request from Symfony tries
     // apparently a best effort at fixing this.
     $filter = "";
     $original_uri = \Request::fullUrl();
     $root = \Request::root();
     if (preg_match("%{$root}\\/spectql\\/(.*)%", $original_uri, $matches)) {
         $query_uri = urldecode($matches[1]);
     }
     $format = "";
     // Fetch the format of the query
     if (preg_match("/.*(:[a-zA-Z]+)&?(.*?)/", $query_uri, $matches)) {
         $format = ltrim($matches[1], ":");
     }
     // Remove the format and any following query string parameters
     if (!empty($format)) {
         $query_uri = preg_replace("/:" . $format . "\\??.*/", '', $query_uri);
     }
     // Initialize the parser with our query string
     $parser = new SPECTQLParser($query_uri);
     $context = array();
     // array of context variables
     $universalquery = $parser->interpret($context);
     // Display the query tree, uncomment in case of debugging
     /*$treePrinter = new TreePrinter();
       $tree = $treePrinter->treeToString($universalquery);
       echo "<pre>";
       echo $tree;
       echo "</pre>";*/
     $interpreter = new UniversalInterpreter(new UniversalFilterTableManager());
     $result = $interpreter->interpret($universalquery);
     // Convert the resulting table object to a php object
     $converter = new TableToPhpObjectConverter();
     $object = $converter->getPhpObjectForTable($result);
     // Perform a clean-up, every property that is empty can be thrown away
     foreach ($object as $index => $property) {
         if ($this->isArrayNull($property)) {
             unset($object[$index]);
         }
     }
     $rootname = "spectqlquery";
     // Get the required properties for the Data object
     $definition_uri = preg_match('/(.*?)\\{.*/', $uri, $matches);
     // If no selection statement is given, abort the processing of the query
     if (empty($matches)) {
         \App::abort(400, "Please provide a select statement with the SPECTQL query (e.g. { column_1, column_2 }).");
     }
     $definition_uri = $matches[1];
     $definition_repo = \App::make('Tdt\\Core\\Repositories\\Interfaces\\DefinitionRepositoryInterface');
     $definition = $definition_repo->getByIdentifier($definition_uri);
     if (!empty($definition)) {
         $source_definition = $definition_repo->getDefinitionSource($definition['source_id'], $definition['source_type']);
     }
     $rest_parameters = str_replace($definition['collection_uri'] . '/' . $definition['resource_name'], '', $uri);
     $rest_parameters = ltrim($rest_parameters, '/');
     $rest_parameters = explode('/', $rest_parameters);
     if (empty($rest_parameters[0]) && !is_numeric($rest_parameters[0])) {
         $rest_parameters = array();
     }
     $data = new Data();
     $data->data = $object;
     // Specify it's a SPECTQL result
     $data->is_spectql = true;
     $data->rest_parameters = $rest_parameters;
     // Add definition to the object
     $data->definition = $definition;
     // Add source definition to the object
     $data->source_definition = $source_definition;
     // Return the formatted response with content negotiation
     return ContentNegotiator::getResponse($data, $format);
 }