public function onControllerMatched(FilterControllerEvent $event)
 {
     if ('loginPage' != $event->getRequest()->get('_route') && (bool) SettingsBag::get('maintenance_mode') === true) {
         if (!$this->container['securityAuthorizationChecker']->isGranted('ROLE_BACKEND_USER')) {
             $matchedCtrl = $event->getController()[0];
             if ($matchedCtrl instanceof AppController) {
                 throw new MaintenanceModeException($matchedCtrl);
             } else {
                 throw new MaintenanceModeException();
             }
         }
     }
 }
Exemplo n.º 2
0
 /**
  * Add a default translation locale for static routes and
  * node SEO data.
  *
  * * [parent assignations…]
  * * **_default_locale**
  * * meta
  *     * siteName
  *     * siteCopyright
  *     * siteDescription
  */
 public function prepareBaseAssignation()
 {
     parent::prepareBaseAssignation();
     $translation = $this->getService('defaultTranslation');
     $this->assignation['_default_locale'] = $translation->getLocale();
     $this->assignation['meta'] = ['siteName' => SettingsBag::get('site_name'), 'siteCopyright' => SettingsBag::get('site_copyright'), 'siteDescription' => SettingsBag::get('seo_description')];
     return $this;
 }
Exemplo n.º 3
0
 /**
  * Send an email to reset user password.
  *
  * @param  UrlGenerator $urlGenerator
  *
  * @return boolean
  */
 public function sendPasswordResetLink(UrlGenerator $urlGenerator)
 {
     $emailContact = SettingsBag::get('email_sender');
     if (empty($emailContact)) {
         $emailContact = "*****@*****.**";
     }
     $siteName = SettingsBag::get('site_name');
     if (empty($siteName)) {
         $siteName = "Unnamed site";
     }
     $assignation = ['resetLink' => $urlGenerator->generate('loginResetPage', ['token' => $this->user->getConfirmationToken()], true), 'user' => $this->user, 'site' => $siteName, 'mailContact' => $emailContact];
     $emailBody = Kernel::getService('twig.environment')->render('users/reset_password_email.html.twig', $assignation);
     /*
      * inline CSS
      */
     $htmldoc = new InlineStyle($emailBody);
     $htmldoc->applyStylesheet(file_get_contents(ROADIZ_ROOT . "/src/Roadiz/CMS/Resources/css/transactionalStyles.css"));
     // Create the message
     $message = \Swift_Message::newInstance();
     // Give the message a subject
     $message->setSubject(Kernel::getService('translator')->trans('reset.password.request'));
     // Set the From address with an associative array
     $message->setFrom([$emailContact => $siteName]);
     // Set the To addresses with an associative array
     $message->setTo([$this->user->getEmail()]);
     // Give it a body
     $message->setBody($htmldoc->getHTML(), 'text/html');
     // Send the message
     return Kernel::getService('mailer')->send($message);
 }
Exemplo n.º 4
0
 protected function commonSettingList(Request $request, $settingGroup = null)
 {
     $criteria = [];
     if (null !== $settingGroup) {
         $criteria = ['settingGroup' => $settingGroup];
     }
     /*
      * Manage get request to filter list
      */
     $listManager = $this->createEntityListManager('RZ\\Roadiz\\Core\\Entities\\Setting', $criteria, ['name' => 'ASC']);
     $listManager->handle();
     $this->assignation['filters'] = $listManager->getAssignation();
     $settings = $listManager->getEntities();
     $this->assignation['settings'] = [];
     foreach ($settings as $setting) {
         $form = $this->buildShortEditForm($setting);
         $form->handleRequest($request);
         if ($form->isValid() && $form->getData()['id'] == $setting->getId()) {
             try {
                 $this->editSetting($form->getData(), $setting);
                 $msg = $this->getTranslator()->trans('setting.%name%.updated', ['%name%' => $setting->getName()]);
                 $this->publishConfirmMessage($request, $msg);
             } catch (EntityAlreadyExistsException $e) {
                 $this->publishErrorMessage($request, $e->getMessage());
             }
             if (null !== $settingGroup) {
                 return $this->redirect($this->generateUrl('settingGroupsSettingsPage', ['settingGroupId' => $settingGroup->getId()]));
             } else {
                 return $this->redirect($this->generateUrl('settingsHomePage'));
             }
         }
         $document = null;
         if ($setting->getType() == NodeTypeField::DOCUMENTS_T) {
             $document = SettingsBag::getDocument($setting->getName());
         }
         $this->assignation['settings'][] = ['setting' => $setting, 'form' => $form->createView(), 'document' => $document];
     }
     return null;
 }
