getBaseUrl() public method

The base URL never ends with a /. This is similar to getBasePath(), except that it also includes the script filename (e.g. index.php) if one exists.
public getBaseUrl ( ) : string
return string The raw URL (i.e. not urldecoded)
 /**
  * @param CanonicalUrlEvent $event
  */
 public function generateUrlCanonical(CanonicalUrlEvent $event)
 {
     if ($event->getUrl() !== null) {
         return;
     }
     $parseUrlByCurrentLocale = $this->getParsedUrlByCurrentLocale();
     if (empty($parseUrlByCurrentLocale['host'])) {
         return;
     }
     // Be sure to use the proper domain name
     $canonicalUrl = $parseUrlByCurrentLocale['scheme'] . '://' . $parseUrlByCurrentLocale['host'];
     // preserving a potential subdirectory, e.g. http://somehost.com/mydir/index.php/...
     $canonicalUrl .= $this->request->getBaseUrl();
     // Remove script name from path, e.g. http://somehost.com/index.php/...
     $canonicalUrl = preg_replace("!/index(_dev)?\\.php!", '', $canonicalUrl);
     $path = $this->request->getPathInfo();
     if (!empty($path) && $path != "/") {
         $canonicalUrl .= $path;
         $canonicalUrl = rtrim($canonicalUrl, '/');
     } else {
         $queryString = $this->request->getQueryString();
         if (!empty($queryString)) {
             $canonicalUrl .= '/?' . $queryString;
         }
     }
     $event->setUrl($canonicalUrl);
 }
 /**
  * Format a collection of documentation data.
  *
  * @param  array        $collection
  * @param  null         $resource
  * @internal param $array [ApiDoc] $collection
  * @return string|array
  */
 public function format(array $collection, $resource = null)
 {
     $result = $this->formatter->format($collection, $resource);
     if ($resource !== null) {
         $result['basePath'] = $this->request->getBaseUrl() . $result['basePath'];
     }
     return $result;
 }
Example #3
0
 /**
  * Generates JavaScript code that starts client side application.
  *
  * @param Request $request Incoming request.
  * @param array $operator Current operator.
  * @return string JavaScript code that starts "users" client side
  *   application.
  */
 protected function startJsApplication(Request $request, $operator)
 {
     // Load dialogs style options
     $chat_style = new ChatStyle(ChatStyle::getCurrentStyle());
     $chat_style_config = $style_config = $chat_style->getConfigurations();
     // Load page style options
     $page_style_config = $style_config = $this->getStyle()->getConfigurations();
     return sprintf('jQuery(document).ready(function() {Mibew.Application.start(%s);});', json_encode(array('server' => array('url' => $this->generateUrl('users_update'), 'requestsFrequency' => Settings::get('updatefrequency_operator')), 'agent' => array('id' => $operator['operatorid']), 'page' => array('mibewBasePath' => $request->getBasePath(), 'mibewBaseUrl' => $request->getBaseUrl(), 'showOnlineOperators' => Settings::get('showonlineoperators') == '1', 'showVisitors' => Settings::get('enabletracking') == '1', 'showPopup' => Settings::get('enablepopupnotification') == '1', 'threadTag' => $page_style_config['users']['thread_tag'], 'visitorTag' => $page_style_config['users']['visitor_tag'], 'agentLink' => $request->getBaseUrl() . '/operator/chat', 'geoLink' => Settings::get('geolink'), 'trackedLink' => $request->getBaseUrl() . '/operator/history/user-track', 'banLink' => $request->getBaseUrl() . '/operator/ban', 'inviteLink' => $request->getBaseUrl() . '/operator/invite', 'chatWindowParams' => $chat_style_config['chat']['window'], 'geoWindowParams' => Settings::get('geolinkparams'), 'trackedUserWindowParams' => $page_style_config['tracked']['user_window'], 'trackedVisitorWindowParams' => $page_style_config['tracked']['visitor_window'], 'banWindowParams' => $page_style_config['ban']['window'], 'inviteWindowParams' => $chat_style_config['chat']['window']))));
 }
 public function getRedirectUrl()
 {
     $redirectUrl = $this->map->getUrlTo();
     if (!$this->isAbsoluteUrl($redirectUrl) && ($baseUrl = $this->request->getBaseUrl())) {
         $redirectUrl = $baseUrl . $redirectUrl;
     }
     $redirectUrl = $this->applyReplacements($redirectUrl);
     return $redirectUrl;
 }
 /**
  * @param ItemInterface $item
  *
  * @return bool
  */
 public function matchItem(ItemInterface $item)
 {
     $requestUri = $this->request->getRequestUri();
     $baseUrl = $this->request->getBaseUrl() . '/';
     $uri = $item->getUri();
     if ($uri === $requestUri) {
         return true;
     } else {
         if ($uri !== $baseUrl && substr($requestUri, 0, strlen($uri)) === $uri) {
             return true;
         }
     }
     return null;
 }
