/**
  * 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()));
     }
 }
 /**
  * Create a new site from a site template
  *
  * This command uses a site template located in a sitePackage to create a new site with a new subdomain.
  *
  * @param string $sitePackage Package key of the Site containing the template under Templates/Content/Sites.xml
  * @param string $siteName The sitename
  * @param string $baseDomain The base domain name e.g. site.com => will be used like $siteName.site.com
  * @return void
  */
 public function newSiteCommand($sitePackage, $siteName, $baseDomain)
 {
     try {
         $site = $this->siteService->importSiteFromTemplate($sitePackage, $siteName, $baseDomain);
         $this->outputLine('Created a new site "%s"', array($site->getName()));
     } catch (\Exception $e) {
         $this->systemLogger->logException($e);
         $this->outputLine('An error occured during site creation, check error log for details');
     }
 }
 /**
  * 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' => $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;
 }
 /**
  * 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);
     }
 }
 /**
  * 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();
     }
 }
 /**
  * Send a new notification that a comment has been created
  *
  * @param \TYPO3\TYPO3CR\Domain\Model\NodeInterface $commentNode The comment node
  * @param \TYPO3\TYPO3CR\Domain\Model\NodeInterface $postNode The post node
  * @return void
  */
 public function sendNewCommentNotification(NodeInterface $commentNode, NodeInterface $postNode)
 {
     if ($this->settings['notifications']['to']['email'] === '') {
         return;
     }
     if (!class_exists('TYPO3\\SwiftMailer\\Message')) {
         $this->systemLogger->logException(new \TYPO3\Flow\Exception('The package "TYPO3.SwiftMailer" is required to send notifications!', 1359473932));
         return;
     }
     try {
         $mail = new Message();
         $mail->setFrom(array($commentNode->getProperty('emailAddress') => $commentNode->getProperty('author')))->setTo(array($this->settings['notifications']['to']['email'] => $this->settings['notifications']['to']['name']))->setSubject('New comment on blog post "' . $postNode->getProperty('title') . '"' . ($commentNode->getProperty('spam') ? ' (SPAM)' : ''))->setBody($commentNode->getProperty('text'))->send();
     } catch (\Exception $e) {
         $this->systemLogger->logException($e);
     }
 }
 /**
  * @param \TYPO3\Form\Core\Model\FinisherContext $finisherContext
  * @return void
  * @throws \TYPO3\Setup\Exception
  */
 public function importSite(\TYPO3\Form\Core\Model\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 \TYPO3\Setup\Exception(sprintf('The package key "%s" already exists.', $formValues['packageKey']), 1346759486);
         }
         $packageKey = $formValues['packageKey'];
         $siteName = $formValues['siteName'];
         $generatorService = $this->objectManager->get('TYPO3\\Neos\\Kickstarter\\Service\\GeneratorService');
         $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 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.', 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.', array($packageKey, $exception->getMessage()));
             $this->quit(1);
         }
     }
     $this->outputLine('Import of site "%s" finished.', array($site->getName()));
 }
 /**
  * Create a new site.
  *
  * @param string $site Site to import
  * @param string $packageKey Package Name to create
  * @param string $siteName Site Name to create
  * @Flow\Validate(argumentName="$packageKey", type="\TYPO3\Neos\Validation\Validator\PackageKeyValidator")
  * @return void
  */
 public function createSiteAction($site, $packageKey = '', $siteName = '')
 {
     if ($packageKey !== '' && $this->packageManager->isPackageActive('TYPO3.Neos.Kickstarter')) {
         if ($this->packageManager->isPackageAvailable($packageKey)) {
             $this->addFlashMessage('The package key "%s" already exists.', 'Invalid package key', Message::SEVERITY_ERROR, array(htmlspecialchars($packageKey)), 1412372021);
             $this->redirect('index');
         }
         $generatorService = $this->objectManager->get('TYPO3\\Neos\\Kickstarter\\Service\\GeneratorService');
         $generatorService->generateSitePackage($packageKey, $siteName);
     } else {
         $packageKey = $site;
     }
     $deactivatedSitePackages = $this->deactivateAllOtherSitePackages($packageKey);
     if (count($deactivatedSitePackages) > 0) {
         $this->flashMessageContainer->addMessage(new Message(sprintf('The existing Site Packages "%s" were deactivated, in order to prevent interactions with the newly created package "%s".', htmlspecialchars(implode(', ', $deactivatedSitePackages)), htmlspecialchars($packageKey))));
     }
     $this->packageManager->activatePackage($packageKey);
     if ($packageKey !== '') {
         try {
             $this->siteImportService->importFromPackage($packageKey);
             $this->addFlashMessage('The site has been created.', '', 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);
         }
     } else {
         $this->addFlashMessage('No site selected for import and no package name provided.', 'No site selected', Message::SEVERITY_ERROR, array(), 1412372554);
         $this->redirect('newSite');
     }
     $this->unsetLastVisitedNodeAndRedirect('index');
 }
 /**
  * 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, array('TYPO3\\Flow\\Persistence\\Doctrine\\CountWalker'));
         $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());
     }
 }
 /**
  * Handles the given exception
  *
  * @param \Exception $exception The exception object
  * @return void
  */
 public function handleException(\Exception $exception)
 {
     // Ignore if the error is suppressed by using the shut-up operator @
     if (error_reporting() === 0) {
         return;
     }
     if (is_object($this->systemLogger)) {
         $this->systemLogger->logException($exception);
     }
     switch (PHP_SAPI) {
         case 'cli':
             $this->echoExceptionCli($exception);
             break;
         default:
             $this->echoExceptionWeb($exception);
     }
 }
 /**
  * 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);
 }
 /**
  * Sends a mail and creates a system logger entry if sending failed
  *
  * @param Message $mail
  * @return boolean TRUE on success, otherwise FALSE
  */
 protected function sendMail(Message $mail)
 {
     $numberOfRecipients = 0;
     // ignore exceptions but log them
     $exceptionMessage = '';
     try {
         $numberOfRecipients = $mail->send();
     } catch (\Exception $e) {
         $this->systemLogger->logException($e);
         $exceptionMessage = $e->getMessage();
     }
     if ($numberOfRecipients < 1) {
         $this->systemLogger->log('Could not send notification email "' . $mail->getSubject() . '"', LOG_ERR, ['exception' => $exceptionMessage, 'message' => $mail->getSubject(), 'id' => (string) $mail->getHeaders()->get('Message-ID')]);
         return false;
     }
     return true;
 }
