Exemple #1
1
 function beforeSave($insert)
 {
     if (parent::beforeSave($insert)) {
         $file = UploadedFile::getInstance($this, 'image');
         if ($file && $file->error === UPLOAD_ERR_OK) {
             // Ищем, есть ли уже такой загруженный файл
             $file_model = Files::findOne(['hash' => md5_file($file->tempName)]);
             if ($file_model) {
                 $file_model->repeats++;
             } else {
                 $file_model = new Files();
                 $file_model->saveImageFile($file);
                 $file_model->repeats = 1;
             }
             $file_model->save();
             $this->file_id = $file_model->id;
         } else {
             $this->addError('image', 'Невозможно загрузить файл');
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
Exemple #2
0
 public function actionIndex($id, $tagId = null)
 {
     $project = $this->loadModel('app\\models\\Project', $id);
     $this->view->params['appSettings'] = ['app_name' => $project->title];
     if (!\Yii::$app->user->can('viewProject', ['project' => $project])) {
         throw new ForbiddenHttpException('Access denied');
     }
     $model = new Files();
     if (($files = UploadedFile::getInstances($model, 'file')) && !\Yii::$app->user->isGuest) {
         foreach ($files as $file) {
             $model = new Files();
             $model->file = $file->name;
             $model->project_id = $project->id;
             $model->tags = $_POST['Files']['tags'];
             if ($model->save()) {
                 $file->saveAs($this->_getFolder($model) . $file->name);
             } else {
                 die(var_dump($file->getErrors()));
             }
         }
     }
     $searchModel = new FilesSearch();
     $searchModel->project_id = (int) $project->id;
     if (isset($tagId)) {
         $searchModel->tagId = $tagId;
     }
     $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
     $model->tags = null;
     return $this->render('index', ['model' => $model, 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'project' => $project, 'tagId' => $tagId]);
 }
 public function saveFile($data)
 {
     $file = new Files();
     $src = $file->getSrc($data['image']);
     $name = $file->getName($data['image']);
     $fid = $file->saveFile($src, $name);
     return $fid;
 }
 public function removeAction()
 {
     if (!$this->isXmlHttpRequest()) {
         throw new \Exception('Неверный тип запроса!');
     }
     if (!is_null($this->request->getPost('id'))) {
         $id = (int) $this->request->getPost('id');
         $filesModel = new Files();
         $filesModel->removeFile($id);
     } else {
         throw new \Exception('Неверный тип запроса!');
     }
     echo json_encode(array('success' => 1));
     exit;
 }
Exemple #5
0
 public function upload()
 {
     // привет                                     Inflector::slug(pathinfo($file->name, PATHINFO_FILENAME))
     if ($this->validate()) {
         //$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
         //$this->imageFile->saveAs('uploads/' . mb_convert_encoding($this->imageFile->baseName, "Windows-1251", "UTF-8" ) . '.' . $this->imageFile->extension);
         $new_file_name = md5($this->imageFile->baseName . time()) . '.' . $this->imageFile->extension;
         $this->imageFile->saveAs('uploads/' . $new_file_name);
         $file = new Files();
         $file->filename = $new_file_name;
         $file->title = $this->imageFile->baseName . '.' . $this->imageFile->extension;
         $file->save();
         return true;
     } else {
         return false;
     }
 }
Exemple #6
0
 public function save($runValidation = true, $attributes = NULL)
 {
     $class = get_class($this);
     if ($class == 'Accounts') {
         if (Accounts::findOne($this->id)) {
             $this->isNewRecord = false;
         }
     }
     $a = parent::save($runValidation, $attributes);
     if ($a) {
         //if (isset($_POST['Files'])) {
         //$this->attributes = $_POST['Files'];
         $tmps = \yii\web\UploadedFile::getInstancesByName('Files');
         // proceed if the images have been set
         if (isset($tmps) && count($tmps) > 0) {
             \Yii::info('saved');
             // go through each uploaded image
             $configPath = \app\helpers\Linet3Helper::getSetting("company.path");
             foreach ($tmps as $image => $pic) {
                 $img_add = new Files();
                 $img_add->name = $pic->name;
                 //it might be $img_add->name for you, filename is just what I chose to call it in my model
                 $img_add->path = "files/";
                 $img_add->parent_type = get_class($this);
                 $img_add->parent_id = $this->id;
                 // this links your picture model to the main model (like your user, or profile model)
                 $img_add->save();
                 // DONE
                 if ($pic->saveAs($img_add->getFullFilePath())) {
                     // add it to the main model now
                 } else {
                     echo 'Cannot upload!';
                 }
             }
             if (isset($_FILES)) {
                 Yii::info(print_r($_FILES, true));
                 unset($_FILES);
                 $tmps = \yii\web\UploadedFile::reset();
             }
             //}
         }
     }
     //endFile
     return $a;
 }
Exemple #7
0
 public static function delete($id)
 {
     $fl = Files::find($id);
     if (!is_null($fl->first())) {
         return $fl->delete();
     } else {
         return false;
     }
 }
Exemple #8
0
 public function backupDB()
 {
     $dumper = new dbMaster();
     $sql = $dumper->getDump(false);
     $file = new Files();
     $file->name = "DB Backup " . date("d-m-Y_H_i") . ".sql";
     $file->path = '.';
     $file->save();
     $file->writeFile($sql);
     $this->DBback = $file->id;
 }
Exemple #9
0
 private function getItems()
 {
     $res = [];
     $images = Files::getAttachedFiles(\app\models\Resources::$tableId, $this->_config['album']);
     foreach ($images as $im) {
         $cfg['content'] = '<img src="' . $im->url . '"/>';
         if ($this->_config['showHeader']) {
             $cfg['caption'] = str_replace('{*title*}', $im->title, $this->_config['headerTemplate']);
         }
         $res[] = $cfg;
     }
     return $res;
 }
Exemple #10
0
 public function delete($id)
 {
     $fl = Files::find($id);
     $anak = $fl->anak;
     $del = FilesDAO::delete($id);
     if ($del) {
         unlink($fl->file_path . '/' . $fl->file_name);
         Session::flash('message', "Files dengan nama {$fl->nama} telah dihapus!");
     } else {
         Session::flash('message', "Error, Files with {$id} not found!");
     }
     return Redirect::to('/dash/anak/files/view/' . $anak->id);
 }
Exemple #11
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Files::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 50], 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]);
     $query->andFilterWhere(['id' => $this->id, 'project_id' => $this->project_id]);
     if (isset($this->tagId)) {
         CommonHelper::addCriteriaForTagid($query, TagModel::MODEL_FILES, $this->tagId);
     }
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $query->andFilterWhere(['like', 'file', $this->file]);
     return $dataProvider;
 }
