/**
  * @param RequestResponseEvent $event
  */
 public function listen(RequestResponseEvent $event)
 {
     $context = $this->container->getSecurityContext();
     if ($context->getToken() && $context->getToken()->getUser()) {
         $this->container->getSession()->set($this->container->getParameter('cms_authentication.session.storage_key'), $context->getToken());
     }
 }
 /**
  * @param RequestResponseEvent $event
  */
 public function listen(RequestResponseEvent $event)
 {
     $request = $event->getRequest();
     $cmsPrefix = $this->container->getParameter('cms.prefix');
     if (strpos($request->getPathInfo(), $cmsPrefix) === 0) {
         //in any way we should try to extract data from session
         $session = $this->container->getSession();
         $tokenParameter = $this->container->getParameter('cms_authentication.session.storage_key');
         $securityContext = $this->container->getSecurityContext();
         if ($session->has($tokenParameter)) {
             $securityContext->setToken($session->get($tokenParameter));
             $this->container->getEventDispatcher()->dispatch(AuthController::TOKEN_CHANGE_EVENT, new DataAgnosticEvent());
         }
         //non-authorized users that are not on anonymous paths are getting redirected to login
         if ((!$securityContext->getToken() || !$securityContext->getToken()->getUser()) && !in_array($request->getPathInfo(), $this->container->getParameter('cms_authentication.paths.anonymous'))) {
             if ($request->isXmlHttpRequest()) {
                 $event->setResponse(new Response(AuthController::EMPTY_BODY, AuthController::FAILURE_STATUS));
             } else {
                 $event->setResponse(new RedirectResponse($this->container->getRouter()->generate('cms_authentication_login')));
             }
             $event->stopPropagation();
         }
         //authorized users on login path are redirected to dashboard
         if ($securityContext->getToken() && $securityContext->getToken()->getUser() && strpos($request->getPathInfo(), $this->container->getParameter('cms_authentication.paths.login')) === 0) {
             $event->setResponse(new RedirectResponse($cmsPrefix));
             $event->stopPropagation();
         }
     }
 }
