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(); }
/** * * @param CUploadedFile $fileInstance */ public function addFile($fileInstance, $filename = false, $extraFormat = false) { $filePath = $this->pathToData . DIRECTORY_SEPARATOR . $this->prefix . $this->id . DIRECTORY_SEPARATOR; $accessModel = new PropertyfileModel(); $generateName = 'u' . md5(uniqid("")); $fullNameParts = explode('.', $fileInstance->getName()); if (!$extraFormat) { $format = array_pop($fullNameParts); } else { $format = $extraFormat; } if (!$filename) { $filename = $generateName; } else { $filename = str_replace(' ', '', $filename); } $generateName .= $generateName . '.' . $format; $folder = YII::getPathOfAlias('application.data.id' . $this->id) . DIRECTORY_SEPARATOR; if (!is_dir($folder)) { return false; } $accessModel->unsetAttributes(); $accessModel->setAttributes(array('property_id' => $this->id, 'filename' => $filename . '.' . $format, 'systempath' => $generateName)); if (!$accessModel->save()) { return false; } if (!$fileInstance->saveAs($folder . $generateName, false)) { var_dump($filename . '.' . $format); v($folder . $generateName); return false; } $resultData = array('filename' => $filename, 'systemname' => $generateName, 'id' => $accessModel->getAttribute('id')); return $resultData; }
/** * @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 run() { $this->prepare(); if ($file = new CUploadedFile($this->md5($_FILES['file']['name']), $_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['size'], $_FILES['file']['error'])) { if ($file->saveAs($this->basePath . $file->getName())) { $this->append($file->getName()); } } }
/** * Saves the resource file after the record is saved * @see CActiveRecord::afterSave() */ public function afterSave() { if (is_object($this->_uploadedFile)) { if (!$this->_uploadedFile->saveAs($this->fullPath)) { rename($this->_uploadedFile->tempName, $this->fullPath); } } elseif ($this->_content !== null) { file_put_contents($this->fullPath, $this->_content); } parent::afterSave(); }
public function changeLogo(CUploadedFile $uploadedFile) { $basePath = Yii::app()->getModule('cabinet')->getUploadPath(); //создаем каталог для аватарок, если не существует if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) { throw new CException(Yii::t('default', 'It is not possible to create directory for logos!')); } $filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName; // обновить файл //$this->removeOldLogo(); if (!$uploadedFile->saveAs($basePath . $filename)) { throw new CException(Yii::t('default', 'It is not possible to save logos!')); } // получить запись лого $photo = $this->with('photo')->find('photo.id=:id', [':id' => $this->logo_id]); $webroot = Yii::getpathOfAlias('webroot'); $trimPath = str_replace($webroot, '', $basePath); $logoFileOld = null; $File = new File(); $File->model = 'Company'; $File->type = 'image'; $File->size = filesize($basePath . $filename); $File->name = $filename; $File->path = $trimPath . $filename; $File->record_id = 0; if (!is_null($photo['photo'])) { $File->id = $photo['photo']['id']; $File->isNewRecord = false; $logoFileOld = $photo['photo']['path']; } if ($File->save()) { if (0 != strcmp($logoFileOld, $File->path)) { @unlink($webroot . $logoFileOld); } } else { yii::log("changeLogo save FAILED id=[" . $File->id . "]", "info"); } if ($this->logo_id != $File->id) { // поменять logo_id $this->logo_id = $File->id; if ($this->validate(['logo_id'])) { if (true === $this->update(['logo_id'])) { } else { Yii::log("changeLogo update logo_id FAILED", 'info'); } } else { Yii::log("changeLogo validate logo_id FAILED", 'info'); } } //$this->logo = $filename; return true; }
protected function beforeSave() { if (parent::beforeSave()) { if ($this->getIsNewRecord()) { $this->status = self::STATUS_WAIT; $this->createdAt = date('Y-m-d H:i:s'); $basePath = Yii::getPathOfAlias('application.runtime') . '/tmp/payout'; if (!file_exists($basePath)) { mkdir($basePath, 0777, true); } $path = $basePath . '/' . md5(time() . $this->file->getName()); $this->filePath = $path; $this->fileName = $this->file->getName(); $this->fileSize = $this->file->getSize(); $this->file->saveAs($path); } $this->modifiedAt = date('Y-m-d H:i:s'); return true; } return false; }
/** * 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; } }
/** * Устанавливает новый аватар * * @param CUploadedFile $uploadedFile * * @throws CException * * @return boolean */ public function changeAvatar(CUploadedFile $uploadedFile) { $basePath = Yii::app()->getModule('user')->getUploadPath(); //создаем каталог для аватарок, если не существует if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) { throw new CException(Yii::t('UserModule.user', 'It is not possible to create directory for avatars!')); } $filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName; $this->removeOldAvatar(); if (!$uploadedFile->saveAs($basePath . $filename)) { throw new CException(Yii::t('UserModule.user', 'It is not possible to save avatar!')); } $this->use_gravatar = false; $this->avatar = $filename; return true; }
/** * Sets up new image * @param CUploadedFile $uploadedFile */ public function changeImage(CUploadedFile $uploadedFile) { $photosDir = $this->imagesDir; $basePath = Yii::app()->basePath . '/www' . $photosDir; //создаем каталог, если не существует if (!file_exists($basePath)) { mkdir($basePath); } $basePath .= '/'; $filename = $this->owner->{$this->idAttr} . '_' . str_replace(array('.', ' '), '_', microtime()) . '.' . $uploadedFile->extensionName; if ($this->owner->{$this->imagePathAttr}) { //remove old resized images if (file_exists($basePath . $this->owner->{$this->imagePathAttr})) { unlink($basePath . $this->owner->{$this->imagePathAttr}); } foreach (glob($basePath . $this->owner->{$this->idAttr} . '_*.*') as $oldThumbnail) { unlink($oldThumbnail); } } $uploadedFile->saveAs($filepath = $basePath . $filename); if (is_array($this->resize)) { $sizes = array_values($this->resize); $width = $sizes[0]; $height = !empty($sizes[1]) ? $sizes[1] : $width; $this->resizeImage($filepath, $filepath, $width, $height); } $this->owner->{$this->imagePathAttr} = $filename; if ($this->thumbnailsToCreate && is_array($this->thumbnailsToCreate)) { foreach ($this->thumbnailsToCreate as $size) { $this->createImageThumbnail($size); } } }
public static function uploadFile(CUploadedFile $upload, $additional = null, $deleteTempFile = true) { $filename = self::makeUploadFilePath(param('uploadBasePath'), $upload->extensionName); $result = $upload->saveAs($filename['path'], $deleteTempFile); if ($result) { return $filename; } else { return false; } }
public function beforeValidate() { $behavior = $this->_behavior; $owner = $behavior->owner; $ownerClass = get_class($owner); $attribute = $behavior->attribute; if (!$behavior->delete) { // Delete command not given, getting uploaded file. if ($behavior->uploadcare !== null) { if ($owner->{$attribute} != '') { $fileId = $owner->{$attribute}; $file = $this->_uploadcareApi->getFile($fileId); $fileUrl = $file->getUrl(); $uploadedFile = $file->data['original_filename']; } else { if (get_parent_class($behavior) == 'CActiveRecordBehavior' && !$owner->isNewRecord) { $owner->{$attribute} = $ownerClass::model()->findByPk($owner->primaryKey)->{$attribute}; } $uploadedFile = ''; } } else { if (($uploadedFile = CUploadedFile::getInstance($owner, $behavior->attributePostName)) === null && !$owner->isNewRecord) { $owner->{$attribute} = $ownerClass::model()->findByPk($owner->primaryKey)->{$attribute}; } } if ($behavior->uploadcare === null && is_object($uploadedFile) || $behavior->uploadcare !== null && !empty($uploadedFile)) { // A file has been uploaded. Creating destination folders if they don't exist and getting a unique name for the file. foreach ($behavior->mkdir as $dir) { if (!is_dir($dir)) { mkdir($dir); } } if (!is_dir($behavior->dir)) { mkdir($behavior->dir); } if (!is_dir($behavior->tempDir)) { mkdir($behavior->tempDir); } $fileNameClean = strtolower(preg_replace('/[^A-Za-z0-9_\\-\\.]|\\.(?=.*\\.)/', '', str_replace(' ', '_', $this->removeAccents($uploadedFile)))); if (strpos($fileNameClean, '.') === 0) { $fileNameClean = 'file' . $fileNameClean; } $i = -1; while (true) { $i++; if ($i > 0) { $fileName = $this->fileSuffix($fileNameClean, $i); } else { $fileName = $fileNameClean; } $fileTempName = $this->_currentTime . '_' . $fileName; if (file_exists($behavior->dir . '/' . $fileName)) { continue; } $glob = glob($behavior->tempDir . '/*' . $fileName); if (!empty($glob)) { continue; } if (isset($behavior->formats)) { if (file_exists($behavior->dir . '/' . $this->fileSuffix($fileName, $behavior->previewImageSuffix))) { continue; } $continue = false; foreach ($behavior->formats as $format => $dimensions) { if (file_exists($behavior->dir . '/' . $this->fileSuffix($fileName, $format))) { $continue = true; break; } } if ($continue) { continue; } } break; } // Sending file to temporary folder regardless of validation (we need it for preview and other things). if ($behavior->uploadcare !== null) { // Manually wrapping the file in CUploadedFile object to allow for validations to occur. $bytes = file_put_contents($behavior->tempDir . '/' . $fileTempName, file_get_contents($fileUrl)); $finfo = new finfo(); $mimeType = $finfo->file($behavior->tempDir . '/' . $fileTempName, FILEINFO_MIME); $uploadedFile = new CUploadedFile($fileTempName, $behavior->tempDir . '/' . $fileTempName, $mimeType, $bytes, UPLOAD_ERR_OK); // Re-adding validators that we removed before for bugfix. foreach ($this->_fileValidators as $validator) { $owner->validatorList->add($validator); } } else { $uploadedFile->saveAs($behavior->tempDir . '/' . $fileTempName); } $owner->{$attribute} = $uploadedFile; // Must set uploadedFile and not string of file name otherwis:e the file type validation bugs out. $behavior->tempName = $fileTempName; if (isset($behavior->formats)) { try { // Trying to make preview thumbnail (because we must show it even if there is an error). $image = Yii::app()->image->load($behavior->tempDir . '/' . $fileTempName); $imageSize = getimagesize($behavior->tempDir . '/' . $fileTempName); if (!$behavior->onlyResizeIfBigger || $imageSize[0] > $behavior->previewImageSize[0] || $imageSize[1] > $behavior->previewImageSize[1]) { $image->resize($behavior->previewImageSize[0], $behavior->previewImageSize[1])->quality(90)->sharpen(15); } $image->save($behavior->tempDir . '/' . $this->fileSuffix($fileTempName, $behavior->previewImageSuffix)); } catch (Exception $e) { $behavior->showPreviewImage = false; // Making of preview failed probably wrong file format, don't show it. } } } elseif ($behavior->tempName != '') { $owner->{$attribute} = $behavior->tempName; } // No file uploaded. Re-using tempName if present (image was uploaded previously). } elseif (get_parent_class($behavior) == 'CActiveRecordBehavior' && $behavior->uploadcare !== null && !$owner->isNewRecord && $owner->{$attribute} == '') { $owner->{$attribute} = $ownerClass::model()->findByPk($owner->primaryKey)->{$attribute}; } // With uploadcare, we must re-set the attribute if deleting or it bugs. }
/** * 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; }