createDirectory() public static method

This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.
public static createDirectory ( string $path, integer $mode = 509, boolean $recursive = true ) : boolean
$path string path of the directory to be created.
$mode integer the permission to be set for the created directory.
$recursive boolean whether to create parent directories if they do not exist.
return boolean whether the directory is created successfully
示例#1
1
 public function attachFile()
 {
     try {
         $model = $this->owner;
         $fileName = Inflector::slug($model->fullAddress) . '.pdf';
         $folder = $this->getModelSubDir() . '/';
         $model->pdf_path = $fileName;
         $pdf = new Pdf(['mode' => Pdf::MODE_UTF8, 'destination' => Pdf::DEST_FILE, 'content' => Yii::$app->view->render('@frontend/views/site/real-estate/print', ['model' => $model]), 'methods' => ['SetHeader' => ['Rapport ' . $model->fullAddress], 'SetFooter' => ['|Pagina {PAGENO}|']], 'filename' => Yii::getAlias('@uploadsBasePath') . "/files/{$folder}{$fileName}"]);
         $this->file = $pdf;
         BaseFileHelper::removeDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}");
         if (!BaseFileHelper::createDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}")) {
             throw new Exception(Yii::t('app', 'Failed to create the file upload directory'));
         }
         // Save and update model
         $pdf->render();
         $model->save();
         return true;
     } catch (yii\base\Exception $e) {
         return $e->getMessage();
     }
 }
示例#2
0
 /**
  * @param $srcImagePath
  * @param bool $preset
  * @return string Path to cached file
  * @throws \Exception
  */
 private function createCachedFile($srcImagePath, $pathToSave, $size = null)
 {
     BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true);
     $size = $size ? $this->parseSize($size) : false;
     //        if($this->graphicsLibrary == 'Imagick'){
     $image = new \Imagick($srcImagePath);
     $image->setImageCompressionQuality(100);
     if ($size) {
         if ($size['height'] && $size['width']) {
             $image->cropThumbnailImage($size['width'], $size['height']);
         } elseif ($size['height']) {
             $image->thumbnailImage(0, $size['height']);
         } elseif ($size['width']) {
             $image->thumbnailImage($size['width'], 0);
         } else {
             throw new \Exception('Error at $this->parseSize($sizeString)');
         }
     }
     $image->writeImage($pathToSave);
     //        }
     if (!is_file($pathToSave)) {
         throw new \Exception('Error while creating cached file');
     }
     return $image;
 }
示例#3
0
 public function upload($upload_dir = 'product_image')
 {
     $file_name = [];
     if ($this->validate()) {
         $app_root = Yii::getAlias('@approot');
         $upload_path = "{$app_root}/uploads/{$upload_dir}/";
         if (!file_exists($upload_path)) {
             BaseFileHelper::createDirectory($upload_path, 0777, TRUE);
         } else {
             if (!is_dir($upload_path)) {
                 unlink($upload_path);
                 $this->upload($upload_dir);
             }
         }
         foreach ($this->imageFiles as $file) {
             $file_path = "{$upload_path}{$file->baseName}.{$file->extension}";
             $file->saveAs($file_path);
             $file_info['name'] = 'product_image';
             $file_info['type'] = $file->type;
             $file_info['value'] = $file->baseName . '.' . $file->extension;
             $file_name[] = $file_info;
         }
         return $file_name;
     } else {
         return false;
     }
 }
 private function cacheDir()
 {
     $dir = Yii::getAlias(self::$cache_dir);
     if (!file_exists($dir)) {
         BaseFileHelper::createDirectory($dir, '0755');
     }
     return $dir;
 }
示例#5
0
 /**
  *
  * Method copies image file to module store and creates db record.
  *
  * @param $absolutePath
  * @param bool $isFirst
  * @return bool|Image
  * @throws \Exception
  */
 public function attachImage($absolutePath, $isMain = false, $name = '')
 {
     //        var_dump($_FILES);
     //        die;
     if (isset($_FILES['UploadForm'])) {
         $fileRealName = $_FILES['UploadForm']['name']['file'];
     } else {
         if (isset($_FILES['gallery'])) {
             $fileRealName = $_FILES['gallery']['name'];
         } else {
             $fileRealName = $absolutePath;
         }
     }
     if (!preg_match('#http#', $absolutePath)) {
         if (!file_exists($absolutePath)) {
             throw new \Exception('File not exist! :' . $absolutePath);
         }
     } else {
         //nothing
     }
     if (!$this->owner->primaryKey) {
         throw new \Exception('Owner must have primaryKey when you attach image!');
     }
     $pictureFileName = substr(md5(microtime(true) . $absolutePath), 4, 6) . '.' . pathinfo($fileRealName, PATHINFO_EXTENSION);
     $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
     $storePath = $this->getModule()->getStorePath($this->owner);
     $newAbsolutePath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName;
     BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true);
     copy($absolutePath, $newAbsolutePath);
     if (!file_exists($newAbsolutePath)) {
         throw new \Exception('Cant copy file! ' . $absolutePath . ' to ' . $newAbsolutePath);
     }
     if ($this->getModule()->className === null) {
         $image = new models\Image();
     } else {
         $class = $this->getModule()->className;
         $image = new $class();
     }
     $image->itemId = $this->owner->primaryKey;
     $image->filePath = $pictureSubDir . '/' . $pictureFileName;
     $image->modelName = $this->getModule()->getShortClass($this->owner);
     $image->name = $name;
     $image->urlAlias = $this->getAlias($image);
     if (!$image->save()) {
         return false;
     }
     if (count($image->getErrors()) > 0) {
         $ar = array_shift($image->getErrors());
         unlink($newAbsolutePath);
         throw new \Exception(array_shift($ar));
     }
     $img = $this->owner->getImage();
     //If main image not exists
     if (is_object($img) && get_class($img) == 'rico\\yii2images\\models\\PlaceHolder' or $img == null or $isMain) {
         $this->setMainImage($image);
     }
     return $image;
 }