Exemple #12
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Files::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'solicitation_id' => $this->solicitation_id]);
     $query->andFilterWhere(['like', 'filename', $this->filename]);
     return $dataProvider;
 }
Exemple #13
0
 public function upload()
 {
     if ($this->validate()) {
         $path = $this->getStoreInfo();
         $store_to = $path['real'] . $path['route'];
         if (!file_exists($store_to)) {
             FileHelper::createDirectory($store_to);
         }
         foreach ($this->files as $f) {
             $image = $this->isImageFile($f);
             $new_fn = $this->newFileName($f->baseName, $f->extension, $image);
             if ($f->saveAs($store_to . $new_fn)) {
                 $model = new Files();
                 if ($image) {
                     $model->attachBehavior('imageFileBehavior', ['class' => ImageBehavior::className()]);
                 }
                 $model->filename = $new_fn;
                 $model->base_dir = $path['real'];
                 $model->base_url = $path['web'];
                 $model->path = $path['route'];
                 $model->title = $f->baseName;
                 $model->alias = str_replace('.' . $f->extension, '', $new_fn);
                 $model->attach_table = $this->tableId;
                 $model->attach_id = $this->id;
                 if ($model->save()) {
                     $this->_uploadedIds[] = $model->id;
                 }
                 $this->_fn = $new_fn;
                 $this->_url = $path['web'] . $path['route'] . $new_fn;
             }
             //TODO обработка ошибки сохранения файла
         }
         return true;
     }
     return false;
 }
 public function actionGetCard($cid)
 {
     $company = Company::find()->where(['id' => $cid])->asArray()->one();
     $address = Address::find()->where(['id' => $company['address_id']])->asArray()->one();
     $shedule = Shedule::find()->where(['company_id' => $cid])->asArray()->all();
     $brand = Company::find()->where(['id' => $cid])->one()->brand;
     $service = Company::find()->where(['id' => $cid])->one()->service;
     $srv = ArrayHelper::getColumn($service, 'category_id');
     $category = Category::find()->where(['id' => $srv])->asArray()->indexBy('id')->all();
     $srv = ArrayHelper::map($service, 'id', 'name', 'category_id');
     $spoffer = SpecialOffer::find()->where(['company_id' => $cid])->asArray()->one();
     $file = Files::find()->where(['id' => $spoffer['file_id']])->asArray()->one();
     Yii::$app->response->format = Response::FORMAT_JSON;
     $response = ['company' => $company, 'address' => $address, 'shedule' => $shedule, 'brand' => $brand, 'category' => $category, 'service' => $srv, 'spoffer' => $spoffer, 'file' => $file];
     return $response;
 }
