예제 #1
0
 public function actionUploadFile()
 {
     try {
         $channelId = yii::app()->request->getParam('channelId');
         $file = CUploadedFile::getInstanceByName('file');
         $oldName = $file->getName();
         $type = $file->getType();
         $newName = date('Ymdhis') . '.' . $file->getExtensionName();
         $attachment = new TSAttachment();
         $attachment->Attachment_Old_Name = $oldName;
         $attachment->Attachment_New_Name = $newName;
         $attachment->Attachment_File_Type = $type;
         $attachment->Attachment_Belong_Channel = $channelId;
         $attachment->Attachment_Upload_Time = date("Y-m-d H:i:s", time());
         $attachment->Attachment_Author = yii::app()->user->currUserName;
         $attachment->Attachment_Path = Yii::getPathOfAlias('application.assets') . '/upload';
         $uploadFile = Yii::getPathOfAlias('application.assets') . '/upload//' . $newName;
         $flag = $file->saveAs($uploadFile);
         $length = $attachment->save();
         if ($flag && $length > 0) {
             echo json_encode(array('flag' => 'SUCCESS', 'message' => '上传附件成功!'), JSON_UNESCAPED_UNICODE);
         } else {
             echo json_encode(array('flag' => 'ERROR', 'message' => '上传附件失败!'), JSON_UNESCAPED_UNICODE);
         }
     } catch (Exception $e) {
         echo json_encode(array('flag' => 'Exception', 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
     }
 }
예제 #2
0
 /**
  * Обработка изображения в форме тизера
  */
 public function actionImage()
 {
     if ($file = CUploadedFile::getInstanceByName('file')) {
         $file = $this->_uploadImage($file);
     } elseif (isset($_REQUEST['url'])) {
         $file = $this->_downloadImageByUrl($_REQUEST['url']);
     }
     if (isset($file)) {
         if (!isset($file['error'])) {
             $file = $this->_prepareImage($file);
         }
         echo json_encode(array('file' => array_diff_key($file, array('tmpName' => ''))));
         Yii::app()->end();
     } elseif (isset($_REQUEST['crop']) && isset($_REQUEST['fileName'])) {
         try {
             /** @var Image $img */
             $img = Yii::app()->image->load(Yii::app()->params->docTmpPath . DIRECTORY_SEPARATOR . basename($_REQUEST['fileName']));
             $outputFileName = CFile::createUniqueFileName(Yii::app()->params->imageBasePath, '.' . $img->image['ext'], 't_');
             $img->resize((int) $_REQUEST['crop']['w'], (int) $_REQUEST['crop']['h'], Image::NONE)->crop(Yii::app()->params->teaserImageWidth, Yii::app()->params->teaserImageHeight, (int) $_REQUEST['crop']['y'], (int) $_REQUEST['crop']['x'])->save(Yii::app()->params->imageBasePath . DIRECTORY_SEPARATOR . $outputFileName);
         } catch (CException $e) {
             echo json_encode(array('error' => $e->getMessage()));
             Yii::app()->end();
         }
         echo json_encode(array('fileName' => $outputFileName));
         Yii::app()->end();
     }
 }
예제 #3
0
 public function afterValidate($event)
 {
     $this->prepareDataDirectory();
     $file = CUploadedFile::getInstanceByName($this->uploadInstance);
     if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) {
         $uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName());
         $fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
         $relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
         if ($file->saveAs($fullFilePath)) {
             #echo $fullFilePath;exit;
             if (!$this->Owner->isNewRecord) {
                 $this->deleteFile($this->Owner->path);
             }
             if (!$this->Owner->title) {
                 $this->Owner->title = P3StringHelper::cleanName($file->name, 32);
             }
             $this->Owner->path = $relativeFilePath;
             $this->Owner->mimeType = $file->type;
             $this->Owner->size = $file->size;
             $this->Owner->originalName = $file->name;
             $this->Owner->md5 = md5_file($fullFilePath);
         } else {
             $this->Owner->addError('filePath', 'File uploaded failed!');
         }
     } else {
         if ($this->Owner->isNewRecord) {
             #$this->Owner->addError('filePath', 'No file uploaded!');
             Yii::trace('No file uploaded!');
         }
     }
 }
예제 #4
0
 public function upload($name = '')
 {
     if (!$name) {
         throw new CException(Yii::t('no file name'));
     }
     $file = CUploadedFile::getInstanceByName($name);
     if (!$file->hasError) {
         //生成目录
         $filename = md5(time()) . '.' . $file->extensionName;
         $filepath = $this->getDirByTime() . DIRECTORY_SEPARATOR;
         $allFilePath = $this->_dirPath . DIRECTORY_SEPARATOR . $filepath . $filename;
         if (!$this->createDir($this->_dirPath . DIRECTORY_SEPARATOR . $filepath) || !is_writable($this->_dirPath . DIRECTORY_SEPARATOR . $filepath)) {
             throw new CException(Yii::t('yii', 'dir can not create or can not writeable'));
         }
         if ($file->saveAs($allFilePath)) {
             //获取图片宽和高
             $picSize = getimagesize($allFilePath);
             $imgInfo = array('name' => $file->name, 'filepath' => $filepath, 'filename' => $filename, 'filesize' => $file->size, 'type' => $file->extensionName, 'mark' => 'img', 'imgwidth' => $picSize[0], 'imgheight' => $picSize[1], 'create_time' => time());
             //素材数据入库
             $model = new Material();
             $model->attributes = $imgInfo;
             $model->save();
             $imgInfo['id'] = $model->id;
             return $imgInfo;
         } else {
             throw new CException(Yii::t('yii', 'file save error'));
         }
     } else {
         throw new CException(Yii::t('yii', 'there is an error for upload ,error:{error}', array('{error}' => $file->error)));
     }
 }