Exemplo n.º 5
0
 /**
  * Return available page translation information.
  *
  * Be careful, for static routes Roadiz will generate a localized
  * route identifier suffixed with "Locale" text. In case of "force_locale"
  * setting to true, Roadiz will always use suffixed route.
  *
  * ## example return value
  *
  *     array (size=3)
  *       'en' =>
  *         array (size=4)
  *             'name' => string 'newsPage'
  *             'url' => string 'http://localhost/news/test'
  *             'locale' => string 'en'
  *             'active' => boolean false
  *             'translation' => string 'English'
  *       'fr' =>
  *         array (size=4)
  *             'name' => string 'newsPageLocale'
  *             'url' => string 'http://localhost/fr/news/test'
  *             'locale' => string 'fr'
  *             'active' => boolean true
  *             'translation' => string 'French'
  *       'es' =>
  *         array (size=4)
  *             'name' => string 'newsPageLocale'
  *             'url' => string 'http://localhost/es/news/test'
  *             'locale' => string 'es'
  *             'active' => boolean false
  *             'translation' => string 'Spanish'
  *
  * @param Request $request
  * @param boolean $absolute Generate absolute url or relative paths
  *
  * @return $this
  */
 public function getTranslationMenuAssignation(Request $request, $absolute = false)
 {
     $attr = $request->attributes->all();
     $query = $request->query->all();
     $name = "";
     $forceLocale = (bool) SettingsBag::get('force_locale');
     if (in_array("node", array_keys($attr), true)) {
         $node = $attr["node"];
     } else {
         $node = null;
     }
     if ($node === null && !empty($attr["_route"])) {
         $translations = Kernel::getService('em')->getRepository("RZ\\Roadiz\\Core\\Entities\\Translation")->findAllAvailable();
         $attr["_route"] = RouteHandler::getBaseRoute($attr["_route"]);
     } elseif (null !== $node) {
         $translations = $node->getHandler()->getAvailableTranslations();
         $translations = array_filter($translations, function (Translation $trans) {
             if ($trans->isAvailable()) {
                 return true;
             }
             return false;
         });
         $name = "node";
     } else {
         return [];
     }
     $return = [];
     foreach ($translations as $translation) {
         $url = null;
         if ($node) {
             $urlGenerator = new NodesSourcesUrlGenerator($request, $node->getHandler()->getNodeSourceByTranslation($translation), $forceLocale);
             $url = $urlGenerator->getUrl($absolute);
             if (!empty($query)) {
                 $url .= "?" . http_build_query($query);
             }
         } elseif (!empty($attr["_route"])) {
             /*
              * Use suffixed route if locales are forced or
              * if it’s not default translation.
              */
             if (true === $forceLocale || !$translation->isDefaultTranslation()) {
                 $name = $attr["_route"] . "Locale";
                 $attr["_route_params"]["_locale"] = $translation->getLocale();
             } else {
                 $name = $attr["_route"];
                 if (in_array("_locale", array_keys($attr["_route_params"]), true)) {
                     unset($attr["_route_params"]["_locale"]);
                 }
             }
             $url = Kernel::getService("urlGenerator")->generate($name, array_merge($attr["_route_params"], $query), $absolute);
         }
         if (null !== $url) {
             $return[$translation->getLocale()] = ['name' => $name, 'url' => $url, 'locale' => $translation->getLocale(), 'active' => $this->translation == $translation ? true : false, 'translation' => $translation->getName()];
         }
     }
     return $return;
 }