Exemple #15
0
 public function search($params)
 {
     $query = Files::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     //        if (!$this->validate()) {
     //            // uncomment the following line if you do not want to return any records when validation fails
     //            // $query->where('0=1');
     //            return $dataProvider;
     //        }
     //        $query->andFilterWhere([
     //            'facult' => $this->facult,
     //            'department' => $this->department,
     //            'predmet' => $this->visable_type,
     //        ]);
     return $dataProvider;
 }
Exemple #16
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Files::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     $query->joinWith('user');
     $query->joinWith('user.department');
     $query->joinWith('user.department.faculty');
     $query->joinWith('subject');
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'size' => $this->size, 'visable_type' => $this->visable_type]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'path', $this->path])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'password', $this->password])->andFilterWhere(['like', 'user.first_name', $this->first_name])->andFilterWhere(['like', 'department.department_name', $this->department_name])->andFilterWhere(['like', 'faculty.faculty_name', $this->faculty_name])->andFilterWhere(['like', 'subject.subject_name', $this->subject_name])->andFilterWhere(['like', 'user.last_name', $this->last_name]);
     return $dataProvider;
 }
 public function run($table, $id)
 {
     /*        $onlyExtensions = array_map( function ($ext) { return '*.'.$ext; },
                 Yii::$app->controller->module->imageAllowExtensions
             );
             
             $filesPath = FileHelper::findFiles(Yii::$app->controller->module->getSaveDir(), [
                 'recursive' => true,
                 'only' => $onlyExtensions
             ]);*/
     $files = Files::getAttachedFiles($table, $id);
     $res = [];
     foreach ($files as $file) {
         $file->attachBehavior('image', ['class' => ImageBehavior::className()]);
         $res[] = ['thumb' => $file->thumbnailUrl, 'image' => $file->url, 'title' => $file->title];
     }
     return $res;
 }
Exemple #18
0
 function run()
 {
     // && $model->contact(Yii::$app->params['adminEmail'])
     $this->enable_form = $this->allow_comments();
     $comment = new Comments();
     $comment->parent_id = 0;
     if ($this->enable_form && $comment->load(Yii::$app->request->post()) && $comment->validate()) {
         Yii::$app->session->setFlash('commentFormSubmitted');
         $comment->active = true;
         $comment->user_id = Yii::$app->user->isGuest ? null : Yii::$app->user->identity->id;
         $comment->ip = ip2long(Yii::$app->request->getUserIP());
         $comment->agent = Yii::$app->request->getUserAgent();
         $comment->saveUploadedImage('file');
         $comment->save();
         return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl());
     }
     $query = new Query();
     $query->addSelect('c.*, f.filename, f.thumb_filename, f.size, u.username')->from([Comments::tableName() . ' c'])->leftJoin(User::tableName() . ' u', 'u.id = c.user_id')->leftJoin(Files::tableName() . ' f', 'f.id = c.image_id')->where(['c.active' => true])->andWhere(['c.post_id' => $this->post_id]);
     $comment->post_id = $this->post_id;
     return $this->render('comments/comments_box', ['comments' => $this->buildTree($query->all()), 'model' => $comment, 'enable' => $this->enable_form]);
 }
