Example #1
0
 public function afterSave($event)
 {
     if (!empty($_FILES)) {
         $model = $this->getOwner();
         $file = new File();
         $file->filename = UploadUtils::createUniquefilename($_FILES[self::NAME]['name'], UploadUtils::getPath(self::$fileDir));
         if (move_uploaded_file($_FILES[self::NAME]['tmp_name'], UploadUtils::getPath(self::$fileDir) . DIRECTORY_SEPARATOR . $file->filename)) {
             $file->entity = get_class($model);
             $file->EXid = $model->getPrimaryKey();
             $file->uid = Yii::app()->user->id;
             $file->tag = $this->tag;
             $file->weight = 0;
             $file->timestamp = time();
             $file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
             $file->filesize = $_FILES[self::NAME]['size'];
             $file->status = File::STATUS_SAVED;
             // Ensure all other files of the entity are deleted
             //UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);
             if ($file->save()) {
                 Yii::trace("File saved " . $file . "!!!!");
             } else {
                 Yii::log("Could not save File " . print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
             }
         } else {
             Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
         }
     } else {
         Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
     }
 }
Example #2
0
 public function actionCreates()
 {
     $model = new News();
     $file = new File();
     $model->member_id = Yii::app()->user->id;
     $model->create_at = date('Y-m-d H:i:s');
     $model->update_at = date('Y-m-d H:i:s');
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['News']) && isset($_POST['File'])) {
         $model->attributes = $_POST['News'];
         $file->attributes = $_POST['File'];
         $model->pic = 'noimage.jpg';
         $model->validate();
         $file->validate();
         if ($model->getErrors() == null && $file->getErrors() == null) {
             $file->file = CUploadedFile::getInstance($file, 'file');
             if ($file->file != null) {
                 $filename = time() . '.' . $file->file->getExtensionName();
                 $file->file->saveAs(Yii::app()->params['pathUpload'] . $filename);
                 $model->pic = $filename;
             } else {
                 $model->pic = 'noimage.jpg';
             }
             if ($model->save()) {
                 $this->redirect(array('view', 'id' => $model->news_id));
             }
         }
     }
     $this->render('create', array('model' => $model, 'file' => $file));
 }
 public function control()
 {
     $this->redirectToSternIndiaEndPoint();
     $config = Config::getInstance();
     if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') {
         $target_dir = new FileSystem('upload/');
         $file = new File('foo', $target_dir);
         $name = date('D_d_m_Y_H_m_s_');
         $name = $name . $file->getName();
         $file->setName($name);
         $config = Config::getInstance();
         $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M')));
         $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5());
         try {
             // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
             $file->upload();
             //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
         } catch (Exception $e) {
             $errors = $file->getErrors();
         }
         $csvReader = new CSVReader();
         $destinationFile = $target_dir->directory . $file->getNameWithExtension();
         $data = $csvReader->parse_file($destinationFile);
         //$country= DAOFactory::getDAO('LocationDAO');
         foreach ($data as $loc_arr) {
             Utils::processLocation($loc_arr);
         }
         //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__);
         $target_dir = "uploads/";
         $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
         $uploadOk = 1;
         $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
         // Check if image file is a actual image or fake image
         if (isset($_POST["submit"])) {
             $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
             if ($check !== false) {
                 echo "File is an image - " . $check["mime"] . ".";
                 $uploadOk = 1;
             } else {
                 echo "File is not an image.";
                 $uploadOk = 0;
             }
         }
     }
     return $this->generateView();
 }