Exemplo n.º 6
0
 public function register(Container $container)
 {
     $container['request'] = function ($c) {
         return Request::createFromGlobals();
     };
     $container['requestStack'] = function ($c) {
         $stack = new RequestStack();
         $stack->push($c['request']);
         return $stack;
     };
     $container['requestContext'] = function ($c) {
         $rc = new RequestContext();
         $rc->fromRequest($c['request']);
         return $rc;
     };
     $container['resolver'] = function ($c) {
         return new ControllerResolver();
     };
     $container['httpKernel'] = function ($c) {
         return new HttpKernel($c['dispatcher'], $c['resolver'], $c['requestStack']);
     };
     $container['urlMatcher'] = function ($c) {
         if (RouteCollectionSubscriber::needToDumpUrlTools()) {
             return new UrlMatcher($c['routeCollection'], $c['requestContext']);
         } else {
             return new MixedUrlMatcher($c['requestContext'], $c['dynamicUrlMatcher'], (bool) $c['config']['install'], $c['stopwatch']);
         }
     };
     $container['dynamicUrlMatcher'] = function ($c) {
         return new NodeUrlMatcher($c['requestContext'], $c['em'], $c['stopwatch']);
     };
     $container['urlGeneratorClass'] = function ($c) {
         return '\\GlobalUrlGenerator';
     };
     $container['urlGenerator'] = function ($c) {
         if (RouteCollectionSubscriber::needToDumpUrlTools()) {
             return new UrlGenerator($c['routeCollection'], $c['requestContext'], $c['logger']);
         } else {
             $className = $c['urlGeneratorClass'];
             return new $className($c['requestContext']);
         }
     };
     $container['httpUtils'] = function ($c) {
         return new HttpUtils($c['urlGenerator'], $c['urlMatcher']);
     };
     $container['routeListener'] = function ($c) {
         return new TimedRouteListener($c['urlMatcher'], $c['requestContext'], null, $c['requestStack'], $c['stopwatch']);
     };
     if (isset($container['config']['install']) && true === $container['config']['install']) {
         /*
          * Get Install routes
          */
         $container['routeCollection'] = function ($c) {
             $installClassname = Kernel::INSTALL_CLASSNAME;
             $installClassname::setupDependencyInjection($c);
             return new InstallRouteCollection($installClassname);
         };
     } else {
         /*
          * Get App routes
          */
         $container['routeCollection'] = function ($c) {
             $c['stopwatch']->start('routeCollection');
             $rCollection = new RoadizRouteCollection($c['backendClass'], $c['frontendThemes'], SettingsBag::get('static_domain_name'));
             $c['stopwatch']->stop('routeCollection');
             return $rCollection;
         };
     }
     return $container;
 }
Exemplo n.º 7
0
 /**
  * Prepare backend and frontend routes and logic.
  *
  * @return boolean
  */
 public function initEvents()
 {
     if ($this->isDebug() || RouteCollectionSubscriber::needToDumpUrlTools()) {
         $this->container['dispatcher']->addSubscriber(new RouteCollectionSubscriber($this->container['routeCollection'], $this->container['stopwatch']));
     }
     $this->container['dispatcher']->addSubscriber($this->container['routeListener']);
     /*
      * Events
      */
     $this->container['dispatcher']->addListener(KernelEvents::REQUEST, [$this, 'onKernelRequest']);
     $this->container['dispatcher']->addListener(KernelEvents::REQUEST, [$this->container['firewall'], 'onKernelRequest']);
     $this->container['dispatcher']->addListener(KernelEvents::CONTROLLER, [new \RZ\Roadiz\Core\Events\ControllerMatchedEvent($this, $this->container['stopwatch']), 'onControllerMatched']);
     $this->container['dispatcher']->addSubscriber(new MaintenanceModeSubscriber($this->container));
     /*
      * If debug, alter HTML responses to append Debug panel to view
      */
     if (true === (bool) SettingsBag::get('display_debug_panel')) {
         $this->container['dispatcher']->addSubscriber($this->container['debugPanel']);
     }
 }
Exemplo n.º 8
0
 /**
  * Add a default translation locale for static routes and
  * node SEO data.
  *
  * * [parent assignations…]
  * * **_default_locale**
  * * meta
  *     * siteName
  *     * siteCopyright
  *     * siteDescription
  */
 public function prepareBaseAssignation()
 {
     parent::prepareBaseAssignation();
     $translation = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Translation')->findDefault();
     $this->assignation['_default_locale'] = $translation->getLocale();
     $this->assignation['meta'] = ['siteName' => SettingsBag::get('site_name'), 'siteCopyright' => SettingsBag::get('site_copyright'), 'siteDescription' => SettingsBag::get('seo_description')];
     return $this;
 }
Exemplo n.º 9
0
 /**
  * Get CSS font-face properties for current font.
  *
  * @param CsrfTokenManagerInterface $csrfTokenManager
  *
  * @return string CSS output
  */
 public function getCSSFontFace(CsrfTokenManagerInterface $csrfTokenManager)
 {
     $assignation = ['font' => $this->font, 'site' => SettingsBag::get('site_name'), 'fontFolder' => '/' . Font::getFilesFolderName(), 'csrfTokenManager' => $csrfTokenManager];
     return $this->getTwig()->render('fonts/fontfamily.css.twig', $assignation);
 }
