getExtension() public method

\SplFileInfo::getExtension() is not available before PHP 5.3.6
public getExtension ( ) : string
return string The extension
Example #1
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     parent::buildView($view, $form, $options);
     $data = $form->getData();
     if (is_string($data)) {
         $data = ['filename' => basename($data), 'url' => $data];
     }
     if (is_array($data)) {
         if (!isset($view->var['url']) && isset($data['url'])) {
             $view->vars['url'] = $data['url'];
         }
         if (!isset($view->var['filename']) && isset($data['filename'])) {
             $view->vars['filename'] = $data['filename'];
         }
     }
     // autodetect type of upload
     $uploadtype = $options['uploadtype'];
     if (isset($view->vars['filename'])) {
         $file = new File($view->vars['filename'], false);
         $view->vars['filetype'] = $file->getExtension();
         switch ($file->getExtension()) {
             case 'png':
             case 'jpg':
             case 'jpeg':
             case 'gif':
                 $uploadtype = 'image';
                 break;
             case 'mp4':
                 $uploadtype = 'video';
                 break;
             case 'mp3':
             case 'm4v':
                 $uploadtype = 'audio';
                 break;
             default:
                 break;
         }
     }
     $view->vars['uploadtype'] = $uploadtype;
     $view->vars['placeholdWidth'] = $options['placeholdWidth'];
     $view->vars['placeholdHeight'] = $options['placeholdHeight'];
     $view->vars['placeholdText'] = $options['placeholdText'];
     $view->vars['ratio'] = $options['ratio'];
     $view->vars['remove'] = $options['remove'];
     $pattern = $options['pattern'];
     if ($pattern != null) {
         if (!$this->container->hasParameter($pattern)) {
             throw new \Exception('You must define an existing pattern');
         }
         $patternSize = $this->container->getParameter($pattern);
         $view->vars['label'] .= ' (Max width: ' . $patternSize['width'] . ', Max height: ' . $patternSize['height'] . ')';
     }
 }
 /**
  * @param Contribution $contribution
  * @param File         $file
  *
  * @return string
  */
 public function generateRelativePath(Contribution $contribution, File $file)
 {
     $path = $contribution->getAuthProvider() . DIRECTORY_SEPARATOR;
     $path .= $contribution->getIdentifier();
     $path .= '.' . ($file->guessExtension() ?: $file->getExtension());
     return $path;
 }
Example #3
0
 /**
  * Use Symfony components to guess the file extension.
  *
  * @return string
  *         File extension
  */
 public function getExtension()
 {
     if (!is_null($this->extension)) {
         return $this->extension;
     }
     return $this->extension = $this->info->getExtension() ?: $this->info->guessExtension();
 }
Example #4
0
 protected static function boot()
 {
     parent::boot();
     static::updating(function ($model) {
         $changed = $model->getDirty();
         if (isset($changed['name'])) {
             $slug = $model->gallery->slug;
             $path = public_path() . '/gallery_assets/galleries/' . $slug;
             //Get old file
             $oldPath = $path . '/' . $model->file;
             $file = new File($oldPath);
             //Set the new file with original extension
             $newName = strtolower(str_slug($model->name) . '_' . str_random(5)) . '.' . $file->getExtension();
             $renamed = $path . '/' . $newName;
             //Rename asset
             if (rename($file, $renamed)) {
                 $model->setAttribute('file', $newName);
                 return true;
             } else {
                 return false;
             }
         }
         return true;
     });
     static::deleting(function ($model) {
         $slug = $model->gallery->slug;
         $path = public_path() . '/gallery_assets/galleries/' . $slug;
         $oldPath = $path . '/' . $model->file;
         $file = new File($oldPath);
         @unlink($file);
         //@ to prevent errors
         return true;
     });
 }
 protected function getExtension()
 {
     $extension = 'jpg';
     if (in_array(strtolower($this->realImage->getExtension()), static::$allowedExtensions)) {
         $extension = strtolower($this->realImage->getExtension());
     }
     return $extension;
 }
