/** * @throws FileException */ public function upload() { if ($this->file instanceof File) { $name = sha1($this->file->getClientOriginalName() . uniqid() . getrandmax()) . '.' . $this->file->guessExtension(); $this->file->move($this->getWeb() . $this->folder, $name); $this->file = $name; } else { throw new FileException('It must be a Symfony\\Component\\HttpFoundation\\File\\File instance'); } }
public function upload() { if (null === $this->file) { return; } // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error $this->file->move($this->getUploadRootDir(), $this->charte_file); unset($this->file); }
/** * @param FormEvent $event */ public function move(FormEvent $event) { $data = $event->getData(); if (is_callable($this->dstDir)) { $dstDir = call_user_func($this->dstDir, $event->getForm()->getParent()->getData()); } else { $dstDir = $this->dstDir; } if (!empty($data)) { foreach ($data as $key => $path) { // First check if the file is still in tmp directory $originalFilename = $this->rootDir . '/../web/' . trim($path, '/'); $destinationFilename = $this->rootDir . '/../web/' . trim($dstDir, '/') . '/' . basename($path); $webPath = rtrim($dstDir, '/') . '/' . basename($path); if (file_exists($originalFilename)) { // if it does, then move it to the destination and update the data $file = new File($originalFilename); $file->move(dirname($destinationFilename)); // modify the form data with the new path $data[$key] = $webPath; } else { // otherwise check if it is already on the destination if (file_exists($destinationFilename)) { // if it does, simply modify the form data with the new path // modify the form data with the new path $data[$key] = $webPath; } else { // TODO : check if we need to throw an exception here unset($data[$key]); } } } $event->setData($data); } }
protected function handle() { $request = $this->getRequest(); $posts = $request->request; $file_path = $posts->get('image_path'); $x = $posts->get('x'); $y = $posts->get('y'); $w = $posts->get('w'); $h = $posts->get('h'); $path_info = pathinfo($file_path); $imagine = new Imagine(); $raw_image = $imagine->open($file_path); $large_image = $raw_image->copy(); $large_image->crop(new Point($x, $y), new Box($w, $h)); $large_file_path = "{$path_info['dirname']}/{$path_info['filename']}_large.{$path_info['extension']}"; $large_image->save($large_file_path, array('quality' => 70)); $origin_dir_name = $path_info['dirname']; $new_directory = str_replace('/tmp', '', $origin_dir_name); $new_file = new File($large_file_path); $new_file->move($new_directory, "{$path_info['filename']}.{$path_info['extension']}"); $container = $this->getContainer(); $cdn_url = $container->getParameter('cdn_url'); $new_uri = $cdn_url . '/upload/' . $path_info['filename'] . '.' . $path_info['extension']; @unlink($large_file_path); @unlink($file_path); return new JsonResponse(array('picture_uri' => $new_uri)); }
/** * @param File $image * @param string $prefix * @param String $path * @return string */ public function moveFile(File $image, $path, $prefix = '') { $extension = $image->guessExtension(); $code = strtoupper($this->request->get('code')); $fileName = $code . '-' . $prefix . '.' . $extension; $image->move(public_path() . $path, $fileName); return $path . $fileName; }
/** * {@inheritDoc} * * Use the move function provided by Symfony File Object */ public function move(BaseFileInterface $baseFile) { $name = $this->getNamer()->rename($baseFile); $file = new File($this->getUri($baseFile)); $baseFile->setPath(sprintf('%s/%s', $this->getUploadDir(), $name)); $baseFile->setName($name); $file->move($this->getUploadDir(), $name); }
/** * Save uploaded file without validation * * @param File $file * @param string $newLocation * @param string $newName * @throws FileException * @return File */ protected function saveFile(File $file, $newLocation, $newName = "") { $name = $file->getClientOriginalName(); if ($newName) { $name = $newName; } return $file->move($this->createFolderIfNotExist($newLocation), $this->getUniqueFileName($name, $newLocation)); }
/** * Set the avatar of the object to be a specific file * * @param File|null $file The avatar file * @return self */ public function setAvatarFile($file) { if ($file) { $filename = $this->getAvatarFileName(); $file->move(DOC_ROOT . static::AVATAR_LOCATION, $filename); $this->setAvatar(static::AVATAR_LOCATION . $filename); } return $this; }
public function storeFileInPath($path, File $file, $name = null) { $filename = $name ? $name : $file->getClientOriginalName(); for ($i = 2; file_exists($path . $filename); $i++) { $filename = $i . '_' . $filename; } $file->move($path, $filename); return $filename; }
protected function handle() { $request = $this->getRequest(); $posts = $request->request; $crop_type = $request->query->get('type'); $file_path = $posts->get('image_path'); $x = $posts->get('x'); $y = $posts->get('y'); $w = $posts->get('w'); $h = $posts->get('h'); $path_info = pathinfo($file_path); $imagine = new Imagine(); $raw_image = $imagine->open($file_path); $large_image = $raw_image->copy(); $large_image->crop(new Point($x, $y), new Box($w, $h)); $large_file_path = "{$path_info['dirname']}/{$path_info['filename']}_large.{$path_info['extension']}"; $large_image->save($large_file_path, array('quality' => 100)); $origin_dir_name = $path_info['dirname']; $new_file = new File($large_file_path); // 重命名文件 if ($crop_type == 'icon') { $format_dir = '/favicon/{yyyy}{mm}{dd}'; } elseif ($crop_type == 'logo') { $format_dir = '/logo/{yyyy}{mm}{dd}'; } else { $format_dir = '/image/{yyyy}{mm}{dd}'; } $format_filename = '{time}{rand:6}'; $t = time(); $d = explode('-', date("Y-y-m-d-H-i-s")); $new_path = str_replace("{yyyy}", $d[0], $format_dir); $new_path = str_replace("{yy}", $d[1], $new_path); $new_path = str_replace("{mm}", $d[2], $new_path); $new_path = str_replace("{dd}", $d[3], $new_path); $new_path = str_replace("{hh}", $d[4], $new_path); $new_path = str_replace("{ii}", $d[5], $new_path); $new_path = str_replace("{ss}", $d[6], $new_path); $new_file_name = $format_filename; $new_file_name = str_replace("{time}", $t, $new_file_name); $new_file_name = preg_replace("/[\\|\\?\"\\<\\>\\/\\*\\\\]+/", '', $new_file_name); //替换随机字符串 $randNum = rand(1, 10000000000) . rand(1, 10000000000); if (preg_match("/\\{rand\\:([\\d]*)\\}/i", $new_file_name, $matches)) { $new_file_name = preg_replace("/\\{rand\\:[\\d]*\\}/i", substr($randNum, 0, $matches[1]), $new_file_name); } $new_file_name = $new_file_name . '.' . $path_info['extension']; $new_directory = str_replace('/tmp', '/upload' . $new_path, $origin_dir_name); $new_file->move($new_directory, $new_file_name); $container = $this->getContainer(); $cdn_url = $container->getParameter('cdn_url'); $new_uri = $cdn_url . '/upload' . $new_path . '/' . $new_file_name; @unlink($large_file_path); @unlink($file_path); return new JsonResponse(array('picture_uri' => $new_uri)); }
/** * Set the avatar of the object to be a specific file * * @param File|null $file The avatar file * @return self */ public function setAvatarFile($file) { if ($file) { // We don't use File's fread() because it's unavailable in less // recent PHP versions $path = $file->getPath() . '/' . $file->getFilename(); $content = file_get_contents($path); $path = $this->getAvatarPath(null, false, false); $filename = $this->getAvatarFileName($content); $file->move(DOC_ROOT . $path, $filename); $this->setAvatar($path . $filename); } return $this; }
public function testMove() { $path = __DIR__ . '/Fixtures/test.copy.gif'; $targetPath = __DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'test.target.gif'; @unlink($path); @unlink($targetPath); copy(__DIR__ . '/Fixtures/test.gif', $path); $file = new File($path); $file->move($targetPath); $this->assertTrue(file_exists($targetPath)); $this->assertFalse(file_exists($path)); $this->assertEquals($targetPath, $file->getPath()); @unlink($path); @unlink($targetPath); }
/** * @param \Exolnet\Image\Imageable $image * @param \Symfony\Component\HttpFoundation\File\File $file * @return bool * @throws \Exolnet\Core\Exceptions\ServiceValidationException */ public function store(Imageable $image, File $file) { if (!$image->getFilename()) { throw new ServiceValidationException('Could not store image with an empty filename.'); } $path = dirname($image->getImagePath()); $filename = basename($image->getImagePath()); if (!$this->filesystem->exists($path)) { $this->filesystem->makeDirectory($path, 0755, true); } if (!$this->filesystem->isWritable($path)) { throw new ServiceValidationException('The image base path "' . $path . '" is not writable.'); } $file->move($path, $filename); return true; }
/** * Move the uploaded file from the temporary location to the permanent one * if required by configuration. * * @throws FileUploadException * * @return true */ public function move() { $this->checkDirectories(); $targetDir = $this->getTargetFileDirectory(); $targetFile = $this->getTargetFileName(); try { $this->file->move($targetDir, $targetFile); $this->fullPath = realpath($targetDir . DIRECTORY_SEPARATOR . $targetFile); $this->app['logger.system']->debug('[BoltForms] Moving uploaded file to ' . $this->fullPath . '.', array('event' => 'extensions')); } catch (FileException $e) { $error = 'File upload aborted as the target directory could not be writen to.'; $this->app['logger.system']->error('[BoltForms] ' . $error . ' Check permissions on ' . $targetDir, array('event' => 'extensions')); throw new FileUploadException('File upload aborted as the target directory could not be writen to.'); } return true; }
/** * @param resource|string|UploadedFile $resource * @return string Asset identifier */ public function put($resource) { $tmpFileName = tempnam('/tmp', 'test_'); if ($resource instanceof UploadedFile) { $pathinfo = pathinfo($tmpFileName); $resource->move($pathinfo['dirname'], $pathinfo['basename']); } else { file_put_contents($tmpFileName, $resource); } $checksum = sha1_file($tmpFileName); $file = new File($tmpFileName); $targetFileName = $checksum . '.' . $file->guessExtension(); $target = $file->move($this->storageDirectory, $targetFileName); $filesystem = new Filesystem(); $filesystem->chmod($target, 0777); return $targetFileName; }
public function testMoveToAnUnexistentDirectory() { $sourcePath = __DIR__ . '/Fixtures/test.copy.gif'; $targetDir = __DIR__ . '/Fixtures/directory/sub'; $targetPath = $targetDir . '/test.copy.gif'; @unlink($sourcePath); @unlink($targetPath); @rmdir($targetDir); copy(__DIR__ . '/Fixtures/test.gif', $sourcePath); $file = new File($sourcePath); $movedFile = $file->move($targetDir); $this->assertFileExists($targetPath); $this->assertFileNotExists($sourcePath); $this->assertEquals(realpath($targetPath), $movedFile->getRealPath()); @unlink($sourcePath); @unlink($targetPath); @rmdir($targetDir); }
/** * Move files of extension type. * * @param string|array $extension The extensions you need to find * @param string $actualDir Source directory * @param string $targetDir Target directory * @param bool $throwExceptionIfNotFound Throws an exeption if files are not found * * @throws Exception If files are not found */ protected function moveFiles($extension, $actualDir, $targetDir, $throwExceptionIfNotFound = true) { if (!is_array($extension)) { $extension = (array) $extension; } $finder = new Finder(); $finder->files()->in($actualDir); foreach ($extension as $ext) { $finder->name($ext); } if (iterator_count($finder) < 1) { if (!$throwExceptionIfNotFound) { return; } throw new \Exception(sprintf('There is no files with extensions %s.', implode(', ', $extension))); } foreach ($finder as $file) { $f = new File($file->getRealpath(), true); $f->move($targetDir, $file->getFilename()); } }
private function clean($root, $path) { $dels = array(); $dir = opendir($path); while ($entry = @readdir($dir)) { if (is_dir($path . '/' . $entry) && $entry != '.' && $entry != '..') { $dels[] = $path . '/' . $entry; $this->clean($root, $path . '/' . $entry); } elseif ($entry != '.' && $entry != '..') { $file = new File($path . '/' . $entry); if (in_array($file->getMimeType(), $this->mimeTypes)) { $file->move($root, $entry); } else { $this->remove($path . '/' . $entry); } } } closedir($dir); foreach ($dels as $del) { $this->remove($del); } }
public function edit(Application $app, Request $request, $id = null) { /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */ $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete'); $softDeleteFilter->setExcludes(array('Eccube\\Entity\\ProductClass')); $has_class = false; if (is_null($id)) { $Product = new \Eccube\Entity\Product(); $ProductClass = new \Eccube\Entity\ProductClass(); $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE); $Product->setDelFlg(Constant::DISABLED)->addProductClass($ProductClass)->setStatus($Disp); $ProductClass->setDelFlg(Constant::DISABLED)->setStockUnlimited(true)->setProduct($Product); $ProductStock = new \Eccube\Entity\ProductStock(); $ProductClass->setProductStock($ProductStock); $ProductStock->setProductClass($ProductClass); } else { $Product = $app['eccube.repository.product']->find($id); if (!$Product) { throw new NotFoundHttpException(); } // 規格あり商品か $has_class = $Product->hasProductClass(); if (!$has_class) { $ProductClasses = $Product->getProductClasses(); $ProductClass = $ProductClasses[0]; $ProductStock = $ProductClasses[0]->getProductStock(); } } $builder = $app['form.factory']->createBuilder('admin_product', $Product); // 規格あり商品の場合、規格関連情報をFormから除外 if ($has_class) { $builder->remove('class'); } $form = $builder->getForm(); if (!$has_class) { $ProductClass->setStockUnlimited((bool) $ProductClass->getStockUnlimited()); $form['class']->setData($ProductClass); } // ファイルの登録 $images = array(); $ProductImages = $Product->getProductImage(); foreach ($ProductImages as $ProductImage) { $images[] = $ProductImage->getFileName(); } $form['images']->setData($images); $categories = array(); $ProductCategories = $Product->getProductCategories(); foreach ($ProductCategories as $ProductCategory) { /* @var $ProductCategory \Eccube\Entity\ProductCategory */ $categories[] = $ProductCategory->getCategory(); } $form['Category']->setData($categories); if ('POST' === $request->getMethod()) { $form->handleRequest($request); if ($form->isValid()) { $Product = $form->getData(); if (!$has_class) { $ProductClass = $form['class']->getData(); $app['orm.em']->persist($ProductClass); // 在庫情報を作成 if (!$ProductClass->getStockUnlimited()) { $ProductStock->setStock($ProductClass->getStock()); } else { // 在庫無制限時はnullを設定 $ProductStock->setStock(null); } $app['orm.em']->persist($ProductStock); } // カテゴリの登録 // 一度クリア /* @var $Product \Eccube\Entity\Product */ foreach ($Product->getProductCategories() as $ProductCategory) { $Product->removeProductCategory($ProductCategory); $app['orm.em']->remove($ProductCategory); } $app['orm.em']->persist($Product); $app['orm.em']->flush(); $count = 1; $Categories = $form->get('Category')->getData(); foreach ($Categories as $Category) { $ProductCategory = new \Eccube\Entity\ProductCategory(); $ProductCategory->setProduct($Product)->setProductId($Product->getId())->setCategory($Category)->setCategoryId($Category->getId())->setRank($count); $app['orm.em']->persist($ProductCategory); $count++; /* @var $Product \Eccube\Entity\Product */ $Product->addProductCategory($ProductCategory); } // 画像の登録 $add_images = $form->get('add_images')->getData(); foreach ($add_images as $add_image) { $ProductImage = new \Eccube\Entity\ProductImage(); $ProductImage->setFileName($add_image)->setProduct($Product)->setRank(1); $Product->addProductImage($ProductImage); $app['orm.em']->persist($ProductImage); // 移動 $file = new File($app['config']['image_temp_realdir'] . '/' . $add_image); $file->move($app['config']['image_save_realdir']); } // 画像の削除 $delete_images = $form->get('delete_images')->getData(); foreach ($delete_images as $delete_image) { $ProductImage = $app['eccube.repository.product_image']->findOneBy(array('file_name' => $delete_image)); // 追加してすぐに削除した画像は、Entityに追加されない if ($ProductImage instanceof \Eccube\Entity\ProductImage) { $Product->removeProductImage($ProductImage); $app['orm.em']->remove($ProductImage); } $app['orm.em']->persist($Product); // 削除 $fs = new Filesystem(); $fs->remove($app['config']['image_save_realdir'] . '/' . $delete_image); } $app['orm.em']->persist($Product); $app['orm.em']->flush(); $ranks = $request->get('rank_images'); if ($ranks) { foreach ($ranks as $rank) { list($filename, $rank_val) = explode('//', $rank); $ProductImage = $app['eccube.repository.product_image']->findOneBy(array('file_name' => $filename, 'Product' => $Product)); $ProductImage->setRank($rank_val); $app['orm.em']->persist($ProductImage); } } $app['orm.em']->flush(); $app->addSuccess('admin.register.complete', 'admin'); return $app->redirect($app->url('admin_product_product_edit', array('id' => $Product->getId()))); } else { $app->addError('admin.register.failed', 'admin'); } } // 検索結果の保持 $searchForm = $app['form.factory']->createBuilder('admin_search_product')->getForm(); if ('POST' === $request->getMethod()) { $searchForm->handleRequest($request); } return $app->render('Product/product.twig', array('Product' => $Product, 'form' => $form->createView(), 'searchForm' => $searchForm->createView(), 'has_class' => $has_class, 'id' => $id)); }
/** * $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; }
/** * Moves the file to a new location. * * @param string $directory The destination folder * @param string $name The new file name * * @return File A File object representing the new file * * @throws FileException if the file has not been uploaded via Http * * @api */ public function move($directory, $name = null) { if ($this->isValid() && ($this->test || is_uploaded_file($this->getPathname()))) { return parent::move($directory, $name); } throw new FileException(sprintf('The file "%s" has not been uploaded via Http', $this->getPathname())); }
public function edit(Application $app, Request $request, $id = null) { $has_class = false; if (is_null($id)) { $Product = new \Eccube\Entity\Product(); $ProductClass = new \Eccube\Entity\ProductClass(); $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE); $Product->setDelFlg(Constant::DISABLED)->addProductClass($ProductClass)->setStatus($Disp); $ProductClass->setDelFlg(Constant::DISABLED)->setStockUnlimited(true)->setProduct($Product); $ProductStock = new \Eccube\Entity\ProductStock(); $ProductClass->setProductStock($ProductStock); $ProductStock->setProductClass($ProductClass); } else { $Product = $app['eccube.repository.product']->find($id); if (!$Product) { throw new NotFoundHttpException(); } // 規格あり商品か $has_class = $Product->hasProductClass(); if (!$has_class) { $ProductClasses = $Product->getProductClasses(); $ProductClass = $ProductClasses[0]; $BaseInfo = $app['eccube.repository.base_info']->get(); if ($BaseInfo->getOptionProductTaxRule() == Constant::ENABLED && $ProductClass->getTaxRule() && !$ProductClass->getTaxRule()->getDelFlg()) { $ProductClass->setTaxRate($ProductClass->getTaxRule()->getTaxRate()); } $ProductStock = $ProductClasses[0]->getProductStock(); } } $builder = $app['form.factory']->createBuilder('admin_product', $Product); // 規格あり商品の場合、規格関連情報をFormから除外 if ($has_class) { $builder->remove('class'); } $event = new EventArgs(array('builder' => $builder, 'Product' => $Product), $request); $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_INITIALIZE, $event); $form = $builder->getForm(); if (!$has_class) { $ProductClass->setStockUnlimited((bool) $ProductClass->getStockUnlimited()); $form['class']->setData($ProductClass); } // ファイルの登録 $images = array(); $ProductImages = $Product->getProductImage(); foreach ($ProductImages as $ProductImage) { $images[] = $ProductImage->getFileName(); } $form['images']->setData($images); $categories = array(); $ProductCategories = $Product->getProductCategories(); foreach ($ProductCategories as $ProductCategory) { /* @var $ProductCategory \Eccube\Entity\ProductCategory */ $categories[] = $ProductCategory->getCategory(); } $form['Category']->setData($categories); $Tags = array(); $ProductTags = $Product->getProductTag(); foreach ($ProductTags as $ProductTag) { $Tags[] = $ProductTag->getTag(); } $form['Tag']->setData($Tags); if ('POST' === $request->getMethod()) { $form->handleRequest($request); if ($form->isValid()) { $Product = $form->getData(); if (!$has_class) { $ProductClass = $form['class']->getData(); // 個別消費税 $BaseInfo = $app['eccube.repository.base_info']->get(); if ($BaseInfo->getOptionProductTaxRule() == Constant::ENABLED) { if ($ProductClass->getTaxRate()) { if ($ProductClass->getTaxRule() && !$ProductClass->getTaxRule()->getDelFlg()) { $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate()); } else { $taxrule = $app['eccube.repository.tax_rule']->newTaxRule(); $taxrule->setTaxRate($ProductClass->getTaxRate()); $taxrule->setApplyDate(new \DateTime()); $taxrule->setProduct($Product); $taxrule->setProductClass($ProductClass); $ProductClass->setTaxRule($taxrule); } } else { if ($ProductClass->getTaxRule()) { $ProductClass->getTaxRule()->setDelFlg(Constant::ENABLED); } } } $app['orm.em']->persist($ProductClass); // 在庫情報を作成 if (!$ProductClass->getStockUnlimited()) { $ProductStock->setStock($ProductClass->getStock()); } else { // 在庫無制限時はnullを設定 $ProductStock->setStock(null); } $app['orm.em']->persist($ProductStock); } // カテゴリの登録 // 一度クリア /* @var $Product \Eccube\Entity\Product */ foreach ($Product->getProductCategories() as $ProductCategory) { $Product->removeProductCategory($ProductCategory); $app['orm.em']->remove($ProductCategory); } $app['orm.em']->persist($Product); $app['orm.em']->flush(); $count = 1; $Categories = $form->get('Category')->getData(); foreach ($Categories as $Category) { $ProductCategory = new \Eccube\Entity\ProductCategory(); $ProductCategory->setProduct($Product)->setProductId($Product->getId())->setCategory($Category)->setCategoryId($Category->getId())->setRank($count); $app['orm.em']->persist($ProductCategory); $count++; /* @var $Product \Eccube\Entity\Product */ $Product->addProductCategory($ProductCategory); } // 画像の登録 $add_images = $form->get('add_images')->getData(); foreach ($add_images as $add_image) { $ProductImage = new \Eccube\Entity\ProductImage(); $ProductImage->setFileName($add_image)->setProduct($Product)->setRank(1); $Product->addProductImage($ProductImage); $app['orm.em']->persist($ProductImage); // 移動 $file = new File($app['config']['image_temp_realdir'] . '/' . $add_image); $file->move($app['config']['image_save_realdir']); } // 画像の削除 $delete_images = $form->get('delete_images')->getData(); foreach ($delete_images as $delete_image) { $ProductImage = $app['eccube.repository.product_image']->findOneBy(array('file_name' => $delete_image)); // 追加してすぐに削除した画像は、Entityに追加されない if ($ProductImage instanceof \Eccube\Entity\ProductImage) { $Product->removeProductImage($ProductImage); $app['orm.em']->remove($ProductImage); } $app['orm.em']->persist($Product); // 削除 $fs = new Filesystem(); $fs->remove($app['config']['image_save_realdir'] . '/' . $delete_image); } $app['orm.em']->persist($Product); $app['orm.em']->flush(); $ranks = $request->get('rank_images'); if ($ranks) { foreach ($ranks as $rank) { list($filename, $rank_val) = explode('//', $rank); $ProductImage = $app['eccube.repository.product_image']->findOneBy(array('file_name' => $filename, 'Product' => $Product)); $ProductImage->setRank($rank_val); $app['orm.em']->persist($ProductImage); } } $app['orm.em']->flush(); // 商品タグの登録 // 商品タグを一度クリア $ProductTags = $Product->getProductTag(); foreach ($ProductTags as $ProductTag) { $Product->removeProductTag($ProductTag); $app['orm.em']->remove($ProductTag); } // 商品タグの登録 $Tags = $form->get('Tag')->getData(); foreach ($Tags as $Tag) { $ProductTag = new ProductTag(); $ProductTag->setProduct($Product)->setTag($Tag); $Product->addProductTag($ProductTag); $app['orm.em']->persist($ProductTag); } $app['orm.em']->flush(); $event = new EventArgs(array('form' => $form, 'Product' => $Product), $request); $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE, $event); $app->addSuccess('admin.register.complete', 'admin'); return $app->redirect($app->url('admin_product_product_edit', array('id' => $Product->getId()))); } else { $app->addError('admin.register.failed', 'admin'); } } // 検索結果の保持 $builder = $app['form.factory']->createBuilder('admin_search_product'); $event = new EventArgs(array('builder' => $builder, 'Product' => $Product), $request); $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_SEARCH, $event); $searchForm = $builder->getForm(); if ('POST' === $request->getMethod()) { $searchForm->handleRequest($request); } return $app->render('Product/product.twig', array('Product' => $Product, 'form' => $form->createView(), 'searchForm' => $searchForm->createView(), 'has_class' => $has_class, 'id' => $id)); }
/** * {@inheritDoc} */ public function load(ObjectManager $manager) { // Cocktails $daiquiri = $this->getReference("daiquiri"); $pinaColada = $this->getReference("pinaColada"); $margarita = $this->getReference("margarita"); $sexOnTheBeach = $this->getReference("sexOnTheBeach"); $caipirinha = $this->getReference("caipirinha"); $cosmopolitan = $this->getReference("cosmopolitan"); $blueLagoon = $this->getReference("blueLagoon"); $tequilaSunrise = $this->getReference("tequilaSunrise"); $boraBora = $this->getReference("boraBora"); $zombie = $this->getReference("zombie"); $fs = new Filesystem(); $path = $this->container->getParameter('kernel.root_dir') . '/../src/Automatiz/ApiBundle/DataFixtures/Images/'; $fs->remove($this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'); $fs->copy($path . "daiquirii.jpg", $path . "daiquirii-copy.jpg"); $file = new File($path . "daiquirii-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $daiquiri->setImage($image); $manager->persist($daiquiri); $fs->copy($path . "pina-colada.jpg", $path . "pina-colada-copy.jpg"); $file = new File($path . "pina-colada-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $pinaColada->setImage($image); $manager->persist($pinaColada); $fs->copy($path . "margarita.jpg", $path . "margarita-copy.jpg"); $file = new File($path . "margarita-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $margarita->setImage($image); $manager->persist($margarita); $fs->copy($path . "sex-on-the-beach.jpg", $path . "sex-on-the-beach-copy.jpg"); $file = new File($path . "sex-on-the-beach-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $sexOnTheBeach->setImage($image); $manager->persist($sexOnTheBeach); $fs->copy($path . "caipirinha.jpg", $path . "caipirinha-copy.jpg"); $file = new File($path . "caipirinha-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $caipirinha->setImage($image); $manager->persist($caipirinha); $fs->copy($path . "cosmopolitan.jpg", $path . "cosmopolitan-copy.jpg"); $file = new File($path . "cosmopolitan-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $cosmopolitan->setImage($image); $manager->persist($cosmopolitan); $fs->copy($path . "blue-lagoon.jpg", $path . "blue-lagoon-copy.jpg"); $file = new File($path . "blue-lagoon-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $blueLagoon->setImage($image); $manager->persist($blueLagoon); $fs->copy($path . "tequila-sunrise.jpg", $path . "tequila-sunrise-copy.jpg"); $file = new File($path . "tequila-sunrise-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $tequilaSunrise->setImage($image); $manager->persist($tequilaSunrise); $fs->copy($path . "bora-bora.jpg", $path . "bora-bora-copy.jpg"); $file = new File($path . "bora-bora-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $boraBora->setImage($image); $manager->persist($boraBora); $fs->copy($path . "zombie.jpg", $path . "zombie-copy.jpg"); $file = new File($path . "zombie-copy.jpg"); $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures'; $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($imageDir, $fileName); $image = new Image(); $image->setFile($fileName); $image->setPath($imageDir); $image->setUrl("/uploads/cocktails_pictures/" . $fileName); $zombie->setImage($image); $manager->persist($zombie); $manager->flush(); }
private function resizeImages($dir,$image){ $container = $this->container; $imagemanagerResponse = $container->get('liip_imagine.controller'); $filterConfiguration = $container->get('liip_imagine.filter.configuration'); $configuracion = $filterConfiguration->get('my_thumb'); $filterConfiguration->set('my_thumb', $configuracion); $imagemanagerResponse->filterAction($this->getRequest(),'/images/ids/'.$dir.'/'.$image,'my_thumb'); $fileTemporal = new File('media/cache/my_thumb/images/ids/'.$dir.'/'.$image); $fileTemporal->move('images/ids/'.$dir.'/',$image); $document = new Document(); $document->deleteDir("/media/cache/my_thumb/images/ids/".$dir); }
public function changeIndexPicture($filePath, $options) { $pathinfo = pathinfo($filePath); $imagine = new Imagine(); $rawImage = $imagine->open($filePath); $largeImage = $rawImage->copy(); $largeImage->crop(new Point($options['x'], $options['y']), new Box($options['width'], $options['height'])); $largeImage->resize(new Box(216, 120)); $largeFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}_large.{$pathinfo['extension']}"; $largeImage->save($largeFilePath, array('quality' => 90)); $largeFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}_large.{$pathinfo['extension']}"; $largeFileRecord = $this->getFileService()->uploadFile('article', new File($largeFilePath)); $uri = $largeFileRecord['uri']; $fileOriginalName = basename($uri); $fileOriginalExtension = pathinfo($uri, PATHINFO_EXTENSION); $fileOriginalNameNew = str_replace(".{$fileOriginalExtension}", "_orig.{$fileOriginalExtension}", $fileOriginalName); $fileOriginalPath = str_replace(array('public://', "{$fileOriginalName}"), '', $uri); $fileOriginalDirectory = $pathinfo['dirname'] . '/' . $fileOriginalPath; $fileOriginalDirectory = str_replace(array("/tmp", '\\tmp'), "", $fileOriginalDirectory); $fileOriginalDirectory = substr($fileOriginalDirectory, 0, -1); $new_file = new File($filePath); $file_res = $new_file->move($fileOriginalDirectory, $fileOriginalNameNew); @unlink($filePath); $webPath = realpath($this->getKernel()->getParameter('topxia.upload.public_directory')) . "/"; return array('fileOriginalName' => $fileOriginalName, 'fileOriginalNameNew' => $fileOriginalNameNew, 'fileOriginalPath' => str_replace($webPath, "", $fileOriginalDirectory)); }
/** * Saves the given file in a temporary directory and remember the name of temporary file in a session * * @param File $file * @param string $temporaryFilePrefix * @param string $temporaryFileExtension */ public function saveImportingFile(File $file, $temporaryFilePrefix, $temporaryFileExtension) { $tmpFileName = $this->fileSystemOperator->generateTemporaryFileName($temporaryFilePrefix, $temporaryFileExtension); $file->move(dirname($tmpFileName), basename($tmpFileName)); $this->session->set($this->getImportFileSessionKey($temporaryFilePrefix, $temporaryFileExtension), $tmpFileName); }
/** * Moves the file to a new location. * * @param string $directory The destination folder * @param string $name The new file name * * @return File A File object representing the new file * * @throws FileException if, for any reason, the file could not have been moved */ public function move($directory, $name = null) { if ($this->isValid()) { if ($this->test) { return parent::move($directory, $name); } $target = $this->getTargetFile($directory, $name); if (!@move_uploaded_file($this->getPathname(), $target)) { $error = error_get_last(); throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message']))); } @chmod($target, 0666 & ~umask()); return $target; } throw new FileException($this->getErrorMessage()); }
/** * Move the file * * @param FileInfo $fileInfo * @param string $new_file_name */ public function moveFile(FileInfo $fileInfo, $new_file_name) { try { $this->validateFile($fileInfo); $file_path = $fileInfo->getFilepath(true); $file = new File($file_path, false); $file->move($new_file_name); } catch (\Exception $e) { $this->getFileManager()->throwError("Cannot move file or directory", 500, $e); } }
public function testMoveFailing() { $path = __DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'test.copy.gif'; $targetPath = '/thisfolderwontexist'; @unlink($path); @unlink($targetPath); copy(__DIR__ . '/Fixtures/test.gif', $path); $file = new File($path); try { $file->move($targetPath); $this->fail('File::move should throw an exception.'); } catch (FileException $e) { } $this->assertFileExists($path); $this->assertFileNotExists($path . $targetPath . 'test.gif'); $this->assertEquals($path, $file->getPath()); @unlink($path); @unlink($targetPath); }
/** * @param File $file * @param User $user */ private function uploadFile(File $file, User $user) { $filename = 'emergya-' . $user->getNick() . '.' . $file->getClientOriginalExtension(); $file->move($this->getParameter('uploads_directory'), $filename); $user->setAvatar($filename); }