Exemplo n.º 10
0
 public function register(Container $container)
 {
     $container['request'] = function ($c) {
         return Request::createFromGlobals();
     };
     $container['requestStack'] = function ($c) {
         $stack = new RequestStack();
         $stack->push($c['request']);
         return $stack;
     };
     $container['requestContext'] = function ($c) {
         $rc = new RequestContext();
         $rc->fromRequest($c['request']);
         return $rc;
     };
     $container['resolver'] = function ($c) {
         return new ControllerResolver();
     };
     $container['httpKernel'] = function ($c) {
         return new HttpKernel($c['dispatcher'], $c['resolver'], $c['requestStack']);
     };
     $container['router'] = function ($c) {
         $router = new ChainRouter($c['logger']);
         $router->add($c['staticRouter']);
         $router->add($c['nodeRouter']);
         return $router;
     };
     $container['staticRouter'] = function ($c) {
         return new StaticRouter($c['routeCollection'], ['cache_dir' => (bool) $c['config']['devMode'] ? null : ROADIZ_ROOT . '/cache/routing', 'debug' => (bool) $c['config']['devMode'], 'generator_cache_class' => 'StaticUrlGenerator', 'matcher_cache_class' => 'StaticUrlMatcher'], $c['requestContext'], $c['logger']);
     };
     $container['nodeRouter'] = function ($c) {
         return new NodeRouter($c['em'], ['cache_dir' => (bool) $c['config']['devMode'] ? null : ROADIZ_ROOT . '/cache/routing', 'debug' => (bool) $c['config']['devMode'], 'generator_cache_class' => 'NodeUrlGenerator', 'matcher_cache_class' => 'NodeUrlMatcher'], $c['requestContext'], $c['logger'], $c['stopwatch']);
     };
     $container['urlGenerator'] = function ($c) {
         return $c['staticRouter']->getGenerator();
     };
     $container['httpUtils'] = function ($c) {
         return new HttpUtils($c['router'], $c['router']);
     };
     $container['routeListener'] = function ($c) {
         return new TimedRouteListener($c['router'], $c['requestContext'], null, $c['requestStack'], $c['stopwatch']);
     };
     $container['routeCollection'] = function ($c) {
         if (isset($c['config']['install']) && true === $c['config']['install']) {
             /*
              * Get Install routes
              */
             $installClassname = Kernel::INSTALL_CLASSNAME;
             $installClassname::setupDependencyInjection($c);
             return new InstallRouteCollection($installClassname);
         } else {
             /*
              * Get App routes
              */
             $rCollection = new RoadizRouteCollection($c['backendClass'], $c['frontendThemes'], SettingsBag::get('static_domain_name'), $c['stopwatch']);
             return $rCollection;
         }
     };
     return $container;
 }
Exemplo n.º 11
0
 private function embedDocument($data, $folderId = null)
 {
     $handlers = $this->getService('document.platforms');
     if (isset($data['embedId']) && isset($data['embedPlatform']) && in_array($data['embedPlatform'], array_keys($handlers))) {
         $class = $handlers[$data['embedPlatform']];
         $finder = new $class($data['embedId']);
         if ($finder instanceof YoutubeEmbedFinder) {
             $finder->setKey(SettingsBag::get('google_server_id'));
         }
         if ($finder instanceof SoundcloudEmbedFinder) {
             $finder->setKey(SettingsBag::get('soundcloud_client_id'));
         }
         if ($finder->exists()) {
             $document = $finder->createDocumentFromFeed($this->getContainer());
             if (null !== $document && null !== $folderId && $folderId > 0) {
                 $folder = $this->getService('em')->find('RZ\\Roadiz\\Core\\Entities\\Folder', (int) $folderId);
                 $document->addFolder($folder);
                 $folder->addDocument($document);
                 $this->getService('em')->flush();
             }
             return $document;
         } else {
             throw new \RuntimeException("embedId.does_not_exist", 1);
         }
     } else {
         throw new \RuntimeException("bad.request", 1);
     }
 }
Exemplo n.º 12
0
 /**
  * Get a FQDN base url for static resources.
  *
  * You should fill “static_domain_name” setting after your
  * static domain name. Do not forget to create a virtual host
  * for this domain to serve the same content as your primary domain.
  *
  * If “static_domain_name” is empty, this method returns baseUrl
  *
  * @return string
  */
 public function getStaticBaseUrl()
 {
     $staticDomain = SettingsBag::get('static_domain_name');
     if (!empty($staticDomain)) {
         return $this->convertUrlToStaticDomainUrl($this->getAbsoluteBaseUrl());
     } else {
         return $this->getBasePath();
     }
 }