示例#6
0
 public function generateModul()
 {
     BaseFileHelper::createDirectory($this->moduleDirectory, 509, true);
     $content = $this->modulInner();
     $moduleFullName = $this->moduleDirectory . $this->moduleName . '.php';
     $myFail = fopen($moduleFullName, "w");
     fwrite($myFail, $content);
     fclose($myFail);
     return true;
 }
示例#7
0
 public function actionUpdate($id = null)
 {
     $model = new Article();
     if ($model->load(Yii::$app->request->post())) {
         $request = Yii::$app->request->post('Article');
         $id = $request['id'];
         if ($id) {
             $model = Article::findOne($id);
             $model->attributes = $request;
         }
         if ($model->save()) {
             $this->updateOrder('cid=' . $model->cid, '&langs=' . $model->langs);
             $files = \yii\web\UploadedFile::getInstances($model, 'upload_files');
             if (isset($files) && count($files) > 0) {
                 $mPath = \Yii::getAlias('@webroot') . '/images/article/news_' . $model->id;
                 if (!is_dir($mPath)) {
                     \yii\helpers\BaseFileHelper::createDirectory($mPath);
                 }
                 foreach ($files as $file) {
                     if ($request['cid'] == '12') {
                         $mPic = $file->baseName . '.' . $file->extension;
                     } else {
                         $mPic = 'nkc_' . substr(number_format(time() * rand(), 0, '', ''), 0, 14) . '.' . $file->extension;
                     }
                     //Upload Images
                     if ($file->saveAs($mPath . '/' . $mPic)) {
                         $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                         $image->resize(1024, 1024);
                         $image->save($mPath . '/' . $mPic);
                         //resize images thumb
                         $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                         $image->resize(250, 250);
                         $mThumb = $mPath . '/thumb/';
                         if (!is_dir($mThumb)) {
                             \yii\helpers\BaseFileHelper::createDirectory($mThumb);
                         }
                         $image->save($mThumb . $mPic);
                     }
                 }
             }
             return $this->redirect(array('index'));
         } else {
             print_r($model->getErrors());
             exit;
         }
     }
     if ($id) {
         $model = Article::findOne($id);
     } else {
         $sess = Yii::$app->session->get('sessArticle');
         $model->langs = $sess['langs'];
         $model->cid = $sess['cid'];
     }
     return $this->render('update', ['model' => $model]);
 }
 /**
  * Copies the image to the assets folder and save's it in the database.
  *
  * @param   string  $absolutePath   The path were the image is uploaded   
  * @param   bool    $isMain         A flag to determine if the image is the main image
  * @param   string  $identifier     The index that has to be set for the image in the database
  * @return  bool|Image
  * @throws  \Exception
  */
 public function attachImage($absolutePath, $isMain = false, $identifier = '')
 {
     if (!preg_match('#http#', $absolutePath)) {
         if (!file_exists($absolutePath)) {
             throw new \Exception('File not exist! :' . $absolutePath);
         }
     } else {
         //nothing
     }
     if (!$this->owner->primaryKey) {
         throw new \Exception('Owner must have primaryKey when you attach image!');
     }
     $pictureFileName = basename($absolutePath);
     $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
     $storePath = $this->getModule()->getStorePath($this->owner);
     $newAbsolutePath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName;
     BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true);
     copy($absolutePath, $newAbsolutePath);
     unlink($absolutePath);
     if (!file_exists($newAbsolutePath)) {
         throw new \Exception('Cant copy file! ' . $absolutePath . ' to ' . $newAbsolutePath);
     }
     $image = new Image();
     $image->itemId = $this->owner->primaryKey;
     $image->filePath = $pictureSubDir . '/' . $pictureFileName;
     $image->modelName = $this->getModule()->getShortClass($this->owner);
     $image->urlAlias = $this->getAlias($image);
     $image->identifier = $identifier;
     $image->name = substr(yii\helpers\Inflector::slug($pictureFileName), 0, -3);
     // Get the highest position
     // @todo Create function
     $owner = $this->owner;
     $query = (new yii\db\Query())->select('MAX(`position`)')->from(Image::tableName())->where(['modelName' => yii\helpers\StringHelper::basename($owner::className())]);
     $command = $query->createCommand();
     $image->position = $command->queryOne(\PDO::FETCH_COLUMN) + 1;
     if (!$image->save()) {
         return false;
     }
     // Add the translations
     foreach (Yii::$app->params['languages'] as $language => $data) {
         $imageLang = new ImageLang();
         $imageLang->language = $language;
         $image->link('translations', $imageLang);
     }
     if (count($image->getErrors()) > 0) {
         $ar = array_shift($image->getErrors());
         unlink($newAbsolutePath);
         throw new \Exception(array_shift($ar));
     }
     $img = $this->owner->getImage();
     $this->setMainImage($image);
     return $image;
 }