예제 #5
0
 /**
  * Feltölt egy fájlt a megadott tantárgyhoz.
  * @param int $id A tantárgy azonosítója
  */
 public function actionUpload($id)
 {
     if (!Yii::app()->user->getId()) {
         throw new CHttpException(403, 'A funkció használatához be kell jelentkeznie');
     }
     $id = (int) $id;
     $file = CUploadedFile::getInstanceByName("to_upload");
     if ($file == null) {
         throw new CHttpException(404, 'Nem lett fájl kiválasztva a feltöltéshez');
     }
     $filename = $file->getName();
     $localFileName = sha1($filename . microtime()) . "." . CFileHelper::getExtension($filename);
     if (in_array(strtolower(CFileHelper::getExtension($filename)), Yii::app()->params["deniedexts"])) {
         throw new CHttpException(403, ucfirst(CFileHelper::getExtension($filename)) . ' kiterjesztésű fájl nem tölthető fel a szerverre');
     }
     $model = new File();
     $model->subject_id = $id;
     $model->filename_real = $filename;
     $model->filename_local = $localFileName;
     $model->description = htmlspecialchars($_POST["description"]);
     $model->user_id = Yii::app()->user->getId();
     $model->date_created = new CDbExpression('NOW()');
     $model->date_updated = new CDbExpression('NOW()');
     $model->downloads = 0;
     $model->save();
     if ($file->saveAs("upload/" . $localFileName)) {
         $this->redirect(Yii::App()->createUrl("file/list", array("id" => $id)));
     }
 }
예제 #6
0
 public function run()
 {
     $file = CUploadedFile::getInstanceByName('file');
     $path = $this->getUniquePath($this->filesDir(), $file->extensionName);
     $file->saveAs($path);
     echo CHtml::link($file->name, "http://" . $_SERVER["HTTP_HOST"] . '/' . $path);
 }
