/**
  * 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;
 }
 /**
  * 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;
         }
     }
 }
    /**
     * 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);
        }
    }
 /**
  * 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);
 }
 /**
  * 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;
 }
Ejemplo n.º 7
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());
 }
Ejemplo n.º 8
0
 /**
  * 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));
 }
 /**
  * @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;
 }
Ejemplo n.º 10
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');
 }
 /**
  * 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;
 }
Ejemplo n.º 14
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;
 }
 /**
  * Imports a resource (file) from the given location as a persistent resource.
  * On a successful import this method returns a Resource object representing the
  * newly imported persistent resource.
  *
  * @param string $uri An URI (can also be a path and filename) pointing to the resource to import
  * @return \TYPO3\Flow\Resource\Resource A resource object representing the imported resource or FALSE if an error occurred.
  * @api
  */
 public function importResource($uri)
 {
     $pathInfo = pathinfo($uri);
     if (isset($pathInfo['extension']) && substr(strtolower($pathInfo['extension']), -3, 3) === 'php') {
         $this->systemLogger->log('Import of resources with a "php" extension is not allowed.', LOG_WARNING);
         return FALSE;
     }
     $temporaryTargetPathAndFilename = $this->environment->getPathToTemporaryDirectory() . uniqid('Flow_ResourceImport_');
     if (copy($uri, $temporaryTargetPathAndFilename) === FALSE) {
         $this->systemLogger->log('Could not copy resource from "' . $uri . '" to temporary file "' . $temporaryTargetPathAndFilename . '".', LOG_WARNING);
         return FALSE;
     }
     $hash = sha1_file($temporaryTargetPathAndFilename);
     $finalTargetPathAndFilename = $this->persistentResourcesStorageBaseUri . $hash;
     if (rename($temporaryTargetPathAndFilename, $finalTargetPathAndFilename) === FALSE) {
         unlink($temporaryTargetPathAndFilename);
         $this->systemLogger->log('Could not copy temporary file from "' . $temporaryTargetPathAndFilename . '" to final destination "' . $finalTargetPathAndFilename . '".', LOG_WARNING);
         return FALSE;
     }
     $this->fixFilePermissions($finalTargetPathAndFilename);
     $resource = $this->createResourceFromHashAndFilename($hash, $pathInfo['basename']);
     $this->attachImportedResource($resource);
     return $resource;
 }
 /**
  * Determines the path to the precompiled reflection data.
  *
  * @return string
  */
 protected function getPrecompiledReflectionStoragePath()
 {
     return Files::concatenatePaths([$this->environment->getPathToTemporaryDirectory(), 'PrecompiledReflectionData/']) . '/';
 }
 /**
  * Factory method which creates an EntityManager.
  *
  * @return EntityManager
  * @throws \TYPO3\Flow\Configuration\Exception\InvalidConfigurationException
  */
 public function create()
 {
     $config = new Configuration();
     $config->setClassMetadataFactoryName(Mapping\ClassMetadataFactory::class);
     $cache = new CacheAdapter();
     // must use ObjectManager in compile phase...
     $cache->setCache($this->objectManager->get(CacheManager::class)->getCache('Flow_Persistence_Doctrine'));
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     $resultCache = new CacheAdapter();
     // must use ObjectManager in compile phase...
     $resultCache->setCache($this->objectManager->get(CacheManager::class)->getCache('Flow_Persistence_Doctrine_Results'));
     $config->setResultCacheImpl($resultCache);
     if (is_string($this->settings['doctrine']['sqlLogger']) && class_exists($this->settings['doctrine']['sqlLogger'])) {
         $configuredSqlLogger = $this->settings['doctrine']['sqlLogger'];
         $sqlLoggerInstance = new $configuredSqlLogger();
         if ($sqlLoggerInstance instanceof SQLLogger) {
             $config->setSQLLogger($sqlLoggerInstance);
         } else {
             throw new InvalidConfigurationException(sprintf('TYPO3.Flow.persistence.doctrine.sqlLogger must point to a \\Doctrine\\DBAL\\Logging\\SQLLogger implementation, %s given.', get_class($sqlLoggerInstance)), 1426150388);
         }
     }
     $eventManager = $this->buildEventManager();
     $flowAnnotationDriver = $this->objectManager->get(Mapping\Driver\FlowAnnotationDriver::class);
     $config->setMetadataDriverImpl($flowAnnotationDriver);
     $proxyDirectory = Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'Doctrine/Proxies'));
     Files::createDirectoryRecursively($proxyDirectory);
     $config->setProxyDir($proxyDirectory);
     $config->setProxyNamespace('TYPO3\\Flow\\Persistence\\Doctrine\\Proxies');
     $config->setAutoGenerateProxyClasses(false);
     // Set default host to 127.0.0.1 if there is no host configured but a dbname
     if (empty($this->settings['backendOptions']['host']) && !empty($this->settings['backendOptions']['dbname'])) {
         $this->settings['backendOptions']['host'] = '127.0.0.1';
     }
     // The following code tries to connect first, if that succeeds, all is well. If not, the platform is fetched directly from the
     // driver - without version checks to the database server (to which no connection can be made) - and is added to the config
     // which is then used to create a new connection. This connection will then return the platform directly, without trying to
     // detect the version it runs on, which fails if no connection can be made. But the platform is used even if no connection can
     // be made, which was no problem with Doctrine DBAL 2.3. And then came version-aware drivers and platforms...
     $connection = DriverManager::getConnection($this->settings['backendOptions'], $config, $eventManager);
     try {
         $connection->connect();
     } catch (ConnectionException $exception) {
         $settings = $this->settings['backendOptions'];
         $settings['platform'] = $connection->getDriver()->getDatabasePlatform();
         $connection = DriverManager::getConnection($settings, $config, $eventManager);
     }
     $entityManager = EntityManager::create($connection, $config, $eventManager);
     $flowAnnotationDriver->setEntityManager($entityManager);
     if (isset($this->settings['doctrine']['dbal']['mappingTypes']) && is_array($this->settings['doctrine']['dbal']['mappingTypes'])) {
         foreach ($this->settings['doctrine']['dbal']['mappingTypes'] as $typeName => $typeConfiguration) {
             Type::addType($typeName, $typeConfiguration['className']);
             $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping($typeConfiguration['dbType'], $typeName);
         }
     }
     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);
         }
     }
     if (isset($this->settings['doctrine']['dql']) && is_array($this->settings['doctrine']['dql'])) {
         $this->applyDqlSettingsToConfiguration($this->settings['doctrine']['dql'], $config);
     }
     return $entityManager;
 }
 /**
  * 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)
 {
     if ($this->debug) {
         $this->systemLogger->log('storage ' . $this->name . ': importUploadedResource');
     }
     $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), 1375267007);
     }
     $newSourcePathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'Sbruggmann_FlowKeyCDN_' . 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), 1375267045);
     }
     $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->uploadFile($newSourcePathAndFilename, $originalFilename);
     return $resource;
 }
Ejemplo n.º 19
0
 /**
  * Returns the path to a local file representing this resource for use with read-only file operations such as reading or copying.
  *
  * Note that you must not store or publish file paths returned from this method as they will change with every request.
  *
  * @return string Absolute path and filename pointing to the temporary local copy of this resource
  * @throws Exception
  * @api
  */
 public function createTemporaryLocalCopy()
 {
     if ($this->temporaryLocalCopyPathAndFilename === null) {
         $temporaryPathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'ResourceFiles/';
         try {
             Files::createDirectoryRecursively($temporaryPathAndFilename);
         } catch (\TYPO3\Flow\Utility\Exception $exception) {
             throw new Exception(sprintf('Could not create the temporary directory %s while trying to create a temporary local copy of resource %s (%s).', $temporaryPathAndFilename, $this->sha1, $this->filename), 1416221864);
         }
         $temporaryPathAndFilename .= $this->getCacheEntryIdentifier();
         $temporaryPathAndFilename .= '-' . microtime(true);
         if (function_exists('posix_getpid')) {
             $temporaryPathAndFilename .= '-' . str_pad(posix_getpid(), 10);
         } else {
             $temporaryPathAndFilename .= '-' . (string) getmypid();
         }
         $temporaryPathAndFilename = trim($temporaryPathAndFilename);
         $temporaryFileHandle = fopen($temporaryPathAndFilename, 'w');
         if ($temporaryFileHandle === false) {
             throw new Exception(sprintf('Could not create the temporary file %s while trying to create a temporary local copy of resource %s (%s).', $temporaryPathAndFilename, $this->sha1, $this->filename), 1416221864);
         }
         $resourceStream = $this->getStream();
         if ($resourceStream === false) {
             throw new Exception(sprintf('Could not open stream for resource %s ("%s") from collection "%s" while trying to create a temporary local copy.', $this->sha1, $this->filename, $this->collectionName), 1416221863);
         }
         stream_copy_to_stream($resourceStream, $temporaryFileHandle);
         fclose($resourceStream);
         fclose($temporaryFileHandle);
         $this->temporaryLocalCopyPathAndFilename = $temporaryPathAndFilename;
     }
     return $this->temporaryLocalCopyPathAndFilename;
 }
 /**
  * Initializes the Configuration Manager, the Flow settings and the Environment service
  *
  * @param Bootstrap $bootstrap
  * @return void
  * @throws \TYPO3\Flow\Exception
  */
 public static function initializeConfiguration(Bootstrap $bootstrap)
 {
     $context = $bootstrap->getContext();
     $packageManager = $bootstrap->getEarlyInstance(PackageManagerInterface::class);
     $configurationManager = new ConfigurationManager($context);
     $configurationManager->injectConfigurationSource(new YamlSource());
     $configurationManager->loadConfigurationCache();
     $configurationManager->setPackages($packageManager->getActivePackages());
     $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow');
     $environment = new Environment($context);
     if (isset($settings['utility']['environment']['temporaryDirectoryBase'])) {
         $defaultTemporaryDirectoryBase = FLOW_PATH_DATA . '/Temporary';
         if (FLOW_PATH_TEMPORARY_BASE !== $defaultTemporaryDirectoryBase) {
             throw new \TYPO3\Flow\Exception(sprintf('It seems like the PHP default temporary base path has been changed from "%s" to "%s" via the FLOW_PATH_TEMPORARY_BASE environment variable. If that variable is present, the TYPO3.Flow.utility.environment.temporaryDirectoryBase setting must not be specified!', $defaultTemporaryDirectoryBase, FLOW_PATH_TEMPORARY_BASE), 1447707261);
         }
         $environment->setTemporaryDirectoryBase($settings['utility']['environment']['temporaryDirectoryBase']);
     } else {
         $environment->setTemporaryDirectoryBase(FLOW_PATH_TEMPORARY_BASE);
     }
     $configurationManager->setTemporaryDirectoryPath($environment->getPathToTemporaryDirectory());
     $lockManager = new LockManager($settings['utility']['lockStrategyClassName'], ['lockDirectory' => Files::concatenatePaths([$environment->getPathToTemporaryDirectory(), 'Lock'])]);
     Lock::setLockManager($lockManager);
     $packageManager->injectSettings($settings);
     $bootstrap->getSignalSlotDispatcher()->dispatch(ConfigurationManager::class, 'configurationManagerReady', array($configurationManager));
     $bootstrap->setEarlyInstance(ConfigurationManager::class, $configurationManager);
     $bootstrap->setEarlyInstance(Environment::class, $environment);
 }
 /**
  * Publishes the specified source file to this target, with the given relative path.
  *
  * @param resource $sourceStream
  * @param string $relativeTargetPathAndFilename
  * @param ResourceMetaDataInterface $metaData
  * @throws Exception
  * @return void
  */
 protected function publishFile($sourceStream, $relativeTargetPathAndFilename, ResourceMetaDataInterface $metaData)
 {
     if ($this->debug) {
         $this->systemLogger->log('target ' . $this->name . ': publishFile $relativeTargetPathAndFilename: ' . $relativeTargetPathAndFilename);
     }
     if (!isset($this->existingObjectsInfo)) {
         if ($this->debug) {
             $this->systemLogger->log('target ' . $this->name . ': - publishFile 1');
         }
     }
     $temporaryTargetPathAndFilename = $this->environment->getPathToTemporaryDirectory() . uniqid('TYPO3_Flow_ResourceImport_');
     file_put_contents($temporaryTargetPathAndFilename, $sourceStream);
     $this->uploadFile($temporaryTargetPathAndFilename, $relativeTargetPathAndFilename);
     fclose($sourceStream);
 }
 /**
  * Render a answer level bar chart from the project score
  *
  * @param $project Project
  * @return string The filename of the file
  */
 public function getAnswerLevelBarChartImage($project)
 {
     /* Create and populate the pData object */
     $data = new pData();
     // get and process the basis score data
     $basisScoreData = $this->getScoreData($project);
     $axisLabels = array();
     foreach ($basisScoreData as $category) {
         $axisLabels[] = $category['categoryName'];
     }
     // get the project score
     $scoreData = $this->getProcessedSubmission($project);
     $projectScoreData = array();
     $answeredQuestionRatios = array();
     $thresholdRatios = array();
     foreach ($scoreData['sections'] as $section) {
         $projectScoreData[] = number_format($section['weightedScore'], 2, '.', '\'');
         $answeredQuestionRatios[] = number_format($section['answeredQuestionRatio'] * 100, 0);
         $thresholdRatios[] = number_format($section['thresholdRatio'] * 100, 0);
     }
     // Data for good performance
     $data->addPoints($answeredQuestionRatios, 'answeredQuestionRatio');
     $data->setSerieDescription('answeredQuestionRatio', 'Answer Level');
     $data->setPalette('answeredQuestionRatio', array('R' => 31, 'G' => 119, 'B' => 180));
     // Data for modest performance
     $data->addPoints($thresholdRatios, 'thresholdRatio');
     $data->setSerieDescription('thresholdRatio', 'Threshold');
     $data->setPalette('thresholdRatio', array('R' => 215, 'G' => 32, 'B' => 49));
     $data->setSerieWeight('thresholdRatio', 4);
     /* Define the absissa serie */
     $data->addPoints($axisLabels, 'Categories');
     $data->setAbscissa('Categories');
     $data->setAxisUnit(0, '%');
     /* Create the pChart object */
     $image = new pImage(1800, 1000, $data);
     /* Set the default font properties */
     $fontPath = FLOW_PATH_PACKAGES . 'Application/GIB.GradingTool/Resources/Private/Fonts/Cambria.ttf';
     $image->setFontProperties(array('FontName' => $fontPath, 'FontSize' => 20, 'R' => 0, 'G' => 0, 'B' => 0));
     /* Create the chart */
     $image->setGraphArea(80, 60, 1720, 540);
     $scaleSettings = array('XMargin' => 20, 'YMargin' => 0, 'Factors' => array(1), 'LabelRotation' => 70, 'Floating' => TRUE, 'DrawSubTicks' => TRUE, 'CycleBackground' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'ManualScale' => array(0 => array('Min' => 0, 'Max' => 100)));
     $image->drawScale($scaleSettings);
     $image->setShadow(TRUE, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
     /* Create the bar chart for the answered question ratio */
     $data->setSerieDrawable('answeredQuestionRatio', TRUE);
     $data->setSerieDrawable('thresholdRatio', FALSE);
     $image->drawBarChart(array('Interleave' => 2));
     /* Create the line chart for the threshold ratio */
     $data->setSerieDrawable('answeredQuestionRatio', FALSE);
     $data->setSerieDrawable('thresholdRatio', TRUE);
     $image->drawLineChart(array('DisplayColor' => DISPLAY_AUTO));
     $image->setShadow(FALSE);
     /* Create a legend */
     $data->setSerieDrawable('answeredQuestionRatio', TRUE);
     $data->setSerieDrawable('thresholdRatio', TRUE);
     $legendOptions = array('Style' => LEGEND_BOX, 'Mode' => LEGEND_HORIZONTAL, 'FontSize' => 30, 'R' => 255, 'G' => 255, 'B' => 255, 'IconAreaWidth' => 50, 'IconAreaHeight' => 50, 'BoxWidth' => 25, 'BoxHeight' => 25);
     $image->drawLegend(0, 900, $legendOptions);
     $temporaryBarChartFile = tempnam($this->environmentUtility->getPathToTemporaryDirectory(), 'barchart.png');
     $image->render($temporaryBarChartFile);
     return $temporaryBarChartFile;
 }
Ejemplo n.º 23
0
 /**
  * @Given /^I have the following policies:$/
  */
 public function iHaveTheFollowingPolicies(PyStringNode $string)
 {
     $testingPolicyPathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'Policy.yaml';
     file_put_contents($testingPolicyPathAndFilename, $string->getRaw());
 }