Modifies an existing media.

@param UploadedFile $uploadedFile
@param $data
@param UserInterface $user

@throws FileVersionNotFoundException
@throws InvalidMediaTypeException

@return Media
553485
private function modifyMedia($uploadedFile, $data, $user)
    {
        $mediaEntity = $this->getEntityById($data['id']);
        $mediaEntity->setChanger($user);
        $mediaEntity->setChanged(new \DateTime());

        $files = $mediaEntity->getFiles();
        if (!isset($files[0])) {
            throw new FileNotFoundException('File was not found in media entity with the id . ' . $data['id']);
        }

        /** @var File $file */
        $file = $files[0]; // currently a media can only have one file

        $file->setChanger($user);
        $file->setChanged(new \DateTime());

        $version = $file->getVersion();

        $currentFileVersion = $file->getFileVersion($version);

        if (!$currentFileVersion) {
            throw new FileVersionNotFoundException($mediaEntity->getId(), $version);
        }

        if ($uploadedFile) {
            // new uploaded file
            ++$version;
            $this->validator->validate($uploadedFile);
            $type = $this->typeManager->getMediaType($uploadedFile->getMimeType());
            if ($type !== $mediaEntity->getType()->getId()) {
                throw new InvalidMediaTypeException('New media version must have the same media type.');
            }

            $data['storageOptions'] = $this->storage->save(
                $uploadedFile->getPathname(),
                $this->getNormalizedFileName($uploadedFile->getClientOriginalName()),
                $currentFileVersion->getStorageOptions()
            );
            $data['name'] = $uploadedFile->getClientOriginalName();
            $data['size'] = intval($uploadedFile->getSize());
            $data['mimeType'] = $uploadedFile->getMimeType();
            $data['properties'] = $this->getProperties($uploadedFile);
            $data['type'] = [
                'id' => $type,
            ];
            $data['version'] = $version;

            $fileVersion = clone $currentFileVersion;
            $this->em->persist($fileVersion);

            $fileVersion->setChanged(new \DateTime());
            $fileVersion->setChanger($user);
            $fileVersion->setCreated(new \DateTime());
            $fileVersion->setCreator($user);
            $fileVersion->setDownloadCounter(0);

            $file->setVersion($version);
            $fileVersion->setVersion($version);
            $fileVersion->setFile($file);
            $file->addFileVersion($fileVersion);

            // delete old fileversion from cache
            $this->formatManager->purge(
                $mediaEntity->getId(),
                $currentFileVersion->getName(),
                $currentFileVersion->getMimeType(),
                $currentFileVersion->getStorageOptions()
            );
        } else {
            // not setable in update
            $data['name'] = null;
            $data['size'] = null;
            $data['type'] = null;
            $data['version'] = null;
            $data['mimeType'] = null;
            $data['storageOptions'] = null;
            $data['changed'] = date('Y-m-d H:i:s');

            if ((isset($data['focusPointX']) && $data['focusPointX'] != $currentFileVersion->getFocusPointX())
                || (isset($data['focusPointY']) && $data['focusPointY'] != $currentFileVersion->getFocusPointY())
            ) {
                $currentFileVersion->increaseSubVersion();
                $this->formatManager->purge(
                    $mediaEntity->getId(),
                    $currentFileVersion->getName(),
                    $currentFileVersion->getMimeType(),
                    $currentFileVersion->getStorageOptions()
                );
            }
        }

        $media = new Media($mediaEntity, $data['locale'], null);

        $media = $this->setDataToMedia(
            $media,
            $data,
            $user
        );

        $this->em->persist($media->getEntity());
        $this->em->flush();

        return $media;
    }
532700
public function initializeMediaFromUploadedFile(UploadedFile $uploadedFile, $folderId, $siteId, $title = null)
    {
        /** @var MediaInterface $media */
        $media = new $this->mediaClass();
        $media->setSiteId($siteId);
        $media->setFile($uploadedFile);
        $media->setFilesystemName($uploadedFile->getFilename());
        $media->setMediaFolder($this->folderRepository->find($folderId));
        $media->setName($uploadedFile->getClientOriginalName());
        $media->setMimeType($uploadedFile->getMimeType());
        if (null === $title) {
            $title = $uploadedFile->getFilename();
        }
        foreach ($this->frontLanguages as $language) {
            $media->addTitle($language, $title);
        }

        return $media;
    }