예제 #7
0
 public static function save($typeModel, $idModel, $files_field_name = 'upload', $need_file_name = '')
 {
     $Upload = CUploadedFile::getInstanceByName($files_field_name);
     if (is_null($Upload)) {
         return false;
     }
     $folder = self::makePath($typeModel, $idModel);
     if (!file_exists($folder)) {
         mkdir($folder, 0777, true);
     }
     if ($need_file_name == '') {
         $newName = str_replace('.' . $Upload->getExtensionName(), '', urlencode($Upload->getName())) . "-" . date("YmdHis", time()) . '.' . $Upload->getExtensionName();
     } else {
         //добавка для сохранения кадров под конкретным именем
         $newName = $need_file_name;
     }
     $newPath = $folder . self::DS . $newName;
     if ($Upload->saveAs($newPath)) {
         if (file_exists($newPath)) {
             return $newName;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
 public function actionCreate()
 {
     $id = intval($_GET['id']);
     if (!$id) {
         exit('error 1');
     }
     $dir = Yii::app()->params['uploadPathImage'] . 'gallery/' . $id;
     $upload = CUploadedFile::getInstanceByName('Filedata');
     if ($upload->getSize()) {
         $model = new GalleryImage();
         $model->gallery_id = $id;
         $model->save();
         if (!file_exists($dir)) {
             mkdir($dir, 0777, true);
         }
         $bigFile = $dir . '/' . $model->id . '_origin.' . $upload->getExtensionName();
         $smallFile = $dir . '/' . $model->id . '.' . $upload->getExtensionName();
         $upload->saveAs($bigFile);
         // 压缩文件
         $image = Yii::app()->image->load($bigFile);
         $image->resize(Yii::app()->params['uploadMaxWidth'], Yii::app()->params['uploadMaxHeight'])->quality(Yii::app()->params['uploadQuality']);
         $image->save($smallFile);
         $model->file = $id . '/' . $model->id . '.' . $upload->getExtensionName();
         $model->save();
         echo json_encode(['id' => $model->id, 'file' => $model->file]);
     } else {
         exit('error 2');
     }
 }
 public function actionImport()
 {
     if (isset($_POST['importnow']) || isset($_FILES['importfile'])) {
         $this->hasErrors = false;
         $this->errors = array(array());
         $filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . '../../../../assets/upload.sql';
         if (file_exists($filePath)) {
             unlink($filePath);
         }
         if ($_FILES['importfile']['error'] != 0) {
             $this->hasErrors = true;
             if ($_FILES['importfile']['error'] == 4) {
                 $this->errors = array(array(Yii::t('lazy8', 'Returned error = 4 which means no file given'), Yii::t('lazy8', 'Select a file and try again')));
             } else {
                 $this->errors = array(array(Yii::t('lazy8', 'Returned error') . ' = ' . $_FILES['importfile']['error'], Yii::t('lazy8', 'Select a file and try again')));
             }
         } else {
             $importFile = CUploadedFile::getInstanceByName('importfile');
             $importFile->saveAs($filePath);
             $this->importTemplates($filePath);
         }
     } else {
         if (isset($_GET['importing'])) {
             $this->hasErrors = true;
             $this->errors = array(array(Yii::t('lazy8', 'Upload failed.  Possibly the file was too big.'), Yii::t('lazy8', 'Select a file and try again')));
         } else {
             $this->hasErrors = false;
             $this->errors = array(array());
         }
     }
     $this->render('showimport');
 }
 public function actionuploadDocuments()
 {
     if (!empty(Yii::app()->user->_data)) {
         $userId = Yii::app()->user->_data->id;
     }
     // getting project Id
     $projectId = Yii::app()->request->getPost('project_id');
     if (isset($_POST['YumUserdocuments']) && isset($_POST['YumUserdocuments']['name'])) {
         $model = new YumUserdocuments();
         $model->attributes = $_POST['YumUserdocuments'];
         $model->name = CUploadedFile::getInstanceByName('YumUserdocuments[name]');
         if ($model->name instanceof CUploadedFile) {
             //  $userId =5;
             // Prepend the id of the user to avoid filename conflicts
             $fileName = $_FILES['YumUserdocuments']['name']['name'];
             $filePath = Yum::module('userdocuments')->documentPath . '/' . $userId . '_' . $_FILES['YumUserdocuments']['name']['name'];
             $model->name->saveAs($filePath);
             $attrArr = array('name' => $fileName, 'path' => $filePath, 'created_by' => $userId);
             $model->attributes = $attrArr;
             if ($model->save(false)) {
                 if ($projectId) {
                     $userProjectDocuments = new YumUserdocumentsprojects();
                     $attrArrProject = array('project_id' => $projectId, 'userdocuments_id' => $model['userdocuments_id'], 'created_by' => $userId);
                     $userProjectDocuments->attributes = $attrArrProject;
                     if ($userProjectDocuments->save()) {
                         Yum::setFlash(Yum::t('The Document was uploaded successfully'));
                         $this->redirect(array('//userproject/userproject/projectdetails?project_id=' . $projectId));
                     }
                 }
                 Yum::setFlash(Yum::t('The Document was uploaded successfully'));
                 $this->redirect(array('//userdocuments/userdocuments/index'));
             }
         }
     }
 }
예제 #11
0
 public function actionImage()
 {
     $params = Yii::app()->params;
     $file = CUploadedFile::getInstanceByName('imgFile');
     if ($file === null || $file->getHasError()) {
         $this->jsonReturn($file === null ? 1 : $file->getError(), '上传失败,请联系管理员');
     }
     $imagesize = getimagesize($file->getTempName());
     if ($imagesize === false) {
         $this->jsonReturn(1, '请上传正确格式的图片');
     }
     $basePath = $params->staticPath;
     $extension = image_type_to_extension($imagesize[2]);
     $md5 = md5(file_get_contents($file->getTempName()));
     $filename = $md5 . $extension;
     $dirname = 'upload/' . $md5[0] . '/';
     $fullPath = $params->staticPath . $dirname . $filename;
     $fullDir = dirname($fullPath);
     if (!is_dir($fullDir)) {
         mkdir($fullDir, 0755, true);
     }
     if (file_exists($fullPath) || $file->saveAs($fullPath)) {
         $url = $params->staticUrlPrefix . $dirname . $filename;
         $this->jsonReturn(0, '', $url);
     } else {
         $this->jsonReturn(1, '上传失败,请联系管理员');
     }
 }
예제 #12
0
 public function actionUpload($obj = null)
 {
     if (Yii::app()->user->isGuest) {
         $this->redirect('/');
     }
     if (!$obj) {
         $obj = 'default';
     }
     if ($_FILES['uploadFile']) {
         $fileExt = array('doc', 'docx', 'xls', 'xlsx', 'txt', 'mp3');
         $imageExt = array('jpg', 'gif', 'png', 'jpeg');
         $serverPath = dirname(Yii::app()->request->scriptFile);
         $folder = '/userdata/uploads/u' . Yii::app()->user->id . '/';
         $file = CUploadedFile::getInstanceByName('uploadFile');
         $fileName = time() . '.' . $file->getExtensionName();
         if (in_array(strtolower($file->getExtensionName()), $fileExt) || in_array(strtolower($file->getExtensionName()), $imageExt)) {
             if (in_array(strtolower($file->getExtensionName()), $imageExt)) {
                 UploadImages::upload($file->getTempName(), $fileName, $serverPath . $folder, 'tinymce', $obj . '_text_image');
             } else {
                 if (!is_dir(Yii::getPathOfAlias('webroot') . $folder)) {
                     mkdir(Yii::getPathOfAlias('webroot') . $folder, 0777, true);
                 }
                 $file->saveAs(Yii::getPathOfAlias('webroot') . $folder . $fileName);
             }
             header("Content-type: application/xml; charset=utf-8");
             exit('<?xml version="1.0" encoding="utf8"?><result>' . $folder . 'resize/' . $fileName . '</result>');
         } else {
             exit('Запрещенный формат файла');
         }
     } else {
         exit('No file');
     }
 }
 /**
  * Get an instance of CuploadedFile. Catches errors and throws a BadFileUploadException
  * @var string $filesVariableName
  */
 public static function getByNameAndCatchError($filesVariableName)
 {
     assert('is_string($filesVariableName)');
     $uploadedFile = CUploadedFile::getInstanceByName($filesVariableName);
     if ($uploadedFile == null) {
         throw new FailedFileUploadException(Zurmo::t('Core', 'The file did not exist'));
     } elseif ($uploadedFile->getHasError()) {
         $error = $uploadedFile->getError();
         $messageParams = array('{file}' => $uploadedFile->getName(), '{limit}' => self::getSizeLimit());
         if ($error == UPLOAD_ERR_NO_FILE) {
             $message = Zurmo::t('Core', 'The file did not exist');
         } elseif ($error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE) {
             $message = Zurmo::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.', $messageParams);
         } elseif ($error == UPLOAD_ERR_PARTIAL) {
             $message = Zurmo::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.', $messageParams);
         } elseif ($error == UPLOAD_ERR_NO_TMP_DIR) {
             $message = Zurmo::t('yii', 'Missing the temporary folder to store the uploaded file "{file}".', $messageParams);
         } elseif ($error == UPLOAD_ERR_CANT_WRITE) {
             $message = Zurmo::t('yii', 'Failed to write the uploaded file "{file}" to disk.', $messageParams);
         } elseif (defined('UPLOAD_ERR_EXTENSION') && $error == UPLOAD_ERR_EXTENSION) {
             $message = Zurmo::t('yii', 'File upload was stopped by extension.');
         } else {
             //Unsupported or unknown error.
             $message = Zurmo::t('Core', 'There was an error uploading the file.');
         }
         throw new FailedFileUploadException($message);
     } else {
         return $uploadedFile;
     }
 }
 public function actionEditAvatar()
 {
     $model = YumUser::model()->findByPk(Yii::app()->user->id);
     if (isset($_POST['YumUser'])) {
         $model->attributes = $_POST['YumUser'];
         $model->setScenario('avatarUpload');
         if (Yum::module('avatar')->avatarMaxWidth != 0) {
             $model->setScenario('avatarSizeCheck');
         }
         $model->avatar = CUploadedFile::getInstanceByName('YumUser[avatar]');
         if ($model->validate()) {
             if ($model->avatar instanceof CUploadedFile) {
                 // Prepend the id of the user to avoid filename conflicts
                 $filename = Yum::module('avatar')->avatarPath . '/' . $model->id . '_' . $_FILES['YumUser']['name']['avatar'];
                 $model->avatar->saveAs($filename);
                 $model->avatar = $filename;
                 if ($model->save()) {
                     Yum::setFlash(Yum::t('The image was uploaded successfully'));
                     Yum::log(Yum::t('User {username} uploaded avatar image {filename}', array('{username}' => $model->username, '{filename}' => $model->avatar)));
                     $this->redirect(array('//profile/profile/view'));
                 }
             }
         }
     }
     $this->render('edit_avatar', array('model' => $model));
 }
예제 #15
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'ubah' page.
  */
 public function actionTambah()
 {
     $model = new UploadMonitorForm();
     $monitor = new Monitor();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['UploadMonitorForm'])) {
         $scriptFile = CUploadedFile::getInstanceByName('UploadMonitorForm[nama_file]');
         if (isset($scriptFile)) {
             $ini_array = parse_ini_file($scriptFile->tempName, true);
             // echo "Nama: {$ini_array['description']['name']} <br />";
             // echo "Descripsi: {$ini_array['description']['description']} <br />";
             // echo "Perintah: {$ini_array['config']['command']} <br />";
             // echo "Output: {$ini_array['config']['output']} <br />";
             // echo "View: {$ini_array['config']['view']}";
             //$monitor = new Monitor;
             $monitor->nama = $ini_array['description']['name'];
             $monitor->deskripsi = $ini_array['description']['description'];
             $monitor->perintah = $ini_array['config']['command'];
             $monitor->output_type_id = OutputType::model()->find("nama = '{$ini_array['config']['output']}'")->id;
             $monitor->view_type_id = isset($ini_array['config']['view']) ? ViewType::model()->find("nama = '{$ini_array['config']['view']}'")->id : NULL;
             $monitor->prefix = isset($ini_array['config']['prefix']) ? $ini_array['config']['prefix'] : NULL;
             $monitor->suffix = isset($ini_array['config']['suffix']) ? $ini_array['config']['suffix'] : NULL;
             if ($monitor->save()) {
                 $this->redirect(array('ubah', 'id' => $monitor->id));
             }
         }
     }
     $this->render('tambah', array('model' => $model, 'monitor' => $monitor));
 }
예제 #16
0
 /**
  * Upload file and process it for mapping.
  */
 public function actionUpload()
 {
     // Get import post
     $import = craft()->request->getRequiredPost('import');
     // Get file
     $file = \CUploadedFile::getInstanceByName('file');
     // Is file valid?
     if (!is_null($file)) {
         // Determine folder
         $folder = craft()->path->getStoragePath() . 'import/';
         // Ensure folder exists
         IOHelper::ensureFolderExists($folder);
         // Get filepath - save in storage folder
         $path = $folder . $file->getName();
         // Save file to Craft's temp folder for later use
         $file->saveAs($path);
         // Put vars in model
         $model = new ImportModel();
         $model->filetype = $file->getType();
         // Validate filetype
         if ($model->validate()) {
             // Get columns
             $columns = craft()->import->columns($path);
             // Send variables to template and display
             $this->renderTemplate('import/_map', array('import' => $import, 'file' => $path, 'columns' => $columns));
         } else {
             // Not validated, show error
             craft()->userSession->setError(Craft::t('This filetype is not valid') . ': ' . $model->filetype);
         }
     } else {
         // No file uploaded
         craft()->userSession->setError(Craft::t('Please upload a file.'));
     }
 }
예제 #17
0
 public function actionRedactorUpload()
 {
     $uploadPath = '/../uploads/';
     if (Settings::get('gallery', 'upload_path')) {
         $uploadPath = '/' . trim(Settings::get('gallery', 'upload_path'), '/') . '/';
     }
     $uploadUrl = '/uploads/';
     if (Settings::get('gallery', 'upload_url')) {
         $uploadUrl = Settings::get('gallery', 'upload_url');
     }
     $uploadPath = rtrim($uploadPath, '/') . '/editor/';
     $uploadPath = Yii::app()->basePath . $uploadPath;
     if (!is_dir($uploadPath)) {
         mkdir($uploadPath, 0777, true);
         chmod($uploadPath, 0777);
         //throw new CHttpException(500, "{$this->path} does not exists.");
     } else {
         if (!is_writable($uploadPath)) {
             chmod($uploadPath, 0777);
             //throw new CHttpException(500, "{$this->path} is not writable.");
         }
     }
     $file = CUploadedFile::getInstanceByName('file');
     $fileName = time() . $file->getName();
     $file->saveAs($uploadPath . $fileName);
     $url = Yii::app()->baseUrl . $uploadUrl . 'editor/' . $fileName;
     $array = array('filelink' => $url);
     echo stripslashes(json_encode($array));
 }
 public function actionUpload()
 {
     if (Yii::app()->user->isGuest) {
         echo "No access";
     } else {
         $property_id = Yii::app()->user->getState('property_id');
         $fileInstance = CUploadedFile::getInstanceByName('file');
         $isImage = substr($fileInstance->getType(), 0, 5) == 'image' ? true : false;
         $filename = YII::app()->request->getPost('filename', false);
         $filer = new propertyFile($property_id);
         $result = $filer->addFile($fileInstance, $filename);
         $sysFile = $filer->getFile($result['systemname']);
         $format = $filer->getFileFormat($result['systemname']);
         $filer2 = new propertyFile($property_id);
         $filer2->addFile($fileInstance, $this->getOriginName($filename, $format));
         /*             * Resize image if size > 4mb  . GD  */
         if ($isImage) {
             $systemFile = $filer->getFile($result['systemname']);
             list($width, $height) = getimagesize($systemFile['filepath']);
             if ($fileInstance->size >= 4194304 || $width > 600 || $height > 400) {
                 if (file_exists($systemFile['filepath'])) {
                     $newImg = $this->imageConverting($systemFile['filepath'], 600, 500, FALSE, $format);
                     unlink($systemFile['filepath']);
                     imagejpeg($newImg, $systemFile['filepath']);
                 }
             }
             $minname = $this->getMinname($systemFile['filepath'], $format);
             $minfile = $this->imageConverting($systemFile['filepath'], 200, 200, FALSE, $format);
             imagejpeg($minfile, $minname);
         }
         echo json_encode($result);
         die;
     }
 }
예제 #19
0
 /**
  * Redactor image upload.
  *
  * @param string $name Model name
  * @param string $attr Model attribute
  * @throws CHttpException
  */
 public function actionRedactorImageUpload($name, $attr)
 {
     $name = (string) $name;
     $attribute = (string) $attr;
     // Make Yii think this is a AJAX request.
     $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
     $file = CUploadedFile::getInstanceByName('file');
     if ($file instanceof CUploadedFile) {
         if (!in_array(strtolower($file->getExtensionName()), array('gif', 'png', 'jpg', 'jpeg'))) {
             throw new CHttpException(500, CJSON::encode(array('error' => Yii::t('YcmModule.ycm', 'Invalid file extension "{ext}".', array('{ext}' => $file->getExtensionName())))));
         }
         $fileName = trim(md5($attribute . time() . uniqid(rand(), true))) . '.' . $file->getExtensionName();
         $attributePath = $this->module->getAttributePath($name, $attribute);
         if (!is_dir($attributePath)) {
             if (!mkdir($attributePath, $this->module->permissions, true)) {
                 throw new CHttpException(500, CJSON::encode(array('error' => Yii::t('YcmModule.ycm', 'Could not create folder "{dir}". Make sure "uploads" folder is writable.', array('{dir}' => $attributePath)))));
             }
         }
         $path = $attributePath . DIRECTORY_SEPARATOR . $fileName;
         if (file_exists($path) || !$file->saveAs($path)) {
             throw new CHttpException(500, CJSON::encode(array('error' => Yii::t('YcmModule.ycm', 'Could not save file or file exists: "{file}".', array('{file}' => $path)))));
         }
         $attributeUrl = $this->module->getAttributeUrl($name, $attribute, $fileName);
         $data = array('filelink' => $attributeUrl);
         echo CJSON::encode($data);
         exit;
     } else {
         throw new CHttpException(500, CJSON::encode(array('error' => Yii::t('YcmModule.ycm', 'Could not upload file.'))));
     }
 }
 public function actionCreate($id, $iddoc, $dane, $tipdoc, $doc)
 {
     $this->layout = 'main_box';
     $modelgrid = new DocumentoNuevo();
     $modelgrid->unsetAttributes();
     $modelgrid->documentoanexo_id = $id;
     $tabla = DocumentoAnexo::model()->findBypk($id)->tabla;
     switch ($tabla) {
         case 'matricula':
             $modelgrid->matriculaespejo_id = $iddoc;
             break;
         case 'docente':
             $modelgrid->docenteespejo_id = $iddoc;
             break;
         case 'administrativo':
             $modelgrid->administrativoespejo_id = $iddoc;
             break;
     }
     $model = new DocumentoNuevo();
     Controller::scriptBasico(7);
     $this->performAjaxValidation($model, 'documento-nuevo-form');
     if (isset($_POST['DocumentoNuevo'])) {
         $model->setAttributes($_POST['DocumentoNuevo']);
         switch ($tabla) {
             case 'matricula':
                 $model->matriculaespejo_id = $iddoc;
                 break;
             case 'docente':
                 $model->docenteespejo_id = $iddoc;
                 break;
             case 'administrativo':
                 $model->administrativoespejo_id = $iddoc;
                 break;
         }
         $model->documentoanexo_id = $id;
         $model->CODIGO_DANE_SEDE = $dane;
         $model->TIPO_DOCUMENTO = $tipdoc;
         $model->NRO_DOCUMENTO = $doc;
         $rutaupload = Yii::getPathOfAlias('webroot') . "//uploads//";
         $rutapath = "..//descargas//";
         if (CUploadedFile::getInstanceByName('archivo_upload') != null) {
             $semilla = Date('d_m_Y_h_i_s_');
             $model->archivo = CUploadedFile::getInstanceByName('archivo_upload');
             $namefile = $semilla . $model->archivo;
             $model->archivo->saveAs($rutapath . $namefile);
             $model->archivo = $namefile;
         } elseif (copy($rutaupload . $model->archivo, $rutapath . $model->archivo)) {
             unlink($rutaupload . $model->archivo);
         }
         if ($model->save()) {
             if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                 Yii::app()->end();
             } else {
                 $this->redirect(array('create', 'id' => $id, 'iddoc' => $iddoc, 'dane' => $dane, 'tipdoc' => $tipdoc, 'doc' => $doc));
             }
         }
     }
     $this->render('create', array('model' => $model, 'id' => $id, 'iddoc' => $iddoc, 'modelgrid' => $modelgrid));
 }