Example #6
0
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $pathInfo = rawurldecode($request->getPathInfo());
     foreach ($this->map as $path => $app) {
         if (0 === strpos($pathInfo, $path)) {
             $server = $request->server->all();
             $server['SCRIPT_FILENAME'] = $server['SCRIPT_NAME'] = $server['PHP_SELF'] = $request->getBaseUrl() . $path;
             $attributes = $request->attributes->all();
             $attributes[static::ATTR_PREFIX] = $request->getBaseUrl() . $path;
             $newRequest = $request->duplicate(null, null, $attributes, null, null, $server);
             return $app->handle($newRequest, $type, $catch);
         }
     }
     return $this->app->handle($request, $type, $catch);
 }
Example #7
0
 /**
  * @param FormBuilderInterface $builder
  * @param array                $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
     if (extension_loaded('intl')) {
         $builder->add('locale', 'select2', array('choices' => Intl::getLocaleBundle()->getLocaleNames(), 'constraints' => new Constraints\NotBlank(array('message' => 'Please select a locale')), 'placeholder' => '', 'choices_as_values' => false));
     } else {
         $builder->add('locale', null, array('data' => 'en', 'read_only' => true, 'help' => 'The only currently supported locale is "en". To choose a different locale, please install the \'intl\' extension'));
     }
     $builder->add('currency', 'select2', array('choices' => $currencies, 'constraints' => new Constraints\NotBlank(array('message' => 'Please select a currency')), 'placeholder' => '', 'choices_as_values' => false));
     $builder->add('base_url', null, array('constraints' => new Constraints\NotBlank(array('message' => 'Please set the application base url')), 'data' => $this->request->getSchemeAndHttpHost() . $this->request->getBaseUrl()));
     if (0 === $this->userCount) {
         $builder->add('username', null, array('constraints' => new Constraints\NotBlank(array('message' => 'Please enter a username'))));
         $builder->add('email_address', 'email', array('constraints' => array(new Constraints\NotBlank(array('message' => 'Please enter a email')), new Constraints\Email())));
         $builder->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'The password fields must match.', 'options' => array('attr' => array('class' => 'password-field')), 'required' => true, 'first_options' => array('label' => 'Password'), 'second_options' => array('label' => 'Repeat Password'), 'constraints' => array(new Constraints\NotBlank(array('message' => 'You must enter a secure password')), new Constraints\Length(array('min' => 6)))));
     }
 }
 public function indexAction(Request $request, $slug)
 {
     //echo '<pre>';print_r($slug);die;
     $page = new Page();
     $page->setUrl($request->getRequestUri());
     $page->setTitle('Homepage');
     $page->setSlug($slug);
     $site = new Site();
     $site->setBaseurl($request->getBaseUrl());
     $github = new \stdClass();
     $github->user = '******';
     $github->repo = 'bootstrap-bundle';
     $site->setGithub($github);
     $data = $site->getData();
     $data['showcase'] = Yaml::parse(__DIR__ . '/../Resources/data/showcase.yml');
     $data['translations'] = Yaml::parse(__DIR__ . '/../Resources/data/translations.yml');
     $site->setData($data);
     $site->setDownload(array('dist' => 'https://github.com/twbs/bootstrap/releases/download/v3.2.0/bootstrap-3.2.0-dist.zip', 'source' => 'https://github.com/twbs/bootstrap/archive/v3.2.0.zip', 'sass' => 'https://github.com/twbs/bootstrap-sass/archive/v3.2.0.tar.gz'));
     $site->setCdn(array('css' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css', 'css_theme' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css', 'js' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'));
     $site->setTime(new \DateTime());
     /*$content = $this->render(
           'BootstrapBundle:pages:' . $slug . '.html.twig',
           array(
               'site' => $site
           )
       )->getContent();*/
     if ($slug == 'index') {
         $file = 'home';
     } else {
         $file = 'default';
     }
     return $this->render('BootstrapBundle:layouts:' . $file . '.html.twig', array('page' => $page, 'site' => $site, 'slug' => $slug));
 }
 /**
  * Attempt to fetch the gallery's XML via a sub-request to another page.
  *
  * This assumes that the gallery XML has already been embedded within a normal
  * HTML page, at the given path, within a <script> block.
  *
  * @param string $path
  *   The Drupal path to use for the sub-request.
  * @param string $id
  *   The id to search for within the sub-request content that will contain
  *   the embedded XML.
  * @return string
  *   The embedded XML if found or an empty string.
  */
 protected function fetchXmlSubRequest($path, $id)
 {
     $xml = '';
     // We want to pass-through all details of the master request, but for some
     // reason the sub-request may fail with a 406 if some server params unique
     // to an XMLHttpRequest are used. So we reset those to generic values by
     // just removing them from the request details passed-through.
     $server = $this->request->server;
     $server->remove('HTTP_ACCEPT');
     $server->remove('HTTP_X_REQUESTED_WITH');
     $subRequest = Request::create($this->request->getBaseUrl() . '/' . $path, 'GET', $this->request->query->all(), $this->request->cookies->all(), $this->request->files->all(), $server->all());
     // @todo: See if this session check is needed.
     $session = $this->request->getSession();
     if ($session) {
         $subRequest->setSession($session);
     }
     $subResponse = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     // Search for the XML within the sub-request markup. We could parse the
     // DOM for this with DOMDocument, but a regex lookup is more lightweight.
     $matches = array();
     preg_match('/<script[^>]*id=\\"' . $id . '\\"[^>]*>(.*)<\\/script>/simU', $subResponse->getContent(), $matches);
     if (!empty($matches[1]) && strpos($matches[1], '<?xml') === 0) {
         $xml = $matches[1];
         // Set the cache tags directly from the sub-request response.
         if ($subResponse instanceof CacheableResponseInterface) {
             $response_cacheability = $subResponse->getCacheableMetadata();
             $this->cacheTags = Cache::mergeTags($this->cacheTags, $response_cacheability->getCacheTags());
         }
     }
     return $xml;
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     if (strpos($request->getRequestUri(), 'installer') !== false || !$this->isInstalled()) {
         define('MAUTIC_INSTALLER', 1);
     }
     if (defined('MAUTIC_INSTALLER')) {
         $uri = $request->getRequestUri();
         if (strpos($uri, 'installer') === false) {
             $base = $request->getBaseUrl();
             //check to see if the .htaccess file exists or if not running under apache
             if (strpos(strtolower($_SERVER['SERVER_SOFTWARE']), 'apache') === false || !file_exists(__DIR__ . '../.htaccess') && strpos($base, 'index') === false) {
                 $base .= '/index.php';
             }
             return new RedirectResponse($base . '/installer');
         }
     }
     if (false === $this->booted) {
         $this->boot();
     }
     // Check for an an active db connection and die with error if unable to connect
     if (!defined('MAUTIC_INSTALLER')) {
         $db = $this->getContainer()->get('database_connection');
         try {
             $db->connect();
         } catch (\Exception $e) {
             error_log($e);
             throw new \Mautic\CoreBundle\Exception\DatabaseConnectionException($this->getContainer()->get('translator')->trans('mautic.core.db.connection.error', ['%code%' => $e->getCode()]));
         }
     }
     return parent::handle($request, $type, $catch);
 }
 public function checkShorturlAction(Application $app, Request $request)
 {
     $enabledExtentions = $app['extensions']->getEnabled();
     $config = $enabledExtentions['shorturl']->config;
     $shorturl = $request->query->get('shorturl');
     $recordId = $request->query->get('recordId');
     $response = new \stdClass();
     $response->status = 'ok';
     $url = $app['paths']['hosturl'] . $request->getBaseUrl() . '/' . ($config['prefix'] ? $config['prefix'] . '/' : '') . $shorturl;
     $response->msg = 'This record will be accessible via <a href="' . $url . '" target="_blank">' . $url . '</a>.';
     // Check length & chars
     if (!preg_match('/[a-zA-Z0-9\\-_.]{2,' . $config['maxlength'] . '}$/', $shorturl)) {
         $response->status = 'error';
         $response->msg = 'Shorturl must at least have two characters and can only contain a-z, A-Z, 0-9, ".", "-" and "_".';
     }
     // check if unique
     $contentTypes = $app['config']->get('contenttypes');
     foreach ($contentTypes as $name => $contentType) {
         foreach ($contentType['fields'] as $key => $field) {
             if ($field['type'] === 'shorturl') {
                 $contentTypeContent = $app['storage']->getContent($name, array());
                 foreach ($contentTypeContent as $content) {
                     if ($content['id'] !== $recordId && !empty($content[$key]) && $content[$key] == $shorturl) {
                         $response->status = 'error';
                         $response->msg = 'Shorturl already exists.';
                         break;
                     }
                 }
             }
         }
     }
     return $app->json($response);
 }