Exemplo n.º 13
0
 /**
  * Prepare backend and frontend routes and logic.
  *
  * @return boolean
  */
 public function initEvents()
 {
     /*
      * Events
      */
     $this->container['dispatcher']->addSubscriber($this->container['routeListener']);
     $this->container['dispatcher']->addListener(KernelEvents::REQUEST, [$this, 'onKernelRequest'], 60);
     $this->container['dispatcher']->addListener(KernelEvents::REQUEST, [$this->container['firewall'], 'onKernelRequest']);
     $this->container['dispatcher']->addListener(KernelEvents::CONTROLLER, [new \RZ\Roadiz\Core\Events\ControllerMatchedEvent($this, $this->container['stopwatch']), 'onControllerMatched']);
     if (!$this->isInstallMode()) {
         $this->container['dispatcher']->addSubscriber(new ResponseHeaderSubscriber($this->container['securityAuthorizationChecker'], $this->container['securityTokenStorage']));
     }
     $this->container['dispatcher']->addSubscriber(new MaintenanceModeSubscriber($this->container));
     /*
      * If debug, alter HTML responses to append Debug panel to view
      */
     if (true === (bool) SettingsBag::get('display_debug_panel')) {
         $this->container['dispatcher']->addSubscriber($this->container['debugPanel']);
     }
 }
Exemplo n.º 14
0
 /**
  * Prepare and handle a CustomForm Form then send a confirm email.
  *
  * * This method will return an assignation **array** if form is not validated.
  *     * customForm
  *     * fields
  *     * form
  * * If form is validated, **RedirectResponse** will be returned.
  *
  * @param Symfony\Component\HttpFoundation\Request          $request
  * @param RZ\Roadiz\Core\Entities\CustomForm                $customFormsEntity
  * @param Symfony\Component\Form\FormFactoryInterface       $formFactory
  * @param Doctrine\ORM\EntityManager                        $em
  * @param \Twig_Environment                                 $twigEnv
  * @param \Swift_Mailer                                     $mailer
  * @param Symfony\Component\Translation\Translator          $translator
  * @param Symfony\Component\HttpFoundation\RedirectResponse $redirection
  * @param Psr\Log\LoggerInterface|null                      $logger
  * @param boolean                                           $forceExpanded
  * @param string|null                                       $emailSender
  *
  * @return array|Symfony\Component\HttpFoundation\RedirectResponse
  */
 public static function prepareAndHandleCustomFormAssignation(Request $request, CustomForm $customFormsEntity, FormFactoryInterface $formFactory, EntityManager $em, \Twig_Environment $twigEnv, \Swift_Mailer $mailer, Translator $translator, RedirectResponse $redirection, LoggerInterface $logger = null, $forceExpanded = false, $emailSender = null)
 {
     $assignation = [];
     $assignation['customForm'] = $customFormsEntity;
     $assignation['fields'] = $customFormsEntity->getFields();
     $form = static::buildForm($request, $customFormsEntity, $formFactory, $forceExpanded);
     $form->handleRequest($request);
     if ($form->isValid()) {
         try {
             $data = $form->getData();
             $data["ip"] = $request->getClientIp();
             /*
              * add custom form answer
              */
             $assignation["emailFields"] = static::addCustomFormAnswer($data, $customFormsEntity, $em);
             $msg = $translator->trans('customForm.%name%.send', ['%name%' => $customFormsEntity->getDisplayName()]);
             $request->getSession()->getFlashBag()->add('confirm', $msg);
             if (null !== $logger) {
                 $logger->info($msg);
             }
             $assignation['title'] = $translator->trans('new.answer.form.%site%', ['%site%' => $customFormsEntity->getDisplayName()]);
             if (null !== $emailSender && false !== filter_var($emailSender, FILTER_VALIDATE_EMAIL)) {
                 $assignation['mailContact'] = $emailSender;
             } else {
                 $assignation['mailContact'] = SettingsBag::get('email_sender');
             }
             /*
              * Send answer notification
              */
             static::sendAnswer(['mailContact' => $assignation['mailContact'], 'fields' => $assignation["emailFields"], 'customForm' => $customFormsEntity, 'title' => $translator->trans('new.answer.form.%site%', ['%site%' => $customFormsEntity->getDisplayName()])], $customFormsEntity->getEmail(), $twigEnv, $mailer);
             return $redirection;
         } catch (EntityAlreadyExistsException $e) {
             $request->getSession()->getFlashBag()->add('error', $e->getMessage());
             if (null !== $logger) {
                 $logger->warning($e->getMessage());
             }
             return $redirection;
         }
     }
     $assignation['form'] = $form->createView();
     return $assignation;
 }