Exemple #19
0
 public function send()
 {
     //Yii::import('application.extensions.smtpmail.PHPMailer');
     $mailer = new \yii\swiftmailer\Mailer(["transport" => ['class' => 'Swift_SmtpTransport', 'host' => \app\helpers\Linet3Helper::getSetting('company.mail.server'), 'username' => \app\helpers\Linet3Helper::getSetting('company.mail.user'), 'password' => \app\helpers\Linet3Helper::getSetting('company.mail.password'), 'port' => \app\helpers\Linet3Helper::getSetting('company.mail.port'), 'encryption' => \app\helpers\Linet3Helper::getSetting('company.mail.ssl') ? 'tls' : '']]);
     $mail = $mailer->compose('layouts/html', ['content' => $this->body]);
     //$mail->SetFrom($this->from);
     //echo $this->files;
     if ($this->files != '') {
         $file = Files::findOne($this->files);
         if ($file != null) {
             //echo $file->getFullPath().";;".$file->name;
             $mail->attach($file->getFullFilePath(), ["fileName" => $file->name]);
         }
     }
     $mail->setFrom(\app\helpers\Linet3Helper::getSetting('company.mail.address'))->setTo($this->to)->setSubject($this->subject);
     if ($this->cc != '') {
         $mail->setCc($this->cc);
     }
     if ($this->bcc != '') {
         $mail->setBcc($this->bcc);
     }
     //$mail->AddCC($this->cc); //.$this->cc
     //$mail->AddBcc($this->bcc);
     //$mail->
     //$mail->setHtmlBody($this->body);
     //$mail;
     if (!$mail->send()) {
         //echo "Mailer Error: " . $mail->ErrorInfo;
         throw new Exception(Yii::t('app', "Mailer Error: ") . $mail->ErrorInfo . $mail->Username);
     } else {
         $this->sent++;
         $this->save();
         if (!\app\helpers\Linet3Helper::isConsole()) {
             \Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Message sent!'));
         }
         //echo "Message sent!";
     }
     //*/
     //Yii::$app->end();
 }
Exemple #20
0
 public function files($job)
 {
     $find = Filessearch::where('jobid', '=', $job)->get();
     $find = $find->toArray();
     if (empty($find)) {
         $filessearch = new Filessearch();
         $files = Files::select(array($this->tables['path'] . '.path', $this->tables['filename'] . '.name as filename', 'jobid'))->join($this->tables['filename'], $this->tables['file'] . '.filenameid', '=', $this->tables['filename'] . '.filenameid')->join($this->tables['path'], $this->tables['file'] . '.pathid', '=', $this->tables['path'] . '.pathid')->where('jobid', '=', $job)->remember(10)->get();
         // ->where('jobid','=', $job);
         $files = $files->toArray();
         if (!empty($files)) {
             foreach (array_chunk($files, 1000) as $chunked_files) {
                 $t = Filessearch::insert($chunked_files);
             }
         }
         //$filessearch->getConnection()->insert("INSERT INTO ".($filessearch->getTable())." (path, filename, jobid) ".$files->toSql(), array($job));
     }
     /* Mostra o log do Job */
     $logs = Logs::select(array('logtext'))->where('jobid', '=', $job)->get();
     $logs2 = "";
     foreach ($logs as $log) {
         $logs2[] = preg_replace("/[\t\n]+/", '</br>', $log->logtext);
     }
     //////
     $files = Filessearch::select(array('path', 'filename'))->where('jobid', '=', $job)->orderBy('path', 'asc');
     $files = $files->get();
     //->toArray();
     //$files="";
     if (empty($files)) {
         foreach ($files as $file) {
             $ficheiro[$file->path . $file->name] = '';
         }
         $tree = $this->explodeTree($ficheiro, "/");
         $tree = $this->recursion($tree);
     } else {
         $tree = "";
     }
     // $menu = $this->recursion($tree);
     return View::make('files', array('jobid' => $job, 'logs' => implode($logs2), 'menu' => $menu = $tree));
 }
 function postUpload(Request $request)
 {
     $file = $request->file('file');
     $input = $request->all();
     $validator = Validator::make(['file' => $file, 'extension' => strtolower($file ? $file->getClientOriginalExtension() : 'sss')], ['file' => 'required', 'extension' => 'required|in:csv']);
     if ($validator->fails()) {
         return Redirect::action('MenusController@index')->withErrors($validator);
     }
     $data = [];
     if (Input::hasFile('file')) {
         if (array_key_exists('file', $input)) {
             if ($input['file']->isValid()) {
                 $filename = 'aloha_' . date('Y_m_d_His') . '.' . $input['file']->getClientOriginalExtension();
                 $path = storage_path() . '/upload';
                 $input['file']->move($path, $filename);
                 $file = Files::create(['filename' => $filename]);
                 $data = $this->_import_csv($path, $file->filename);
             }
         }
     }
     return $data;
 }
 public function actionDetaildetshow()
 {
     $id = $_GET['id'];
     $itemdetail = new Itemdetails();
     $detail = $itemdetail->detailDet($id);
     $file = new Files();
     $filelocation = $file->fileLocation($id);
     if ($filelocation) {
         echo '{"success":true,"msg":"请输查询入内容"}';
     } else {
         echo '{"success":true,"msg":"请输查询入内容"}';
     }
 }
 public function download($id)
 {
     $file = Files::findOrFail($id);
     return Response::download(storage_path() . '/upload/' . $file->filename);
 }