示例#9
0
 /**
  *
  * Method copies image file to module store and creates db record.
  *
  * @param string|UploadedFile $newImage
  * @param bool $isMain
  * @return bool|Image
  * @throws \Exception
  */
 public function attachImage($newImage, $isMain = false)
 {
     if (!$this->owner->{$this->idAttribute}) {
         throw new \Exception($this->owner->classname() . ' must have an id when you attach image!');
     }
     $pictureFileName = '';
     if ($newImage instanceof UploadedFile) {
         $sourcePath = $newImage->tempName;
         $imageExt = $newImage->extension;
     } else {
         if (!preg_match('#http#', $newImage)) {
             if (!file_exists($newImage)) {
                 throw new \Exception('File not exist! :' . $newImage);
             }
         } else {
             //nothing
         }
         $sourcePath = $newImage;
         $imageExt = pathinfo($newImage, PATHINFO_EXTENSION);
     }
     $pictureFileName = substr(sha1(microtime(true) . $sourcePath), 4, 12);
     $pictureFileName .= '.' . $imageExt;
     if (!file_exists($sourcePath)) {
         throw new \Exception('Source file doesnt exist! ' . $sourcePath . ' to ' . $newAbsolutePath);
     }
     $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
     $storePath = $this->getModule()->getStorePath($this->owner);
     $destPath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName;
     BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true);
     if (!copy($sourcePath, $destPath)) {
         throw new \Exception('Failed to copy file from ' . $sourcePath . ' to ' . $destPath);
     }
     $image = new $this->modelClass();
     $image->item_id = $this->owner->{$this->idAttribute};
     $image->file_path = $pictureSubDir . '/' . $pictureFileName;
     $image->model_name = $this->getModule()->getShortClass($this->owner);
     $image->url_alias = $this->getAlias($image);
     if (!$image->save()) {
         return false;
     }
     if (count($image->getErrors()) > 0) {
         $ar = array_shift($image->getErrors());
         unlink($newAbsolutePath);
         throw new \Exception(array_shift($ar));
     }
     $img = $this->owner->getImage();
     // If main image not exists
     if (is_object($img) && get_class($img) == 'circulon\\images\\models\\Placeholder' or $img == null or $isMain) {
         $this->setMainImage($image);
     }
     return $image;
 }
 public function upload()
 {
     if ($this->validate()) {
         $image_dir = \Yii::getAlias('@webroot');
         $this->_uploaded_url = implode(DIRECTORY_SEPARATOR, ['', self::DIR_UPLOADS, self::DIR_IMAGES, '']);
         foreach ($this->_segments as $segment) {
             $this->_uploaded_url .= $segment . DIRECTORY_SEPARATOR;
         }
         BaseFileHelper::createDirectory($image_dir . $this->_uploaded_url, 0775, true);
         $this->_uploaded_url .= md5($this->_image_name . time()) . '.' . $this->imageFile->extension;
         $this->imageFile->saveAs($image_dir . $this->_uploaded_url);
         return true;
     } else {
         return false;
     }
 }
示例#11
0
 public function actionFileUploadAvatar()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->user->id;
         $model = User::findOne($id);
         $path = Yii::getAlias("@frontend/web/images/users/");
         BaseFileHelper::createDirectory($path);
         $model->scenario = 'view';
         $file = UploadedFile::getInstance($model, 'imgsource');
         $name = $file->baseName . '.' . $file->extension;
         $file->saveAs($path . DIRECTORY_SEPARATOR . $name);
         $model->imgsource = $name;
         $model->save();
         return true;
     }
     return false;
 }