Exemplo n.º 15
0
 /**
  * @param Symfony\Component\HttpFoundation\Request $request
  *
  * @return Symfony\Component\HttpFoundation\Response $response
  */
 public function cssAction(Request $request)
 {
     $this->assignation['mainColor'] = SettingsBag::get('main_color');
     $this->assignation['nodeTypes'] = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\NodeType')->findBy([]);
     return new Response($this->getTwig()->render('css/mainColor.css.twig', $this->assignation), Response::HTTP_OK, ['content-type' => 'text/css']);
 }
Exemplo n.º 16
0
 /**
  * Send contact form data by email.
  *
  * @return boolean
  */
 protected function send()
 {
     if (empty($this->assignation)) {
         throw new \Exception("Can’t send a contact form without data.", 1);
     }
     $emailBody = $this->templating->render($this->emailTemplate, $this->assignation);
     /*
      * inline CSS
      */
     $htmldoc = new InlineStyle($emailBody);
     $htmldoc->applyStylesheet(file_get_contents(ROADIZ_ROOT . $this->emailStylesheet));
     if (null === $this->receiver) {
         $this->receiver = SettingsBag::get('email_sender');
     }
     /*
      * Add subject
      */
     if (null !== $this->subject) {
         $this->subject = trim(strip_tags($this->subject));
     } else {
         $this->subject = $this->translator->trans('new.contact.form.%site%', ['%site%' => SettingsBag::get('site_name')]);
     }
     // Create the message
     $this->message = \Swift_Message::newInstance()->setSubject($this->subject)->setTo([$this->receiver])->setBody($htmldoc->getHTML(), 'text/html');
     if (null !== $this->sender) {
         // Set the From address with an associative array
         $this->message->setFrom([$this->sender]);
     }
     /*
      * Attach files
      */
     foreach ($this->uploadedFiles as $uploadedFile) {
         $attachment = \Swift_Attachment::fromPath($uploadedFile->getRealPath())->setFilename($uploadedFile->getClientOriginalName());
         $this->message->attach($attachment);
     }
     // Send the message
     return $this->mailer->send($this->message);
 }