Example #6
0
 /**
  * Calculate the filename of the resultant file or version.
  *
  * @param File        $original The original file
  * @param string|null $version  The name of the version, or null
  *
  * @return string The resultant filename
  */
 public function getFilename(File $original, $version = null)
 {
     if (is_null($version)) {
         return $original->getBasename();
     }
     $extension = $original->getExtension();
     $base = $original->getBasename($extension);
     return $base . $version . '.' . $extension;
 }
Example #7
0
 /**
  * @param \Symfony\Component\HttpFoundation\File\File $img
  * @param string                                      $path
  *
  * @return string
  */
 public function saveImg(File $img, $path)
 {
     $imageLib = new ImageLib();
     $imageLib->load($path . $img->getFilename());
     $outputImgName = md5($img->getFilename() . time()) . '.' . $img->getExtension();
     //$imageLib->resizeImage(100, 100, array('crop', 'tr'), true);
     $imageLib->saveImage($path . $outputImgName, 100);
     return $outputImgName;
 }
 /**
  * Replaces the current file with a new file.
  *
  * @param UploadedFile $file           The target file
  * @param File         $filesystemFile The source file
  */
 public function replaceFromFilesystem(UploadedFile $file, File $filesystemFile)
 {
     $file->setOriginalFilename($filesystemFile->getBasename());
     $file->setExtension($filesystemFile->getExtension());
     $file->setMimeType($filesystemFile->getMimeType());
     $file->setSize($filesystemFile->getSize());
     $storage = $this->getStorage($file);
     if ($filesystemFile->getSize() > $this->container->get("partkeepr_systemservice")->getFreeDiskSpace()) {
         throw new DiskSpaceExhaustedException();
     }
     $storage->write($file->getFullFilename(), file_get_contents($filesystemFile->getPathname()), true);
 }
 /**
  * @param $filename
  *
  * @return string
  */
 public function visualizar_archivo($filename = null)
 {
     if ($filename) {
         $pathFile = $this->uploads_directory_name . '/' . $filename;
         $file = new File($pathFile);
         $img = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'pjpeg'];
         if (in_array($file->getExtension(), $img)) {
             return '<img src="' . $this->packages->getUrl($pathFile) . '" height="60">';
         }
         return '<a href="' . $this->packages->getUrl($pathFile) . '" download>Descargar archivo</a>';
     }
 }
 /**
  * @param string $path Path to the file
  *
  * @return Response
  */
 public function getFile($path)
 {
     if (is_file($path)) {
         $file = new File($path);
         $fileContent = file_get_contents($path);
         $response = new Response($fileContent);
         $response->headers->set('Content-Type', $this->getContentType($file->getExtension()));
         $response->setCharset('UTF-8');
         return $response;
     }
     return new Response('File not found', 404);
 }
 protected function sendFile(Gitiki $gitiki, $file, $responseClass)
 {
     try {
         $fileInfo = new File(__DIR__ . '/../Resources/highlightjs/' . $file);
     } catch (FileNotFoundException $e) {
         $gitiki->abort(404, 'The file "%s" does not exists');
     }
     $response = new $responseClass($fileInfo);
     $request = $gitiki['request'];
     $response->headers->set('content-type', $request->getMimeType($fileInfo->getExtension()));
     $response->setMaxAge(0)->isNotModified($request);
     return $response;
 }
 /**
  * @see Command
  *
  * @throws \InvalidArgumentException When the target directory does not exist
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->getContainer()->get('kernel')->getRootDir();
     $targetArg = rtrim($input->getArgument('target'), '/') . '/';
     $rootDir = $this->getContainer()->get('kernel')->getRootDir();
     $targetDir = $rootDir . '/../' . $targetArg;
     $confDir = $rootDir . '/config';
     if (!is_dir($targetDir)) {
         throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target')));
     }
     if (!file_exists($confDir . '/assets.json')) {
         throw new \InvalidArgumentException('The file ' . $confDir . '/assets.json does not exist.');
     }
     $output->writeln("Combining assets");
     $assetsFiles = json_decode(file_get_contents($confDir . '/assets.json'), true);
     foreach ($assetsFiles as $type => $combined) {
         foreach ($combined as $name => $files) {
             file_put_contents($targetDir . $files['output'], '');
             $this->assets[$type][$name] = (array) $files['input'];
             foreach ($this->assets[$type][$name] as $value) {
                 file_put_contents($targetDir . $files['output'], file_get_contents($targetDir . $value), FILE_APPEND);
             }
             $file = $targetDir . $files['output'];
             if (is_file($file)) {
                 $f = new File($file);
                 switch ($f->getExtension()) {
                     case 'css':
                         $resource = new AssetCollection(array(new FileAsset($file)), array(new MinifyCssCompressorFilter()));
                         $resource->load();
                         file_put_contents($file, $resource->dump());
                         $output->writeln(sprintf('File <comment>%s</comment> was combined and minified', $file));
                         break;
                     case 'js':
                         $resource = new AssetCollection(array(new FileAsset($file)), array(new JSMinPlusFilter()));
                         $resource->load();
                         file_put_contents($file, $resource->dump());
                         $output->writeln(sprintf('File <comment>%s</comment> was combined and minified', $file));
                         break;
                 }
             }
         }
     }
 }
Example #13
0
 /**
  * @param File $file
  * @return string
  */
 protected function getNormalizedFilename(File $file)
 {
     if ($file instanceof UploadedFile) {
         $originalFilename = $file->getClientOriginalName();
         $size = $file->getClientSize();
     } else {
         $originalFilename = $file->getFilename();
         $size = $file->getSize();
     }
     $name = preg_replace(self::REGEX_FILENAME_EXT, '', $originalFilename);
     $name = preg_replace(self::REGEX_INVALID_FILENAME_CHARS, '_', $name);
     $hash = substr(sha1(json_encode(array(time(), $name, $size))), 0, 7);
     $ext = $file->getExtension();
     if (!$ext) {
         $ext = explode('.', $originalFilename);
         $ext = end($ext);
     }
     $filename = sprintf('%s_%s.%s', $name, $hash, $ext);
     return $filename;
 }
