/** * @param \CActiveRecord $model * @param string $attribute имя поля, содержащего CUploadedFile. В последствии этому полю будет присвоено имя файла изображения. * @param \CUploadedFile $image * @param array $sizes * * @throws \CException * * @return bool */ public function save(\CActiveRecord $model, $attribute = 'image', \CUploadedFile $image, $sizes = []) { $folderModel = $this->extractPath($model, $attribute, true); if (!file_exists($folderModel)) { mkdir($folderModel); } $imageExtension = isset($this->mimeToExtension[$image->getType()]) ? $this->mimeToExtension[$image->getType()] : 'jpg'; $imageId = $this->getRandomHash($model, $attribute); $imagePathTemp = \Yii::getPathOfAlias('temp') . '/' . $imageId . '.' . $imageExtension; if ($image->saveAs($imagePathTemp)) { foreach ($sizes as $sizeName => $size) { $folderModelAttribute = $this->extractPath($model, $attribute); if (!file_exists($folderModelAttribute)) { mkdir($folderModelAttribute); } $quality = array_key_exists('quality', $size) ? intval($size['quality']) : self::DEFAULT_QUALITY; if ($quality <= 0 or $quality > 100) { $quality = self::DEFAULT_QUALITY; } $pathImageSize = $folderModelAttribute . '/' . $imageId . '_' . $sizeName . '.' . $imageExtension; if (array_key_exists('enabled', $size) and $size['enabled'] == false) { if (array_key_exists('resave', $size) and $size['resave'] == false) { rename($imagePathTemp, $pathImageSize); } else { $this->processor->open($imagePathTemp)->save($pathImageSize, ['quality' => $quality]); } } else { $this->processor->open($imagePathTemp)->thumbnail(new Box($size['width'], $size['height']), (!isset($size['inset']) or $size['inset']) ? ImageInterface::THUMBNAIL_INSET : ImageInterface::THUMBNAIL_OUTBOUND)->save($pathImageSize, ['quality' => $quality]); } } } else { throw new \CException('can not save image'); } return [self::KEY_ID => $imageId, self::KEY_EXT => $imageExtension]; }
public function beforeSave() { if ($this->isNewRecord && !$this->image) { return false; } if ($this->isNewRecord) { $this->realName = $this->generateUniqueName(); $this->name = $this->realName; $this->fullPath = $this->getFullPath(); $this->image->saveAs($this->getFullPath()); $this->mimeType = $this->image->getType(); } return parent::beforeSave(); }
/** * Проверка подходит ли mime тип * @param string $attribute * @param CUploadedFile $file */ private function checkMime($attribute, $file) { if ($this->mime === null) { return true; } if (is_array($this->mime)) { if (in_array($file->getType(), $this->mime)) { return true; } else { return false; } } elseif (is_string($this->mime)) { if ($file->getType() == $this->mime) { return true; } else { return false; } } else { return false; } }
/** * Processes the uploaded image. * @param CUploadedFile $uploadedImg The uploaded image * @param string $title The title (or caption) of this image (optional) * @param string $description The detailed description of this image (optional) * @param string $albumName The name of the album to put the image in (optional) * @return string The ID of new uploaded image | false */ private function saveImg($uploadedImg, $title = '', $description = '', $albumName = '') { // Key $userId = CassandraUtil::import(Yii::app()->user->getId())->__toString(); $key = $userId . '_' . CassandraUtil::uuid1(); // Path $path = realpath(Yii::app()->params['storagePath']) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $userId; if (!is_dir($path)) { mkdir($path, 0775); } if (!empty($albumName)) { $path .= DIRECTORY_SEPARATOR . $albumName; } if (!is_dir($path)) { mkdir($path, 0775); } // Save the image information before processing the image $data = array('storage_path' => $uploadedImg->getTempName(), 'mime_type' => $uploadedImg->getType(), 'extension' => $uploadedImg->getExtensionName(), 'user_id' => Yii::app()->user->getId()); if (!empty($title)) { $data['title'] = $title; } if (!empty($description)) { $data['description'] = $description; } if ($this->insert($key, $data) === false) { $uploadedImg->clean(); return false; } // Render this image into different versions $photoTypes = Setting::model()->photo_types; // Get list of image types in JSON format. Decode it. $photoTypes = json_decode($photoTypes['value'], true); $img = Yii::app()->imagemod->load($data['storage_path']); $convertedImgs = array(); foreach ($photoTypes as $type => $config) { $img->image_convert = 'jpg'; $img->image_resize = true; $img->image_ratio = true; $img->image_x = $config['width']; $img->image_y = $config['height']; if (isset($config['suffix'])) { $img->file_safe_name = $key . $config['suffix'] . '.jpg'; } else { $img->file_safe_name = $key . '.jpg'; } $img->process($path); if (!$img->processed) { // Delete the original image $uploadedImg->clean(); // Delete the record in db $this->delete($key); // Log the error Yii::log('Cannot resize the image ' . $data['storage_path'] . ' to ' . $path . '/' . $img->file_safe_name, 'error', 'application.modules.storage.Storage'); // Delete all converted images foreach ($convertedImgs as $imgType => $imgPath) { unlink($imgPath); } // Return false return false; } else { // Remember the path of converted image $convertedImgs[$type] = $img->file_dst_path; } // Update the database $data = array('storage_path' => $convertedImgs['original'], 'mime_type' => 'image/jpeg', 'extension' => 'jpg'); unset($convertedImgs['original']); $data = array_merge($data, $convertedImgs); if ($this->insert($key, $data) === false) { // Delete the original image $uploadedImg->clean(); // Delete the record in db $this->delete($key); // Log the error Yii::log('Cannot resize the image ' . $data['storage_path'] . ' to ' . $path . '/' . $img->file_safe_name, 'error', 'application.modules.storage.Storage'); // Delete all converted images unlink($data['storage_path']); foreach ($convertedImgs as $imgType => $imgPath) { unlink($imgPath); } // Return false return false; } } // Delete the temporary image $uploadedImg->clean(); return $key; }
/** * Saves a new image. * @param CUploadedFile $file the uploaded image. * @param CActiveRecord $owner the owner model. * @param string $name the image name. Available since 1.2.0 * @param string $path the path to save the file to. Available since 1.2.1. * @return Image the image model. * @throws CException if saving the image fails. */ public function save($file, $name = null, $path = null) { $trx = Yii::app()->db->beginTransaction(); try { $image = new Image(); $image->extension = strtolower($file->getExtensionName()); $image->filename = $file->getName(); $image->byteSize = $file->getSize(); $image->mimeType = $file->getType(); $image->createTime = new CDbExpression('NOW()'); if (empty($name)) { $name = $file->getName(); $name = substr($name, 0, strrpos($name, '.')); } $image->name = $this->normalizeString($name); if ($path !== null) { $image->path = trim($path, '/'); } if ($image->save() === false) { throw new CException(__CLASS__ . ': Failed to save image! Record could not be saved.'); } $path = $this->resolveImagePath($image); if (!file_exists($path) && !$this->createDirectory($path)) { throw new CException(__CLASS__ . ': Failed to save image! Directory could not be created.'); } $path .= $this->resolveFileName($image); if ($file->saveAs($path) === false) { throw new CException(__CLASS__ . ': Failed to save image! File could not be saved.'); } $trx->commit(); return $image; } catch (CException $e) { $trx->rollback(); throw $e; } }
public function setUploadedFile(CUploadedFile $cUploadedFile) { $this->file_name = $cUploadedFile->getName(); $this->mime_type = $cUploadedFile->getType(); $this->size = $cUploadedFile->getSize(); $this->cUploadedFile = $cUploadedFile; }
/** * Uploads single file and store it into given pathBase * @param CUploadedFile $file single file * @return boolean true whether the uploads is succeed */ public static function uploadFile($file, $pathBase = 'cache/', $filename = null, $mimeTypes = null) { $path = Yii::app()->basePath . '/../' . $pathBase; $relativeURL = $pathBase; FileManager::createFolder($path); $rawName = $filename ? $filename : $file->name; $fileNameExtension = $rawName; $URL = false; $filePath = $path . $fileNameExtension; if ($mimeTypes) { $mimeType = $file->getType(); if (in_array($mimeType, $mimeTypes)) { $URL = $file->saveAs($filePath) ? $relativeURL . $fileNameExtension : false; } } else { $URL = $file->saveAs($filePath) ? $relativeURL . $fileNameExtension : false; } $URL ? @chmod($filePath, 0755) : false; return $URL; }
/** * Saves given CUploadedFiles * */ public static function store(CUploadedFile $cUploadedFile) { // Santize Filename $filename = $cUploadedFile->getName(); $filename = trim($filename); $filename = preg_replace("/[^a-z0-9_\\-s\\.]/i", "", $filename); $pathInfo = pathinfo($filename); if (strlen($pathInfo['filename']) > 60) { $pathInfo['filename'] = substr($pathInfo['filename'], 0, 60); } $filename = $pathInfo['filename']; if (isset($pathInfo['extension'])) { $filename .= "." . $pathInfo['extension']; } $file = new File(); if (!self::HasValidExtension($filename)) { return false; } $file->file_name = $filename; $file->title = $cUploadedFile->getName(); $file->mime_type = $cUploadedFile->getType(); #$file->size = $cUploadedFile->getSize(); if ($file->save()) { // Add File to Filebase $file->slurp($cUploadedFile->getTempName()); return $file; } else { return; } }
protected function beforeSave() { if ($this->isNewRecord) { $this->med_created = date('Y-m-d H:i:s'); if (!$this->med_row) { throw new CDbException('Cant save the media if it does not belong to any record'); } $sql = "SELECT IF(MAX(med_order) IS NOT NULL, MAX(med_order), 0) as max_ord FROM " . $this->tableName() . " WHERE med_row = '" . $this->med_row . "' AND med_type = '" . $this->med_type . "'"; $command = Yii::app()->db->createCommand($sql); $result = $command->queryRow(); $this->med_order = $result['max_ord'] + 1; } if ($this->file) { $this->med_type = isset($this->otherMedia) && $this->otherMedia ? $this->otherMedia : self::TYPE_PHOTO; $fileTempName = $this->file->tempName; list($imgWidth, $imgHeight, $type, $attr) = getimagesize($fileTempName); if (strtolower($this->file->extensionName) == 'gif' && $imgHeight * $imgWidth > self::MAX_AVAILABLE_GIF_PIXEL_COUNT) { $this->addError('file', 'Sorry, but GIF image is too large!'); return false; } $fileName = $this->generateUniqFileName(); $this->med_realname = $this->file->getName(); $this->med_filetype = $this->file->getType(); $this->med_filesize = $this->file->getSize(); $ext = $this->file->getExtensionName(); $extension = '.' . $ext; $filePath = $this->getLocalPath(); $this->med_file = $fileName . $extension; /** @var $imageTool \upload */ $imageTool = Yii::app()->imagemod->load($fileTempName); $imageTool->file_new_name_body = $fileName; $imageTool->file_new_name_ext = $ext; $imageTool->process($filePath); $imageDimType = null; if ($imgHeight > $imgWidth) { //vertical image $imageDimType = 'vertical'; if ($imgHeight > $this->resizeHeight) { $imageTool = $this->resizeImageTool($imageTool, $imageDimType, $this->resizeHeight); } } else { //horizontal image $imageDimType = 'horizontal'; if ($imgWidth > $this->resizeWidth) { $imageTool = $this->resizeImageTool($imageTool, $imageDimType, $this->resizeWidth); } } $imageTool->file_new_name_body = $fileName . self::SUFFIX_ORIGINAL; $imageTool->file_new_name_ext = $ext; $imageTool->process($filePath); /*floorplan OR epc*/ if (isset($this->otherMedia) && $this->otherMedia) { foreach ($this->otherMediaSizes as $suffix => $sizes) { if ($imageDimType == 'vertical' && $imgHeight > $sizes['h']) { $imageTool->image_resize = true; $imageTool->image_ratio_x = true; $imageTool->image_y = $sizes['h']; } else { if ($imageDimType == 'horizontal' && $imgWidth > $sizes['w']) { $imageTool->image_resize = true; $imageTool->image_ratio_y = true; $imageTool->image_x = $sizes['w']; } } $imageTool->file_new_name_body = $fileName . $suffix; $imageTool->file_new_name_ext = $ext; $imageTool->process($filePath); } } else { // photograph $croppedFilePath = ''; if (isset($this->cropFactor['w'])) { $imageTool->image_ratio_crop = true; $cropWidth = $this->cropFactor['w'] * $imgWidth / $this->cropFactor['width']; $top = $this->cropFactor['y'] * $imgHeight / $this->cropFactor['height']; $left = $this->cropFactor['x'] * $imgWidth / $this->cropFactor['width']; $right = $imgWidth - ($left + $cropWidth); $bottom = $imgHeight - ($top + $cropWidth); $imageTool->image_crop = array($top, $right, $bottom, $left); $imageTool->file_new_name_body = $fileName . '_crop'; $imageTool->file_new_name_ext = $ext; $imageTool->process($filePath); // Load cropped file and resize $croppedFilePath = $filePath . '/' . $fileName . '_crop' . $extension; $imageTool = Yii::app()->imagemod->load($croppedFilePath); } foreach ($this->photoCropSizes as $suffix => $sizes) { if ($suffix != '_original') { if ($imageDimType == 'vertical') { //horizontal image if (!isset($this->cropFactor['h'])) { $imageTool->image_ratio_crop = true; $top = $bottom = 0; $left = $right = ($imgWidth * $sizes['h'] / $imgHeight - $sizes['w']) / 2 + 1; $imageTool->image_crop = array($top, $right, $bottom, $left); } $imageTool->image_resize = true; $imageTool->image_y = $sizes['h']; $imageTool->image_ratio_x = true; } else { if ($imageDimType == 'horizontal') { if (!isset($this->cropFactor['w'])) { $imageTool->image_ratio_crop = true; $top = ($imgHeight * $sizes['w'] / $imgWidth - $sizes['h']) / 2; $bottom = $top + 1; $left = $right = 0; $imageTool->image_crop = array($top, $right, $bottom, $left); } $imageTool->image_resize = true; $imageTool->image_x = $sizes['w']; $imageTool->image_ratio_y = true; } } $imageTool->file_new_name_body = $fileName . $suffix; $imageTool->file_new_name_ext = $ext; $imageTool->process($filePath); } } if (file_exists($croppedFilePath)) { unlink($croppedFilePath); } } } return parent::beforeSave(); }