示例#12
0
 /**
  * create book.
  * @return Book|null the saved model or null if saving fails
  */
 public function insert()
 {
     $this->preview = UploadedFile::getInstance($this, 'preview');
     if ($this->validate()) {
         $book = new Book();
         $book->name = $this->name;
         $book->date = strtotime($this->date);
         $book->author_id = $this->author_id;
         if ($book->save()) {
             // если сохранило сообщение, то дописываем файл ------------------------------
             $dir = Yii::getAlias(Yii::$app->params['previewPath']);
             // если надо - создаем каталог
             if (!is_dir($dir)) {
                 BaseFileHelper::createDirectory($dir, 0777);
             }
             $uploaded = false;
             $filename = '';
             if ($this->preview) {
                 $filename = 'b' . $book->book_id . 'preview.' . $this->preview->extension;
                 $uploaded = $this->preview->saveAs($dir . '/' . $filename);
                 // урезаем размер файла, что б не грущили 100500мегабайт и пересохраняем
                 $img = Image::getImagine()->open($dir . '/' . $filename);
                 $size = $img->getSize();
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 700;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/' . $filename, ['quality' => 80]);
                 // делаем превьюшку
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 200;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/th_' . $filename, ['quality' => 80]);
             }
             // если файл залился - пишем в базу данные по файлу
             if ($uploaded) {
                 $bookData = Book::findOne($book->book_id);
                 $bookData->preview = $filename;
                 $bookData->save();
             }
             return $book;
         }
     }
     return null;
 }
示例#13
0
 public function actionFileUploadImages()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->request->post("advert_id");
         $path = Yii::getAlias("@frontend/web/uploads/adverts/" . $id);
         BaseFileHelper::createDirectory($path);
         $file = UploadedFile::getInstanceByName('images');
         $name = time() . '.' . $file->extension;
         $file->saveAs($path . DIRECTORY_SEPARATOR . $name);
         $image = $path . DIRECTORY_SEPARATOR . $name;
         $new_name = $path . DIRECTORY_SEPARATOR . "small_" . $name;
         $size = getimagesize($image);
         $width = $size[0];
         $height = $size[1];
         Image::frame($image, 0, '666', 0)->crop(new Point(0, 0), new Box($width, $height))->resize(new Box(1000, 644))->save($new_name, ['quality' => 100]);
         sleep(1);
         return true;
     }
 }
示例#14
0
 public function attachImage($absolutePath, $isMain = false)
 {
     if (!preg_match('#http#', $absolutePath)) {
         if (!file_exists($absolutePath)) {
             throw new \Exception('File not exist! :' . $absolutePath);
         }
     }
     if (!$this->owner->id) {
         throw new \Exception('Owner must have id when you attach image!');
     }
     $pictureFileName = substr(md5(microtime(true) . $absolutePath), 4, 6) . '.' . pathinfo($absolutePath, PATHINFO_EXTENSION);
     $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
     $storePath = $this->getModule()->getStorePath($this->owner);
     $newAbsolutePath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName;
     BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true);
     copy($absolutePath, $newAbsolutePath);
     if (!file_exists($absolutePath)) {
         throw new \Exception('Cant copy file! ' . $absolutePath . ' to ' . $newAbsolutePath);
     }
     if ($this->modelClass === null) {
         $image = new models\Image();
     } else {
         $image = new ${$this->modelClass}();
     }
     $image->itemId = $this->owner->id;
     $image->filePath = $pictureSubDir . '/' . $pictureFileName;
     $image->modelName = $this->getModule()->getShortClass($this->owner);
     $image->urlAlias = $this->getAlias($image);
     if (!$image->save()) {
         return false;
     }
     if (count($image->getErrors()) > 0) {
         $ar = array_shift($image->getErrors());
         unlink($newAbsolutePath);
         throw new \Exception(array_shift($ar));
     }
     $img = $this->owner->getImage();
     if (is_object($img) && get_class($img) == 'pistol88\\gallery\\models\\PlaceHolder' or $img == null or $isMain) {
         $this->setMainImage($image);
     }
     return $image;
 }
示例#15
0
 public function upload()
 {
     if ($this->validate()) {
         $imagable = \Yii::$app->shop_imagable;
         $dir = $imagable->imagesPath . '/shop-product/';
         if (!empty($this->image)) {
             if (!file_exists($dir)) {
                 BaseFileHelper::createDirectory($dir);
             }
             $newFile = $dir . $this->image->name;
             if ($this->image->saveAs($newFile)) {
                 $image_name = $imagable->create('shop-product', $newFile);
                 unlink($newFile);
                 return $image_name;
             } else {
                 throw new Exception('Image saving failed.');
             }
         }
     }
     return false;
 }
 public function attachFile()
 {
     try {
         $model = $this->owner;
         $model->file = UploadedFile::getInstance($model, 'file');
         if ($model->validate() && $model->file) {
             $fileName = Inflector::slug($model->file->baseName) . '.' . $model->file->extension;
             $folder = $this->getModelSubDir() . '/';
             $model->path = $fileName;
             BaseFileHelper::removeDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}");
             if (!BaseFileHelper::createDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}")) {
                 throw new Exception(Yii::t('app', 'Failed to create the file upload directory'));
             }
             $model->file->saveAs(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}{$model->path}");
             $model->save();
         }
         return true;
     } catch (yii\base\Exception $e) {
         return $e->getMessage();
     }
 }