Example #14
0
 public function documentsAction($filename, $originalName = null)
 {
     $documentManager = $this->get('wealthbot_user.document_manager');
     try {
         $file = new File($this->container->getParameter('uploads_documents_dir') . '/' . $filename);
     } catch (FileNotFoundException $e) {
         throw $this->createNotFoundException('File does not exist.');
     }
     if ($file->getExtension() === 'zip') {
         if (null === $originalName) {
             $originalName = $filename;
         }
     } else {
         $document = $documentManager->findDocumentBy(array('filename' => $filename));
         if (!$document) {
             throw $this->createNotFoundException('Document does not exist.');
         }
         if (null === $originalName) {
             $originalName = $document->getOriginalName();
         }
     }
     return $this->prepareResponse($file, $originalName);
 }
Example #15
0
 /**
  * Set file
  *
  * @param File $file
  * @return $this
  */
 public function setFile(File $file = null)
 {
     $this->file = $file;
     if (is_file($this->getAbsolutePath())) {
         $this->temp = $this->getAbsolutePath();
     }
     if (null !== $file) {
         $extension = $file->getExtension() ? $file->getExtension() : $file->guessExtension();
         if ($file instanceof UploadedFile) {
             $this->setOriginalName($file->getClientOriginalName());
             if (!$extension) {
                 $extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
             }
             $filename = sha1($file->getClientOriginalName() . rand(0, 99999)) . '.' . $extension;
             $mimeType = $file->getMimeType();
         } else {
             $this->setOriginalName($file->getFilename());
             $filename = sha1($file->getFilename() . rand(0, 99999)) . '.' . $extension;
             $mimeType = $file->getMimeType();
         }
         $this->setFilename($filename);
         $this->setMimeType($mimeType);
     }
     return $this;
 }