Beispiel #14
0
 /**
  * Return an array with data from the given exception, suitable for being returned
  * in an ExtDirect response.
  *
  * The excpetion is logged to the system logger as well.
  *
  * @param \Exception $exception
  * @return array
  */
 protected function handleException(\Exception $exception, $transactionId = NULL)
 {
     $this->systemLogger->logException($exception);
     // As an exception happened, we now need to check whether detailed exception reporting was enabled.
     $exposeExceptionInformation = $this->settings['ExtDirect']['exposeExceptionInformation'] === TRUE;
     $exceptionWhere = $exception instanceof \TYPO3\Flow\Exception ? ' (ref ' . $exception->getReferenceCode() . ')' : '';
     $exceptionMessage = $exposeExceptionInformation ? 'Uncaught exception #' . $exception->getCode() . $exceptionWhere . ' - ' . $exception->getMessage() : 'An internal error occured';
     return array('type' => 'exception', 'tid' => $transactionId, 'message' => $exceptionMessage, 'where' => $exceptionWhere);
 }
 /**
  * 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;
 }
 /**
  * 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 \Exception) {
             $this->systemLogger->logException($exception);
         }
     }
     switch (PHP_SAPI) {
         case 'cli':
             $this->echoExceptionCli($exception);
             break;
         default:
             $this->echoExceptionWeb($exception);
     }
 }
 /**
  * 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;
 }
 /**
  * Writes out a single property into the XML structure.
  *
  * @param array $data The data as an array, the given property name is looked up there
  * @param string $propertyName The name of the property
  * @param string $elementName an optional name to use, defaults to $propertyName
  * @return void
  */
 protected function writeConvertedElement(array &$data, $propertyName, $elementName = null, $declaredPropertyType = null)
 {
     if (array_key_exists($propertyName, $data) && $data[$propertyName] !== null) {
         $propertyValue = $data[$propertyName];
         $this->xmlWriter->startElement($elementName ?: $propertyName);
         if (!empty($propertyValue)) {
             switch ($declaredPropertyType) {
                 case null:
                 case 'reference':
                 case 'references':
                     break;
                 default:
                     $propertyValue = $this->propertyMapper->convert($propertyValue, $declaredPropertyType);
                     break;
             }
         }
         $this->xmlWriter->writeAttribute('__type', gettype($propertyValue));
         try {
             if (is_object($propertyValue) && !$propertyValue instanceof \DateTime) {
                 $objectIdentifier = $this->persistenceManager->getIdentifierByObject($propertyValue);
                 if ($objectIdentifier !== null) {
                     $this->xmlWriter->writeAttribute('__identifier', $objectIdentifier);
                 }
                 if ($propertyValue instanceof \Doctrine\ORM\Proxy\Proxy) {
                     $className = get_parent_class($propertyValue);
                 } else {
                     $className = get_class($propertyValue);
                 }
                 $this->xmlWriter->writeAttribute('__classname', $className);
                 $this->xmlWriter->writeAttribute('__encoding', 'json');
                 $converted = json_encode($this->propertyMapper->convert($propertyValue, 'array', $this->propertyMappingConfiguration));
                 $this->xmlWriter->text($converted);
             } elseif (is_array($propertyValue)) {
                 foreach ($propertyValue as $key => $element) {
                     $this->writeConvertedElement($propertyValue, $key, 'entry' . $key);
                 }
             } else {
                 if ($propertyValue instanceof \DateTime) {
                     $this->xmlWriter->writeAttribute('__classname', 'DateTime');
                 }
                 $this->xmlWriter->text($this->propertyMapper->convert($propertyValue, 'string', $this->propertyMappingConfiguration));
             }
         } catch (\Exception $exception) {
             $this->xmlWriter->writeComment(sprintf('Could not convert property "%s" to string.', $propertyName));
             $this->xmlWriter->writeComment($exception->getMessage());
             $this->systemLogger->logException($exception);
             $this->exceptionsDuringExport[] = $exception;
         }
         $this->xmlWriter->endElement();
     }
 }
 /**
  * @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 '';
 }
 /**
  * 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->tsRuntime);
             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());
         }
     }
 }
 /**
  * @param string $presetName
  * @param string $partName
  * @param string $dataProviderClassName
  * @param string $importerClassName
  * @param string $logPrefix
  * @param integer $offset
  * @param integer $batchSize
  * @return integer
  * @Flow\Internal
  */
 public function executeBatchCommand($presetName, $partName, $dataProviderClassName, $importerClassName, $logPrefix, $offset = NULL, $batchSize = NULL)
 {
     try {
         $dataProviderOptions = Arrays::getValueByPath($this->settings, implode('.', ['presets', $presetName, $partName, 'dataProviderOptions']));
         /** @var DataProvider $dataProvider */
         $dataProvider = $dataProviderClassName::create(is_array($dataProviderOptions) ? $dataProviderOptions : [], $offset, $batchSize);
         $importerOptions = Arrays::getValueByPath($this->settings, ['presets', $presetName, $partName, 'importerOptions']);
         /** @var Importer $importer */
         $importer = $this->objectManager->get($importerClassName, is_array($importerOptions) ? $importerOptions : []);
         $importer->setLogPrefix($logPrefix);
         $importer->import($dataProvider);
         $this->output($dataProvider->getCount());
     } catch (\Exception $exception) {
         $this->logger->logException($exception);
         $this->quit(1);
     }
 }
 /**
  * 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 string $jobIdentifier
  * @param array $options
  */
 protected function executeJob($jobIdentifier, array $options = [])
 {
     $jobConfiguration = $this->jobConfigurationRepository->findOneByIdentifier($jobIdentifier);
     try {
         $startTime = microtime(true);
         $options = new JobConfigurationOptions($options);
         if ($this->jobRunnerService->execute($jobConfiguration, $options)) {
             if ($jobConfiguration->isAsynchronous()) {
                 $this->flashMessageContainer->addMessage(new Message(sprintf('Job "%s" queued with success', $jobConfiguration->getName())));
             } else {
                 $duration = round(microtime(true) - $startTime, 2);
                 $this->flashMessageContainer->addMessage(new Message(sprintf('Job "%s" exectued with success in %s sec.', $jobConfiguration->getName(), $duration)));
             }
         }
     } catch (\Exception $exception) {
         $this->systemLogger->logException($exception);
         $this->flashMessageContainer->addMessage(new Error(sprintf('Failed to execute job "%s" with message: %s', $jobConfiguration->getName(), $exception->getMessage())));
     }
 }
 /**
  * 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 Thumbnail
  * @throws \Exception
  */
 public function getThumbnail(AssetInterface $asset, ThumbnailConfiguration $configuration)
 {
     $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);
             // 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;
 }
 /**
  * Extract metadata from the content and store it
  *
  * @param string $entryIdentifier The entry identifier
  * @param string $content The raw content including serialized metadata
  * @return string The content without metadata
  * @throws InvalidDataException
  */
 protected function extractMetadata($entryIdentifier, $content)
 {
     $separatorIndex = strpos($content, self::SEPARATOR);
     if ($separatorIndex === FALSE) {
         $exception = new InvalidDataException('Could not find cache metadata in entry with identifier ' . $entryIdentifier, 1433155925);
         if ($this->environment->getContext()->isProduction()) {
             $this->systemLogger->logException($exception);
         } else {
             throw $exception;
         }
     }
     $metadataJson = substr($content, 0, $separatorIndex);
     $metadata = json_decode($metadataJson, TRUE);
     if ($metadata === NULL) {
         $exception = new InvalidDataException('Invalid cache metadata in entry with identifier ' . $entryIdentifier, 1433155926);
         if ($this->environment->getContext()->isProduction()) {
             $this->systemLogger->logException($exception);
         } else {
             throw $exception;
         }
     }
     $this->metadata[$entryIdentifier] = $metadata;
     return substr($content, $separatorIndex + 1);
 }
 /**
  * @param string $firstname
  * @param string $lastname
  * @param string $email
  * @param string $username
  * @param string $password
  * @return \TYPO3\Flow\Error\Result
  */
 public function addUser($firstname, $lastname, $email, $username, $password)
 {
     $result = new \TYPO3\Flow\Error\Result();
     try {
         $userData = ['name' => $username, 'first-name' => $firstname, 'last-name' => $lastname, 'email' => $email, 'password' => ['value' => $password], 'active' => TRUE];
         $uri = rtrim($this->crowdBaseUri, '/') . '/rest/usermanagement/1/user';
         $response = $this->httpClient->post($uri, array('body' => json_encode($userData)));
         $responseData = json_decode($response->getBody()->getContents(), TRUE);
         // TODO Check response data?
     } catch (ClientException $e) {
         $responseError = json_decode($e->getResponse()->getBody()->getContents());
         if (isset($responseError->reason)) {
             switch ($responseError->reason) {
                 case 'INVALID_USER':
                     $result->addError(new \TYPO3\Flow\Error\Error($responseError->message));
                     return $result;
             }
         }
         $userData['password']['value'] = '********';
         $this->systemLogger->logException($e, array('uri' => $uri, 'requestData' => $userData, 'responseStatus' => $e->getResponse()->getStatusCode(), 'responseBody' => $e->getResponse()->getBody()->getContents()));
         $result->addError(new \TYPO3\Flow\Error\Error('There was an unspecified error'));
     }
     return $result;
 }
 /**
  * @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);
     }
 }
Beispiel #28
0
 /**
  * @Flow\AfterThrowing("Ttree\Scheduler\Aspect\LoggingAspect->allTasks")
  * @param JoinPoint $jointPoint
  * @throws \Exception
  */
 public function logTaskException(JoinPoint $jointPoint)
 {
     /** @var Task $task */
     $exception = $jointPoint->getException();
     $this->systemLogger->logException($exception, array('task' => $jointPoint->getClassName()));
 }
 /**
  * @param string $pathAndFilename
  * @return void
  * @throws \Exception
  */
 public function optimizeFile($pathAndFilename)
 {
     try {
         $imageType = exif_imagetype($pathAndFilename);
         $fileExtension = strtolower(pathinfo($pathAndFilename, PATHINFO_EXTENSION));
         if ($imageType !== FALSE && !in_array($imageType, [\IMAGETYPE_JPEG, \IMAGETYPE_PNG, \IMAGETYPE_GIF], TRUE) || $imageType === FALSE && $fileExtension !== 'svg') {
             return;
         }
         $pathAndFilename = realpath($pathAndFilename);
         $cacheIdentifier = md5($pathAndFilename);
         $lastModificationTime = \DateTime::createFromFormat('U', filemtime($pathAndFilename));
         $cachedLastModificationTime = $this->processingCache->get($cacheIdentifier);
         if ($cachedLastModificationTime instanceof \DateTime && $lastModificationTime->getTimestamp() === $lastModificationTime->getTimestamp()) {
             return;
         }
         $useGlobalBinary = $this->settings['useGlobalBinary'];
         $binaryRootPath = 'Private/Library/node_modules/';
         $file = escapeshellarg($pathAndFilename);
         if ($imageType !== FALSE) {
             switch ($imageType) {
                 case \IMAGETYPE_JPEG:
                     if ($this->settings['formats']['jpg']['enabled'] === FALSE) {
                         return;
                     }
                     $library = 'jpegtran';
                     $binaryPath = sprintf('%1$s-bin/vendor/%s', $library);
                     $arguments = sprintf('-copy none -optimize %s -outfile %s %s', $this->settings['formats']['jpg']['progressive'] === TRUE ? '-progressive' : '', $file, $file);
                     if ($this->settings['formats']['jpg']['useGlobalBinary'] === TRUE) {
                         $useGlobalBinary = TRUE;
                     }
                     break;
                 case \IMAGETYPE_PNG:
                     if ($this->settings['formats']['png']['enabled'] === FALSE) {
                         return;
                     }
                     $library = 'optipng';
                     $binaryPath = sprintf('%1$s-bin/vendor/%s', $library);
                     $arguments = sprintf('-o%u -strip all -out %s %s', $this->settings['formats']['png']['optimizationLevel'], $file, $file);
                     if ($this->settings['formats']['png']['useGlobalBinary'] === TRUE) {
                         $useGlobalBinary = TRUE;
                     }
                     break;
                 case \IMAGETYPE_GIF:
                     if ($this->settings['formats']['gif']['enabled'] === FALSE) {
                         return;
                     }
                     $library = 'gifsicle';
                     $binaryPath = sprintf('%1$s/vendor/%1$s', $library);
                     $arguments = sprintf('--batch -O%u %s ', $this->settings['formats']['gif']['optimizationLevel'], $file);
                     if ($this->settings['formats']['gif']['useGlobalBinary'] === TRUE) {
                         $useGlobalBinary = TRUE;
                     }
                     break;
             }
         } else {
             if ($this->settings['formats']['svg']['enabled'] === FALSE) {
                 return;
             }
             $library = 'svgo';
             $binaryPath = sprintf('%1$s/bin/%1$s', $library);
             $arguments = sprintf('%s %s', $this->settings['formats']['svg']['pretty'] === TRUE ? '--pretty' : '', $file);
             if ($this->settings['formats']['svg']['useGlobalBinary'] === TRUE) {
                 $useGlobalBinary = TRUE;
             }
         }
         $binaryPath = $useGlobalBinary === TRUE ? $this->settings['globalBinaryPath'] . $library : $this->packageManager->getPackageOfObject($this)->getResourcesPath() . $binaryRootPath . $binaryPath;
         $cmd = escapeshellcmd($binaryPath) . ' ' . $arguments;
         $output = [];
         exec($cmd, $output, $result);
         $this->systemLogger->log($cmd . ' (' . ((int) $result === 0 ? 'OK' : 'Error: ' . $result) . ')', LOG_INFO, $output);
         $lastModificationTime = \DateTime::createFromFormat('U', filemtime($pathAndFilename));
         $this->processingCache->set($cacheIdentifier, $lastModificationTime);
     } catch (\Exception $exception) {
         $this->systemLogger->logException($exception);
     }
 }