示例#17
0
 public function insert()
 {
     $this->preview = UploadedFile::getInstance($this, 'preview');
     if ($this->validate()) {
         $book = new Book();
         $book->name = $this->name;
         $book->date = strtotime($this->date);
         $book->author_id = $this->author_id;
         if ($book->save()) {
             $dir = Yii::getAlias(Yii::$app->params['previewPath']);
             if (!is_dir($dir)) {
                 BaseFileHelper::createDirectory($dir, 0777);
             }
             $uploaded = false;
             $filename = '';
             if ($this->preview) {
                 $filename = 'b' . $book->book_id . 'preview.' . $this->preview->extension;
                 $uploaded = $this->preview->saveAs($dir . '/' . $filename);
                 $img = Image::getImagine()->open($dir . '/' . $filename);
                 $size = $img->getSize();
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 700;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/' . $filename, ['quality' => 80]);
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 200;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/th_' . $filename, ['quality' => 80]);
             }
             if ($uploaded) {
                 $bookData = Book::findOne($book->book_id);
                 $bookData->preview = $filename;
                 $bookData->save();
             }
             return $book;
         }
     }
     return null;
 }
示例#18
0
 public function actionFileUploadGeneral()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->request->post('id');
         $path = Yii::getAlias('@frontend/web/uploads/adverts/' . $id . '/general');
         BaseFileHelper::createDirectory($path);
         $model = Advert::findOne($id);
         $model->scenario = 'step2';
         $file = UploadedFile::getInstance($model, 'general_image');
         $name = 'general.' . $file->extension;
         $file->saveAs($path . DIRECTORY_SEPARATOR . $name);
         $image = $path . DIRECTORY_SEPARATOR . $name;
         $new_name = $path . DIRECTORY_SEPARATOR . $name;
         $model->general_image = $name;
         $model->save();
         $size = getimagesize($image);
         $width = $size[0];
         $height = $size[1];
         Image::frame($image, 0, '666', 0)->crop(new Point(0, 0), new Box($width, $height))->resize(new Box(1000, 644))->save($new_name, ['quality' => 100]);
         sleep(1);
         return true;
     }
 }
 /**
  * Creates a new ImageManager model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionUpload()
 {
     //set response header
     Yii::$app->getResponse()->format = Response::FORMAT_JSON;
     // Check if the user is allowed to upload the image
     if (Yii::$app->controller->module->canUploadImage == false) {
         // Return the response array to prevent from the action being executed any further
         return [];
     }
     //disable Csrf
     Yii::$app->controller->enableCsrfValidation = false;
     //return default
     $return = $_FILES;
     //set media path
     $sMediaPath = \Yii::$app->imagemanager->mediaPath;
     //create the folder
     BaseFileHelper::createDirectory($sMediaPath);
     //check file isset
     if (isset($_FILES['imagemanagerFiles']['tmp_name'])) {
         //loop through each uploaded file
         foreach ($_FILES['imagemanagerFiles']['tmp_name'] as $key => $sTempFile) {
             //collect variables
             $sFileName = $_FILES['imagemanagerFiles']['name'][$key];
             $sFileExtension = pathinfo($sFileName, PATHINFO_EXTENSION);
             $iErrorCode = $_FILES['imagemanagerFiles']['error'][$key];
             //if uploaded file has no error code  than continue;
             if ($iErrorCode == 0) {
                 //create a file record
                 $model = new ImageManager();
                 $model->fileName = str_replace("_", "-", $sFileName);
                 $model->fileHash = Yii::$app->getSecurity()->generateRandomString(32);
                 //if file is saved add record
                 if ($model->save()) {
                     //move file to dir
                     $sSaveFileName = $model->id . "_" . $model->fileHash . "." . $sFileExtension;
                     //move_uploaded_file($sTempFile, $sMediaPath."/".$sFileName);
                     //save with Imagine class
                     Image::getImagine()->open($sTempFile)->save($sMediaPath . "/" . $sSaveFileName);
                 }
             }
         }
     }
     //echo return json encoded
     return $return;
 }
示例#20
0
 public function createVersion($imagePath, $sizeString = false)
 {
     if (strlen($this->urlAlias) < 1) {
         throw new \Exception('Image without urlAlias!');
     }
     $cachePath = $this->getModule()->getCachePath();
     $subDirPath = $this->getSubDur();
     $fileExtension = pathinfo($this->filePath, PATHINFO_EXTENSION);
     if ($sizeString) {
         $sizePart = '_' . $sizeString;
     } else {
         $sizePart = '';
     }
     $pathToSave = $cachePath . '/' . $subDirPath . '/' . $this->urlAlias . $sizePart . '.' . $fileExtension;
     BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true);
     if ($sizeString) {
         $size = $this->getModule()->parseSize($sizeString);
     } else {
         $size = false;
     }
     if ($this->getModule()->graphicsLibrary == 'Imagick') {
         $image = new \Imagick($imagePath);
         $image->setImageCompressionQuality(100);
         if ($size) {
             if ($size['height'] && $size['width']) {
                 $image->cropThumbnailImage($size['width'], $size['height']);
             } elseif ($size['height']) {
                 $image->thumbnailImage(0, $size['height']);
             } elseif ($size['width']) {
                 $image->thumbnailImage($size['width'], 0);
             } else {
                 throw new \Exception('Something wrong with this->module->parseSize($sizeString)');
             }
         }
         $image->writeImage($pathToSave);
     } else {
         $image = new \abeautifulsite\SimpleImage($imagePath);
         if ($size) {
             if ($size['height'] && $size['width']) {
                 //$image->thumbnail($size['width'], $size['height']);
                 $image->best_fit($size['width'], $size['height']);
             } elseif ($size['height']) {
                 $image->fit_to_height($size['height']);
             } elseif ($size['width']) {
                 $image->fit_to_width($size['width']);
             } else {
                 throw new \Exception('Something wrong with this->module->parseSize($sizeString)');
             }
         }
         //WaterMark
         if ($this->getModule()->waterMark) {
             if (!file_exists(Yii::getAlias($this->getModule()->waterMark))) {
                 throw new Exception('WaterMark not detected!');
             }
             $wmMaxWidth = intval($image->get_width() * 0.4);
             $wmMaxHeight = intval($image->get_height() * 0.4);
             $waterMarkPath = Yii::getAlias($this->getModule()->waterMark);
             $waterMark = new \abeautifulsite\SimpleImage($waterMarkPath);
             if ($waterMark->get_height() > $wmMaxHeight or $waterMark->get_width() > $wmMaxWidth) {
                 $waterMarkPath = $this->getModule()->getCachePath() . DIRECTORY_SEPARATOR . pathinfo($this->getModule()->waterMark)['filename'] . $wmMaxWidth . 'x' . $wmMaxHeight . '.' . pathinfo($this->getModule()->waterMark)['extension'];
                 //throw new Exception($waterMarkPath);
                 if (!file_exists($waterMarkPath)) {
                     $waterMark->fit_to_width($wmMaxWidth);
                     $waterMark->save($waterMarkPath, 100);
                     if (!file_exists($waterMarkPath)) {
                         throw new Exception('Cant save watermark to ' . $waterMarkPath . '!!!');
                     }
                 }
             }
             $image->overlay($waterMarkPath, 'bottom right', 0.5, -10, -10);
         }
         $image->save($pathToSave, 100);
     }
     return $image;
 }
示例#21
0
 /**
  * Creates previews folder (using previewsFolder param in config file and consists of previews folder
  * and id of current record) and returns created folder name. It throws Exception if problems creating folder
  *
  * @return string
  * @throws \yii\base\Exception
  */
 public function getPreviewsFolder()
 {
     $folderName = Yii::$app->params['previewsFolder'] . DIRECTORY_SEPARATOR . $this->id;
     BaseFileHelper::createDirectory($folderName);
     return $folderName;
 }