695212
public function createImage(UploadedFile $uploadedImage)
    {
        $image = $this->imageManager->create();
        $filename = $this->getUniqueFilename($uploadedImage);

        $image->setFilename($filename);
        $image->setMimeType($uploadedImage->getClientMimeType());
        $image->setOrderNr(1);
        $image->setOriginalPath($this->filesystem->getRelativeFilePath($filename));
        $image->setPath($image->getOriginalPath());
        $image->setSize($uploadedImage->getClientSize());
        $image->setTemporary(true);

        $this->imageManager->add($image);

        $fileDir = $this->filesystem->getActualFileDir($filename);

        $uploadedImage->move($fileDir, $image->getFilename());

        return $image;
    }
847613
public function saveCorrection(array $data, User $user)
    {
        $this->om->startFlushSuite();
        $existingCorrection = $this->correctionRepo->findOneBy(['uuid' => $data['id']]);
        $isNew = empty($existingCorrection);
        $correction = $this->serializer->get(Correction::class)->deserialize($data);
        $correction->setUser($user);
        $dropzone = $correction->getDrop()->getDropzone();

        if (!$isNew) {
            $correction->setLastEditionDate(new \DateTime());
        }
        $correction = $this->computeCorrectionScore($correction);
        $this->om->persist($correction);
        $this->om->endFlushSuite();

        if ($isNew) {
            $this->eventDispatcher->dispatch('log', new LogCorrectionStartEvent($dropzone, $correction->getDrop(), $correction));
        } else {
            $this->eventDispatcher->dispatch('log', new LogCorrectionUpdateEvent($dropzone, $correction->getDrop(), $correction));
        }

        return $correction;
    }
1345629
public function getFileFromChunks(UploadedFile $uploadedFile)
    {
        $filename = time() . '-' . $uploadedFile->getClientOriginalName();
        $path = $this->tmpDir . DIRECTORY_SEPARATOR . $filename;

        if (FlowBasic::save($path, $this->tmpDir)) {
            return new UploadedFile($path, $uploadedFile->getClientOriginalName(), $uploadedFile->getClientMimeType());
        }

        return null;
    }
490643
public function setFileUpload(UploadedFile $file = null)
    {
        $propertyName = $this->getFileUploadPropertyName(__FUNCTION__);

        unset($this->fileUploads[$propertyName]);
        if ($file instanceof UploadedFile) {
            $this->fileUploads[$propertyName] = $file;
        }
    }
143155
public function edit(Resource $instance, $form, $userId = null)
    {
        try {
            $uploadedFile = $this->fetchUploadedFile($form);

            $xmlFile = $this->getSharedStimulusFile($uploadedFile);

            $this->getUploadService()->remove($uploadedFile);

            // throws an exception of invalid
            SharedStimulusImporter::isValidSharedStimulus($xmlFile);

            $embeddedFile = static::embedAssets($xmlFile);

            $report = $this->replaceSharedStimulus($instance, $this->getDecodedUri($form), $embeddedFile, $userId);
        } catch (\Exception $e) {
            $message = $e instanceof common_exception_UserReadableException
                ? $e->getUserMessage()
                : __('An error has occurred. Please contact your administrator.');
            $report = Report::createFailure($message);
            $this->logError($e->getMessage());
            $report->setData(['uriResource' => '']);
        }

        return $report;
    }