示例#3
0
 /**
  * Smart fetch from a cache. $prefix and $key are (in most cases) combined yet can be used by cache driver for
  * sharding. Default can be a scalar value OR callable; it will be called only on cache miss (thus saving you some
  * code execution).
  *
  * Additionally, if $timestamp (last modification timestamp of you cache source) is provided and is newer than
  * saved by cache driver, cache miss will be considered.
  *
  * $respectDebug means that, in debug mode, a cache miss will always be considered, disabled by default.
  *
  * Optional $ttl can be specified, although the driver may nor respect it.
  *
  * @param string $prefix
  * @param mixed $key
  * @param null $default
  * @param int $timestamp
  * @param int $ttl
  * @param bool $respectDebug
  * @return mixed
  */
 public function fetch($prefix, $key, $default = null, $timestamp = 0, $ttl = 0, $respectDebug = false)
 {
     if ($respectDebug && $this->container->getParameter('debug')) {
         return $this->store($prefix, $key, $default, $timestamp, $ttl);
     }
     if ($value = $this->driver->get($prefix, $key, $timestamp)) {
         return $value;
     }
     return $this->store($prefix, $key, $default, $timestamp, $ttl);
 }
 /**
  * @return ThemeInterface
  */
 public function getActiveTheme()
 {
     if (!$this->container->hasParameter('cms.active_theme')) {
         throw new \RuntimeException('No active theme set.');
     }
     $themeName = $this->container->getParameter('cms.active_theme');
     if (!isset($this->themes[$themeName])) {
         throw new \InvalidArgumentException("There is no theme [{$themeName}].");
     }
     return $this->themes[$themeName];
 }
 public function finish(ContainerInterface $container)
 {
     $container->setParameter('cms_authentication.provider_key', 'cms_authentication');
     $container['cms_authentication.users.voters'] = function (ContainerInterface $container) {
         $voters = array();
         foreach ($container->getParameter('cms_authentication.users.voters') as $id) {
             $voters[] = $container[$id];
         }
         return $voters;
     };
     $container['cms_authentication.users.access_decision_manager'] = function (ContainerInterface $container) {
         return new AccessDecisionManager($container['cms_authentication.users.voters']);
     };
     $container['cms_authentication.encoder_factory'] = function (ContainerInterface $container) {
         $encoders = array();
         foreach ($container->getParameter('cms_authentication.users.password_encoders') as $user => $encoderClass) {
             $encoders[$user] = new $encoderClass();
         }
         return new EncoderFactory($encoders);
     };
     $container['cms_authentication.users.authentication_manager'] = function (ContainerInterface $container) {
         $providers = array();
         foreach ($container->getParameter('cms_authentication.users.user_providers') as $type => $providersDefinition) {
             if ($type != 'doctrine') {
                 throw new \Exception('Only "doctrine" user providers are allowed now');
             }
             foreach ($providersDefinition as $name => $providerDefinition) {
                 $provider = $container->getDoctrine()->getManager($providerDefinition['em'])->getRepository($providerDefinition['entity']);
                 $provider->setDefaultDomain($container->getParameter('cms_authentication.users.default_domain'));
                 $providers[] = $provider;
             }
             $chainProvider = new ChainUserProvider($providers);
             $realProviders = array(new AnonymousAuthenticationProvider(uniqid()), new DaoAuthenticationProvider($chainProvider, new UserChecker(), $container->getParameter('cms_authentication.provider_key'), $container['cms_authentication.encoder_factory']));
             return new AuthenticationProviderManager($realProviders);
         }
         return new AuthenticationProviderManager($providers);
     };
     $container['security.context'] = function (ContainerInterface $container) {
         return new SecurityContext($container['cms_authentication.users.authentication_manager'], $container['cms_authentication.users.access_decision_manager']);
     };
 }
 public function inject(ContainerInterface $container)
 {
     if (!$container->getParameter('debug')) {
         return;
     }
     $container[$this->name . '.session_collector'] = function () {
         return new SessionCollector();
     };
     $container[$this->name . '.timeline_collector'] = function () {
         return new TimelineCollector();
     };
     $container[$this->name . '.event_collector'] = function () {
         return new EventCollector();
     };
     $container[$this->name . '.monolog_collector'] = function (ContainerInterface $container) {
         return new MonologCollector($container->getLogger());
     };
     $container[$this->name . '.doctrine_collector'] = function (ContainerInterface $container) {
         $debugStack = new DebugStack();
         $container['doctrine.logger']->addLogger($debugStack);
         return new DoctrineCollector($debugStack);
     };
     $container[$this->name . '.debug_bar'] = function ($container) {
         $debugBar = new StandardDebugBar();
         $debugBar->addCollector($container[$this->name . '.session_collector']);
         $debugBar->addCollector($container[$this->name . '.doctrine_collector']);
         $debugBar->addCollector($container[$this->name . '.event_collector']);
         $debugBar->addCollector($container[$this->name . '.monolog_collector']);
         return $debugBar;
     };
     $container[$this->name . '.response_listener'] = new DebugBarResponseListener();
     $container[$this->name . '.assets_listener'] = new AssetsPublishEventListener();
     $container->getEventDispatcher()->addListener(KernelEvent::RESPONSE, array($container[$this->name . '.response_listener'], 'listen'));
     $container->getEventDispatcher()->addListener(FrameworkConsoleEvent::ASSETS_PUBLISH, array($container[$this->name . '.assets_listener'], 'listen'));
     //timeline collector binds to many events at once
     $container->getEventDispatcher()->addSubscriber($container[$this->name . '.timeline_collector']);
 }
示例#7
0
 protected function buildEvents(ContainerInterface $container)
 {
     if ($container->getParameter('debug')) {
         $container['event.dispatcher'] = new TraceableEventDispatcher();
     } else {
         $container['event.dispatcher'] = new EventDispatcher();
     }
 }
示例#8
0
 /**
  * Get file storage external directory path
  *
  * @return string
  */
 public function getExternalPath()
 {
     return $this->container->getParameter('directories.web') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR;
 }
