/**
  * Provides an XML comment containing the exception
  *
  * @param string $typoScriptPath path causing the exception
  * @param \Exception $exception exception to handle
  * @param integer $referenceCode
  * @return string
  */
 protected function handle($typoScriptPath, \Exception $exception, $referenceCode)
 {
     $this->systemLogger->logException($exception);
     if (isset($referenceCode)) {
         return sprintf('<!-- Exception while rendering %s: %s (%s) -->', $this->formatScriptPath($typoScriptPath, ''), htmlspecialchars($exception->getMessage()), $referenceCode);
     } else {
         return sprintf('<!-- Exception while rendering %s: %s -->', $this->formatScriptPath($typoScriptPath, ''), htmlspecialchars($exception->getMessage()));
     }
 }
 /**
  * Renders the exception in HTML for display
  *
  * @param string $typoScriptPath path causing the exception
  * @param \Exception $exception exception to handle
  * @param integer $referenceCode
  * @return string
  */
 protected function handle($typoScriptPath, \Exception $exception, $referenceCode)
 {
     $messageArray = array('header' => 'An exception was thrown while Neos tried to render your page', 'content' => htmlspecialchars($exception->getMessage()), 'stacktrace' => $this->formatTypoScriptPath($typoScriptPath), 'referenceCode' => $this->formatErrorCodeMessage($referenceCode));
     $messageBody = sprintf('<p class="neos-message-content">%s</p>' . '<p class="neos-message-stacktrace"><code>%s</code></p>', $messageArray['content'], $messageArray['stacktrace']);
     if ($referenceCode) {
         $messageBody = sprintf('%s<p class="neos-reference-code">%s</p>', $messageBody, $messageArray['referenceCode']);
     }
     $message = sprintf('<div class="neos-message-header"><div class="neos-message-icon"><i class="icon-warning-sign"></i></div><h1>%s</h1></div>' . '<div class="neos-message-wrapper">%s</div>', $messageArray['header'], $messageBody);
     $this->systemLogger->logException($exception);
     return $message;
 }
 /**
  * Commits new objects and changes to objects in the current persistence
  * session into the backend
  *
  * @param boolean $onlyWhitelistedObjects If TRUE an exception will be thrown if there are scheduled updates/deletes or insertions for objects that are not "whitelisted" (see AbstractPersistenceManager::whitelistObject())
  * @return void
  * @api
  */
 public function persistAll($onlyWhitelistedObjects = false)
 {
     if ($onlyWhitelistedObjects) {
         $unitOfWork = $this->entityManager->getUnitOfWork();
         /** @var \Doctrine\ORM\UnitOfWork $unitOfWork */
         $unitOfWork->computeChangeSets();
         $objectsToBePersisted = $unitOfWork->getScheduledEntityUpdates() + $unitOfWork->getScheduledEntityDeletions() + $unitOfWork->getScheduledEntityInsertions();
         foreach ($objectsToBePersisted as $object) {
             $this->throwExceptionIfObjectIsNotWhitelisted($object);
         }
     }
     if (!$this->entityManager->isOpen()) {
         $this->systemLogger->log('persistAll() skipped flushing data, the Doctrine EntityManager is closed. Check the logs for error message.', LOG_ERR);
         return;
     }
     try {
         $this->entityManager->flush();
     } catch (Exception $exception) {
         $this->systemLogger->logException($exception);
         /** @var Connection $connection */
         $connection = $this->entityManager->getConnection();
         $connection->close();
         $connection->connect();
         $this->systemLogger->log('Reconnected the Doctrine EntityManager to the persistence backend.', LOG_INFO);
         $this->entityManager->flush();
     } finally {
         $this->emitAllObjectsPersisted();
     }
 }
 /**
  * Import sites content
  *
  * This command allows for importing one or more sites or partial content from an XML source. The format must
  * be identical to that produced by the export command.
  *
  * If a filename is specified, this command expects the corresponding file to contain the XML structure. The
  * filename php://stdin can be used to read from standard input.
  *
  * If a package key is specified, this command expects a Sites.xml file to be located in the private resources
  * directory of the given package (Resources/Private/Content/Sites.xml).
  *
  * @param string $packageKey Package key specifying the package containing the sites content
  * @param string $filename relative path and filename to the XML file containing the sites content
  * @return void
  */
 public function importCommand($packageKey = null, $filename = null)
 {
     $exceedingArguments = $this->request->getExceedingArguments();
     if (isset($exceedingArguments[0]) && $packageKey === null && $filename === null) {
         if (file_exists($exceedingArguments[0])) {
             $filename = $exceedingArguments[0];
         } elseif ($this->packageManager->isPackageAvailable($exceedingArguments[0])) {
             $packageKey = $exceedingArguments[0];
         }
     }
     if ($packageKey === null && $filename === null) {
         $this->outputLine('You have to specify either "--package-key" or "--filename"');
         $this->quit(1);
     }
     $site = null;
     if ($filename !== null) {
         try {
             $site = $this->siteImportService->importFromFile($filename);
         } catch (\Exception $exception) {
             $this->systemLogger->logException($exception);
             $this->outputLine('<error>During the import of the file "%s" an exception occurred: %s, see log for further information.</error>', array($filename, $exception->getMessage()));
             $this->quit(1);
         }
     } else {
         try {
             $site = $this->siteImportService->importFromPackage($packageKey);
         } catch (\Exception $exception) {
             $this->systemLogger->logException($exception);
             $this->outputLine('<error>During the import of the "Sites.xml" from the package "%s" an exception occurred: %s, see log for further information.</error>', array($packageKey, $exception->getMessage()));
             $this->quit(1);
         }
     }
     $this->outputLine('Import of site "%s" finished.', array($site->getName()));
 }
 /**
  * Handles the given exception
  *
  * @param object $exception The exception object - can be \Exception, or some type of \Throwable in PHP 7
  * @return void
  */
 public function handleException($exception)
 {
     // Ignore if the error is suppressed by using the shut-up operator @
     if (error_reporting() === 0) {
         return;
     }
     $this->renderingOptions = $this->resolveCustomRenderingOptions($exception);
     if (is_object($this->systemLogger) && isset($this->renderingOptions['logException']) && $this->renderingOptions['logException']) {
         if ($exception instanceof \Throwable) {
             if ($this->systemLogger instanceof ThrowableLoggerInterface) {
                 $this->systemLogger->logThrowable($exception);
             } else {
                 // Convert \Throwable to \Exception for non-supporting logger implementations
                 $this->systemLogger->logException(new \Exception($exception->getMessage(), $exception->getCode()));
             }
         } elseif ($exception instanceof \Exception) {
             $this->systemLogger->logException($exception);
         }
     }
     switch (PHP_SAPI) {
         case 'cli':
             $this->echoExceptionCli($exception);
             break;
         default:
             $this->echoExceptionWeb($exception);
     }
 }
