/**
  * Init the doctrine entity manager.
  *
  * @return Doctrine\ORM\EntityManager
  */
 private function _initEntityManager()
 {
     // New database configuration
     $config = new Configuration();
     $driverImpl = $config->newDefaultAnnotationDriver();
     $config->setMetadataDriverImpl($driverImpl);
     $proxiesPath = $this->_application->getCacheDir() . DIRECTORY_SEPARATOR . 'Proxies';
     $config->setProxyDir($proxiesPath);
     $config->setProxyNamespace('Proxies');
     // Create EntityManager
     $em = EntityManager::create($this->_config, $config);
     if (isset($this->_config['charset'])) {
         try {
             $em->getConnection()->executeUpdate('SET SESSION character_set_client = "' . addslashes($this->_config['charset']) . '";');
             $em->getConnection()->executeUpdate('SET SESSION character_set_connection = "' . addslashes($this->_config['charset']) . '";');
             $em->getConnection()->executeUpdate('SET SESSION character_set_results = "' . addslashes($this->_config['charset']) . '";');
         } catch (\Exception $e) {
             throw new BBException(sprintf('Invalid database character set `%s`', $this->_config['charset']), BBException::INVALID_ARGUMENT, $e);
         }
     }
     if (isset($this->_config['collation'])) {
         try {
             $em->getConnection()->executeUpdate('SET SESSION collation_connection = "' . addslashes($this->_config['collation']) . '";');
         } catch (\Exception $e) {
             throw new BBException(sprintf('Invalid database collation `%s`', $this->_config['collation']), BBException::INVALID_ARGUMENT, $e);
         }
     }
     return $em;
 }
 /**
  * AImportBundle's constructor.
  *
  * @param BBApplication $application
  */
 public function __construct(BBApplication $application)
 {
     $this->_application = $application;
     $this->_config = new Config($this->_dir);
     foreach ($this->_application->getConfig()->getSection('doctrine') as $key => $db_config) {
         $this->_config->setSection($key, $db_config, true);
     }
     $this->_relations = $this->_config->getSection('relations');
     if (0 == count($this->_relations)) {
         return false;
     }
     $log_filepath = $application->getConfig()->getLoggingConfig();
     $log_filepath = $log_filepath['logfile'];
     if ('/' !== $log_filepath[0] || false === is_dir(dirname($log_filepath))) {
         $log_filepath = $application->getBaseDir() . '/log/import.log';
     } else {
         $log_filepath = dirname($log_filepath) . '/import.log';
     }
     $logger = new \BackBee\Logging\Appender\File(array('logfile' => $log_filepath));
     $this->setPhpConf($this->_config->getSection('php_ini'));
     foreach ($this->_relations as $class => $config) {
         $type = true === isset($config['type']) ? $config['type'] : 'import';
         try {
             $this->{$type . ucfirst($class)}($config);
         } catch (SkippedImportException $exc) {
             echo $exc->getMessage() . "\n";
         } catch (\Exception $e) {
             $logger->write(array('d' => date('Y/m/d H:i:s'), 'p' => '', 'm' => $e->getMessage(), 'u' => ''));
         }
     }
     return true;
 }
Exemple #3
0
 /**
  * {@inheritdoc}
  */
 public function decide(TokenInterface $token, array $attributes, $object = null)
 {
     $result = parent::decide($token, $attributes, $object);
     if (false === $result && true === $this->_tryBBTokenOnDenied && null !== $this->_application && null !== $this->_application->getBBUserToken()) {
         $result = parent::decide($this->_application->getBBUserToken(), $attributes, $object);
     }
     return $result;
 }