示例#9
0
 public function handle(Request $request)
 {
     try {
         $requestEvent = new RequestResponseEvent();
         $requestEvent->setRequest($request);
         $this->container->getEventDispatcher()->dispatch(KernelEvent::REQUEST, $requestEvent);
         //here event can be overridden by any listener, so check if we have event
         if ($requestEvent->hasResponse()) {
             return $requestEvent->getResponse();
         }
         if ($request->attributes->has('_controller') && $request->attributes->has('_action')) {
             $controllerName = $request->attributes->get('_controller');
             $action = $request->attributes->get('_action');
             $controllerObject = new $controllerName();
             $controllerObject->setContainer($this->container);
             $response = $controllerObject->{$action}($request);
         } else {
             $router = $this->container->getRouter();
             $configuration = $router->match($request);
             //@todo: recall correctly how symfony deals with that
             $request->attributes = new ParameterBag($configuration);
             //@todo: do not execute controller that ugly
             $controllerDefinition = $this->container->getApplication()->parseControllerName($configuration['controller']);
             //probably there should be a better implementation of a package setting
             $controllerObject = new $controllerDefinition['controller']();
             $controllerObject->setContainer($this->container);
             $action = $controllerDefinition['action'];
             $controllerEvent = new ControllerEvent();
             $controllerEvent->setController($controllerObject);
             $controllerEvent->setAction($action);
             $this->container->getEventDispatcher()->dispatch(KernelEvent::CONTROLLER_START, $controllerEvent);
             $response = $controllerObject->{$action}($request);
             $controllerEvent->setResponse($response);
             $this->container->getEventDispatcher()->dispatch(KernelEvent::CONTROLLER_END, $controllerEvent);
             $response = $controllerEvent->getResponse();
         }
         $responseEvent = new RequestResponseEvent();
         $responseEvent->setRequest($request);
         $responseEvent->setResponse($response);
         $this->container->getEventDispatcher()->dispatch(KernelEvent::RESPONSE, $responseEvent);
         if (!$response instanceof Response) {
             throw new \Exception('Response returned by your controller is not an instance of HttpFoundation\\Response');
         }
         return $response;
     } catch (\Exception $e) {
         //generic exception handler
         $exceptionEvent = new RequestResponseEvent();
         $exceptionEvent->setRequest($request);
         $exceptionEvent->setData($e);
         $this->container->getEventDispatcher()->dispatch(KernelEvent::EXCEPTION, $exceptionEvent);
         if ($exceptionEvent->hasResponse()) {
             $this->container->getEventDispatcher()->dispatch(KernelEvent::RESPONSE, $exceptionEvent);
             return $exceptionEvent->getResponse();
         }
         //process 404 exceptions
         if ($e instanceof ResourceNotFoundException) {
             $notFoundEvent = new RequestResponseEvent();
             $notFoundEvent->setRequest($request);
             $this->container->getEventDispatcher()->dispatch(KernelEvent::ERROR404, $notFoundEvent);
             if ($notFoundEvent->hasResponse()) {
                 $this->container->getEventDispatcher()->dispatch(KernelEvent::RESPONSE, $notFoundEvent);
                 return $notFoundEvent->getResponse();
             }
             if ($this->container->getParameter('debug')) {
                 //in debug env 404 errors are just thrown
                 throw $e;
             } else {
                 return $this->container['exception.controller']->exception404Action($e);
             }
         }
         //process all other exceptions
         if ($this->container->getParameter('debug')) {
             throw $e;
         } else {
             return $this->container['exception.controller']->exception500Action($e);
         }
     }
 }
 public function finish(ContainerInterface $container)
 {
     //finishing locales
     $container->extend('locale.manager', function (LocaleManager $localeManager, ContainerInterface $container) {
         $locales = $container->getParameter('framework.locales');
         foreach ($locales['locales'] as $id => $locale) {
             $localeObject = new Locale();
             $localeObject->setId($id);
             $localeObject->setTitle($locale['title']);
             $localeObject->setActive($locale['active']);
             $localeObject->setCountry($locale['country']);
             $localeObject->setProperties($locale['properties']);
             $localeManager->addLocale($localeObject);
         }
         foreach ($locales['detectors'] as $detector) {
             $localeManager->addDetector($container[$detector]);
         }
         foreach ($locales['storage'] as $storage) {
             $localeManager->addStorage($container[$storage]);
         }
         $localeManager->setCurrent($locales['current']);
         return $localeManager;
     });
     //entity audit
     $container['entity_audit.configuration'] = function (ContainerInterface $container) {
         $config = $container->getParameter('framework.doctrine_audit');
         $configuration = new AuditConfiguration();
         $configuration->setAuditedEntityClasses($config['entities']);
         $configuration->setGlobalIgnoreColumns($config['ignore_columns']);
         $configuration->setRevisionTableName('su_' . $configuration->getRevisionTableName());
         $container->getEventDispatcher()->addListener(AuthController::TOKEN_CHANGE_EVENT, function () use($container, $configuration) {
             $context = $container->getSecurityContext();
             if ($context->getToken() && $context->getToken()->getUser()) {
                 $configuration->setCurrentUsername($context->getToken()->getUser()->getUsername());
             }
         });
         if (!$configuration->getCurrentUsername()) {
             $configuration->setCurrentUsername('anonymous');
         }
         return $configuration;
     };
     $container['entity_audit.manager'] = function (ContainerInterface $container) {
         $config = $container['entity_audit.configuration'];
         return new AuditManager($config);
     };
     //finishing doctrine
     $doctrineConfig = $container->getParameter('framework.doctrine');
     //let's believe that types are needed always
     foreach ($doctrineConfig['types'] as $definition) {
         list($name, $class) = $definition;
         Type::addType($name, $class);
     }
     foreach ($doctrineConfig['type_overrides'] as $definition) {
         list($name, $class) = $definition;
         Type::overrideType($name, $class);
     }
     foreach ($doctrineConfig['event_managers'] as $name => $managerDefinition) {
         $container['doctrine.event_managers.' . $name] = function (ContainerInterface $container) use($managerDefinition) {
             $manager = new EventManager();
             foreach ($managerDefinition['subscribers'] as $id) {
                 $manager->addEventSubscriber($container[$id]);
             }
             $container['entity_audit.manager']->registerEvents($manager);
             return $manager;
         };
     }
     $application = $container->getApplication();
     foreach ($doctrineConfig['configurations'] as $name => $configurationDefinition) {
         $container['doctrine.configurations.' . $name] = function (ContainerInterface $container) use($configurationDefinition, $application) {
             //loading package directories
             $packages = $application->getPackages();
             $paths = array();
             foreach ($packages as $package) {
                 $entityDir = $application->locatePackageRoot($package) . DIRECTORY_SEPARATOR . 'Entity';
                 if (is_dir($entityDir)) {
                     $paths[] = $entityDir;
                 }
             }
             $configuration = Setup::createAnnotationMetadataConfiguration($paths, $container->getParameter('debug'), $container->getParameter('directories.cache') . DIRECTORY_SEPARATOR . 'doctrine');
             if ($container->getParameter('debug')) {
                 $logger = $container['logger.doctrine'];
                 $container['doctrine.logger']->addLogger($logger);
                 $configuration->setSQLLogger($container['doctrine.logger']);
             }
             //Foo:Bar -> \FooPackage\Entity\Bar aliases
             foreach ($packages as $package) {
                 $class = get_class($package);
                 $namespace = substr($class, 0, strrpos($class, '\\')) . '\\Entity';
                 $configuration->addEntityNamespace($application->resolveName($package), $namespace);
             }
             return $configuration;
         };
     }
     foreach ($doctrineConfig['connections'] as $name => $connectionDefinition) {
         $container['doctrine.connections.' . $name] = function (ContainerInterface $container) use($connectionDefinition) {
             if ($connectionDefinition['driver'] != 'mysql') {
                 throw new \Exception('No driver is supported currently but mysql');
             }
             $connection = new Connection(array('host' => $connectionDefinition['host'], 'user' => $connectionDefinition['user'], 'password' => $connectionDefinition['password'], 'dbname' => $connectionDefinition['dbname'], 'charset' => $connectionDefinition['charset']), new PDOMySql\Driver(), $container['doctrine.configurations.' . $connectionDefinition['configuration']], $container['doctrine.event_managers.' . $connectionDefinition['event_manager']]);
             return $connection;
         };
     }
     foreach ($doctrineConfig['entity_managers'] as $name => $entityManagerDefinition) {
         $container['doctrine.entity_managers.' . $name] = function (ContainerInterface $container) use($name, $entityManagerDefinition, $doctrineConfig) {
             $ormConfigurationName = $entityManagerDefinition['configuration'];
             $ormConfiguration = $container['doctrine.configurations.' . $ormConfigurationName];
             $em = EntityManager::create($container['doctrine.connections.' . $entityManagerDefinition['connection']], $ormConfiguration, $container['doctrine.event_managers.' . $entityManagerDefinition['event_manager']]);
             // @DEV, remove
             $em->name = $name;
             foreach ($doctrineConfig['configurations'][$ormConfigurationName]['hydrators'] as $hydratorDefinition) {
                 list($name, $class) = $hydratorDefinition;
                 $reflection = new \ReflectionClass($class);
                 $hydrator = $reflection->newInstanceArgs(array($em));
                 $ormConfiguration->addCustomHydrationMode($name, $hydrator);
             }
             return $em;
         };
     }
     $container['doctrine.doctrine'] = function (ContainerInterface $container) use($doctrineConfig) {
         $connections = array();
         foreach (array_keys($doctrineConfig['connections']) as $name) {
             $connections[$name] = 'doctrine.connections.' . $name;
         }
         $managers = array();
         foreach (array_keys($doctrineConfig['entity_managers']) as $name) {
             $managers[$name] = 'doctrine.entity_managers.' . $name;
         }
         //todo: make default em/con configurable
         return new ManagerRegistry('supra.doctrine', $connections, $managers, $doctrineConfig['default_connection'], $doctrineConfig['default_entity_manager'], 'Doctrine\\ORM\\Proxy\\Proxy');
     };
     //sessions and HttpFoundation
     $sessionConfig = $container->getParameter('framework.session');
     $container['http.session'] = function (ContainerInterface $container) use($sessionConfig) {
         if (PHP_SAPI == 'cli') {
             throw new \Exception('Sessions are not possible in CLI mode');
         }
         $storage = $container[$sessionConfig['storage']];
         $session = new Session($storage);
         $session->start();
         $container['http.request']->setSession($session);
         return $session;
     };
     //mailers
     $mailerConfig = $container->getParameter('framework.swiftmailer');
     $container->setParameter('mailer.mailers', array_map(function ($value) {
         return 'mailer.mailers.' . $value;
     }, array_keys($mailerConfig['mailers'])));
     foreach ($mailerConfig['mailers'] as $id => $configurationDefinition) {
         $container['mailer.mailers.' . $id] = function (ContainerInterface $container) use($configurationDefinition) {
             switch ($configurationDefinition['transport']) {
                 case 'smtp':
                     $transport = \Swift_SmtpTransport::newInstance($configurationDefinition['params']['host'], $configurationDefinition['params']['port']);
                     $transport->setUsername($configurationDefinition['params']['username']);
                     $transport->setPassword($configurationDefinition['params']['password']);
                     break;
                 case 'mail':
                     $transport = \Swift_MailTransport::newInstance();
                     if (isset($transport['params']['extra_params'])) {
                         $transport->setExtraParams($transport['params']['extra_params']);
                     }
                     break;
                 case 'sendmail':
                     $transport = \Swift_SendmailTransport::newInstance();
                     if (isset($configurationDefinition['params']['command'])) {
                         $transport->setCommand($configurationDefinition['params']['command']);
                     }
                     break;
                 case 'null':
                     $transport = \Swift_NullTransport::newInstance();
                     break;
                 default:
                     throw new \Exception(sprintf('Unknown mail transport [%s].', $configurationDefinition['transport']));
             }
             return \Swift_Mailer::newInstance($transport);
         };
     }
     $container['mailer.mailer'] = function (ContainerInterface $container) use($mailerConfig) {
         return $container['mailer.mailers.' . $mailerConfig['default']];
     };
 }
示例#11
0
 /**
  * @todo: move to framwrok config, as always
  * @param ContainerInterface $container
  */
 protected function buildLogger(ContainerInterface $container)
 {
     $container['logger.doctrine'] = function (ContainerInterface $container) {
         return new DebugLogger();
     };
     $container['logger.logger'] = function (ContainerInterface $container) {
         $logger = new Logger('supra');
         if ($container->getParameter('debug')) {
             $sqlLogger = new DebugLogger();
             $sqlLogger->setContainer($container);
             $logger->pushHandler(new StreamHandler($container->getParameter('directories.storage') . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . $container->getParameter('environment') . '.log', Logger::DEBUG));
         } else {
             $logger->pushHandler(new StreamHandler($container->getParameter('directories.storage') . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . $container->getParameter('environment') . '.log', Logger::ERROR));
         }
         return $logger;
     };
 }