Exemplo n.º 17
0
 /**
  * @param Pimple\Container $container [description]
  */
 public function register(Container $container)
 {
     $container['twig.cacheFolder'] = function ($c) {
         return ROADIZ_ROOT . '/cache/twig_cache';
     };
     /*
      * Return every paths to search for twig templates.
      */
     $container['twig.loaderFileSystem'] = function ($c) {
         $vendorDir = realpath(ROADIZ_ROOT . '/vendor');
         // le chemin vers TwigBridge pour que Twig puisse localiser
         // le fichier form_div_layout.html.twig
         $vendorTwigBridgeDir = $vendorDir . '/symfony/twig-bridge';
         return new \Twig_Loader_Filesystem([$vendorTwigBridgeDir . '/Resources/views/Form', ROADIZ_ROOT . '/src/Roadiz/CMS/Resources/views']);
     };
     /*
      * Main twig environment
      */
     $container['twig.environment'] = function ($c) {
         $twig = new \Twig_Environment($c['twig.loaderFileSystem'], ['debug' => $c['config']['devMode'], 'cache' => $c['twig.cacheFolder']]);
         $c['twig.formRenderer']->setEnvironment($twig);
         $twig->addExtension(new FormExtension(new TwigRenderer($c['twig.formRenderer'], $c['csrfTokenManager'])));
         $twig->addFilter($c['twig.markdownExtension']);
         $twig->addFilter($c['twig.inlineMarkdownExtension']);
         $twig->addFilter($c['twig.centralTruncateExtension']);
         /*
          * Extensions
          */
         $twig->addExtension(new TranslationExtension($c['translator']));
         $twig->addExtension(new \Twig_Extensions_Extension_Intl());
         $twig->addExtension($c['twig.routingExtension']);
         $twig->addExtension(new \Twig_Extensions_Extension_Text());
         $twig->addExtension(new BlockRenderExtension($c, Kernel::getInstance()));
         if (true !== $c['config']['install']) {
             $twig->addExtension(new NodesSourcesExtension($c['securityAuthorizationChecker']));
         }
         $twig->addExtension(new DocumentExtension());
         $twig->addExtension(new UrlExtension($c['request'], $c['nodesSourcesUrlCacheProvider'], (bool) \RZ\Roadiz\Core\Bags\SettingsBag::get('force_locale')));
         $twig->addExtension(new RoadizTranslationExtension($c['request']));
         if (null !== $c['twig.cacheExtension']) {
             $twig->addExtension($c['twig.cacheExtension']);
         }
         if (true === $c['config']['devMode']) {
             $twig->addExtension(new \Twig_Extension_Debug());
         }
         return $twig;
     };
     /*
      * Twig form renderer extension
      */
     $container['twig.formRenderer'] = function ($c) {
         return new TwigRendererEngine(['form_div_layout.html.twig']);
     };
     /*
      * Twig routing extension
      */
     $container['twig.routingExtension'] = function ($c) {
         return new RoutingExtension($c['urlGenerator']);
     };
     /*
      * Markdown extension
      */
     $container['twig.markdownExtension'] = function ($c) {
         return new \Twig_SimpleFilter('markdown', function ($object) {
             return Parsedown::instance()->text($object);
         }, ['is_safe' => ['html']]);
     };
     /*
      * InlineMarkdown extension
      */
     $container['twig.inlineMarkdownExtension'] = function ($c) {
         return new \Twig_SimpleFilter('inlineMarkdown', function ($object) {
             return Parsedown::instance()->line($object);
         }, ['is_safe' => ['html']]);
     };
     /*
      * Central Truncate extension
      */
     $container['twig.centralTruncateExtension'] = function ($c) {
         return new \Twig_SimpleFilter('centralTruncate', function ($object, $length, $offset = 0, $ellipsis = "[…]") {
             if (strlen($object) > $length + strlen($ellipsis)) {
                 $str1 = substr($object, 0, floor($length / 2) + floor($offset / 2));
                 $str2 = substr($object, floor($length / 2) * -1 + floor($offset / 2));
                 return $str1 . $ellipsis . $str2;
             } else {
                 return $object;
             }
         });
     };
     /*
      * Twig cache extension
      * see https://github.com/asm89/twig-cache-extension
      */
     $container['twig.cacheExtension'] = function ($c) {
         $resultCacheDriver = $c['em']->getConfiguration()->getResultCacheImpl();
         if ($resultCacheDriver !== null) {
             $cacheProvider = new DoctrineCacheAdapter($resultCacheDriver);
             $cacheStrategy = new LifetimeCacheStrategy($cacheProvider);
             $cacheExtension = new CacheExtension($cacheStrategy);
             return $cacheExtension;
         } else {
             return null;
         }
     };
     return $container;
 }
Exemplo n.º 18
0
 /**
  * Prepare base informations to be rendered in twig templates.
  *
  * ## Available contents
  *
  * - request: Main request object
  * - head
  *     - ajax: `boolean`
  *     - cmsVersion
  *     - cmsVersionNumber
  *     - cmsBuild
  *     - devMode: `boolean`
  *     - baseUrl
  *     - filesUrl
  *     - resourcesUrl
  *     - ajaxToken
  *     - fontToken
  *     - universalAnalyticsId
  *     - useCdn
  * - session
  *     - messages
  *     - id
  *     - user
  * - securityAuthorizationChecker
  *
  * @return $this
  */
 public function prepareBaseAssignation()
 {
     $this->assignation = ['request' => $this->getRequest(), 'head' => ['ajax' => $this->getRequest()->isXmlHttpRequest(), 'cmsVersion' => Kernel::CMS_VERSION, 'cmsVersionNumber' => Kernel::$cmsVersion, 'cmsBuild' => Kernel::$cmsBuild, 'devMode' => (bool) $this->container['config']['devMode'], 'useCdn' => (bool) SettingsBag::get('use_cdn'), 'universalAnalyticsId' => SettingsBag::get('universal_analytics_id'), 'baseUrl' => $this->getRequest()->getAbsoluteBaseUrl(), 'filesUrl' => $this->getRequest()->getBaseUrl() . '/' . Document::getFilesFolderName(), 'resourcesUrl' => $this->getStaticResourcesUrl(), 'ajaxToken' => $this->container['csrfTokenManager']->getToken(static::AJAX_TOKEN_INTENTION), 'fontToken' => $this->container['csrfTokenManager']->getToken(static::FONT_TOKEN_INTENTION)], 'session' => ['id' => $this->getRequest()->getSession()->getId(), 'user' => $this->getUser()]];
     if ($this->container['securityAuthorizationChecker'] !== null) {
         $this->assignation['authorizationChecker'] = $this->container['securityAuthorizationChecker'];
     }
     return $this;
 }
