/**
  * Creates the mocked filesystem used in the tests
  */
 public function setUp()
 {
     vfsStream::setup('Foo');
     $this->mockEnvironment = $this->getMock('TYPO3\\Flow\\Utility\\Environment', array(), array(), '', FALSE);
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://Foo/'));
     $this->mockEnvironment->expects($this->any())->method('getMaximumPathLength')->will($this->returnValue(1024));
 }
 /**
  * Factory method which creates an EntityManager.
  *
  * @return \Doctrine\ORM\EntityManager
  */
 public function create()
 {
     $config = new \Doctrine\ORM\Configuration();
     $config->setClassMetadataFactoryName('TYPO3\\Flow\\Persistence\\Doctrine\\Mapping\\ClassMetadataFactory');
     $cache = new \TYPO3\Flow\Persistence\Doctrine\CacheAdapter();
     // must use ObjectManager in compile phase...
     $cache->setCache($this->objectManager->get('TYPO3\\Flow\\Cache\\CacheManager')->getCache('Flow_Persistence_Doctrine'));
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     $resultCache = new \TYPO3\Flow\Persistence\Doctrine\CacheAdapter();
     // must use ObjectManager in compile phase...
     $resultCache->setCache($this->objectManager->get('TYPO3\\Flow\\Cache\\CacheManager')->getCache('Flow_Persistence_Doctrine_Results'));
     $config->setResultCacheImpl($resultCache);
     if (class_exists($this->settings['doctrine']['sqlLogger'])) {
         $config->setSQLLogger(new $this->settings['doctrine']['sqlLogger']());
     }
     $eventManager = $this->buildEventManager();
     $flowAnnotationDriver = $this->objectManager->get('TYPO3\\Flow\\Persistence\\Doctrine\\Mapping\\Driver\\FlowAnnotationDriver');
     $config->setMetadataDriverImpl($flowAnnotationDriver);
     $proxyDirectory = \TYPO3\Flow\Utility\Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'Doctrine/Proxies'));
     \TYPO3\Flow\Utility\Files::createDirectoryRecursively($proxyDirectory);
     $config->setProxyDir($proxyDirectory);
     $config->setProxyNamespace('TYPO3\\Flow\\Persistence\\Doctrine\\Proxies');
     $config->setAutoGenerateProxyClasses(FALSE);
     $entityManager = \Doctrine\ORM\EntityManager::create($this->settings['backendOptions'], $config, $eventManager);
     $flowAnnotationDriver->setEntityManager($entityManager);
     \Doctrine\DBAL\Types\Type::addType('objectarray', 'TYPO3\\Flow\\Persistence\\Doctrine\\DataTypes\\ObjectArray');
     if (isset($this->settings['doctrine']['filters']) && is_array($this->settings['doctrine']['filters'])) {
         foreach ($this->settings['doctrine']['filters'] as $filterName => $filterClass) {
             $config->addFilter($filterName, $filterClass);
             $entityManager->getFilters()->enable($filterName);
         }
     }
     return $entityManager;
 }
 /**
  * @test
  * @expectedException \TYPO3\Flow\Cache\Exception
  */
 public function setCacheThrowsExceptionOnNonWritableDirectory()
 {
     $this->mockEnvironment = $this->getMockBuilder(\TYPO3\Flow\Utility\Environment::class)->disableOriginalConstructor()->getMock();
     $this->mockEnvironment->expects($this->any())->method('getMaximumPathLength')->will($this->returnValue(1024));
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://non/existing/directory'));
     $this->getSimpleFileBackend();
 }
 public function setUp()
 {
     $this->mockDirectory = vfsStream::setup('WritableFileSystemStorageTest');
     $this->writableFileSystemStorage = $this->getAccessibleMock(WritableFileSystemStorage::class, null, ['testStorage', ['path' => 'vfs://WritableFileSystemStorageTest/']]);
     $this->mockEnvironment = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock();
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://WritableFileSystemStorageTest/'));
     $this->inject($this->writableFileSystemStorage, 'environment', $this->mockEnvironment);
 }
 /**
  * @Flow\Around("method(TYPO3\Neos\Domain\Repository\DomainRepository->findOneByActiveRequest())")
  * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point
  * @return mixed
  */
 public function cacheDomainForActiveRequest(JoinPointInterface $joinPoint)
 {
     if ($this->domainForActiveRequest === FALSE || $this->environment->getContext()->isTesting()) {
         $domain = $joinPoint->getAdviceChain()->proceed($joinPoint);
         $this->domainForActiveRequest = $domain;
     }
     return $this->domainForActiveRequest;
 }
 /**
  * Creates the mocked filesystem used in the tests
  */
 public function setUp()
 {
     vfsStream::setup('Foo');
     $this->mockEnvironment = $this->getMock(\TYPO3\Flow\Utility\Environment::class, array(), array(), '', FALSE);
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://Foo/'));
     $this->mockEnvironment->expects($this->any())->method('getMaximumPathLength')->will($this->returnValue(1024));
     $this->mockCacheManager = $this->getMock(\TYPO3\Flow\Cache\CacheManager::class, array('registerCache'), array(), '', FALSE);
     $this->mockCacheManager->expects($this->any())->method('isCachePersistent')->will($this->returnValue(FALSE));
 }
 /**
  * Creates the mocked filesystem used in the tests
  */
 public function setUp()
 {
     vfsStream::setup('Foo');
     $this->mockEnvironment = $this->getMockBuilder(\TYPO3\Flow\Utility\Environment::class)->disableOriginalConstructor()->getMock();
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://Foo/'));
     $this->mockEnvironment->expects($this->any())->method('getMaximumPathLength')->will($this->returnValue(1024));
     $this->mockCacheManager = $this->getMockBuilder(\TYPO3\Flow\Cache\CacheManager::class)->disableOriginalConstructor()->setMethods(array('registerCache', 'isCachePersistent'))->getMock();
     $this->mockCacheManager->expects($this->any())->method('isCachePersistent')->will($this->returnValue(false));
 }
 /**
  * Initializes the controller
  */
 protected function initializeAction()
 {
     $context = $this->env->getContext();
     if ($context == 'Development') {
         $this->context = 'DEV';
     } else {
         $this->context = 'PRD';
     }
 }
 /**
  * Initializes the manager
  *
  * @return void
  */
 public function initializeObject()
 {
     $this->lockPathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'Flow.lock';
     if (file_exists($this->lockPathAndFilename)) {
         if (filemtime($this->lockPathAndFilename) < time() - self::LOCKFILE_MAXIMUM_AGE) {
             unlink($this->lockPathAndFilename);
         } else {
             $this->siteLocked = TRUE;
         }
     }
 }
 /**
  * Handle an exception depending on the context with an HTML message or XML comment
  *
  * @param array $typoScriptPath path causing the exception
  * @param \Exception $exception exception to handle
  * @param integer $referenceCode
  * @return string
  */
 protected function handle($typoScriptPath, \Exception $exception, $referenceCode)
 {
     $context = $this->environment->getContext();
     if ($context->isDevelopment()) {
         $handler = new HtmlMessageHandler();
     } else {
         $handler = new XmlCommentHandler();
     }
     $handler->setRuntime($this->getRuntime());
     return $handler->handleRenderingException($typoScriptPath, $exception);
 }
 /**
  * Initializes the controller
  */
 protected function initializeAction()
 {
     $context = $this->env->getContext();
     if ($context == 'Development') {
         $this->context = 'DEV';
     } else {
         $this->context = 'PRD';
     }
     $this->connection = new Es\ElasticSearchConnection();
     $this->connection->init();
 }
 public function setUp()
 {
     vfsStream::setup('Foo');
     $this->cacheManager = new \TYPO3\Flow\Cache\CacheManager();
     $this->mockEnvironment = $this->getMockBuilder(\TYPO3\Flow\Utility\Environment::class)->disableOriginalConstructor()->getMock();
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://Foo/'));
     $this->cacheManager->injectEnvironment($this->mockEnvironment);
     $this->mockSystemLogger = $this->getMock(\TYPO3\Flow\Log\SystemLoggerInterface::class);
     $this->cacheManager->injectSystemLogger($this->mockSystemLogger);
     $this->mockConfigurationManager = $this->getMockBuilder(\TYPO3\Flow\Configuration\ConfigurationManager::class)->disableOriginalConstructor()->getMock();
     $this->cacheManager->injectConfigurationManager($this->mockConfigurationManager);
 }
 /**
  * Initializes the controller
  */
 protected function initializeAction()
 {
     date_default_timezone_set('UTC');
     $context = $this->env->getContext();
     if ($context == 'Development') {
         $this->context = 'DEV';
     } else {
         $this->context = 'PRD';
     }
     $this->connection = new Es\ElasticSearchConnection();
     $this->connection->init();
     $this->sprintConfig = $this->ConfigurationManager->getConfiguration('Sprints');
 }
 protected function initializeAction()
 {
     date_default_timezone_set('UTC');
     $this->connection = new Es\ElasticSearchConnection();
     $this->connection->init();
     $context = $this->env->getContext();
     if ($context == 'Development') {
         $this->context = 'DEV';
     } else {
         $this->context = 'PRD';
     }
     if (isset($_GET['page'])) {
         $this->currentPage = intval($_GET['page']);
     }
 }