Example #4
0
 /**
  *  Редактирование язика
  */
 public function anyEdit()
 {
     $id = (int) $this->getRequestParam('id') ?: null;
     if (Arr::get($this->getPostData(), 'submit') !== null) {
         //Редактирование данных в базе
         $data = Arr::extract($this->getPostData(), ['name', 'iso', 'status']);
         try {
             // Загрузка картинки
             $file = new UploadFile('image', new FileSystem('uploads/images'));
             // Optionally you can rename the file on upload
             $file->setName(uniqid());
             // Validate file upload
             $file->addValidations(array(new UploadMimeType(['image/png', 'image/jpg', 'image/gif']), new UploadSize('50M')));
             // Try to upload file
             try {
                 // Success!
                 $file->upload();
                 $data['flag'] = $file->getNameWithExtension();
             } catch (Exception $e) {
                 // Fail!
                 Message::instance()->warning($file->getErrors());
             }
             // здесь надо использовать QueryBuilder потому-что стадартни update исползует метод Baum-а
             Capsule::table('langs')->whereId($id)->update($data);
             Event::fire('Admin.languageUpdate');
         } catch (QueryException $e) {
             Message::instance()->warning('Language was not editing');
         }
     }
     $item = LangModel::find($id);
     if (empty($item)) {
         throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Language']));
     }
     // отправка в шаблон
     $this->layout->content = View::make('back/languages/edit')->with('item', $item);
 }
Example #5
0
 /**
  * Handles a single upload by given CUploadedFile and returns an array
  * of informations.
  *
  * The 'error' attribute of the array, indicates there was an error.
  *
  * Informations on error:
  *       - error: true
  *       - errorMessage: some message
  *       - name: name of the file
  *       - size: file size
  *
  * Informations on success:
  *      - error: false
  *      - name: name of the uploaded file
  *      - size: file size
  *      - guid: of the file
  *      - url: url to the file
  *      - thumbnailUrl: url to the thumbnail if exists
  *
  * @param type $cFile
  * @return Array Informations about the uploaded file
  */
 protected function handleFileUpload($cFile, $object = null, $publicAccess = false)
 {
     $output = array();
     $file = new File();
     $file->setUploadedFile($cFile);
     $file->public_access = $publicAccess;
     if ($object != null) {
         $file->object_id = $object->getPrimaryKey();
         $file->object_model = get_class($object);
     }
     if ($file->validate() && $file->save()) {
         $output['error'] = false;
         $output['guid'] = $file->guid;
         $output['name'] = $file->file_name;
         $output['title'] = $file->title;
         $output['size'] = $file->size;
         $output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
         $output['mimeBaseType'] = $file->getMimeBaseType();
         $output['mimeSubType'] = $file->getMimeSubType();
         $output['url'] = $file->getUrl("", false);
         $output['thumbnailUrl'] = $file->getPreviewImageUrl(200, 200);
     } else {
         $output['error'] = true;
         $output['errors'] = $file->getErrors();
     }
     $output['name'] = $file->file_name;
     $output['size'] = $file->size;
     $output['deleteUrl'] = "";
     $output['deleteType'] = "";
     $output['thumbnailUrl'] = "";
     return $output;
 }