Example #16
0
 public function testGetExtension()
 {
     $file = new File(__DIR__ . '/Fixtures/test.gif');
     $this->assertEquals('gif', $file->getExtension());
 }
Example #17
0
 /**
  * Given a single File, assuming is an image, create a new
  * Image object containing all needed information.
  *
  * This method also persists and flush created entity
  *
  * @param File $file File where to get the image
  *
  * @return ImageInterface Image created
  *
  * @throws InvalidImageException File is not an image
  */
 public function createImage(File $file)
 {
     $fileMime = $file->getMimeType();
     if ('application/octet-stream' === $fileMime) {
         $imageSizeData = getimagesize($file->getPathname());
         $fileMime = $imageSizeData['mime'];
     }
     if (strpos($fileMime, 'image/') !== 0) {
         throw new InvalidImageException();
     }
     $extension = $file->getExtension();
     if (!$extension && $file instanceof UploadedFile) {
         $extension = $file->getClientOriginalExtension();
     }
     /**
      * @var ImageInterface $image
      */
     $image = $this->imageFactory->create();
     if (!isset($imageSizeData)) {
         $imageSizeData = getimagesize($file->getPathname());
     }
     $name = $file->getFilename();
     $image->setWidth($imageSizeData[0])->setHeight($imageSizeData[1])->setContentType($fileMime)->setSize($file->getSize())->setExtension($extension)->setName($name);
     return $image;
 }
Example #18
0
 /**
  * Given a single File, assuming is an image, create a new
  * Image object containing all needed information.
  *
  * This method also persists and flush created entity
  *
  * @param File $file File where to get the image
  *
  * @return ImageInterface Image created
  *
  * @throws InvalidImageException File is not an image
  */
 public function createImage(File $file)
 {
     $fileMime = $file->getMimeType();
     if (strpos($fileMime, 'image/') !== 0) {
         throw new InvalidImageException();
     }
     /**
      * @var ImageInterface $image
      */
     $image = $this->imageFactory->create();
     $imageSizeData = getimagesize($file->getPathname());
     $name = $file->getFilename();
     $image->setWidth($imageSizeData[0])->setHeight($imageSizeData[1])->setContentType($fileMime)->setSize($file->getSize())->setExtension($file->getExtension())->setName($name);
     return $image;
 }
 /**
  * Generate file path relative to contributed media directory
  *
  * @param Contribution $contribution
  * @param SplFileInfo  $file
  *
  * @return string
  */
 public function generateAbsolutePath(Contribution $contribution, File $file)
 {
     return $this->directory . DIRECTORY_SEPARATOR . $contribution->getAuthProvider() . DIRECTORY_SEPARATOR . $contribution->getIdentifier() . '.' . ($file->guessExtension() ?: $file->getExtension());
 }
 /**
  * Upload a file, storing it in the temporary
  *
  * @param File  $file
  * @param Media $media
  *
  * @throws Exception\MediaFileDeniedException
  * @return Media
  */
 public function upload(File $file, Media $media = null)
 {
     if (!$media instanceof Media) {
         $media = new $this->class();
     }
     if ($file instanceof UploadedFile) {
         $extension = $file->getClientOriginalExtension();
         $oldName = $file->getClientOriginalName();
     } else {
         $extension = $file->getExtension();
         $oldName = $file->getFilename();
     }
     $fileMime = $file->getMimeType();
     if (array_key_exists($fileMime, $this->accept) && in_array(strtolower($extension), $this->accept[$fileMime])) {
         $newFileName = null;
         // if the media name is set, use it over a hashed one
         if ($media->getName()) {
             if ($media->getPath() != $file->getPathname()) {
                 $newFileName = $media->getName();
             }
         } else {
             $newFileName = md5(time() . rand()) . "." . $extension;
         }
         if ($newFileName) {
             $file = $file->move($this->storePath, $newFileName);
         }
     } else {
         throw new MediaFileDeniedException($fileMime);
     }
     if ($file instanceof File) {
         /** @var Media $media */
         if (!$media->getTitle()) {
             $media->setTitle($oldName);
         }
         $oldPath = pathinfo($oldName);
         if (!$media->getNameOriginal()) {
             $media->setNameOriginal($oldName);
         }
         if (!$media->getName()) {
             $media->setName($file->getFilename());
         }
         if (!$media->getAlt()) {
             $media->setAlt($oldPath['filename']);
         }
         if (!$media->getCredits()) {
             $media->setCredits($this->user->getUsername());
         }
         $media->setSrc($this->storeDirectory . $file->getFilename());
         $media->setPath($this->storePath . $file->getFilename());
         $this->optimiser->optimise($media);
         $media->setHash(sha1_file($file->getPathname()));
     }
     return $media;
 }