359596
public function import($class, $form, $userId = null)
    {
        $uploadedFile = $this->fetchUploadedFile($form);

        try {
            $service = MediaService::singleton();
            $classUri = $class->getUri();

            $instanceUri = $form instanceof Form
                ? $form->getValue('instanceUri')
                : (isset($form['instanceUri']) ? $form['instanceUri'] : null);

            $fileInfo = $form instanceof Form ? $form->getValue('source') : $form['source'];

            // importing new media
            if (!$instanceUri || $instanceUri === $classUri) {
                //if the file is a zip do a zip import
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    try {
                        self::isValidSharedStimulus($uploadedFile);

                        $mediaResourceUri = $service->createMediaInstance(
                            $uploadedFile,
                            $classUri,
                            \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                            $fileInfo['name'],
                            'application/qti+xml',
                            $userId
                        );

                        if (!$mediaResourceUri) {
                            $report = Report::createFailure(__('Fail to import Shared Stimulus'));
                            $report->setData(['uriResource' => '']);
                        } else {
                            $report = Report::createSuccess(__('Shared Stimulus imported successfully'));
                            $report->add(Report::createSuccess(
                                __('Imported %s', $fileInfo['name']),
                                ['uriResource' => $mediaResourceUri] // 'uriResource' key is needed by javascript in tao/views/templates/form/import.tpl
                            ));
                        }
                    } catch (XmlStorageException $e) {
                        // The shared stimulus is not qti compliant, display error
                        $report = Report::createFailure($e->getMessage());
                        $report->setData(['uriResource' => '']);
                    }
                } else {
                    $report = $this->getZipImporter()->import($class, $form, $userId);
                }
            } else {
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    self::isValidSharedStimulus($uploadedFile);
                    if (in_array($fileInfo['type'], array('application/xml', 'text/xml'))) {
                        $name = basename($fileInfo['name'], 'xml');
                        $name .= 'xhtml';
                        $filepath = \tao_helpers_File::concat([dirname($fileInfo['name']), $name]);
                        $fileResource = fopen($filepath, 'w');
                        $uploadedFileResource = $uploadedFile->readStream();
                        stream_copy_to_stream($uploadedFileResource, $fileResource);
                        fclose($fileResource);
                        fclose($uploadedFileResource);
                    }

                    if (!$service->editMediaInstance(
                        isset($filepath) ? $filepath : $uploadedFile,
                        $instanceUri,
                        \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                        $userId
                    )) {
                        $report = Report::createFailure(__('Fail to edit shared stimulus'));
                    } else {
                        $report = Report::createSuccess(__('Shared Stimulus edited successfully'));
                    }

                    $report->setData(['uriResource' => $instanceUri]);
                } else {
                    $report = $this->getZipImporter()->edit(new \core_kernel_classes_Resource($instanceUri), $form, $userId);
                }
            }

        } catch (\Exception $e) {
            $message = $e instanceof \common_exception_UserReadableException
                ? $e->getUserMessage()
                : __('An error has occurred. Please contact your administrator.');
            $report = Report::createFailure($message);
            $report->setData(['uriResource' => '']);
            $this->logError($e->getMessage());
        }

        $this->getUploadService()->remove($uploadedFile);

        return $report;
    }
1019637
public static function createFromUploadedFile(UploadedFile $file = null)
    {
        if (!$file instanceof UploadedFile) {
            return;
        }

        $instance = new static();

        self::$generic_file->moveUploadedFile(new File($file,
            $file->getClientOriginalName()), null, $instance);

        return $instance;
    }
1020398
public function editUser(
        UserEditData $data = null,
        ?string $name = null
    ): FormInterface {
        $name = $name ?: StringUtil::fqcnToBlockPrefix(UserEditType::class);
        $data = $data ?? new UserEditData();
        $options = null !== $data->getVersionInfo()
            ? ['language_codes' => $data->getVersionInfo()->languageCodes]
            : [];

        return $this->formFactory->createNamed($name, UserEditType::class, $data, $options);
    }
486100
public function deleteUploadedFile(UploadedFile $uploadedFile)
    {
        $file = $uploadedFile->getPathname();
        if ($this->files->isFile($file) === true) {
            $this->files->delete($file);
        }
        $this->cleanDirectory($this->chunkPath());

        return $this;
    }
779190
private static function convertUploadedFiles(array $uploadedFiles)
    {
        $files = [];
        foreach ($uploadedFiles as $name => $uploadedFile) {
            if (!is_array($uploadedFile)) {
                $files[$name] = self::convertUploadedFile($uploadedFile);
                continue;
            }

            $files[$name] = [];
            foreach ($uploadedFile as $file) {
                $files[$name][] = self::convertUploadedFile($file);
            }
        }

        return $files;
    }