Exemplo n.º 19
0
 /**
  * Get current node-source SEO data.
  *
  * @return array
  */
 public function getSEO()
 {
     return ['title' => $this->nodeSource->getMetaTitle() != "" ? $this->nodeSource->getMetaTitle() : $this->nodeSource->getTitle() . ' – ' . SettingsBag::get('site_name'), 'description' => $this->nodeSource->getMetaDescription() != "" ? $this->nodeSource->getMetaDescription() : $this->nodeSource->getTitle() . ', ' . SettingsBag::get('seo_description'), 'keywords' => $this->nodeSource->getMetaKeywords()];
 }
Exemplo n.º 20
0
 /**
  * Build form for theme and site informations.
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *
  * @return Symfony\Component\Form\Forms
  */
 protected function buildInformationsForm(Request $request)
 {
     $siteName = SettingsBag::get('site_name');
     $metaDescription = SettingsBag::get('seo_description');
     $emailSender = SettingsBag::get('email_sender');
     $emailSenderName = SettingsBag::get('email_sender_name');
     $timeZone = $this->getService('config')['timezone'];
     $timeZoneList = (include dirname(__FILE__) . '/Resources/import/timezones.php');
     $defaults = ['site_name' => $siteName != '' ? $siteName : "My website", 'seo_description' => $metaDescription != '' ? $metaDescription : "My website is beautiful!", 'email_sender' => $emailSender != '' ? $emailSender : "", 'email_sender_name' => $emailSenderName != '' ? $emailSenderName : "", 'install_frontend' => true, 'timezone' => $timeZone != '' ? $timeZone : "Europe/Paris"];
     $builder = $this->createFormBuilder($defaults)->add('site_name', 'text', ['required' => true, 'label' => $this->getTranslator()->trans('site_name'), 'constraints' => [new NotBlank()]])->add('email_sender', 'email', ['required' => true, 'label' => $this->getTranslator()->trans('email_sender'), 'constraints' => [new NotBlank()]])->add('email_sender_name', 'text', ['required' => true, 'label' => $this->getTranslator()->trans('email_sender_name'), 'constraints' => [new NotBlank()]])->add('seo_description', 'text', ['required' => false, 'label' => $this->getTranslator()->trans('meta_description')])->add('timezone', 'choice', ['choices' => $timeZoneList, 'label' => $this->getTranslator()->trans('timezone'), 'required' => true]);
     $themesType = new \RZ\Roadiz\CMS\Forms\ThemesType();
     if ($themesType->getSize() > 0) {
         $builder->add('separator_1', new SeparatorType(), ['label' => $this->getTranslator()->trans('themes.frontend.description')])->add('install_theme', 'checkbox', ['required' => false, 'label' => $this->getTranslator()->trans('install_theme')])->add('className', $themesType, ['label' => $this->getTranslator()->trans('theme.selector'), 'required' => true, 'constraints' => [new \Symfony\Component\Validator\Constraints\NotNull(), new \Symfony\Component\Validator\Constraints\Type('string')]]);
     }
     return $builder->getForm();
 }
Exemplo n.º 21
0
 /**
  * Send a contact form by Email.
  *
  * @param array $assignation
  * @param string $receiver
  * @param string|null $subject
  * @param array $files
  *
  * @return boolean
  */
 protected function sendContactForm($assignation, $receiver, $subject = null, $files = null)
 {
     $emailBody = $this->getService('twig.environment')->render('forms/contactForm.html.twig', $assignation);
     /*
      * inline CSS
      */
     $htmldoc = new InlineStyle($emailBody);
     $htmldoc->applyStylesheet(file_get_contents(ROADIZ_ROOT . "/src/Roadiz/CMS/Resources/css/transactionalStyles.css"));
     if (null !== $subject) {
         $subject = trim(strip_tags($subject));
     } else {
         $subject = $this->getTranslator()->trans('new.contact.form.%site%', ['%site%' => SettingsBag::get('site_name')]);
     }
     // Create the message
     $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom([$assignation['email']])->setTo([$receiver])->setBody($htmldoc->getHTML(), 'text/html');
     /*
      * Attach files
      */
     foreach ($files as $uploadedFile) {
         $attachment = \Swift_Attachment::fromPath($uploadedFile->getRealPath())->setFilename($uploadedFile->getClientOriginalName());
         $message->attach($attachment);
     }
     // Send the message
     return $this->getService('mailer')->send($message);
 }