示例#22
0
 /**
  * @param $srcImagePath
  * @param bool $preset
  * @return string Path to cached file
  * @throws \Exception
  */
 public function createCachedFile($srcImagePath, $preset = false)
 {
     if (!$preset) {
         $preset = $this->defaultSize;
     }
     $fileExtension = pathinfo($srcImagePath, PATHINFO_EXTENSION);
     $fileName = pathinfo($srcImagePath, PATHINFO_FILENAME);
     $pathToSave = $this->cachePath . '/' . $preset . '/' . $fileName . '.' . $fileExtension;
     BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true);
     $size = $preset ? $this->parseSize($preset) : false;
     //        if($this->graphicsLibrary == 'Imagick'){
     $image = new \Imagick($srcImagePath);
     $image->setImageCompressionQuality(30);
     if ($size) {
         if ($size['height'] && $size['width']) {
             $image->cropThumbnailImage($size['width'], $size['height']);
         } elseif ($size['height']) {
             $image->thumbnailImage(0, $size['height']);
         } elseif ($size['width']) {
             $image->thumbnailImage($size['width'], 0);
         } else {
             throw new \Exception('Error at $this->parseSize($sizeString)');
         }
     }
     $image->writeImage($pathToSave);
     //        }
     if (!is_file($pathToSave)) {
         throw new \Exception('Error while creating cached file');
     }
     return $image;
 }