Exemple #24
0
 public function actionDownload($id)
 {
     $id = (int) $id;
     $model = Files::findOne($id);
     if ($model === null) {
         throw new \yii\web\HttpException(404, 'The requested page does not exist.');
     }
     //$configPath=\app\helpers\Linet3Helper::getSetting("company.path");
     $file = $model->getFullFilePath();
     //????.$model->id;
     //echo $file.'end';
     return Yii::$app->getResponse()->sendFile($file, $model->name);
     //, file_get_contents()
 }
Exemple #25
0
/* @var $this yii\web\View */
use app\models\Files;
?>
	<div class="col-md-2">
		<div class="panel panel-default">
			<div class="panel-heading">
				Теги
			</div>
			<div class="panel-body">
				dfsdf
				sdsdf
				fg
			</div>
		</div>
	</div>
	
	<div class="col-md-10">
		<div id="gal1">
		<?php 
$imgs = Files::find()->all();
// foreach ($imgs as $img){
// echo "<li style = 'height : 220px; width : 220px; text-align : center; float : left;'><img src='uploads/{$img -> filename}' style = 'max-width : 200px; max-height : 150px;  border-radius : 10px;'><p>{$img -> title}</p></li>";
// }
foreach ($imgs as $img) {
    echo "<img src='thumbnails/{$img->filename}'\n\t\t\t\t\t\talt='{$img->title}'\n\t\t\t\t\t\ttitle='Or here(more priority)'\n\t\t\t\t\t\tdata-desc='some description'\n\t\t\t\t\t\tdata-category='image category here'\n\t\t\t\t\t\tdata-fullsrc='uploads/{$img->filename}'\n\t\t\t\t\t    />";
}
?>
		</div>
	</div>
Exemple #26
0
 public function remove($id)
 {
     $this->setWhere(array('id' => $id));
     $this->delete();
     $filesModel = new Files();
     $filesModel->removeFilesByProject($id);
     $executorsModel = new Executors();
     $executorsModel->setWhere(array('projects_id' => $id));
     $executorsModel->delete();
     $tasksModel = new Tasks();
     $tasksModel->removeTasksByProjectId($id);
 }
 protected function findImage($id)
 {
     if (($model = Files::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('Ресурс не найден');
     }
 }
Exemple #28
0
 public function getFiles()
 {
     return Files::find()->where(['attach_table' => self::$tableId, 'attach_id' => $this->id])->all();
 }
Exemple #29
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getFiles()
 {
     return $this->hasMany(Files::className(), ['user_id' => 'id']);
 }
 /**
  * Downloads file by hash-code
  * @param $code string
  * @return bool|string
  * @throws GoodException if no one file doesn't linked by code
  */
 public function actionGet_file_by_code($code)
 {
     try {
         if (!($file = Files::find()->with('user')->where(['share_link' => $code])->one())) {
             throw new GoodException('Error', 'No such file linked to this code...');
         }
         return $this->downloadFileByPath('../upload/' . $file->user->login . '/' . $file->path);
     } catch (Exception $e) {
         $e->getMessage();
     }
     return false;
 }