Exemple #4
0
 /**
  * Constructor.
  *
  * @param KernelInterface $kernel A KernelInterface instance
  */
 public function __construct(BBApplication $application = null)
 {
     $this->application = $application;
     parent::__construct('BackBee', BBApplication::VERSION . ($application->isDebugMode() ? '/debug' : ''));
     $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $this->application->getEnvironment()));
     $this->getDefinition()->addOption(new InputOption('--app', '-a', InputOption::VALUE_REQUIRED, 'The BackBee application classname.', get_class($this->application)));
     $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.'));
 }
 /**
  * @param \BackBee\Event\Event $event
  */
 public function onPostLoad(Event $event)
 {
     $page = $event->getTarget();
     if (!$page instanceof Page) {
         return;
     }
     $isBbSessionActive = $this->_application->getBBUserToken() === null;
     $page->setUseUrlRedirect($isBbSessionActive);
 }
 /**
  * Class constructor.
  *
  * @param \BackBee\BBApplication $application
  * @param array                  $config
  */
 public function __construct(BBApplication $application, array $config)
 {
     $this->_application = $application;
     if (!isset($config['archive'])) {
         throw new \Exception("Configuration param 'archive' must be provided");
     }
     $this->_config = array_merge_recursive(array('extractedDir' => $application->getTemporaryDir() . '/ZipArchiveConnector/extracted/' . basename($config['archive']) . '/' . date('Y-m-d_His') . '/', 'deleteExtracted' => true), $config);
     $this->_init();
 }
 public static function build(BBApplication $application, $objectIdentity)
 {
     $matches = array();
     if (preg_match(self::$_pattern1, $objectIdentity, $matches)) {
         return new self($application->getEntityManager(), trim($matches[1]), trim($matches[2]));
     } elseif (preg_match(self::$_pattern2, $objectIdentity, $matches)) {
         return new self($application->getEntityManager(), trim($matches[2]), trim($matches[1]));
     }
     return new self($application->getEntityManager(), null, null);
 }
 /**
  *
  */
 public function __construct(BBApplication $app)
 {
     if (empty($this->bundle)) {
         foreach ($app->getBundles() as $bundle) {
             if ($bundle instanceof ThemeCore) {
                 $this->bundle = $bundle;
             }
         }
     }
     parent::__construct($app);
 }
 /**
  * Class constructor.
  *
  * @param \BackBee\BBApplication $application
  * @param array                  $config
  */
 public function __construct(BBApplication $application, array $config)
 {
     $this->_application = $application;
     $this->_config = $config;
     if (true === array_key_exists('basedir', $config)) {
         $this->_basedir = $config['basedir'];
         File::resolveFilepath($this->_basedir, null, array('include_path' => $this->_application->getRepository()));
     } else {
         $this->_basedir = $this->_application->getRepository();
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $force = $input->getOption('force');
     $drop = $input->getOption('drop');
     $this->bbapp = $this->getContainer()->get('bbapp');
     $this->em = $this->initConnection($input, $output);
     $this->checkBeforeUpdate();
     $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths([$this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Bundle', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR . 'DAO', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'ClassContent', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'ClassContent' . DIRECTORY_SEPARATOR . 'Indexes', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Logging', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'NestedNode', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Security', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Site', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Stream' . DIRECTORY_SEPARATOR . 'ClassWrapper', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Util' . DIRECTORY_SEPARATOR . 'Sequence' . DIRECTORY_SEPARATOR . 'Entity', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Workflow']);
     $this->em->getConfiguration()->getMetadataDriverImpl()->addExcludePaths([$this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'ClassContent' . DIRECTORY_SEPARATOR . 'Tests', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'NestedNode' . DIRECTORY_SEPARATOR . 'Tests', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Security' . DIRECTORY_SEPARATOR . 'Tests', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Util' . DIRECTORY_SEPARATOR . 'Tests', $this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'Workflow' . DIRECTORY_SEPARATOR . 'Tests']);
     if (is_dir($this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'vendor')) {
         $this->em->getConfiguration()->getMetadataDriverImpl()->addExcludePaths([$this->bbapp->getBBDir() . DIRECTORY_SEPARATOR . 'vendor']);
     }
     $sqls = $this->getUpdateQueries();
     if ($force || $drop) {
         $metadata = $this->em->getMetadataFactory()->getAllMetadata();
         $schema = new SchemaTool($this->em);
         if ($drop) {
             $sqls = array_merge($schema->getDropDatabaseSQL(), $sqls);
         }
         if ($force) {
             $output->writeln('<info>Running drop/update</info>');
             $this->em->getConnection()->executeUpdate('SET FOREIGN_KEY_CHECKS=0');
             $drop ? $schema->dropDatabase() : '';
             $schema->updateSchema($metadata, true);
             $this->em->getConnection()->executeUpdate('SET FOREIGN_KEY_CHECKS=1');
         }
     }
     $output->writeln(($force ? '<info>SQL executed: </info>' : '<info>SQL to be executed: </info>') . PHP_EOL . implode(";" . PHP_EOL, $sqls) . '');
 }
 /**
  * Dispatch postupload event.
  *
  * @param string $sourcefile
  * @param string $targetfile
  */
 private function dispatchPostUploadEvent($sourcefile, $targetfile)
 {
     if (null !== $this->_application && null !== $this->_application->getEventDispatcher()) {
         $event = new \BackBee\Event\PostUploadEvent($sourcefile, $targetfile);
         $this->_application->getEventDispatcher()->dispatch('file.postupload', $event);
     }
 }
Exemple #12
0
 /**
  * Computes the URL of a page according to a scheme.
  *
  * @param array         $scheme  The scheme to apply
  * @param Page          $page    The page
  * @param  AbstractClassContent $content The optionnal main content of the page
  * @return string        The generated URL
  */
 private function doGenerate($scheme, Page $page, AbstractClassContent $content = null)
 {
     $replacement = ['$parent' => $page->isRoot() ? '' : $page->getParent()->getUrl(false), '$title' => StringUtils::urlize($page->getTitle()), '$datetime' => $page->getCreated()->format('ymdHis'), '$date' => $page->getCreated()->format('ymd'), '$time' => $page->getCreated()->format('His')];
     $matches = [];
     if (preg_match_all('/(\\$content->[a-z]+)/i', $scheme, $matches)) {
         foreach ($matches[1] as $pattern) {
             $property = explode('->', $pattern);
             $property = array_pop($property);
             try {
                 $replacement[$pattern] = StringUtils::urlize($content->{$property});
             } catch (\Exception $e) {
                 $replacement[$pattern] = '';
             }
         }
     }
     $matches = [];
     if (preg_match_all('/(\\$ancestor\\[([0-9]+)\\])/i', $scheme, $matches)) {
         foreach ($matches[2] as $level) {
             $ancestor = $this->application->getEntityManager()->getRepository('BackBee\\NestedNode\\Page')->getAncestor($page, $level);
             if (null !== $ancestor && $page->getLevel() > $level) {
                 $replacement['$ancestor[' . $level . ']'] = $ancestor->getUrl(false);
             } else {
                 $replacement['$ancestor[' . $level . ']'] = '';
             }
         }
     }
     $url = preg_replace('/\\/+/', '/', str_replace(array_keys($replacement), array_values($replacement), $scheme));
     return $this->getUniqueness($page, $url);
 }
 /**
  * Dispatcher constructor.
  *
  * @param \BackBee\BBApplication $application The current instance of BB application
  */
 public function __construct(BBApplication $application = null, Config $config = null)
 {
     $this->application = $application;
     if (null === $config && null !== $application) {
         $config = $application->getConfig();
     }
     if (null !== $config) {
         if (null !== ($events_config = $config->getRawSection('events'))) {
             $this->addListeners($events_config);
         }
     }
     if (null !== $application) {
         $this->container = $this->application->getContainer();
     }
     $this->_is_restored = false;
 }
 /**
  * Updates the content-content indexes for the scheduled AbstractClassContent.
  *
  * @param array $contents_saved
  * @param array $contents_removed
  */
 private static function _updateIdxContentContents(array $contents_saved, array $contents_removed)
 {
     if (null === self::$_application->getSite()) {
         return;
     }
     self::$_em->getRepository('BackBee\\ClassContent\\Indexes\\IdxContentContent')->replaceIdxContentContents(array_diff($contents_saved, self::$_content_content_done))->removeIdxContentContents($contents_removed);
     self::$_content_content_done = array_merge(self::$_content_content_done, $contents_saved);
 }
Exemple #15
0
 private function getBundleClassMetadata()
 {
     $classes = array();
     foreach ($this->_application->getBundles() as $bundle) {
         $classes = array_merge($classes, $this->_getBundleSchema($bundle));
     }
     return $classes;
 }
Exemple #16
0
 /**
  * Override Symfony\Component\Translation\Translator to lazy load every catalogs from:
  *     - BackBee\Resources\translations
  *     - PATH_TO_REPOSITORY\Resources\translations
  *     - PATH_TO_CONTEXT_REPOSITORY\Resources\translations.
  *
  * @param BBApplication $application
  * @param string        $locale
  */
 public function __construct(BBApplication $application, $locale)
 {
     parent::__construct($locale);
     // retrieve default fallback from container and set it
     $fallback = $application->getContainer()->getParameter('translator.fallback');
     $this->setFallbackLocales([$fallback]);
     // xliff is recommended by Symfony so we register its loader as default one
     $this->addLoader('xliff', new XliffFileLoader());
     // define in which directory we should looking at to find xliff files
     $dirToLookingAt = array($application->getBBDir() . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'translations', $application->getRepository() . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'translations');
     if ($application->getRepository() !== $application->getBaseRepository()) {
         $dirToLookingAt[] = $application->getBaseRepository() . 'Resources' . DIRECTORY_SEPARATOR . 'translations';
     }
     // loop in every directory we should looking at and load catalog from file which match to the pattern
     foreach ($dirToLookingAt as $dir) {
         if (true === is_dir($dir)) {
             foreach (scandir($dir) as $filename) {
                 preg_match('/(.+)\\.(.+)\\.xlf$/', $filename, $matches);
                 if (0 < count($matches)) {
                     $this->addResource('xliff', $dir . DIRECTORY_SEPARATOR . $filename, $matches[2], $matches[1]);
                 }
             }
         }
     }
 }
 /**
  * Create new root page
  *
  * @param  \BackBee\Site\Site       $site       Site object
  * @param  \BackBee\Site\Layout     $layout     Layout object
  *
  * @return \BackBee\NestedNode\Page
  */
 private function createRootPage($site, $layout)
 {
     $pagebuilder = $this->bbapp->getContainer()->get('pagebuilder');
     $pagebuilder->setUid(md5('root-' . $site->getLabel()))->setTitle('Home')->setLayout($layout)->setSite($site)->setUrl('/')->putOnlineAndHidden();
     $page = $pagebuilder->getPage();
     $this->entyMgr->persist($page);
     $this->entyMgr->flush($page);
     return $page;
 }
 /**
  * Returns the static folder path to use.
  *
  * @return string
  */
 protected function getStaticDir()
 {
     $staticDir = $this->app->getContainer()->getParameter('theme.static.dir');
     if (!is_dir($staticDir) && !mkdir($staticDir, 0777, true)) {
         $output->writeln("<error>Unable to read or create the folder '{$staticDir}'</error>");
         exit(1);
     }
     return $staticDir;
 }
 /**
  * Trigger a BackBee\Event\Event depending on the entity and event name.
  *
  * @access protected
  *
  * @param string    $eventName The doctrine event name
  * @param Object    $entity    The entity instance
  * @param EventArgs $eventArgs The doctrine event arguments
  */
 protected function _triggerEvent($eventName, $entity, $eventArgs)
 {
     if (null === $this->_application) {
         return;
     }
     $dispatcher = $this->_application->getEventDispatcher();
     if (null !== $dispatcher) {
         $dispatcher->triggerEvent($eventName, $entity, $eventArgs);
     }
 }
 /**
  * Create new superadmin user
  *
  * @param  string   $login         User name
  * @param  string   $password      User password
  * @param  string   $email         User email
  *
  * @return \BackBee\Security\User   The user object
  */
 private function createUser($login, $password, $email)
 {
     $encoderFactory = $this->bbapp->getContainer()->get('security.context')->getEncoderFactory();
     $adminUser = new \BackBee\Security\User($login, $password, 'SuperAdmin', 'SuperAdmin');
     $adminUser->setApiKeyEnabled(true)->setActivated(true);
     $encoder = $encoderFactory->getEncoder($adminUser);
     $adminUser->setPassword($encoder->encodePassword($password, ''))->setEmail($email)->generateRandomApiKey();
     $this->entyMgr->persist($adminUser);
     $this->entyMgr->flush($adminUser);
     return $adminUser;
 }
 /**
  * Returns the default extension for a site.
  *
  * @param \BackBee\Site\Site $site
  *
  * @return string|null
  */
 private function getDefaultExtFromSite(Site $site = null)
 {
     if (null === $site) {
         $site = $this->application->getSite();
     }
     $extension = null;
     if (null !== $site) {
         $extension = $site->getDefaultExtension();
     }
     return $extension;
 }
 protected function triggerEvent($name = 'render', $object = null, $render = null)
 {
     if (null === $this->application) {
         return;
     }
     $dispatcher = $this->application->getEventDispatcher();
     if (null !== $dispatcher) {
         $object = null !== $object ? $object : $this->getObject();
         $event = new RendererEvent($object, null === $render ? $this : array($this, $render));
         $dispatcher->triggerEvent($name, $object, null, $event);
     }
 }
 /**
  * Format the name of an event.
  *
  * @param string $event_name
  * @param object $entity
  *
  * @return string the formated event name
  */
 private function formatEventName($event_name, $entity)
 {
     if (is_object($entity)) {
         $event_name = strtolower(str_replace(NAMESPACE_SEPARATOR, '.', get_class($entity)) . '.' . $event_name);
         if ($entity instanceof \Doctrine\ORM\Proxy\Proxy) {
             $prefix = str_replace(NAMESPACE_SEPARATOR, '.', $this->application->getEntityManager()->getConfiguration()->getProxyNamespace());
             $prefix .= '.' . $entity::MARKER . '.';
             $event_name = str_replace(strtolower($prefix), '', $event_name);
         }
     } else {
         $event_name = strtolower(str_replace(NAMESPACE_SEPARATOR, '.', $entity) . '.' . $event_name);
     }
     $event_name = str_replace(array('backbee.', 'classcontent.'), array('', ''), $event_name);
     return $event_name;
 }
 /**
  * Hdandles classcontent thumbnail request, returns the right thumbnail if it exists, else the default one.
  *
  * @param string $filename
  *
  * @return Response
  */
 public function getClassContentThumbnailAction($filename)
 {
     $base_folder = $this->application->getContainer()->getParameter('classcontent_thumbnail.base_folder');
     $base_directories = array_map(function ($directory) use($base_folder) {
         return str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $directory . '/' . $base_folder);
     }, $this->application->getResourceDir());
     File::resolveFilepath($filename, null, array('include_path' => $base_directories));
     if (false === file_exists($filename)) {
         $filename = $this->getDefaultClassContentThumbnailFilepath($base_directories);
     }
     if (false === file_exists($filename) || false === is_readable($filename)) {
         $request = $this->application->getRequest();
         throw new FrontControllerException(sprintf('The file `%s` can not be found (referer: %s).', $request->getHost() . '/' . $request->getPathInfo(), $request->server->get('HTTP_REFERER')), FrontControllerException::NOT_FOUND);
     }
     return $this->createResourceResponse($filename);
 }
 private function addBundleRights($bundle_def, $aclProvider, $securityIdentity)
 {
     if (false === array_key_exists('resources', $bundle_def) || false === array_key_exists('actions', $bundle_def)) {
         return null;
     }
     $actions = $this->getActions($bundle_def['actions']);
     if (0 === count($actions)) {
         $this->writeln('Notice: none actions defined on bundle' . PHP_EOL);
         return array();
     }
     if (true === is_array($bundle_def['resources'])) {
         foreach ($bundle_def['resources'] as $bundle_name) {
             if (null !== ($bundle = $this->bbapp->getBundle($bundle_name))) {
                 $this->addObjectAcl($bundle, $aclProvider, $securityIdentity, $actions);
             }
         }
     } elseif ('all' === $bundle_def['resources']) {
         foreach ($this->bbapp->getBundles() as $bundle) {
             $this->addObjectAcl($bundle, $aclProvider, $securityIdentity, $actions);
         }
     }
 }
 /**
  * Handles a media file request.
  *
  * @param string $filename The media file to provide
  *
  * @throws FrontControllerException
  *
  * @return Response
  */
 public function mediaAction($type, $filename, $includePath = array())
 {
     $includePath = array_merge($includePath, array($this->application->getStorageDir(), $this->application->getMediaDir()));
     if (null !== $this->application->getBBUserToken()) {
         $includePath[] = $this->application->getTemporaryDir();
     }
     $matches = array();
     if (preg_match('/([a-f0-9]{3})\\/([a-f0-9]{29})\\/(.*)\\.([^\\.]+)/', $filename, $matches)) {
         $filename = $matches[1] . '/' . $matches[2] . '.' . $matches[4];
     } elseif (preg_match('/([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})\\/.*\\.([^\\.]+)/', $filename, $matches)) {
         $filename = $matches[1] . $matches[2] . $matches[3] . $matches[4] . $matches[5] . $matches[6] . $matches[7] . $matches[8] . '.' . $matches[9];
         File::resolveMediapath($filename, null, array('include_path' => $includePath));
     }
     File::resolveFilepath($filename, null, array('include_path' => $includePath));
     $this->application->info(sprintf('Handling image URL `%s`.', $filename));
     if (false === file_exists($filename) || false === is_readable($filename)) {
         $request = $this->application->getRequest();
         throw new FrontControllerException(sprintf('The file `%s` can not be found (referer: %s).', $request->getHost() . '/' . $request->getPathInfo(), $request->server->get('HTTP_REFERER')), FrontControllerException::NOT_FOUND);
     }
     return $this->createMediaResponse($filename);
 }
 /**
  * Stop the current BBApplication instance.
  *
  * @{inheritdoc}
  * @return void
  */
 public function stop()
 {
     parent::stop();
     exit;
 }
 /**
  * @param BBApplication $bbapp
  */
 public function __construct($bbapp, $dsn)
 {
     if (true === $bbapp->isDebugMode()) {
         parent::__construct($dsn);
     }
 }
 public function __construct(BBApplication $application)
 {
     $this->application = $application;
     $this->renderer = $application->getRenderer();
     $this->response = new Response();
 }
Exemple #30
0
 public function removeThumbnail(Layout $layout, BBApplication $app)
 {
     $thumbnailfile = $layout->getPicPath();
     if (empty($thumbnail)) {
         return true;
     }
     File::resolveFilepath($thumbnailfile, null, array('include_path' => $app->getResourceDir()));
     while (true === is_file($thumbnailfile) && true === is_writable($thumbnailfile)) {
         @unlink($thumbnailfile);
         $thumbnailfile = $layout->getPicPath();
         File::resolveFilepath($thumbnailfile, null, array('include_path' => $app->getResourceDir()));
     }
     return true;
 }