Example #12
0
 /**
  * Checks that a given path matches the Request.
  *
  * @param Request $request A Request instance
  * @param string  $path    A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  *
  * @return Boolean true if the path is the same as the one from the Request, false otherwise
  */
 public function checkRequestPath(Request $request, $path)
 {
     if ('/' !== $path[0]) {
         $path = preg_replace('#' . preg_quote($request->getBaseUrl(), '#') . '#', '', $this->generateUrl($path));
     }
     return $path === $request->getPathInfo();
 }
Example #13
0
 public function __construct($routes, Request $request, EventDispatcher $dispatcher, ControllerResolver $resolver)
 {
     $this->deflRes = new NodeResponse();
     $this->context = new RequestContext($request->getBaseUrl(), $request->getMethod(), $request->getHost(), $request->getScheme(), $request->getPort(), $request->getPort());
     $this->matcher = new UrlMatcher($routes, $this->context);
     parent::__construct($dispatcher, $resolver);
 }
 protected function initializeRequestAttributes(Request $request, $master)
 {
     if ($master) {
         // set the context even if the parsing does not need to be done
         // to have correct link generation
         $this->router->setContext(array('base_url' => $request->getBaseUrl(), 'method' => $request->getMethod(), 'host' => $request->getHost(), 'port' => $request->getPort(), 'is_secure' => $request->isSecure()));
     }
     if ($request->attributes->has('_controller')) {
         // routing is already done
         return;
     }
     // add attributes based on the path info (routing)
     try {
         $parameters = $this->router->match($request->getPathInfo());
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], json_encode($parameters)));
         }
         $request->attributes->add($parameters);
         if ($locale = $request->attributes->get('_locale')) {
             $request->getSession()->setLocale($locale);
         }
     } catch (NotFoundException $e) {
         $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
         if (null !== $this->logger) {
             $this->logger->err($message);
         }
         throw new NotFoundHttpException($message, $e);
     } catch (MethodNotAllowedException $e) {
         $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods())));
         if (null !== $this->logger) {
             $this->logger->err($message);
         }
         throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
     }
 }