예제 #21
0
 public function actionUploadImage()
 {
     $file = CUploadedFile::getInstanceByName('upload');
     $model = new BlogImage();
     $model->image = $file;
     if ($model->save()) {
         $this->renderPartial('uploadImage', compact('model'));
     }
 }
예제 #22
0
 /**
  * Method to handle file upload thought XHR2
  * On success returns JSON object with image info.
  * @param $gallery_id string Gallery Id to upload images
  * @throws CHttpException
  */
 public function actionAjaxUpload($gallery_id = null)
 {
     $model = new GalleryPhoto();
     $model->gallery_id = $gallery_id;
     $imageFile = CUploadedFile::getInstanceByName('image');
     $model->file_name = $imageFile->getName();
     $model->setImage($imageFile->getTempName());
     header("Content-Type: application/json");
     echo CJSON::encode(array('id' => $model->id, 'rank' => $model->rank, 'name' => (string) $model->name, 'description' => (string) $model->description, 'preview' => $model->getPreview()));
 }
예제 #23
0
 public function actionUpload()
 {
     $params = Yii::app()->params;
     $file = CUploadedFile::getInstanceByName('avatar');
     try {
         if ($file === null) {
             throw new Exception(Yii::t('common', 'No file uploaded'), 1);
         }
         if ($file->getHasError()) {
             throw new Exception(Yii::t('common', 'Upload failed, please contact the administrator'), $file->getError());
         }
         $imagesize = getimagesize($file->getTempName());
         if ($imagesize === false) {
             throw new Exception(Yii::t('common', 'Invalid file type of image'), 2);
         }
         if ($imagesize[0] > $params['avatar']['width'] || $imagesize[1] > $params['avatar']['height']) {
             throw new Exception(Yii::t('common', 'Image height or width exceeded, the limited width is {width} and height is {height}', array('{width}' => $params['avatar']['width'], '{height}' => $params['avatar']['height'])), 3);
         }
         if (filesize($file->getTempName()) > $params['avatar']['size']) {
             throw new Exception(Yii::t('common', 'File is too large, the limited size is {size}', array('{size}' => sprintf('%.2fMB', $params['avatar']['size'] / 1048576))), 4);
         }
         $basePath = $params->staticPath;
         $extension = image_type_to_extension($imagesize[2]);
         $md5 = md5(file_get_contents($file->getTempName()));
         $filename = $md5 . $extension;
         $dirname = 'upload/' . $md5[0] . '/';
         $fullPath = $params->staticPath . $dirname . $filename;
         $fullDir = dirname($fullPath);
         if (!is_dir($fullDir)) {
             mkdir($fullDir, 0755, true);
         }
         if (file_exists($fullPath) || $file->saveAs($fullPath)) {
             $userAvatar = new UserAvatar();
             $userAvatar->user_id = $this->user->id;
             $userAvatar->md5 = $md5;
             $userAvatar->extension = $extension;
             $userAvatar->width = $imagesize[0];
             $userAvatar->height = $imagesize[1];
             $userAvatar->add_time = time();
             $userAvatar->save(false);
             $this->user->avatar_id = $userAvatar->id;
             $this->user->save();
             $url = $params->staticUrlPrefix . $dirname . $filename;
             $errorCode = 0;
             $errorMsg = '';
         } else {
             throw new Exception(Yii::t('common', 'Upload failed, please contact the administrator'), 1);
         }
     } catch (Exception $e) {
         $url = '';
         $errorCode = $e->getCode();
         $errorMsg = $e->getMessage();
     }
     $this->render('upload', array('url' => $url, 'errorCode' => $errorCode, 'errorMsg' => $errorMsg));
 }