Example #15
0
 /**
  * Verifies the authentication token.
  *
  * @param string $authenticationHash
  * @param string $parameters
  *
  */
 private function verifyAuthentication($authenticationHash, $parameters)
 {
     if (md5($this->settings['webserviceKey'] . $parameters) == $authenticationHash || $this->environment->getContext() == 'Development') {
         return TRUE;
     }
     return FALSE;
 }
    /**
     * Saves the current configuration into a cache file and creates a cache inclusion script
     * in the context's Configuration directory.
     *
     * @return void
     * @throws Exception
     */
    protected function saveConfigurationCache()
    {
        $configurationCachePath = $this->environment->getPathToTemporaryDirectory() . 'Configuration/';
        if (!file_exists($configurationCachePath)) {
            Files::createDirectoryRecursively($configurationCachePath);
        }
        $cachePathAndFilename = $configurationCachePath . str_replace('/', '_', (string) $this->context) . 'Configurations.php';
        $flowRootPath = FLOW_PATH_ROOT;
        $includeCachedConfigurationsCode = <<<EOD
<?php
if (FLOW_PATH_ROOT !== '{$flowRootPath}' || !file_exists('{$cachePathAndFilename}')) {
\tunlink(__FILE__);
\treturn array();
}
return require '{$cachePathAndFilename}';
EOD;
        file_put_contents($cachePathAndFilename, '<?php return ' . var_export($this->configurations, TRUE) . ';');
        if (!is_dir(dirname($this->includeCachedConfigurationsPathAndFilename)) && !is_link(dirname($this->includeCachedConfigurationsPathAndFilename))) {
            Files::createDirectoryRecursively(dirname($this->includeCachedConfigurationsPathAndFilename));
        }
        file_put_contents($this->includeCachedConfigurationsPathAndFilename, $includeCachedConfigurationsCode);
        if (!file_exists($this->includeCachedConfigurationsPathAndFilename)) {
            throw new Exception(sprintf('Could not write configuration cache file "%s". Check file permissions for the parent directory.', $this->includeCachedConfigurationsPathAndFilename), 1323339284);
        }
    }
 /**
  * Gets the patch as zip package from gerrit
  *
  * @param int $patchId
  * @return bool|string
  * @throws \TYPO3\Flow\Utility\Exception
  */
 public function getPatchFromGerrit($patchId)
 {
     $uri = sprintf($this->gerritApiPattern, $patchId, 'revisions/current/patch?zip');
     $outputDirectory = Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'GerritPatches'));
     Files::createDirectoryRecursively($outputDirectory);
     $outputZipFilePath = Files::concatenatePaths(array($outputDirectory, $patchId . '.zip'));
     $httpClient = new Client();
     $httpClient->get($uri)->setResponseBody($outputZipFilePath)->send();
     $zip = new \ZipArchive();
     $zip->open($outputZipFilePath);
     $patchFile = $zip->getNameIndex(0);
     $zip->extractTo($outputDirectory);
     $zip->close();
     Files::unlink($outputZipFilePath);
     return Files::concatenatePaths(array($outputDirectory, $patchFile));
 }
 /**
  * @test
  * @expectedException \TYPO3\Flow\Cache\Exception
  */
 public function setCacheThrowsExceptionIfCachePathLengthExceedsMaximumPathLength()
 {
     $this->mockEnvironment = $this->getMockBuilder('TYPO3\\Flow\\Utility\\Environment')->disableOriginalConstructor()->getMock();
     $this->mockEnvironment->expects($this->any())->method('getMaximumPathLength')->will($this->returnValue(5));
     $this->mockEnvironment->expects($this->any())->method('getPathToTemporaryDirectory')->will($this->returnValue('vfs://Temporary/Directory/'));
     $this->getSimpleFileBackend();
 }
 /**
  * Creates a Doctrine ODM DocumentManager
  *
  * @return \Doctrine\ODM\CouchDB\DocumentManager
  */
 public function create()
 {
     if (isset($this->documentManager)) {
         return $this->documentManager;
     }
     $httpClient = new \Doctrine\CouchDB\HTTP\SocketClient($this->settings['host'], $this->settings['port'], $this->settings['username'], $this->settings['password'], $this->settings['ip']);
     $reader = new \Doctrine\Common\Annotations\AnnotationReader();
     $metaDriver = new \Doctrine\ODM\CouchDB\Mapping\Driver\AnnotationDriver($reader);
     $config = new \Doctrine\ODM\CouchDB\Configuration();
     $config->setMetadataDriverImpl($metaDriver);
     $packages = $this->packageManager->getActivePackages();
     foreach ($packages as $package) {
         $designDocumentRootPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($package->getPackagePath(), 'Migrations/CouchDB/DesignDocuments'));
         if (is_dir($designDocumentRootPath)) {
             $packageDesignDocumentFolders = glob($designDocumentRootPath . '/*');
             foreach ($packageDesignDocumentFolders as $packageDesignDocumentFolder) {
                 if (is_dir($packageDesignDocumentFolder)) {
                     $designDocumentName = strtolower(basename($packageDesignDocumentFolder));
                     $config->addDesignDocument($designDocumentName, 'Radmiraal\\CouchDB\\View\\Migration', array('packageKey' => $package->getPackageKey(), 'path' => $packageDesignDocumentFolder));
                 }
             }
         }
     }
     $proxyDirectory = \TYPO3\Flow\Utility\Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'DoctrineODM/Proxies'));
     \TYPO3\Flow\Utility\Files::createDirectoryRecursively($proxyDirectory);
     $config->setProxyDir($proxyDirectory);
     $config->setProxyNamespace('TYPO3\\Flow\\Persistence\\DoctrineODM\\Proxies');
     $config->setAutoGenerateProxyClasses(TRUE);
     $couchClient = new \Doctrine\CouchDB\CouchDBClient($httpClient, $this->settings['databaseName']);
     $this->documentManager = \Doctrine\ODM\CouchDB\DocumentManager::create($couchClient, $config);
     return $this->documentManager;
 }
 /**
  * Explicitly compile proxy classes
  *
  * The compile command triggers the proxy class compilation.
  * Although a compilation run is triggered automatically by Flow, there might
  * be cases in a production context where a manual compile run is needed.
  *
  * @Flow\Internal
  * @param boolean $force If set, classes will be compiled even though the cache says that everything is up to date.
  * @return void
  */
 public function compileCommand($force = false)
 {
     /** @var VariableFrontend $objectConfigurationCache */
     $objectConfigurationCache = $this->cacheManager->getCache('Flow_Object_Configuration');
     if ($force === false) {
         if ($objectConfigurationCache->has('allCompiledCodeUpToDate')) {
             return;
         }
     }
     /** @var PhpFrontend $classesCache */
     $classesCache = $this->cacheManager->getCache('Flow_Object_Classes');
     $this->proxyClassCompiler->injectClassesCache($classesCache);
     $this->aopProxyClassBuilder->injectObjectConfigurationCache($objectConfigurationCache);
     $this->aopProxyClassBuilder->build();
     $this->dependencyInjectionProxyClassBuilder->build();
     $classCount = $this->proxyClassCompiler->compile();
     $dataTemporaryPath = $this->environment->getPathToTemporaryDirectory();
     Files::createDirectoryRecursively($dataTemporaryPath);
     file_put_contents($dataTemporaryPath . 'AvailableProxyClasses.php', $this->proxyClassCompiler->getStoredProxyClassMap());
     $objectConfigurationCache->set('allCompiledCodeUpToDate', true);
     $classesCacheBackend = $classesCache->getBackend();
     if ($this->bootstrap->getContext()->isProduction() && $classesCacheBackend instanceof FreezableBackendInterface) {
         /** @var FreezableBackendInterface $backend */
         $backend = $classesCache->getBackend();
         $backend->freeze();
     }
     $this->emitFinishedCompilationRun($classCount);
 }
 /**
  * Flush all caches
  *
  * The flush command flushes all caches (including code caches) which have been
  * registered with Flow's Cache Manager. It also removes any session data.
  *
  * If fatal errors caused by a package prevent the compile time bootstrap
  * from running, the removal of any temporary data can be forced by specifying
  * the option <b>--force</b>.
  *
  * This command does not remove the precompiled data provided by frozen
  * packages unless the <b>--force</b> option is used.
  *
  * @param boolean $force Force flushing of any temporary data
  * @return void
  * @see typo3.flow:cache:warmup
  * @see typo3.flow:package:freeze
  * @see typo3.flow:package:refreeze
  */
 public function flushCommand($force = FALSE)
 {
     // Internal note: the $force option is evaluated early in the Flow
     // bootstrap in order to reliably flush the temporary data before any
     // other code can cause fatal errors.
     $this->cacheManager->flushCaches();
     $dataTemporaryPath = $this->environment->getPathToTemporaryDirectory();
     Files::unlink($dataTemporaryPath . 'AvailableProxyClasses.php');
     $this->outputLine('Flushed all caches for "' . $this->bootstrap->getContext() . '" context.');
     if ($this->lockManager->isSiteLocked()) {
         $this->lockManager->unlockSite();
     }
     $frozenPackages = array();
     foreach (array_keys($this->packageManager->getActivePackages()) as $packageKey) {
         if ($this->packageManager->isPackageFrozen($packageKey)) {
             $frozenPackages[] = $packageKey;
         }
     }
     if ($frozenPackages !== array()) {
         $this->outputFormatted(PHP_EOL . 'Please note that the following package' . (count($frozenPackages) === 1 ? ' is' : 's are') . ' currently frozen: ' . PHP_EOL);
         $this->outputFormatted(implode(PHP_EOL, $frozenPackages) . PHP_EOL, array(), 2);
         $message = 'As code and configuration changes in these packages are not detected, the application may respond ';
         $message .= 'unexpectedly if modifications were done anyway or the remaining code relies on these changes.' . PHP_EOL . PHP_EOL;
         $message .= 'You may call <b>package:refreeze all</b> in order to refresh frozen packages or use the <b>--force</b> ';
         $message .= 'option of this <b>cache:flush</b> command to flush caches if Flow becomes unresponsive.' . PHP_EOL;
         $this->outputFormatted($message, array($frozenPackages));
     }
     $this->sendAndExit(0);
 }
 /**
  * Compiles the Doctrine proxy class code using the Doctrine ProxyFactory.
  *
  * @return void
  */
 public function compileProxies()
 {
     Files::emptyDirectoryRecursively(Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'Doctrine/Proxies')));
     /** @var \Doctrine\ORM\Proxy\ProxyFactory $proxyFactory */
     $proxyFactory = $this->entityManager->getProxyFactory();
     $proxyFactory->generateProxyClasses($this->entityManager->getMetadataFactory()->getAllMetadata());
 }
 /**
  * @param FlowResource $originalResource
  * @param array $adjustments
  * @return array resource, width, height as keys
  * @throws ImageFileException
  * @throws InvalidConfigurationException
  * @throws \TYPO3\Flow\Resource\Exception
  */
 public function processImage(FlowResource $originalResource, array $adjustments)
 {
     $additionalOptions = array();
     $adjustmentsApplied = false;
     // TODO: Special handling for SVG should be refactored at a later point.
     if ($originalResource->getMediaType() === 'image/svg+xml') {
         $originalResourceStream = $originalResource->getStream();
         $resource = $this->resourceManager->importResource($originalResourceStream, $originalResource->getCollectionName());
         fclose($originalResourceStream);
         $resource->setFilename($originalResource->getFilename());
         return ['width' => null, 'height' => null, 'resource' => $resource];
     }
     $resourceUri = $originalResource->createTemporaryLocalCopy();
     $resultingFileExtension = $originalResource->getFileExtension();
     $transformedImageTemporaryPathAndFilename = $this->environment->getPathToTemporaryDirectory() . uniqid('ProcessedImage-') . '.' . $resultingFileExtension;
     if (!file_exists($resourceUri)) {
         throw new ImageFileException(sprintf('An error occurred while transforming an image: the resource data of the original image does not exist (%s, %s).', $originalResource->getSha1(), $resourceUri), 1374848224);
     }
     $imagineImage = $this->imagineService->open($resourceUri);
     if ($this->imagineService instanceof \Imagine\Imagick\Imagine && $originalResource->getFileExtension() === 'gif' && $this->isAnimatedGif(file_get_contents($resourceUri)) === true) {
         $imagineImage->layers()->coalesce();
         $layers = $imagineImage->layers();
         $newLayers = array();
         foreach ($layers as $index => $imagineFrame) {
             $imagineFrame = $this->applyAdjustments($imagineFrame, $adjustments, $adjustmentsApplied);
             $newLayers[] = $imagineFrame;
         }
         $imagineImage = array_shift($newLayers);
         $layers = $imagineImage->layers();
         foreach ($newLayers as $imagineFrame) {
             $layers->add($imagineFrame);
         }
         $additionalOptions['animated'] = true;
     } else {
         $imagineImage = $this->applyAdjustments($imagineImage, $adjustments, $adjustmentsApplied);
     }
     if ($adjustmentsApplied === true) {
         $imagineImage->save($transformedImageTemporaryPathAndFilename, $this->getOptionsMergedWithDefaults($additionalOptions));
         $imageSize = $imagineImage->getSize();
         // TODO: In the future the collectionName of the new resource should be configurable.
         $resource = $this->resourceManager->importResource($transformedImageTemporaryPathAndFilename, $originalResource->getCollectionName());
         if ($resource === false) {
             throw new ImageFileException('An error occurred while importing a generated image file as a resource.', 1413562208);
         }
         unlink($transformedImageTemporaryPathAndFilename);
         $pathInfo = UnicodeFunctions::pathinfo($originalResource->getFilename());
         $resource->setFilename(sprintf('%s-%ux%u.%s', $pathInfo['filename'], $imageSize->getWidth(), $imageSize->getHeight(), $pathInfo['extension']));
     } else {
         $originalResourceStream = $originalResource->getStream();
         $resource = $this->resourceManager->importResource($originalResourceStream, $originalResource->getCollectionName());
         fclose($originalResourceStream);
         $resource->setFilename($originalResource->getFilename());
         $imageSize = $this->getImageSize($originalResource);
         $imageSize = new Box($imageSize['width'], $imageSize['height']);
     }
     $this->imageSizeCache->set($resource->getCacheEntryIdentifier(), array('width' => $imageSize->getWidth(), 'height' => $imageSize->getHeight()));
     $result = array('width' => $imageSize->getWidth(), 'height' => $imageSize->getHeight(), 'resource' => $resource);
     return $result;
 }
 /**
  * renders the exception to nice html content element to display, edit, remove, ...
  *
  * @param string $typoScriptPath - path causing the exception
  * @param \Exception $exception - exception to handle
  * @param integer $referenceCode - might be unset
  * @return string
  */
 protected function handle($typoScriptPath, \Exception $exception, $referenceCode)
 {
     $handler = new ContextDependentHandler();
     $handler->setRuntime($this->runtime);
     $output = $handler->handleRenderingException($typoScriptPath, $exception);
     $currentContext = $this->getRuntime()->getCurrentContext();
     if (isset($currentContext['node'])) {
         /** @var NodeInterface $node */
         $node = $currentContext['node'];
         $applicationContext = $this->environment->getContext();
         if ($applicationContext->isProduction() && $this->privilegeManager->isPrivilegeTargetGranted('TYPO3.Neos:Backend.GeneralAccess') && $node->getContext()->getWorkspaceName() !== 'live') {
             $output = '<div class="neos-rendering-exception"><div class="neos-rendering-exception-title">Failed to render element' . $output . '</div></div>';
         }
         return $this->contentElementWrappingService->wrapContentObject($node, $output, $typoScriptPath);
     }
     return $output;
 }
