/**
  * Move resource files to the new locations and adjust records.
  *
  * @param Schema $schema
  * @return void
  */
 public function postUp(Schema $schema)
 {
     $resourcesResult = $this->connection->executeQuery('SELECT persistence_object_identifier, sha1, filename FROM typo3_flow_resource_resource');
     while ($resourceInfo = $resourcesResult->fetch(\PDO::FETCH_ASSOC)) {
         $resourcePathAndFilename = FLOW_PATH_DATA . 'Persistent/Resources/' . $resourceInfo['sha1'];
         $newResourcePathAndFilename = FLOW_PATH_DATA . 'Persistent/Resources/' . $resourceInfo['sha1'][0] . '/' . $resourceInfo['sha1'][1] . '/' . $resourceInfo['sha1'][2] . '/' . $resourceInfo['sha1'][3] . '/' . $resourceInfo['sha1'];
         $mediaType = MediaTypes::getMediaTypeFromFilename($resourceInfo['filename']);
         if (file_exists($resourcePathAndFilename)) {
             $md5 = md5_file($resourcePathAndFilename);
             $filesize = filesize($resourcePathAndFilename);
             if (!file_exists(dirname($newResourcePathAndFilename))) {
                 Files::createDirectoryRecursively(dirname($newResourcePathAndFilename));
             }
             $result = @rename($resourcePathAndFilename, $newResourcePathAndFilename);
         } elseif (file_exists($newResourcePathAndFilename)) {
             $md5 = md5_file($newResourcePathAndFilename);
             $filesize = filesize($newResourcePathAndFilename);
             $result = TRUE;
         } else {
             $this->write(sprintf('Error while migrating database for the new resource management: the resource file "%s" (original filename: %s) was not found, but the resource object with uuid %s needs this file.', $resourcePathAndFilename, $resourceInfo['filename'], $resourceInfo['persistence_object_identifier']));
             continue;
         }
         $this->connection->executeUpdate('UPDATE typo3_flow_resource_resource SET collectionname = ?, mediatype = ?, md5 = ?, filesize = ? WHERE persistence_object_identifier = ?', array('persistent', $mediaType, $md5, $filesize, $resourceInfo['persistence_object_identifier']));
         if ($result === FALSE) {
             $this->write(sprintf('Could not move the data file of resource "%s" from its legacy location at %s to the correct location %s.', $resourceInfo['sha1'], $resourcePathAndFilename, $newResourcePathAndFilename));
         }
     }
     $this->connection->exec('ALTER TABLE typo3_flow_resource_resource ALTER md5 SET NOT NULL');
     $this->connection->exec('ALTER TABLE typo3_flow_resource_resource ALTER collectionname SET NOT NULL');
     $this->connection->exec('ALTER TABLE typo3_flow_resource_resource ALTER mediatype SET NOT NULL');
     $this->connection->exec('ALTER TABLE typo3_flow_resource_resource ALTER filesize SET NOT NULL');
 }
 /**
  * Converts the given request body according to the specified media type
  * Override this method in your custom TypeConverter to support additional media types
  *
  * @param string $requestBody the raw request body
  * @param string $mediaType the configured media type (for example "application/json")
  * @return array
  * @api
  */
 protected function convertMediaType($requestBody, $mediaType)
 {
     $mediaTypeParts = MediaTypes::parseMediaType($mediaType);
     if (!isset($mediaTypeParts['subtype']) || $mediaTypeParts['subtype'] === '') {
         return [];
     }
     $result = [];
     switch ($mediaTypeParts['subtype']) {
         case 'json':
         case 'x-json':
         case 'javascript':
         case 'x-javascript':
             $result = json_decode($requestBody, true);
             if ($result === null) {
                 return [];
             }
             break;
         case 'xml':
             $entityLoaderValue = libxml_disable_entity_loader(true);
             try {
                 $xmlElement = new \SimpleXMLElement(urldecode($requestBody), LIBXML_NOERROR);
                 libxml_disable_entity_loader($entityLoaderValue);
             } catch (\Exception $exception) {
                 libxml_disable_entity_loader($entityLoaderValue);
                 return [];
             }
             $result = Arrays::convertObjectToArray($xmlElement);
             break;
         case 'x-www-form-urlencoded':
         default:
             parse_str($requestBody, $result);
             break;
     }
     return $result;
 }
 /**
  * Converts the given request body according to the specified media type
  * Override this method in your custom TypeConverter to support additional media types
  *
  * @param string $requestBody the raw request body
  * @param string $mediaType the configured media type (for example "application/json")
  * @return array
  * @api
  */
 protected function convertMediaType($requestBody, $mediaType)
 {
     $mediaTypeParts = MediaTypes::parseMediaType($mediaType);
     if (!isset($mediaTypeParts['subtype']) || $mediaTypeParts['subtype'] === '') {
         return array();
     }
     $result = array();
     switch ($mediaTypeParts['subtype']) {
         case 'json':
         case 'x-json':
         case 'javascript':
         case 'x-javascript':
             $result = json_decode($requestBody, TRUE);
             if ($result === NULL) {
                 return array();
             }
             break;
         case 'xml':
             try {
                 $xmlElement = new \SimpleXMLElement(urldecode($requestBody), LIBXML_NOERROR);
             } catch (\Exception $e) {
                 return array();
             }
             $result = Arrays::convertObjectToArray($xmlElement);
             break;
         case 'x-www-form-urlencoded':
         default:
             parse_str($requestBody, $result);
             break;
     }
     return $result;
 }
 /**
  * Map the given resource to a media model class.
  *
  * @param Resource $resource
  * @param array $additionalProperties Optional properties that can be taken into account for deciding the model class. what you get here can depend on the caller, so you should always fallback to something based on the resource.
  * @return string
  */
 public function map(Resource $resource, array $additionalProperties = array())
 {
     $mediaType = MediaTypes::getMediaTypeFromFilename($resource->getFilename());
     foreach ($this->settings['patterns'] as $pattern => $mappingInformation) {
         if (preg_match($pattern, $mediaType)) {
             return $mappingInformation['className'];
         }
     }
     return $this->settings['default'];
 }
 /**
  * @param string $value
  * @throws Exception
  * @throws \TYPO3\Flow\Resource\Exception
  * @throws \TYPO3\Flow\Utility\Exception
  */
 protected function initializeValue($value)
 {
     if (!is_array($value)) {
         throw new Exception('Value must be an array, with source URI (sourceUri) and filename (filename)', 1425981082);
     }
     if (!isset($value['sourceUri'])) {
         throw new Exception('Missing source URI', 1425981083);
     }
     $sourceUri = trim($value['sourceUri']);
     if (!isset($value['filename'])) {
         throw new Exception('Missing filename URI', 1425981084);
     }
     $filename = trim($value['filename']);
     $overrideFilename = isset($value['overrideFilename']) ? trim($value['overrideFilename']) : $filename;
     if (!isset($this->options['downloadDirectory'])) {
         throw new Exception('Missing download directory data type option', 1425981085);
     }
     Files::createDirectoryRecursively($this->options['downloadDirectory']);
     $temporaryFileAndPathname = trim($this->options['downloadDirectory'] . $filename);
     $this->download($sourceUri, $temporaryFileAndPathname);
     $sha1Hash = sha1_file($temporaryFileAndPathname);
     # Try to add file extenstion if missing
     if (!$this->downloadCache->has($sha1Hash)) {
         $fileExtension = pathinfo($temporaryFileAndPathname, PATHINFO_EXTENSION);
         if (trim($fileExtension) === '') {
             $mimeTypeGuesser = new MimeTypeGuesser();
             $mimeType = $mimeTypeGuesser->guess($temporaryFileAndPathname);
             $this->logger->log(sprintf('Try to guess mime type for "%s" (%s), result: %s', $sourceUri, $filename, $mimeType), LOG_DEBUG);
             $fileExtension = MediaTypes::getFilenameExtensionFromMediaType($mimeType);
             if ($fileExtension !== '') {
                 $oldTemporaryDestination = $temporaryFileAndPathname;
                 $temporaryDestination = $temporaryFileAndPathname . '.' . $fileExtension;
                 copy($oldTemporaryDestination, $temporaryDestination);
                 $this->logger->log(sprintf('Rename "%s" to "%s"', $oldTemporaryDestination, $temporaryDestination), LOG_DEBUG);
             }
         }
     }
     $resource = $this->resourceManager->getResourceBySha1($sha1Hash);
     if ($resource === NULL) {
         $resource = $this->resourceManager->importResource($temporaryFileAndPathname);
         if ($filename !== $overrideFilename) {
             $resource->setFilename($overrideFilename);
         }
     }
     $this->temporaryFileAndPathname = $temporaryFileAndPathname;
     $this->downloadCache->set($sha1Hash, ['sha1Hash' => $sha1Hash, 'filename' => $filename, 'sourceUri' => $sourceUri, 'temporaryFileAndPathname' => $temporaryFileAndPathname]);
     $this->value = $resource;
 }
 /**
  * @param array $module
  * @return mixed
  */
 public function indexAction(array $module)
 {
     $moduleRequest = new ActionRequest($this->request);
     $moduleRequest->setArgumentNamespace('moduleArguments');
     $moduleRequest->setControllerObjectName($module['controller']);
     $moduleRequest->setControllerActionName($module['action']);
     if (isset($module['format'])) {
         $moduleRequest->setFormat($module['format']);
     }
     if ($this->request->hasArgument($moduleRequest->getArgumentNamespace()) === true && is_array($this->request->getArgument($moduleRequest->getArgumentNamespace()))) {
         $moduleRequest->setArguments($this->request->getArgument($moduleRequest->getArgumentNamespace()));
     }
     foreach ($this->request->getPluginArguments() as $argumentNamespace => $argument) {
         $moduleRequest->setArgument('--' . $argumentNamespace, $argument);
     }
     $modules = explode('/', $module['module']);
     $moduleConfiguration = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $modules));
     $moduleConfiguration['path'] = $module['module'];
     if (!$this->menuHelper->isModuleEnabled($moduleConfiguration['path'])) {
         throw new DisabledModuleException(sprintf('The module "%s" is disabled. You can enable it with the "enabled" flag in Settings.yaml.', $module['module']), 1437148922);
     }
     $moduleBreadcrumb = array();
     $path = array();
     foreach ($modules as $moduleIdentifier) {
         array_push($path, $moduleIdentifier);
         $config = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $path));
         $moduleBreadcrumb[implode('/', $path)] = $config;
     }
     $moduleRequest->setArgument('__moduleConfiguration', $moduleConfiguration);
     $moduleResponse = new Response($this->response);
     $this->dispatcher->dispatch($moduleRequest, $moduleResponse);
     if ($moduleResponse->hasHeader('Location')) {
         $this->redirectToUri($moduleResponse->getHeader('Location'), 0, $moduleResponse->getStatusCode());
     } elseif ($moduleRequest->getFormat() !== 'html') {
         $mediaType = MediaTypes::getMediaTypeFromFilename('file.' . $moduleRequest->getFormat());
         if ($mediaType !== 'application/octet-stream') {
             $this->controllerContext->getResponse()->setHeader('Content-Type', $mediaType);
         }
         return $moduleResponse->getContent();
     } else {
         $user = $this->securityContext->getPartyByType('TYPO3\\Neos\\Domain\\Model\\User');
         $sites = $this->menuHelper->buildSiteList($this->controllerContext);
         $this->view->assignMultiple(array('moduleClass' => implode('-', $modules), 'moduleContents' => $moduleResponse->getContent(), 'title' => $moduleRequest->hasArgument('title') ? $moduleRequest->getArgument('title') : $moduleConfiguration['label'], 'rootModule' => array_shift($modules), 'submodule' => array_shift($modules), 'moduleConfiguration' => $moduleConfiguration, 'moduleBreadcrumb' => $moduleBreadcrumb, 'user' => $user, 'modules' => $this->menuHelper->buildModuleList($this->controllerContext), 'sites' => $sites));
     }
 }
 /**
  * @test
  * @dataProvider mediaTypesWithAndWithoutParameters
  */
 public function trimMediaTypeReturnsJustTheTypeAndSubTypeWithoutParameters($mediaType, $expectedResult)
 {
     $actualResult = MediaTypes::trimMediaType($mediaType);
     $this->assertSame($expectedResult, $actualResult);
 }
 /**
  * Update the resource on an asset.
  *
  * @param AssetInterface $asset
  * @param FlowResource $resource
  * @param array $options
  * @throws InvalidArgumentValueException
  * @return void
  */
 public function updateAssetResourceAction(AssetInterface $asset, FlowResource $resource, array $options = [])
 {
     $sourceMediaType = MediaTypes::parseMediaType($asset->getMediaType());
     $replacementMediaType = MediaTypes::parseMediaType($resource->getMediaType());
     // Prevent replacement of image, audio and video by a different mimetype because of possible rendering issues.
     if (in_array($sourceMediaType['type'], ['image', 'audio', 'video']) && $sourceMediaType['type'] !== $replacementMediaType['type']) {
         $this->addFlashMessage('Resources of type "%s" can only be replaced by a similar resource. Got type "%s"', '', Message::SEVERITY_WARNING, [$sourceMediaType['type'], $resource->getMediaType()], 1462308179);
         $this->redirect('index');
     }
     parent::updateAssetResourceAction($asset, $resource, $options);
 }
 /**
  * Returns a file extension fitting to the media type of this asset
  *
  * @return string
  */
 public function getFileExtension()
 {
     return MediaTypes::getFilenameExtensionFromMediaType($this->resource->getMediaType());
 }
 /**
  * Returns the Media Type for this resource
  *
  * @return string The IANA Media Type
  * @api
  */
 public function getMediaType()
 {
     if ($this->mediaType === null) {
         return MediaTypes::getMediaTypeFromFilename($this->filename);
     } else {
         return $this->mediaType;
     }
 }
 /**
  * Strips off any parameters from the given media type and returns just the type
  * and subtype in the format "type/subtype".
  * @see \TYPO3\Flow\Utility\MediaTypes::trimMediaType()
  *
  * @param string $rawMediaType The full media type, for example "application/json; charset=UTF-8"
  * @return string Just the type and subtype, for example "application/json"
  * @deprecated since Flow 2.1. Use \TYPO3\Flow\Utility\MediaTypes::trimMediaType() instead
  */
 public static function trimMediaType($rawMediaType)
 {
     return MediaTypes::trimMediaType($rawMediaType);
 }
 /**
  * Initializes the controller
  *
  * This method should be called by the concrete processRequest() method.
  *
  * @param \TYPO3\Flow\Mvc\RequestInterface $request
  * @param \TYPO3\Flow\Mvc\ResponseInterface $response
  * @throws \TYPO3\Flow\Mvc\Exception\UnsupportedRequestTypeException
  */
 protected function initializeController(\TYPO3\Flow\Mvc\RequestInterface $request, \TYPO3\Flow\Mvc\ResponseInterface $response)
 {
     if (!$request instanceof ActionRequest) {
         throw new \TYPO3\Flow\Mvc\Exception\UnsupportedRequestTypeException(get_class($this) . ' only supports action requests – requests of type "' . get_class($request) . '" given.', 1187701131);
     }
     $this->request = $request;
     $this->request->setDispatched(true);
     $this->response = $response;
     $this->uriBuilder = new UriBuilder();
     $this->uriBuilder->setRequest($this->request);
     $this->arguments = new Arguments(array());
     $this->controllerContext = new ControllerContext($this->request, $this->response, $this->arguments, $this->uriBuilder);
     $mediaType = $request->getHttpRequest()->getNegotiatedMediaType($this->supportedMediaTypes);
     if ($mediaType === null) {
         $this->throwStatus(406);
     }
     if ($request->getFormat() === null) {
         $this->request->setFormat(MediaTypes::getFilenameExtensionFromMediaType($mediaType));
     }
 }
 /**
  * Returns the Media Type for this resource
  *
  * @return string The IANA Media Type
  * @api
  */
 public function getMediaType()
 {
     return MediaTypes::getMediaTypeFromFilename('x.' . $this->getFileExtension());
 }
 /**
  * Set the suggested filename of this Object
  *
  * @param string $filename
  * @return void
  */
 public function setFilename($filename)
 {
     $pathInfo = UnicodeFunctions::pathinfo($filename);
     $extension = isset($pathInfo['extension']) ? '.' . strtolower($pathInfo['extension']) : '';
     $this->filename = $pathInfo['filename'] . $extension;
     $this->mediaType = MediaTypes::getMediaTypeFromFilename($this->filename);
 }