示例#23
0
 /**
  * Получить путь
  * @param $field
  * @param bool $relative
  * @return bool|string
  * @throws \yii\base\Exception
  */
 protected function getPath($field, $relative = false)
 {
     if ($this->path === null) {
         $this->path = DIRECTORY_SEPARATOR . $this->getFolder() . DIRECTORY_SEPARATOR . $field . $this->getFolderPath();
         BaseFileHelper::createDirectory(\Yii::getAlias($this->root . $this->path));
     }
     return $relative ? $this->path : \Yii::getAlias($this->root . $this->path);
 }
示例#24
0
 public function actionUploadFile()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->request->post('sale_id');
         $path = Yii::$app->params['uploadSalePath'] . DIRECTORY_SEPARATOR . $id;
         BaseFileHelper::createDirectory($path);
         $file = UploadedFile::getInstanceByName('files');
         if (file_exists($path . DIRECTORY_SEPARATOR . $file->name)) {
             return false;
         }
         $model = new SaleFiles();
         $model->sale_id = $id;
         $model->name = $file->name;
         if ($model->save()) {
             if ($model->save()) {
                 if (!$file->saveAs($path . DIRECTORY_SEPARATOR . $model->name)) {
                     $model->delete();
                 }
             }
         }
         sleep(1);
         return true;
     }
     return false;
 }
示例#25
0
文件: Sale.php 项目: dench/resistor
 public function afterSave($insert, $changedAttributes)
 {
     parent::afterSave($insert, $changedAttributes);
     // Photo copy - Start
     if ($insert && Yii::$app->request->post('photos')) {
         $new_path = Yii::$app->params['uploadSalePath'] . DIRECTORY_SEPARATOR . $this->id;
         BaseFileHelper::createDirectory($new_path);
         foreach (Yii::$app->request->post('photos') as $k => $v) {
             $old_photo = SalePhoto::findOne($k);
             if ($old_photo) {
                 $old = Yii::$app->params['uploadSalePath'] . DIRECTORY_SEPARATOR . $v . DIRECTORY_SEPARATOR . $old_photo->id . '.jpg';
                 if (file_exists($old)) {
                     $new_photo = new SalePhoto();
                     $new_photo->sale_id = $this->id;
                     if ($new_photo->save()) {
                         $new_photo->sort = $new_photo->id;
                         $new_photo->hash = md5_file($old);
                         if ($new_photo->save()) {
                             if (!copy($old, $new_path . DIRECTORY_SEPARATOR . $new_photo->id . '.jpg')) {
                                 $new_photo->delete();
                             }
                         }
                     }
                 }
             }
         }
     }
     // Photo copy - End
     $code = sprintf("%02d", $this->region_id) . sprintf("%03d", $this->district_id) . $this->id;
     Yii::$app->db->createCommand()->update('sale', ['code' => $code], ['id' => $this->id])->execute();
 }
示例#26
0
 private function CreateDir($folderName)
 {
     if ($folderName != NULL) {
         $basePath = Album::getUploadPath();
         if (BaseFileHelper::createDirectory($basePath . $folderName, 0777)) {
             BaseFileHelper::createDirectory($basePath . $folderName . '/thumbnail', 0777);
         }
     }
     return;
 }
示例#27
0
文件: update.php 项目: jatuponp/iweb
             <div class="file-input">
                 <div class="file-preview-thumbnails">            
                     <?php 
 $mPath = \Yii::getAlias('@webroot') . '/images/article/news_' . $model->id;
 $mUrl = \Yii::getAlias('@web') . '/images/article/news_' . $model->id;
 if (!is_dir($mPath)) {
     \yii\helpers\BaseFileHelper::createDirectory($mPath);
 }
 foreach (scandir($mPath) as $img) {
     if ($img != '.' && $img != '..' && $img != 'thumb') {
         $mThumb = $mUrl . '/thumb/' . $img;
         //ตรวจสอบภาพตัวอย่าง ว่าถูกสร้างขึ้นมาหรือยัง
         if (!file_exists($mThumb)) {
             //ตรวจสอบโฟลเดอร์ภาพตัวอย่าง
             if (!is_dir($mPath . '/thumb')) {
                 \yii\helpers\BaseFileHelper::createDirectory($mPath . '/thumb/');
             }
             //สร้างภาพตัวอ่ย่าง
             $image = \Yii::$app->image->load($mPath . '/' . $img);
             $image->resize(250, 250);
             $image->save($mPath . '/thumb/' . $img);
         }
         echo '<div class="file-preview-frame">';
         echo '<div class="close fileinput-remove text-right"><a href="' . Url::to(['article/delimage', 'id' => $model->id, 'file' => $img]) . '">×</a></div>';
         echo '<img src="' . $mThumb . '" class="file-preview-image"/>';
         echo '</div>';
     }
 }
 ?>
                     <div class="clearfix"></div>
                 </div>