Example #21
0
    /**
     * @inheritDoc
     */
    public function getExtension()
    {
        if ($this->moved) {
            return parent::getExtension();
        }

        if ($ext = pathinfo($this->getOriginalName(), PATHINFO_EXTENSION)) {
            return '.'.$ext;
        }

        return '';
    }
 /**
  * @param FileInfo $info
  *
  * @return string
  */
 protected function getExtensionFromFileInfo(FileInfo $info)
 {
     return $info instanceof UploadedFile ? $info->getClientOriginalExtension() : $info->getExtension();
 }
 /**
  * Creates a dummy file to testing purposes
  *
  * @param $file
  *
  * @return DummyFile
  */
 protected function createDummyFile($file)
 {
     $file = new File($file);
     $dummyFile = $file->getFileInfo()->getBasename("." . $file->getExtension()) . time() . "." . $file->getExtension();
     $dummyFile = $this->getParameter("kernel.cache_dir") . "/" . $dummyFile;
     copy($file->getPathname(), $dummyFile);
     return new DummyFile($dummyFile);
 }
Example #24
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // get the status
         $status = \SpoonFilter::getPostValue('status', array('active', 'draft'), 'active');
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // validate fields
         $this->frm->getField('title')->isFilled(BL::err('TitleIsRequired'));
         $this->frm->getField('text')->isFilled(BL::err('FieldIsRequired'));
         $this->frm->getField('publish_on_date')->isValid(BL::err('DateIsInvalid'));
         $this->frm->getField('publish_on_time')->isValid(BL::err('TimeIsInvalid'));
         $this->frm->getField('category_id')->isFilled(BL::err('FieldIsRequired'));
         // validate meta
         $this->meta->validate();
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['id'] = $this->id;
             $item['meta_id'] = $this->meta->save();
             // this is used to let our model know the status (active, archive, draft) of the edited item
             $item['revision_id'] = $this->record['revision_id'];
             $item['category_id'] = (int) $this->frm->getField('category_id')->getValue();
             $item['user_id'] = $this->frm->getField('user_id')->getValue();
             $item['language'] = BL::getWorkingLanguage();
             $item['title'] = $this->frm->getField('title')->getValue();
             $item['introduction'] = $this->frm->getField('introduction')->getValue();
             $item['text'] = $this->frm->getField('text')->getValue();
             $item['publish_on'] = BackendModel::getUTCDate(null, BackendModel::getUTCTimestamp($this->frm->getField('publish_on_date'), $this->frm->getField('publish_on_time')));
             $item['edited_on'] = BackendModel::getUTCDate();
             $item['hidden'] = $this->frm->getField('hidden')->getValue();
             $item['allow_comments'] = $this->frm->getField('allow_comments')->getChecked() ? 'Y' : 'N';
             $item['status'] = $status;
             if ($this->imageIsAllowed) {
                 $item['image'] = $this->record['image'];
                 // the image path
                 $imagePath = FRONTEND_FILES_PATH . '/blog/images';
                 // create folders if needed
                 $fs = new Filesystem();
                 $fs->mkdir(array($imagePath . '/source', $imagePath . '/128x128'));
                 // If the image should be deleted, only the database entry is refreshed.
                 // The revision should keep it's file.
                 if ($this->frm->getField('delete_image')->isChecked()) {
                     // reset the name
                     $item['image'] = null;
                 }
                 // new image given?
                 if ($this->frm->getField('image')->isFilled()) {
                     // build the image name
                     // we use the previous revision-id in the filename to make the filename unique between
                     // the different revisions, to prevent that a new file would
                     // overwrite images of previous revisions that have the same title, and thus, the same filename
                     $item['image'] = $this->meta->getURL() . '-' . BL::getWorkingLanguage() . '-' . $item['revision_id'] . '.' . $this->frm->getField('image')->getExtension();
                     // upload the image & generate thumbnails
                     $this->frm->getField('image')->generateThumbnails($imagePath, $item['image']);
                 } elseif ($item['image'] != null) {
                     // generate the new filename
                     $image = new File($imagePath . '/source/' . $item['image']);
                     $newName = $this->meta->getURL() . '-' . BL::getWorkingLanguage() . '-' . $item['revision_id'] . '.' . $image->getExtension();
                     // extract the filenames excluding …-[language]-[revision-id].jpg
                     // to properly compare them to eachother
                     $regex = '/(.*)-[a-z]{2}-[0-9]+\\.(.*)/';
                     // only copy if the new name differs from the old filename
                     if (preg_replace($regex, '$1', $newName) != preg_replace($regex, '$1', $item['image'])) {
                         // loop folders
                         foreach (BackendModel::getThumbnailFolders($imagePath, true) as $folder) {
                             $fs->copy($folder['path'] . '/' . $item['image'], $folder['path'] . '/' . $newName);
                         }
                         // assign the new name to the database
                         $item['image'] = $newName;
                     }
                 }
             } else {
                 $item['image'] = null;
             }
             // update the item
             $item['revision_id'] = BackendBlogModel::update($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_edit', array('item' => $item));
             // recalculate comment count so the new revision has the correct count
             BackendBlogModel::reCalculateCommentCount(array($this->id));
             // save the tags
             BackendTagsModel::saveTags($item['id'], $this->frm->getField('tags')->getValue(), $this->URL->getModule());
             // active
             if ($item['status'] == 'active') {
                 // edit search index
                 BackendSearchModel::saveIndex($this->getModule(), $item['id'], array('title' => $item['title'], 'text' => $item['text']));
                 // ping
                 if ($this->get('fork.settings')->get($this->URL->getModule(), 'ping_services', false)) {
                     BackendModel::ping(SITE_URL . BackendModel::getURLForBlock($this->URL->getModule(), 'detail') . '/' . $this->meta->getURL());
                 }
                 // build URL
                 $redirectUrl = BackendModel::createURLForAction('Index') . '&report=edited&var=' . urlencode($item['title']) . '&id=' . $this->id . '&highlight=row-' . $item['revision_id'];
             } elseif ($item['status'] == 'draft') {
                 // draft: everything is saved, so redirect to the edit action
                 $redirectUrl = BackendModel::createURLForAction('Edit') . '&report=saved-as-draft&var=' . urlencode($item['title']) . '&id=' . $item['id'] . '&draft=' . $item['revision_id'] . '&highlight=row-' . $item['revision_id'];
             }
             // append to redirect URL
             if ($this->categoryId != null) {
                 $redirectUrl .= '&category=' . $this->categoryId;
             }
             // everything is saved, so redirect to the overview
             $this->redirect($redirectUrl);
         }
     }
 }
 /**
  * @param File $file
  * @return string
  */
 private function determineContentType(File $file)
 {
     switch ($file->getExtension()) {
         case 'css':
             return 'text/css';
         case 'js':
             return 'text/javascript';
         case 'svg':
             return 'image/svg+xml';
         case 'ttf':
             return 'application/x-font-ttf';
         case 'otf':
             return 'application/x-font-opentype';
         case 'eot':
             return 'application/vnd.ms-fontobject';
         case 'woff':
             return 'application/font-woff';
         case 'woff2':
             return 'application/font-woff2';
         case 'sfnt':
             return 'application/font-sfnt';
         default:
             if ($mimeType = $file->getMimeType()) {
                 return $mimeType;
             } else {
                 return 'text/plain';
             }
     }
 }
 public static function getFileExtension(File $file)
 {
     return $file instanceof UploadedFile ? $file->getClientOriginalExtension() : $file->getExtension();
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function getExtension()
 {
     return $this->extension ?: parent::getExtension();
 }
Example #28
0
 public function testGetExtensionReturnsEmptyString()
 {
     $file = new File(__DIR__ . '/Fixtures/test');
     $this->assertEquals('', $file->getExtension());
 }
 /**
  * $current_uri String actual uri of the file
  * $dest_folder String future uri of the file starting from web/upload folder
  * $lifetime DateTime lifetime of the file. If time goes over this limit, the file will be deleted.
  **/
 public function upload(File $file, $dest_folder = '', \DateTime $lifetime = null)
 {
     if ($file instanceof UploadedFile) {
         if ($file->getError() !== null && $file->getError() !== 0) {
             throw new UploadException($file->getErrorMessage());
         }
     }
     //preparing dir name
     $dest_folder = date('Ymd') . '/' . date('G') . '/' . $dest_folder;
     //checking mimetypes
     $mimeTypePassed = false;
     foreach ($this->allowedMimetypes as $mimeType) {
         if (preg_match('@' . $mimeType . '@', $file->getMimeType())) {
             $mimeTypePassed = true;
         }
     }
     if (!$mimeTypePassed) {
         throw new InvalidMimeTypeException('Only following filetypes are allowed : ' . implode(', ', $this->allowedMimetypes));
     }
     $fs = new Filesystem();
     if (!$fs->exists($this->uploadDir . $dest_folder)) {
         $fs->mkdir($this->uploadDir . $dest_folder);
     }
     $em = $this->entityManager;
     $media = new Media();
     $media->setMime($file->getMimeType());
     // If there's one, we try to generate a new name
     $extension = $file->getExtension();
     // Sanitizing the filename
     $slugify = new Slugify();
     if ($file instanceof UploadedFile) {
         if (empty($extension)) {
             $extension = $file->getClientOriginalExtension();
             if (empty($extension)) {
                 $extension = $file->guessClientExtension();
             }
         }
         $filename = $slugify->slugify(basename($file->getClientOriginalName(), $extension)) . '.' . $extension;
     } else {
         if (empty($extension)) {
             $extension = $file->guessClientExtension();
         }
         $filename = $slugify->slugify(basename($file->getFilename(), $extension)) . '.' . $extension;
     }
     // A media can have a lifetime and will be deleted with the cleanup function
     if (!empty($lifetime)) {
         $media->setLifetime($lifetime);
     }
     // Checking for a media with the same name
     $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($dest_folder . $filename);
     $mediaExists = count($mediaExists) > 0;
     if ($mediaExists === false) {
         $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename);
     }
     if ($mediaExists === true) {
         $filename = basename($filename, '.' . $extension);
         $i = 1;
         do {
             $media->setName($filename . '-' . $i++ . '.' . $extension);
             $media->setUri($dest_folder . $media->getName());
             $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($media->getUri());
             $mediaExists = count($mediaExists) > 0;
             if ($mediaExists === false) {
                 $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename);
             }
         } while ($mediaExists === true);
     } else {
         $media->setName($filename);
         $media->setUri($dest_folder . $media->getName());
     }
     $file->move($this->uploadDir . $dest_folder, $media->getName());
     chmod($this->uploadDir . $dest_folder . $media->getName(), 0664);
     // Getting the salt defined in parameters.yml
     $secret = $this->container->getParameter('secret');
     $media->setSecretKey(hash('sha256', $secret . $media->getName() . $media->getUri()));
     $em->persist($media);
     $em->flush();
     return $media;
 }
Example #30
0
 /**
  * @return bool
  */
 public function isExtensionValid()
 {
     return $this->file && in_array($this->file->getExtension(), self::$assetsTypesMap[$this->type][$this->file->getMimeType()]);
 }