Example #25
0
 /**
  * @param string $sitePackage
  * @param string $siteName
  * @param string $baseDomain
  * @return Site
  */
 public function importSiteFromTemplate($sitePackage, $siteName, $baseDomain = '')
 {
     if (empty($baseDomain)) {
         $request = Request::createFromEnvironment();
         $baseDomain = $request->getBaseUri()->getHost();
     }
     $siteTemplate = new StandaloneView();
     $siteTemplate->setTemplatePathAndFilename(FLOW_PATH_PACKAGES . 'Sites/' . $sitePackage . '/Resources/Private/Templates/Content/Sites.xml');
     $siteTemplate->assignMultiple(['siteName' => $siteName, 'siteNodeName' => \TYPO3\TYPO3CR\Utility::renderValidNodeName($siteName), 'packageKey' => $sitePackage]);
     $generatedSiteImportXmlContent = $siteTemplate->render();
     $dataTemporaryPath = $this->environment->getPathToTemporaryDirectory();
     $temporarySiteXml = $dataTemporaryPath . uniqid($siteName) . '.xml';
     file_put_contents($temporarySiteXml, $generatedSiteImportXmlContent);
     $site = $this->siteImportService->importFromFile($temporarySiteXml);
     $domain = new Domain();
     $domain->setActive(true);
     $domain->setSite($site);
     $domain->setHostPattern(\TYPO3\TYPO3CR\Utility::renderValidNodeName($siteName) . '.' . $baseDomain);
     $this->domainRepository->add($domain);
     return $site;
 }
 /**
  * Flushes all registered caches
  *
  * @param boolean $flushPersistentCaches If set to TRUE, even those caches which are flagged as "persistent" will be flushed
  * @return void
  * @api
  */
 public function flushCaches($flushPersistentCaches = FALSE)
 {
     $this->createAllCaches();
     /** @var FrontendInterface $cache */
     foreach ($this->caches as $identifier => $cache) {
         if (!$flushPersistentCaches && $this->isCachePersistent($identifier)) {
             continue;
         }
         $cache->flush();
     }
     $this->configurationManager->flushConfigurationCache();
     $dataTemporaryPath = $this->environment->getPathToTemporaryDirectory();
     Files::unlink($dataTemporaryPath . 'AvailableProxyClasses.php');
 }
 /**
  * Builds the URI
  *
  * @param array $arguments optional URI arguments. Will be merged with $this->arguments with precedence to $arguments
  * @return string The URI
  * @api
  */
 public function build(array $arguments = array())
 {
     $arguments = Arrays::arrayMergeRecursiveOverrule($this->arguments, $arguments);
     $arguments = $this->mergeArgumentsWithRequestArguments($arguments);
     $uri = $this->router->resolve($arguments);
     $this->lastArguments = $arguments;
     if (!$this->environment->isRewriteEnabled()) {
         $uri = 'index.php/' . $uri;
     }
     $httpRequest = $this->request->getHttpRequest();
     if ($this->createAbsoluteUri === true) {
         $uri = $httpRequest->getBaseUri() . $uri;
     } elseif (!$this->createRelativePaths) {
         $uri = $httpRequest->getScriptRequestPath() . $uri;
     }
     if ($this->section !== '') {
         $uri .= '#' . $this->section;
     }
     return $uri;
 }
 /**
  * Prepare an uploaded file to be imported as resource object. Will check the validity of the file,
  * move it outside of upload folder if open_basedir is enabled and check the filename.
  *
  * @param array $uploadInfo
  * @return array Array of string with the two keys "filepath" (the path to get the filecontent from) and "filename" the filename of the originally uploaded file.
  * @throws Exception
  */
 protected function prepareUploadedFileForImport(array $uploadInfo)
 {
     $openBasedirEnabled = (bool) ini_get('open_basedir');
     $temporaryTargetPathAndFilename = $uploadInfo['tmp_name'];
     $pathInfo = UnicodeFunctions::pathinfo($uploadInfo['name']);
     if (!is_uploaded_file($temporaryTargetPathAndFilename)) {
         throw new Exception('The given upload file "' . strip_tags($pathInfo['basename']) . '" was not uploaded through PHP. As it could pose a security risk it cannot be imported.', 1422461503);
     }
     if ($openBasedirEnabled === TRUE) {
         // Move uploaded file to a readable folder before trying to read sha1 value of file
         $newTemporaryTargetPathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'ResourceUpload.' . uniqid() . '.tmp';
         if (move_uploaded_file($temporaryTargetPathAndFilename, $newTemporaryTargetPathAndFilename) === FALSE) {
             throw new Exception(sprintf('The uploaded file "%s" could not be moved to the temporary location "%s".', $temporaryTargetPathAndFilename, $newTemporaryTargetPathAndFilename), 1375199056);
         }
         $temporaryTargetPathAndFilename = $newTemporaryTargetPathAndFilename;
     }
     if (!is_file($temporaryTargetPathAndFilename)) {
         throw new Exception(sprintf('The temporary file "%s" of the file upload does not exist (anymore).', $temporaryTargetPathAndFilename), 1375198998);
     }
     return array('filepath' => $temporaryTargetPathAndFilename, 'filename' => $pathInfo['basename']);
 }
 /**
  * Returns the publish path and filename to be used to publish the specified persistent resource
  *
  * @Flow\Around("method(TYPO3\Flow\Resource\Publishing\FileSystemPublishingTarget->buildPersistentResourcePublishPathAndFilename()) && setting(TYPO3.Flow.security.enable)")
  * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point
  * @return mixed Result of the target method
  */
 public function rewritePersistentResourcePublishPathAndFilenameForPrivateResources(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint)
 {
     $resource = $joinPoint->getMethodArgument('resource');
     /** @var $configuration \TYPO3\Flow\Security\Authorization\Resource\SecurityPublishingConfiguration */
     $configuration = $resource->getPublishingConfiguration();
     $returnFilename = $joinPoint->getMethodArgument('returnFilename');
     if ($configuration === NULL || $configuration instanceof \TYPO3\Flow\Security\Authorization\Resource\SecurityPublishingConfiguration === FALSE) {
         return $joinPoint->getAdviceChain()->proceed($joinPoint);
     }
     $publishingPath = FALSE;
     $allowedRoles = $configuration->getAllowedRoles();
     if (count(array_intersect($allowedRoles, $this->securityContext->getRoles())) > 0) {
         $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($joinPoint->getProxy()->getResourcesPublishingPath(), 'Persistent/', $this->session->getID())) . '/';
         $filename = $resource->getResourcePointer()->getHash() . '.' . $resource->getFileExtension();
         \TYPO3\Flow\Utility\Files::createDirectoryRecursively($publishingPath);
         $this->accessRestrictionPublisher->publishAccessRestrictionsForPath($publishingPath);
         if ($this->settings['resource']['publishing']['fileSystem']['mirrorMode'] === 'link') {
             foreach ($allowedRoles as $role) {
                 $roleDirectory = \TYPO3\Flow\Utility\Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'PrivateResourcePublishing/', $role));
                 \TYPO3\Flow\Utility\Files::createDirectoryRecursively($roleDirectory);
                 if (file_exists($publishingPath . $role)) {
                     if (\TYPO3\Flow\Utility\Files::is_link(\TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))) && realpath(\TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))) === $roleDirectory) {
                         continue;
                     }
                     unlink($publishingPath . $role);
                     symlink($roleDirectory, \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role)));
                 } else {
                     symlink($roleDirectory, \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role)));
                 }
             }
             $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $allowedRoles[0])) . '/';
         }
         if ($returnFilename === TRUE) {
             $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $filename));
         }
     }
     return $publishingPath;
 }