예제 #24
0
 public function actionCreate()
 {
     if (isset($_POST['phone']) & isset($_POST['title']) & isset($_POST['content']) & isset($_POST['place']) & isset($_POST['create_time']) & isset($_POST['uid'])) {
         //用户积分修改
         $u = user_load($_POST['uid']);
         $edit = array('field_jifen' => array('und' => array(0 => array('value' => $u->field_jifen['und'][0]['value'] + 3))));
         user_save($u, $edit);
         $node->title = $_POST['title'];
         $node->field_phone['und'][0]['value'] = $_POST['phone'];
         $node->type = "sr";
         $node->body['und'][0]['value'] = $_POST['content'];
         $node->uid = $_POST['uid'];
         $node->language = 'zh-hans';
         $node->status = 0;
         //(1 or 0): published or not
         $node->promote = 0;
         //(1 or 0): promoted to front page
         $node->comment = 2;
         // 0 = comments disabled, 1 = read only, 2 = read/write
         //$node->field_riq['und'][0]['value'] =date('Y:m:d H:i:s');
         $node->field_riq['und'][0]['value'] = $_POST['create_time'];
         $node->field_src['und'][0]['value'] = $_POST['place'];
         $node->field_status['und'][0]['value'] = '处理中';
         //默认为匿名
         if (isset($_POST['name'])) {
             $node->field_shimin['und'][0]['value'] = $_POST['name'];
         }
         $image = CUploadedFile::getInstanceByName('img');
         if (is_object($image) && get_class($image) === 'CUploadedFile') {
             $dir = Yii::getPathOfAlias('webroot') . '/assets/urban/';
             //$ext = $image->getExtensionName();
             $fileName = uniqid() . '.jpg';
             $name = $dir . $fileName;
             $image->saveAs($name, true);
             $file = (object) array('uid' => $_POST['uid'], 'uri' => $name, 'filemime' => file_get_mimetype($filepath), 'status' => 1);
             $file = file_copy($file, 'public://pictures/urban');
             $node->field_tux['und'][0] = (array) $file;
         }
         $node = node_submit($node);
         // Prepare node for saving
         node_save($node);
         $basic = new basic();
         $basic->error_code = 0;
         //$basic->error_msg="no input parameters";
         $jsonObj = CJSON::encode($basic);
         echo $jsonObj;
     } else {
         $basic = new basic();
         $basic->error_code = 1;
         $basic->error_msg = "no input parameters";
         $jsonObj = CJSON::encode($basic);
         echo $jsonObj;
     }
 }