219940
public function import($class, $form, $userId = null)
    {
        try {
            $uploadedFile = $this->fetchUploadedFile($form);
            $resource = new core_kernel_classes_Class($form instanceof Form ? $form->getValue('classUri') : $form['classUri']);

            // unzip the file
            try {
                \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::LONG);
                $directory = $this->extractArchive($uploadedFile);
                \helpers_TimeOutHelper::reset();
            } catch (\Exception $e) {
                $report = Report::createFailure(__('Unable to extract the archive'));
                $report->setData(['uriResource' => '']);

                return $report;
            }

            // get list of directory in order to create classes
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::CURRENT_AS_FILEINFO | \RecursiveDirectoryIterator::SKIP_DOTS),
                \RecursiveIteratorIterator::LEAVES_ONLY
            );

            $service = MediaService::singleton();
            $language = $form instanceof Form ? $form->getValue('lang') : $form['lang'];

            $this->directoryMap = [
                rtrim($directory, DIRECTORY_SEPARATOR) => $resource->getUri()
            ];
            $report = Report::createSuccess(__('Media imported successfully'));

            /** @var $file \SplFileInfo */
            foreach ($iterator as $file) {
                if ($file->isFile()) {
                    $this->logInfo('File ' . $file->getPathname());
                    if (isset($this->directoryMap[$file->getPath()])) {
                        $classUri = $this->directoryMap[$file->getPath()];
                    } else {
                        $classUri = $this->createClass($file->getPath());
                    }

                    $mediaResourceUri = $service->createMediaInstance($file->getRealPath(), $classUri, $language, $file->getFilename(), null, $userId);
                    $report->add(Report::createSuccess(
                        __('Imported %s', substr($file->getRealPath(), strlen($directory))),
                        ['uriResource' => $mediaResourceUri] // 'uriResource' key is needed by javascript in tao/views/templates/form/import.tpl
                    ));
                }
            }
        } catch (\Exception $e) {
            $message = $e instanceof \common_exception_UserReadableException
                ? $e->getUserMessage()
                : __('An error has occurred. Please contact your administrator.');
            $report = Report::createFailure($message);
            $this->logError($e->getMessage());
            $report->setData(['uriResource' => '']);
        }

        return $report;
    }
1188169
public function createFileFromUpload(Upload $file, User $actor)
    {
        // Generate a guaranteed unique Uuid.
        while ($uuid = Uuid::uuid4()->toString()) {
            if (!$this->findByUuid($uuid)) {
                break;
            }
        }

        return (new File())->forceFill([
            'uuid'      => $uuid,
            'base_name' => $this->getBasename($file, $uuid),
            'size'      => $file->getSize(),
            'type'      => $file->getClientMimeType(),
            'actor_id'  => $actor->id,
        ]);
    }
623325
private function getSubFolder(UploadedFile $uploadedFile)
    {
        // Find mime type
        $mimeType = $uploadedFile->getMimeType();

        // Clean mime-type for charset
        // and other useless stuff
        if (strpos($mimeType, ';')) {
            $mimeType = explode(';', $mimeType);

            return strtolower($mimeType[0]);
        }

        // Force mime-type to lowercase
        $mimeType = strtolower($mimeType);

        // Split mime-type into type and extension
        $mimeType = explode('/', $mimeType);

        return ($mimeType[0] == 'image') ? 'images/original' : 'data';
    }
159211
private function doRequestUpload(UploadedFile $file)
    {
        $tmpDirectory = $this->getApplication()->getTemporaryDir();
        $data = [];

        if (null !== $file) {
            if ($file->isValid()) {
                if ($file->getClientSize() <= $file->getMaxFilesize()) {
                    $data = $this->buildData($file->getClientOriginalName(), $file->guessExtension());
                    $file->move($tmpDirectory, $data['filename']);
                    $data['size'] = round($file->getClientSize() / 1024, 2);
                    if ($imageInfo = @getimagesize( $data['path'])) {
                        if (isset($imageInfo[0]) && isset($imageInfo[1])) {
                            $data['width'] = $imageInfo[0];
                            $data['height'] = $imageInfo[1];
                        }
                    } else {
                        $data['width'] = 0;
                        $data['height'] = 0;
                    }
                } else {
                    throw new BadRequestHttpException('Too big file, the max file size is ' . $file->getMaxFilesize());
                }
            } else {
                throw new BadRequestHttpException($file->getErrorMessage());
            }
        }

        return $data;
    }
270050
private function validateExtension(UploadedFile $uploadedFile) {
        $pathInfo = pathinfo($uploadedFile->getName());
        if(!isset($pathInfo['extension'])) {
            throw new Exception('No Extension Found(' . $uploadedFile->getName() . ')', 401);
        }
        $extension = strtolower($pathInfo['extension']);
        if(!in_array($extension, $this->getAllowedExtensions())) {
            throw new Exception('Invalid Type of File Uploaded, valid types: ' . implode(', ', $this->getAllowedExtensions()), 401);
        }
    }