Example #15
0
 /**
  * @param Request $request
  * @return mixed
  */
 private function getRefererParams(Request $request)
 {
     $referer = $request->headers->get('referer');
     $baseUrl = $request->getBaseUrl();
     $lastPath = substr($referer, strpos($referer, $baseUrl) + strlen($baseUrl));
     return $this->get('router')->getMatcher()->match($lastPath);
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function indexAction(Request $request)
 {
     if (null === ($node = $this->get('cms.node')->get($this->node_id))) {
         return new Response('Node doen\'t exist.');
     }
     if ($node->isDeleted() or $node->isNotActive()) {
         return new Response('Node is not active.');
     }
     $cacheKey = md5('smart_module.widget.yaml_params' . $this->node_id . $this->controller . $this->params);
     if (false === ($path = $this->getCacheService()->get($cacheKey))) {
         $path = Yaml::parse($this->params);
         $path['_controller'] = $this->node_id . ':' . $this->controller;
         $path['_node'] = $node;
         $path['_route_params']['slug'] = substr(str_replace($request->getBaseUrl(), '', $this->get('cms.router')->getPath($node)), 1);
         $this->getCacheService()->set($cacheKey, $path, ['smart_module.widget', 'folder', 'node_' . $this->node_id, 'node']);
     }
     if ($this->get('cms.module')->has($path['_node']->getModule()) and !empty($this->controller)) {
         $originalTpl = $node->getTemplate();
         $node->setTemplate($this->tamplate_theme);
         $response = $this->forward($this->node_id . ':' . $this->controller, $path);
         $node->setTemplate($originalTpl);
     } else {
         return new Response('Module "' . $path['_node']->getModule() . '" is unavailable.');
     }
     if ($response->isServerError()) {
         //return new Response($response->getStatusCode() . ' ' . Response::$statusTexts[$response->getStatusCode()]);
         return $response;
         // @todo FS#402
     }
     if (strlen(trim($response->getContent())) > 0) {
         $response->setContent($this->open_tag . "\n" . $response->getContent() . "\n" . $this->close_tag);
     }
     return $response;
 }
Example #17
0
 /**
  * Provide the install.html file.
  *
  * @param Request $request The request to process.
  *
  * @return Response
  */
 public function installAction(Request $request)
 {
     // Special case, already setup. Redirect to index then.
     if ($this->isInstalled()) {
         return new RedirectResponse($request->getUri() . 'index.html');
     }
     return new Response(str_replace('var TENSIDEApi=window.location.href.split(\'#\')[0];', 'var TENSIDEApi=\'' . $request->getSchemeAndHttpHost() . $request->getBaseUrl() . '/\';', file_get_contents($this->getAssetsDir() . '/install.html')), 200, ['Content-Type' => 'text/html; charset=UTF-8']);
 }
Example #18
0
 /**
  * @param Request $request
  * @return string
  */
 public static function completeTrailingSlash(Request $request)
 {
     $queryString = $request->getQueryString();
     if ($queryString !== null) {
         $queryString = '?' . $queryString;
     }
     return $request->getBaseUrl() . $request->getPathInfo() . '/' . $queryString;
 }
Example #19
0
 /**
  * @param Request $request
  * @param string $code
  *
  * @return Response
  */
 public function switchAction(Request $request, $code)
 {
     if (!in_array($code, $this->localeProvider->getAvailableLocalesCodes())) {
         throw new HttpException(Response::HTTP_NOT_ACCEPTABLE, sprintf('The locale code "%s" is invalid.', $code));
     }
     $this->localeChangeHandler->handle($code);
     return new RedirectResponse($request->headers->get('referer', $request->getBaseUrl()));
 }
 /**
  * This action applies a given filter to a given image, saves the image and
  * outputs it to the browser at the same time
  *
  * @param string $path
  * @param string $filter
  *
  * @return Response
  */
 public function filter($path, $filter)
 {
     $path = '/' . ltrim($path, '/');
     //TODO: find out why I need double urldecode to get a valid path
     $browserPath = urldecode(urldecode($this->cachePathResolver->getBrowserPath($path, $filter)));
     $basePath = $this->request->getBaseUrl();
     if (!empty($basePath) && 0 === strpos($browserPath, $basePath)) {
         $browserPath = substr($browserPath, strlen($basePath));
     }
     // if cache path cannot be determined, return 404
     if (null === $browserPath) {
         throw new NotFoundHttpException('Image doesn\'t exist');
     }
     $realPath = $this->webRoot . $browserPath;
     $sourcePath = $this->sourceRoot . $path;
     if (!file_exists($sourcePath)) {
         throw new NotFoundHttpException(sprintf('Source image not found in "%s"', $sourcePath));
     }
     $ext = pathinfo($sourcePath, PATHINFO_EXTENSION);
     if ($ext == 'gif' && $this->isAnimatedGif(fopen($sourcePath, 'r'))) {
         ob_start();
         echo stream_get_contents(fopen($sourcePath, 'r'));
         return new Response(ob_get_clean(), 201, array('content-type' => 'image/gif'));
     }
     // if the file has already been cached, we're probably not rewriting
     // correctly, hence make a 301 to proper location, so browser remembers
     if (file_exists($realPath)) {
         return new Response('', 301, array('location' => $this->request->getBasePath() . $browserPath));
     }
     $dir = pathinfo($realPath, PATHINFO_DIRNAME);
     if (!is_dir($dir)) {
         if (!$this->filesystem->mkdir($dir)) {
             throw new \RuntimeException(sprintf('Could not create directory %s', $dir));
         }
     }
     ob_start();
     try {
         // TODO: get rid of hard-coded quality and format
         $this->filterManager->get($filter)->apply($this->imagine->open($sourcePath))->save($realPath, array('quality' => $this->filterManager->getOption($filter, "quality", 100)))->show($this->filterManager->getOption($filter, "format", "png"));
         // TODO: add more media headers
         return new Response(ob_get_clean(), 201, array('content-type' => 'image/' . $this->filterManager->getOption($filter, "format", "png")));
     } catch (\Exception $e) {
         ob_end_clean();
         throw $e;
     }
 }
 /**
  * {@inheritDoc}
  */
 public function resolve(Request $request, $path, $filter)
 {
     $browserPath = $this->decodeBrowserPath($this->getBrowserPath($path, $filter));
     $this->basePath = $request->getBaseUrl();
     $targetPath = $this->getFilePath($path, $filter);
     // if the file has already been cached, we're probably not rewriting
     // correctly, hence make a 301 to proper location, so browser remembers
     if (file_exists($targetPath)) {
         // Strip the base URL of this request from the browserpath to not interfere with the base path.
         $baseUrl = $request->getBaseUrl();
         if ($baseUrl && 0 === strpos($browserPath, $baseUrl)) {
             $browserPath = substr($browserPath, strlen($baseUrl));
         }
         return new RedirectResponse($request->getBasePath() . $browserPath);
     }
     return $targetPath;
 }
 /**
  * Outputs a link to the database updates URL.
  */
 public function databaseUpdatesMenuItem(Request $request)
 {
     // @todo Simplify with https://www.drupal.org/node/2548095
     $base_url = str_replace('/update.php', '', $request->getBaseUrl());
     $url = (new Url('system.db_update'))->setOption('base_url', $base_url);
     $build['main'] = array('#type' => 'link', '#title' => $this->t('Run database updates'), '#url' => $url, '#access' => $url->access($this->currentUser()));
     return $build;
 }
 protected function init(Request $request)
 {
     $this->request = $request;
     $this->baseUrl = 'http://' . $this->request->getHost() . $this->request->getBaseUrl() . $this->request->getPathInfo();
     $this->manager = $this->get('doctrine_mongodb')->getManager();
     $this->repository = $this->manager->getRepository('AppBundle:UserEvent');
     $this->queryBuilder = $this->repository->createQueryBuilder();
     $this->dbCount = $this->queryBuilder->getQuery()->execute()->count();
 }
Example #24
0
 public function fromRequest(Request $request)
 {
     $this->setBaseUrl($request->getBaseUrl());
     $this->setMethod($request->getMethod());
     $this->setHost($request->getHost());
     $this->setScheme($request->getScheme());
     $this->setHttpPort($request->isSecure() ? $this->httpPort : $request->getPort());
     $this->setHttpsPort($request->isSecure() ? $request->getPort() : $this->httpsPort);
 }
 /**
  * This action applies a given filter to a given image, saves the image and
  * outputs it to the browser at the same time
  *
  * @param string $path
  * @param string $filter
  *
  * @return Response
  *
  * @throws Exception
  */
 public function filterAction($path, $filter)
 {
     $baseUrl = $this->request->getBaseUrl();
     try {
         try {
             $cachedPath = $this->cacheManager->cacheImage($baseUrl, $path, $filter);
         } catch (RuntimeException $e) {
             if (!isset($this->notFoundImages[$filter])) {
                 throw $e;
             }
             $path = $this->notFoundImages[$filter];
             $cachedPath = $this->cacheManager->cacheImage($baseUrl, $path, $filter);
         }
     } catch (RouteNotFoundException $e) {
         throw new NotFoundHttpException('Filter doesn\'t exist.');
     }
     // if cache path cannot be determined, return 404
     if (null === $cachedPath) {
         throw new NotFoundHttpException('Image doesn\'t exist');
     }
     try {
         // Using File instead of Imagine::open(), because i.e. image/x-icon is not widely supported.
         $file = new ImageFile($cachedPath, false);
         // TODO: add more media headers
         $headers = ['content-type' => $file->getMimeType(), 'content-length' => $file->getSize()];
         $response = new Response($file->getContents(), 201, $headers);
         // Cache
         if (!($cacheType = $this->filterManager->getOption($filter, 'cache_type', false))) {
             return $response;
         }
         $cacheType === 'public' ? $response->setPublic() : $response->setPrivate();
         $cacheExpires = $this->filterManager->getOption($filter, 'cache_expires', '1 day');
         $expirationDate = new DateTime('+' . $cacheExpires);
         $maxAge = $expirationDate->format('U') - time();
         if ($maxAge < 0) {
             throw new InvalidArgumentException('Invalid cache expiration date');
         }
         $response->setExpires($expirationDate);
         $response->setMaxAge($maxAge);
         return $response;
     } catch (Exception $e) {
         throw $e;
     }
 }
 /**
  * Check if page is an alias for another page
  *
  * @param Request $request
  * @param PageInterface $page
  * @return bool|RedirectResponse
  */
 public function getRedirect(Request $request, PageInterface $page)
 {
     if (method_exists($page, 'getAlias') && $page instanceof PageInterface) {
         if ($alias = $page->getAlias()) {
             $alias->getFullPath();
             $baseUrl = $request->getBaseUrl();
             return new RedirectResponse($baseUrl . $alias->getFullPath());
         }
     }
     return false;
 }
Example #27
0
 /**
  * Updates the RequestContext info based on a HttpFoundation Request.
  *
  * @param Request $request A Request instance
  */
 public function fromRequest(Request $request)
 {
     $this->setBaseUrl($request->getBaseUrl());
     $this->setPathInfo($request->getPathInfo());
     $this->setMethod($request->getMethod());
     $this->setHost($request->getHost());
     $this->setScheme($request->getScheme());
     $this->setHttpPort($request->isSecure() ? $this->httpPort : $request->getPort());
     $this->setHttpsPort($request->isSecure() ? $request->getPort() : $this->httpsPort);
     $this->setQueryString($request->server->get('QUERY_STRING', ''));
 }
 /**
  * Match menu item
  *
  * @param ItemInterface $item Menu item
  *
  * @return bool|null
  */
 public function matchItem(ItemInterface $item)
 {
     if (null === $this->request) {
         return null;
     }
     $controller = $this->request->attributes->get('_controller');
     preg_match('#Controller\\\\([a-zA-Z]*)Controller#', $controller, $matches);
     $controllerName = null;
     if (!empty($matches[1])) {
         $controllerName = mb_strtolower($matches[1], mb_detect_encoding($matches[1]));
     }
     if (empty($controllerName)) {
         return null;
     }
     $route = $item->getUri();
     $routeRequest = $this->request->getBaseUrl() . '/' . $controllerName . '/';
     if ($route == $routeRequest) {
         return true;
     }
     return null;
 }
Example #29
0
 /**
  * Builds a page with form for add/edit operator.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  * @throws NotFoundException If the operator with specified ID is not found
  *   in the system.
  */
 public function showFormAction(Request $request)
 {
     $operator = $this->getOperator();
     $page = array('opid' => false, 'errors' => $request->attributes->get('errors', array()));
     $op_id = false;
     if ($request->attributes->has('operator_id')) {
         // Load and validate an operator to edit
         $op_id = $request->attributes->getInt('operator_id');
         $op = operator_by_id($op_id);
         if (!$op) {
             throw new NotFoundException('The operator is not found.');
         }
         // Show an error if the admin password hasn't been set yet.
         $no_password = check_password_hash($operator['vclogin'], '', $operator['vcpassword']) && !$request->query->has('stored');
         if ($no_password) {
             $page['errors'][] = getlocal('No Password set for the Administrator');
         }
         $page['formlogin'] = $op['vclogin'];
         $page['formname'] = $op['vclocalename'];
         $page['formemail'] = $op['vcemail'];
         $page['formcommonname'] = $op['vccommonname'];
         $page['formcode'] = $op['code'];
         $page['opid'] = $op['operatorid'];
     }
     // Override group's fields from the request if it's needed. This
     // case will take place when a save handler fails and passes the request
     // to this action.
     if ($request->isMethod('POST')) {
         // The login field can be disabled in the form. In that case it will
         // not has a value. Thus we should override login field only when it
         // is set.
         if ($request->request->has('login')) {
             $page['formlogin'] = $request->request->get('login');
         }
         $page['formname'] = $request->request->get('name');
         $page['formemail'] = $request->request->get('email');
         $page['formcommonname'] = $request->request->get('commonname');
         $page['formcode'] = $request->request->get('code');
     }
     $can_modify = $op_id == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator) || is_capable(CAN_ADMINISTRATE, $operator);
     $page['stored'] = $request->query->has('stored');
     $page['canmodify'] = $can_modify ? '1' : '';
     // The login cannot be changed for existing operators because it will
     // make the stored password hash invalid.
     $page['canchangelogin'] = is_capable(CAN_ADMINISTRATE, $operator) && !$op_id;
     $page['title'] = getlocal('Operator details');
     $page['menuid'] = $op_id == $operator['operatorid'] ? 'profile' : 'operators';
     $page['requirePassword'] = !$op_id;
     $page['formaction'] = $request->getBaseUrl() . $request->getPathInfo();
     $page = array_merge($page, prepare_menu($operator));
     $page['tabs'] = $this->buildTabs($request);
     return $this->render('operator_edit', $page);
 }
Example #30
-1
 protected function canBeRedirected(Request $request, RedirectResponse $response)
 {
     $targetRequest = Request::create($response->getTargetUrl());
     $stripUrl = function ($path) {
         return preg_replace('/#.+$/', '', $path);
     };
     $targetPath = $stripUrl($targetRequest->getBaseUrl() . $targetRequest->getPathInfo());
     $currentPath = $stripUrl($request->getBaseUrl() . $request->getPathInfo());
     return $targetPath !== $currentPath;
 }