예제 #25
0
 public function actionImage()
 {
     if (request()->getIsPostRequest() && user()->checkAccess('upload_file')) {
         $upload = CUploadedFile::getInstanceByName('imgFile');
         $this->uploadImage($upload, UPLOAD_TYPE_PICTURE, 'images');
     } else {
         $data = array('error' => 1, 'message' => t('you_do_not_have_enough_permissions'));
         echo CJSON::encode($data);
         exit(0);
     }
 }
예제 #26
0
 public function __construct($name, $target, $type = '*', $size = '2048')
 {
     if (is_array($name)) {
         $this->instance = CUploadedFile::getInstance($name[0], $name[1]);
     } else {
         $this->instance = CUploadedFile::getInstanceByName($name);
     }
     $this->type = $type;
     $this->target = $target;
     $this->setSize($size);
 }
예제 #27
0
 public function actionUpdatePdf()
 {
     $file = '../epaper2/assets/pdf/';
     //echo $file;
     $pdf = CUploadedFile::getInstanceByName('file');
     if (is_object($pdf) && get_class($pdf) === 'CUploadedFile') {
         // 判断实例化是否成功
         $name = $file . '/' . $pdf->name;
         $pdf->saveAs($name);
     }
     header("Location: " . Yii::app()->name . "tydaily2/?q=myresult/3");
 }