Esempio n. 6
0
 /**
  * Returns the query result count
  *
  * @return integer The query result count
  * @throws Exception\DatabaseConnectionException
  * @api
  */
 public function count()
 {
     try {
         $originalQuery = $this->queryBuilder->getQuery();
         $dqlQuery = clone $originalQuery;
         $dqlQuery->setParameters($originalQuery->getParameters());
         $dqlQuery->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]);
         $offset = $dqlQuery->getFirstResult();
         $limit = $dqlQuery->getMaxResults();
         if ($offset !== null) {
             $dqlQuery->setFirstResult(null);
         }
         $numberOfResults = (int) $dqlQuery->getSingleScalarResult();
         if ($offset !== null) {
             $numberOfResults = max(0, $numberOfResults - $offset);
         }
         if ($limit !== null) {
             $numberOfResults = min($numberOfResults, $limit);
         }
         return $numberOfResults;
     } catch (\Doctrine\ORM\ORMException $ormException) {
         $this->systemLogger->logException($ormException);
         return 0;
     } catch (\PDOException $pdoException) {
         throw new Exception\DatabaseConnectionException($pdoException->getMessage(), $pdoException->getCode());
     }
 }
Esempio n. 7
0
 /**
  * Output an error message and log the exception.
  *
  * @param \Exception $exception
  * @return void
  */
 protected function handleException(\Exception $exception)
 {
     $this->outputLine('<error>%s</error>', [$exception->getMessage()]);
     $this->outputLine();
     $this->outputLine('The exception details have been logged to the Flow system log.');
     $this->systemLogger->logException($exception);
     $this->quit(1);
 }
 /**
  * Get a single property reduced to a simple type (no objects) representation
  *
  * @param NodeInterface $node
  * @param string $propertyName
  * @return mixed
  */
 public function getProperty(NodeInterface $node, $propertyName)
 {
     if ($propertyName[0] === '_') {
         $propertyValue = ObjectAccess::getProperty($node, ltrim($propertyName, '_'));
     } else {
         $propertyValue = $node->getProperty($propertyName);
     }
     $dataType = $node->getNodeType()->getPropertyType($propertyName);
     try {
         $convertedValue = $this->convertValue($propertyValue, $dataType);
     } catch (PropertyException $exception) {
         $this->systemLogger->logException($exception);
         $convertedValue = null;
     }
     if ($convertedValue === null) {
         $convertedValue = $this->getDefaultValueForProperty($node->getNodeType(), $propertyName);
     }
     return $convertedValue;
 }
 /**
  * Returns a thumbnail of the given asset
  *
  * If the maximum width / height is not specified or exceeds the original asset's dimensions, the width / height of
  * the original asset is used.
  *
  * @param AssetInterface $asset The asset to render a thumbnail for
  * @param ThumbnailConfiguration $configuration
  * @return ImageInterface
  * @throws \Exception
  */
 public function getThumbnail(AssetInterface $asset, ThumbnailConfiguration $configuration)
 {
     // Calculates the dimensions of the thumbnail to be generated and returns the thumbnail image if the new
     // dimensions differ from the specified image dimensions, otherwise the original image is returned.
     if ($asset instanceof ImageInterface) {
         if ($asset->getWidth() === null && $asset->getHeight() === null) {
             return $asset;
         }
         $maximumWidth = $configuration->getMaximumWidth() > $asset->getWidth() ? $asset->getWidth() : $configuration->getMaximumWidth();
         $maximumHeight = $configuration->getMaximumHeight() > $asset->getHeight() ? $asset->getHeight() : $configuration->getMaximumHeight();
         if ($configuration->isUpScalingAllowed() === false && $maximumWidth === $asset->getWidth() && $maximumHeight === $asset->getHeight()) {
             return $asset;
         }
     }
     $assetIdentifier = $this->persistenceManager->getIdentifierByObject($asset);
     $configurationHash = $configuration->getHash();
     if (!isset($this->thumbnailCache[$assetIdentifier])) {
         $this->thumbnailCache[$assetIdentifier] = [];
     }
     if (isset($this->thumbnailCache[$assetIdentifier][$configurationHash])) {
         $thumbnail = $this->thumbnailCache[$assetIdentifier][$configurationHash];
     } else {
         $thumbnail = $this->thumbnailRepository->findOneByAssetAndThumbnailConfiguration($asset, $configuration);
         $this->thumbnailCache[$assetIdentifier][$configurationHash] = $thumbnail;
     }
     $async = $configuration->isAsync();
     if ($thumbnail === null) {
         try {
             $thumbnail = new Thumbnail($asset, $configuration, $async);
             $this->emitThumbnailCreated($thumbnail);
             // If the thumbnail strategy failed to generate a valid thumbnail
             if ($async === false && $thumbnail->getResource() === null && $thumbnail->getStaticResource() === null) {
                 $this->thumbnailRepository->remove($thumbnail);
                 return null;
             }
             if (!$this->persistenceManager->isNewObject($asset)) {
                 $this->thumbnailRepository->add($thumbnail);
             }
             $asset->addThumbnail($thumbnail);
             // Allow thumbnails to be persisted even if this is a "safe" HTTP request:
             $this->persistenceManager->whiteListObject($thumbnail);
             $this->thumbnailCache[$assetIdentifier][$configurationHash] = $thumbnail;
         } catch (NoThumbnailAvailableException $exception) {
             $this->systemLogger->logException($exception);
             return null;
         }
         $this->persistenceManager->whiteListObject($thumbnail);
         $this->thumbnailCache[$assetIdentifier][$configurationHash] = $thumbnail;
     } elseif ($thumbnail->getResource() === null && $async === false) {
         $this->refreshThumbnail($thumbnail);
     }
     return $thumbnail;
 }
 /**
  * @param string $resourcePath
  * @return string
  */
 protected function getStaticResourceWebBaseUri($resourcePath)
 {
     $localizedResourcePathData = $this->i18nService->getLocalizedFilename($resourcePath);
     $matches = array();
     try {
         if (preg_match('#resource://([^/]+)/Public/(.*)#', current($localizedResourcePathData), $matches) === 1) {
             $packageKey = $matches[1];
             $path = $matches[2];
             return $this->resourceManager->getPublicPackageResourceUri($packageKey, $path);
         }
     } catch (\Exception $exception) {
         $this->systemLogger->logException($exception);
     }
     return '';
 }