Example #30
0
 /**
  * Imports a resource (file) as specified in the given upload info array as a
  * persistent resource.
  *
  * On a successful import this method returns a Resource object representing
  * the newly imported persistent resource.
  *
  * @param array $uploadInfo An array detailing the resource to import (expected keys: name, tmp_name)
  * @param string $collectionName Name of the collection this uploaded resource should be part of
  * @return string A resource object representing the imported resource
  * @throws Exception
  * @api
  */
 public function importUploadedResource(array $uploadInfo, $collectionName)
 {
     $pathInfo = pathinfo($uploadInfo['name']);
     $originalFilename = $pathInfo['basename'];
     $sourcePathAndFilename = $uploadInfo['tmp_name'];
     if (!file_exists($sourcePathAndFilename)) {
         throw new Exception(sprintf('The temporary file "%s" of the file upload does not exist (anymore).', $sourcePathAndFilename), 1428909075);
     }
     $newSourcePathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'Flownative_Aws_S3_' . uniqid() . '.tmp';
     if (move_uploaded_file($sourcePathAndFilename, $newSourcePathAndFilename) === false) {
         throw new Exception(sprintf('The uploaded file "%s" could not be moved to the temporary location "%s".', $sourcePathAndFilename, $newSourcePathAndFilename), 1428909076);
     }
     $sha1Hash = sha1_file($newSourcePathAndFilename);
     $md5Hash = md5_file($newSourcePathAndFilename);
     $resource = new Resource();
     $resource->setFilename($originalFilename);
     $resource->setCollectionName($collectionName);
     $resource->setFileSize(filesize($newSourcePathAndFilename));
     $resource->setSha1($sha1Hash);
     $resource->setMd5($md5Hash);
     $this->s3Client->putObject(array('Bucket' => $this->bucketName, 'Body' => fopen($newSourcePathAndFilename, 'rb'), 'ContentLength' => $resource->getFileSize(), 'ContentType' => $resource->getMediaType(), 'Key' => $this->keyPrefix . $sha1Hash));
     return $resource;
 }