예제 #28
0
 /**
  * Returns an array of instances starting with specified array name.
  *
  * If multiple files were uploaded and saved as 'Files[0]', 'Files[1]', 'Files[n]'..., you can have them all by
  * passing 'Files' as array name.
  *
  * @param string $name                  The name of the array of files
  * @param bool   $lookForSingleInstance If set to true, will look for a single instance of the given name.
  *
  * @return UploadedFile[] The array of UploadedFile objects. Empty array is returned if no adequate upload was
  *                        found. Please note that this array will contain all files from all subarrays regardless
  *                        how deeply nested they are.
  */
 public static function getInstancesByName($name, $lookForSingleInstance = true)
 {
     $name = static::_normalizeName($name);
     $instances = parent::getInstancesByName($name);
     if (!$instances && $lookForSingleInstance) {
         $singleInstance = parent::getInstanceByName($name);
         if ($singleInstance) {
             $instances[] = $singleInstance;
         }
     }
     return $instances;
 }
예제 #29
0
 public function actionEdit()
 {
     if (empty($_POST)) {
         $info = IndexModule::model()->findByPk($_REQUEST['id']);
         $types = IndexModule::model()->getType('', 'array');
         $viewData = array();
         $viewData['info'] = $info;
         $viewData['types'] = $types;
         $this->render('edit', $viewData);
         exit;
     }
     $res = array('statusCode' => 200, 'message' => '修改成功!');
     try {
         $banner_name = '';
         $image = CUploadedFile::getInstanceByName('img');
         if ($image) {
             //$dir = Yii::getPathOfAlias('webroot').'/images/indexmodule';
             $imageConfig = Yii::app()->params['image']['module_banner'];
             $dir = $imageConfig['path'];
             // $extension = substr(strrchr($image->name, '.'), 1);
             $extension = $image->getExtensionName();
             $banner_name = time() . '_' . $_REQUEST['id'] . '.' . $extension;
             $imagePath = $dir . '/' . $banner_name;
             $image->saveAs($imagePath, true);
         }
         $m = IndexModule::model()->findByPk($_REQUEST['id']);
         $m->title = $_REQUEST['title'];
         $m->link = $_REQUEST['link'];
         if ($banner_name) {
             $m->img = $banner_name;
         }
         $m->describtion = $_REQUEST['describtion'];
         $m->product_ids = $_REQUEST['product_ids'];
         $m->type = $_REQUEST['type'];
         $m->sort = $_REQUEST['sort'];
         $m->is_show = $_REQUEST['is_show'];
         $m->start_time = strtotime($_REQUEST['start_time']);
         $m->end_time = strtotime($_REQUEST['end_time']);
         $m->add_time = time();
         $flag = $m->save();
         //todo 删除原图片
         if (!$flag) {
             throw new exception('修改失败');
         }
     } catch (Exception $e) {
         $res['statusCode'] = 300;
         $res['message'] = '失败【' . $e->getMessage() . '】';
     }
     $res['navTabId'] = 'indexModuleList';
     $res['callbackType'] = 'closeCurrent';
     $res['forwardUrl'] = '/manage/indexModule/index';
     $this->ajaxDwzReturn($res);
 }
예제 #30
0
 public function actionUpload()
 {
     $image = new Content();
     $image->file = CUploadedFile::getInstanceByName('file');
     if ($image->validate(array('file'))) {
         if ($image->file->saveAs(Yii::app()->basePath . '/../images/' . time() . '_' . strtolower($image->file->name))) {
             echo CHtml::image(Yii::app()->baseUrl . '/images/' . time() . '_' . strtolower($image->file->name));
             Yii::app()->end();
         }
     }
     throw new CHttpException(403, 'The server is crying in pain as you try to upload bad stuff');
 }