Esempio n. 11
0
 /**
  * Finally evaluate the TypoScript path
  *
  * As PHP does not like throwing an exception here, we render any exception using the configured TypoScript exception
  * handler and will also catch and log any exceptions resulting from that as a last resort.
  *
  * @return string
  */
 public function __toString()
 {
     try {
         return (string) $this->objectAccess();
     } catch (\Exception $exceptionHandlerException) {
         try {
             // Throwing an exception in __toString causes a fatal error, so if that happens we catch them and use the context dependent exception handler instead.
             $contextDependentExceptionHandler = new ContextDependentHandler();
             $contextDependentExceptionHandler->setRuntime($this->fusionRuntime);
             return $contextDependentExceptionHandler->handleRenderingException($this->path, $exception);
         } catch (\Exception $contextDepndentExceptionHandlerException) {
             $this->systemLogger->logException($contextDepndentExceptionHandlerException, array('path' => $this->path));
             return sprintf('<!-- Exception while rendering exception in %s: %s (%s) -->', $this->path, $contextDepndentExceptionHandlerException->getMessage(), $contextDepndentExceptionHandlerException instanceof Exception ? 'see reference code ' . $contextDepndentExceptionHandlerException->getReferenceCode() . ' in log' : $contextDepndentExceptionHandlerException->getCode());
         }
     }
 }
 /**
  * Render the Uri.
  *
  * @return string The rendered URI or NULL if no URI could be resolved for the given node
  * @throws NeosException
  */
 public function evaluate()
 {
     $baseNode = null;
     $baseNodeName = $this->getBaseNodeName() ?: 'documentNode';
     $currentContext = $this->tsRuntime->getCurrentContext();
     if (isset($currentContext[$baseNodeName])) {
         $baseNode = $currentContext[$baseNodeName];
     } else {
         throw new NeosException(sprintf('Could not find a node instance in TypoScript context with name "%s" and no node instance was given to the node argument. Set a node instance in the TypoScript context or pass a node object to resolve the URI.', $baseNodeName), 1373100400);
     }
     try {
         return $this->linkingService->createNodeUri($this->tsRuntime->getControllerContext(), $this->getNode(), $baseNode, $this->getFormat(), $this->isAbsolute(), $this->getAdditionalParams(), $this->getSection(), $this->getAddQueryString(), $this->getArgumentsToBeExcludedFromQueryString());
     } catch (NeosException $exception) {
         $this->systemLogger->logException($exception);
         return '';
     }
 }
 /**
  * @param array $source
  * @param PropertyMappingConfigurationInterface $configuration
  * @return PersistentResource|FlowError
  * @throws \Exception
  */
 protected function handleFileUploads(array $source, PropertyMappingConfigurationInterface $configuration = null)
 {
     if (!isset($source['error']) || $source['error'] === \UPLOAD_ERR_NO_FILE) {
         if (isset($source['originallySubmittedResource']) && isset($source['originallySubmittedResource']['__identity'])) {
             return $this->persistenceManager->getObjectByIdentifier($source['originallySubmittedResource']['__identity'], PersistentResource::class);
         }
         return null;
     }
     if ($source['error'] !== \UPLOAD_ERR_OK) {
         switch ($source['error']) {
             case \UPLOAD_ERR_INI_SIZE:
             case \UPLOAD_ERR_FORM_SIZE:
             case \UPLOAD_ERR_PARTIAL:
                 return new FlowError(Files::getUploadErrorMessage($source['error']), 1264440823);
             default:
                 $this->systemLogger->log(sprintf('A server error occurred while converting an uploaded resource: "%s"', Files::getUploadErrorMessage($source['error'])), LOG_ERR);
                 return new FlowError('An error occurred while uploading. Please try again or contact the administrator if the problem remains', 1340193849);
         }
     }
     if (isset($this->convertedResources[$source['tmp_name']])) {
         return $this->convertedResources[$source['tmp_name']];
     }
     try {
         $resource = $this->resourceManager->importUploadedResource($source, $this->getCollectionName($source, $configuration));
         $this->convertedResources[$source['tmp_name']] = $resource;
         return $resource;
     } catch (\Exception $exception) {
         $this->systemLogger->log('Could not import an uploaded file', LOG_WARNING);
         $this->systemLogger->logException($exception);
         return new FlowError('During import of an uploaded file an error occurred. See log for more details.', 1264517906);
     }
 }
 /**
  * Import redirects from CSV file
  *
  * This command is used to (re)import CSV files containing redirects.
  * The argument ``filename`` is the name of the file you uploaded to the root folder.
  * This operation requires the package ``league/csv``. Install it by running ``composer require league/csv``.
  * Structure per line is:
  * ``sourcePath``,``targetPath``,``statusCode``,``host`` (optional)
  * After a successful import a report will be shown. While `++` marks newly created redirects, `~~` marks already
  * existing redirect source paths along with the used status code and ``source``.
  * ``redirect:import`` will not delete pre-existing redirects. To do this run ``redirect:removeall`` before
  * the import. Be aware that this will also delete all automatically generated redirects.
  *
  * @param string $filename CSV file path
  * @return void
  */
 public function importCommand($filename)
 {
     $hasErrors = false;
     $this->outputLine();
     if (!class_exists(Reader::class)) {
         $this->outputWarningForLeagueCsvPackage();
     }
     if (!is_readable($filename)) {
         $this->outputLine('<error>Sorry, but the file "%s" is not readable or does not exist...</error>', [$filename]);
         $this->outputLine();
         $this->sendAndExit(1);
     }
     $this->outputLine('<b>Import redirects from "%s"</b>', [$filename]);
     $this->outputLine();
     $reader = Reader::createFromPath($filename);
     $counter = 0;
     foreach ($reader as $index => $row) {
         $skipped = false;
         list($sourceUriPath, $targetUriPath, $statusCode, $hosts) = $row;
         $hosts = Arrays::trimExplode('|', $hosts);
         if ($hosts === []) {
             $hosts = [null];
         }
         $forcePersist = false;
         foreach ($hosts as $key => $host) {
             $host = trim($host);
             $host = $host === '' ? null : $host;
             $redirect = $this->redirectStorage->getOneBySourceUriPathAndHost($sourceUriPath, $host);
             $isSame = $this->isSame($sourceUriPath, $targetUriPath, $host, $statusCode, $redirect);
             if ($redirect !== null && $isSame === false) {
                 $this->outputRedirectLine('<info>--</info>', $redirect);
                 $this->redirectStorage->removeOneBySourceUriPathAndHost($sourceUriPath, $host);
                 $forcePersist = true;
             } elseif ($isSame === true) {
                 $this->outputRedirectLine('<comment>~~</comment>', $redirect);
                 unset($hosts[$key]);
                 $skipped = true;
             }
         }
         if ($skipped === true && $hosts === []) {
             continue;
         }
         if ($forcePersist) {
             $this->persistenceManager->persistAll();
         }
         try {
             $redirects = $this->redirectStorage->addRedirect($sourceUriPath, $targetUriPath, $statusCode, $hosts);
             /** @var Redirect $redirect */
             foreach ($redirects as $redirect) {
                 $this->outputRedirectLine('<info>++</info>', $redirect);
                 $messageArguments = [$redirect->getSourceUriPath(), $redirect->getTargetUriPath(), $redirect->getStatusCode(), $redirect->getHost() ?: 'all host'];
                 $this->logger->log(vsprintf('Redirect import success, sourceUriPath=%s, targetUriPath=%s, statusCode=%d, hosts=%s', $messageArguments), LOG_ERR);
             }
             $this->persistenceManager->persistAll();
         } catch (Exception $exception) {
             $messageArguments = [$sourceUriPath, $targetUriPath, $statusCode, $hosts ? json_encode($hosts) : 'all host'];
             $this->outputLine('   <error>!!</error> %s => %s <comment>(%d)</comment> - %s', $messageArguments);
             $this->outputLine('      Message: %s', [$exception->getMessage()]);
             $this->logger->log(vsprintf('Redirect import error, sourceUriPath=%s, targetUriPath=%s, statusCode=%d, hosts=%s', $messageArguments), LOG_ERR);
             $this->logger->logException($exception);
             $hasErrors = true;
         }
         $counter++;
         if ($counter % 50 === 0) {
             $this->persistenceManager->persistAll();
             $this->persistenceManager->clearState();
         }
     }
     $this->outputLine();
     if ($hasErrors === true) {
         $this->outputLine('   <error>!!</error> some errors appeared during import, please check the log or the CLI output.');
     }
     $this->outputLegend();
 }
 /**
  * @param FinisherContext $finisherContext
  * @return void
  * @throws Exception
  */
 public function importSite(FinisherContext $finisherContext)
 {
     $formValues = $finisherContext->getFormRuntime()->getFormState()->getFormValues();
     if (isset($formValues['prune']) && intval($formValues['prune']) === 1) {
         $this->nodeDataRepository->removeAll();
         $this->workspaceRepository->removeAll();
         $this->domainRepository->removeAll();
         $this->siteRepository->removeAll();
         $this->persistenceManager->persistAll();
     }
     if (!empty($formValues['packageKey'])) {
         if ($this->packageManager->isPackageAvailable($formValues['packageKey'])) {
             throw new Exception(sprintf('The package key "%s" already exists.', $formValues['packageKey']), 1346759486);
         }
         $packageKey = $formValues['packageKey'];
         $siteName = $formValues['siteName'];
         $generatorService = $this->objectManager->get(\Neos\SiteKickstarter\Service\GeneratorService::class);
         $generatorService->generateSitePackage($packageKey, $siteName);
     } elseif (!empty($formValues['site'])) {
         $packageKey = $formValues['site'];
     }
     $this->deactivateOtherSitePackages($packageKey);
     $this->packageManager->activatePackage($packageKey);
     if (!empty($packageKey)) {
         try {
             $contentContext = $this->contextFactory->create(array('workspaceName' => 'live'));
             $this->siteImportService->importFromPackage($packageKey, $contentContext);
         } catch (\Exception $exception) {
             $finisherContext->cancel();
             $this->systemLogger->logException($exception);
             throw new SetupException(sprintf('Error: During the import of the "Sites.xml" from the package "%s" an exception occurred: %s', $packageKey, $exception->getMessage()), 1351000864);
         }
     }
 }
 /**
  * Import a site from site package.
  *
  * @param string $packageKey Package from where the import will come
  * @Flow\Validate(argumentName="$packageKey", type="\Neos\Neos\Validation\Validator\PackageKeyValidator")
  * @return void
  */
 public function importSiteAction($packageKey)
 {
     try {
         $this->siteImportService->importFromPackage($packageKey);
         $this->addFlashMessage('The site has been imported.', '', null, array(), 1412372266);
     } catch (\Exception $exception) {
         $this->systemLogger->logException($exception);
         $this->addFlashMessage('Error: During the import of the "Sites.xml" from the package "%s" an exception occurred: %s', 'Import error', Message::SEVERITY_ERROR, array(htmlspecialchars($packageKey), htmlspecialchars($exception->getMessage())), 1412372375);
     }
     $this->unsetLastVisitedNodeAndRedirect('index');
 }