示例#28
0
 /**
  * @param integer $id
  * @return boolean
  */
 public function upload($id)
 {
     if ($this->validate()) {
         $name = ActivityImage::find()->where(['id_activity' => $id])->max('name');
         if (!$name) {
             $counter = 0;
         } else {
             $array = explode(".", $name);
             $counter = $array[0] + 1;
         }
         $folder = Yii::getAlias('@activity/' . $id);
         if (!file_exists($folder)) {
             BaseFileHelper::createDirectory($folder);
         }
         foreach ($this->imageFiles as $file) {
             $file->saveAs($folder . '/' . $counter . '.jpg');
             Image::thumbnail(Yii::getAlias('@activity/' . $id . '/' . $counter . '.jpg'), 120, 120)->save(Yii::getAlias('@activity/' . $id . '/thumb' . $counter . '.jpg'), ['quality' => 80]);
             $newImage = new ActivityImage();
             $newImage->id_activity = $id;
             $newImage->name = $counter . '.jpg';
             $newImage->save();
             $counter++;
         }
         return true;
     } else {
         return false;
     }
 }
示例#29
0
 /**
  * Tries to create a cached resized image.
  * @TODO: try imagemagick and fallback to GD if not found
  * @param type $path
  * @param type $preset
  * @param type $expires
  * @return string
  */
 public function get($path, $preset, $expires = 31536000)
 {
     if (strpos($path, 'http') !== false) {
         $sourceImagePath = $path;
     } else {
         $sourceImagePath = $this->sourcePath . $path;
     }
     $fileExtension = pathinfo($sourceImagePath, PATHINFO_EXTENSION);
     $fileName = pathinfo($sourceImagePath, PATHINFO_FILENAME);
     list($width, $height) = getimagesize($sourceImagePath);
     $pathToSave = $this->cachePath . '/imagecache/' . $preset . '/' . $fileName . '.' . $fileExtension;
     BaseFileHelper::createDirectory(dirname($this->sourcePath . $pathToSave), 0777, true);
     // expired ?
     if (is_file($this->sourcePath . $pathToSave) && ($lastModified = filemtime($this->sourcePath . $pathToSave))) {
         $expiresIn = $lastModified + $expires;
         if (time() > $expiresIn) {
             unlink($this->sourcePath . $pathToSave);
         }
     }
     // not expired but cached
     if (is_file($this->sourcePath . $pathToSave)) {
         return $pathToSave;
     }
     $preset = strtolower($preset);
     $parts = explode('x', $preset);
     $newWidth = intval($parts['0']);
     $newHeight = isset($parts['1']) ? intval($parts['1']) : 0;
     if (strpos($path, 'http') !== false) {
         // read the external image
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $path);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         $content = curl_exec($ch);
         curl_close($ch);
         if (empty($content)) {
             return $path;
         }
         $image = imagecreatefromstring($content);
     } else {
         switch ($fileExtension) {
             case 'jpeg':
             case 'jpg':
                 $image = imagecreatefromjpeg($sourceImagePath);
                 break;
             case 'gif':
                 $image = imagecreatefromgif($sourceImagePath);
                 break;
             case 'png':
                 $image = imagecreatefrompng($sourceImagePath);
                 break;
         }
     }
     if (!empty($newWidth) && !empty($newHeight)) {
     } elseif (!empty($newWidth)) {
         $x = $newWidth * 100 / $width;
         $newHeight = ceil($height * $x / 100);
     } elseif (!empty($newHeight)) {
         $x = $newHeight * 100 / $height;
         $newWidth = ceil($width * $x / 100);
     }
     $tmp = imagecreatetruecolor($newWidth, $newHeight);
     imagecopyresampled($tmp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
     switch ($fileExtension) {
         case 'jpeg':
         case 'jpg':
             imagejpeg($tmp, $this->sourcePath . $pathToSave, 100);
             break;
         case 'gif':
             imagegif($tmp, $this->sourcePath . $pathToSave, 100);
             break;
         case 'png':
             imagealphablending($tmp, false);
             imagesavealpha($tmp, true);
             imagepng($tmp, $this->sourcePath . $pathToSave, 9);
             break;
     }
     return $pathToSave;
 }
 /**
  * Downloads an image from the Skarabee server
  * 
  * @param   string  $url    The image url
  * @param   string  $name   The name of the image
  * @return  boolean
  */
 protected function downloadSkarabeeImage($url, $name)
 {
     $dir = Yii::getAlias('@uploadsBasePath/img');
     // Download the file
     $file = file_get_contents($url);
     // Create the real estate dir if does not exist
     BaseFileHelper::createDirectory($dir . DIRECTORY_SEPARATOR . 'RealEstates', 0775, true);
     // Store in the filesystem.
     $fp = fopen($dir . DIRECTORY_SEPARATOR . 'RealEstates' . DIRECTORY_SEPARATOR . $name, 'w');
     $r = fwrite($fp, $file);
     fclose($fp);
     return $r;
 }