Example #6
0
 /**
  * Редактирование пункта меню
  */
 public function anyEdit()
 {
     $id = (int) $this->getRequestParam('id') ?: null;
     $model = MenuItemModel::find($id);
     $entityModel = $model->entities()->first();
     if (empty($model)) {
         throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Article']));
     }
     if (Arr::get($this->getPostData(), 'submit') !== null) {
         $data = Arr::extract($this->getPostData(), ['slug', 'icon', 'parentId', 'status', 'entity', 'content']);
         $parent = MenuItemModel::find($data['parentId']);
         // Транзакция для Записание данных в базу
         try {
             Capsule::connection()->transaction(function () use($data, $model, $parent, $entityModel) {
                 // Загрузка картинки
                 $file = new UploadFile('image', new FileSystem('uploads/images'));
                 // Optionally you can rename the file on upload
                 $file->setName(uniqid());
                 // Validate file upload
                 $file->addValidations(array(new UploadMimeType(['image/png', 'image/jpg', 'image/gif']), new UploadSize('50M')));
                 // Try to upload file
                 try {
                     // Success!
                     $file->upload();
                     $data['icon'] = $file->getNameWithExtension();
                 } catch (Exception $e) {
                     // Fail!
                     Message::instance()->warning($file->getErrors());
                 }
                 $entityModel->update(['text' => $data['entity']]);
                 foreach ($data['content'] as $iso => $d) {
                     $langId = Lang::instance()->getLang($iso)['id'];
                     EntityTranslationModel::updateOrCreate(['id' => $d['id']], ['text' => $d['text'], 'lang_id' => $langId, 'entity_id' => $entityModel->id]);
                 }
                 Event::fire('Admin.entitiesUpdate');
                 // если нету нового изображения оставить прежний
                 $data['icon'] ?: $model->icon;
                 $model->update(['slug' => $data['slug'], 'status' => $data['status'], 'icon' => $data['icon']]);
                 if ($parent) {
                     $model->makeChildOf($parent);
                 } else {
                     $model->makeRoot($parent);
                 }
             });
             Message::instance()->success('Menu Item was successfully edited');
         } catch (Exception $e) {
             Message::instance()->warning('Menu Item was don\'t edited');
         }
     }
     $model = MenuItemModel::find($id);
     $entityModel = $model->entities()->first();
     // Загрузка контента для каждово языка
     $contents = [];
     foreach (Lang::instance()->getLangsExcept(Lang::DEFAULT_LANGUAGE) as $iso => $lang) {
         $contents[$iso] = $entityModel->translations()->where('lang_id', '=', $lang['id'])->first();
     }
     $this->layout->content = View::make('back/menus/edit')->with('node', $model::getNode())->with('item', $model)->with('contents', $contents);
 }
 public function actionSoalToefl($id)
 {
     $rnd = rand(0, 9999);
     $inputSoal = new InputSoal();
     if (isset($_POST['InputSoal'])) {
         $inputSoal->attributes = $_POST['InputSoal'];
         if ($inputSoal->validate()) {
             //create a file model
             $file = new File();
             $uploadedFile = CUploadedFile::getInstance($inputSoal, 'file');
             $fileName = "{$rnd}-{$uploadedFile}";
             $file->file = $fileName;
             $file->jenis = $inputSoal->jenis;
             if ($file->save()) {
                 //if(!empty($uploadedFile))
                 //$uploadedFile=CUploadedFile::getInstance($file,'file');
                 if (isset($uploadedFile)) {
                     if ($inputSoal->jenis == 'L') {
                         $uploadedFile->saveAs(Yii::app()->basePath . '/../music/test/' . $fileName);
                     } else {
                         if ($inputSoal->jenis == 'R') {
                             $uploadedFile->saveAs(Yii::app()->basePath . '/../document/test/' . $fileName);
                         }
                     }
                 }
                 $soal = new Soal();
                 $soal->attributes = $inputSoal->attributes;
                 $soal->id_file = $file->id_file;
                 if ($soal->save()) {
                     $kuissoal = new Modultestsoal();
                     $kuissoal->id_modultest = $id;
                     $kuissoal->id_soal = $soal->id_soal;
                     if ($kuissoal->save()) {
                         //redirect to index page
                         //Koneksi ke Database
                         $con = mysqli_connect('localhost', 'root', '', 'toefl');
                         // Check connection
                         if (mysqli_connect_errno()) {
                             echo "Failed to connect to MySQL: " . mysqli_connect_error();
                         }
                         $result = mysqli_query($con, "SELECT * FROM t_modultest where id_modulTest = " . $id);
                         while ($row = mysqli_fetch_array($result)) {
                             $idToefl = $row['id_toefl'];
                             //idModulTest = 15
                         }
                         $this->redirect(array('modulTest/viewSoalToeflTest', 'id' => $idToefl));
                     } else {
                         //get the error message
                         $inputSoal->addErrors($soal->getErrors());
                     }
                 } else {
                     //get the error message
                     $inputSoal->addErrors($soal->getErrors());
                 }
             } else {
                 //get the error message
                 $inputSoal->addErrors($soal->getErrors());
             }
         } else {
             //get the error message
             $inputSoal->addErrors($file->getErrors());
         }
     }
     //display input soal-form
     $this->render('Soal', array('model' => $inputSoal));
 }