/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $image_name = $this->temp_path . $model->{$this->uploadParam}->name; $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name); // watermark if ($this->watermark != '') { $image = Image::watermark($image_name, $this->watermark)->save($image_name); } if ($image->save($image_name)) { // create Thumbnail if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) { Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name); } $result = ['filelink' => $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST')); } }
public function actionViewAdvert($id) { $model = Advert::findOne($id); $data = ['name', 'email', 'text']; $model_feedback = new DynamicModel($data); $model_feedback->addRule('name', 'required'); $model_feedback->addRule('email', 'required'); $model_feedback->addRule('text', 'required'); $model_feedback->addRule('email', 'email'); if (Yii::$app->request->isPost) { if ($model_feedback->load(Yii::$app->request->post()) && $model_feedback->validate()) { Yii::$app->common->sendMail('Subject Advert', $model_feedback->text); } } $user = $model->user; $images = Common::getImageAdvert($model, false); $current_user = ['email' => '', 'username' => '']; if (!Yii::$app->user->isGuest) { $current_user['email'] = Yii::$app->user->identity->email; $current_user['username'] = Yii::$app->user->identity->username; } $coords = str_replace(['(', ')'], '', $model->location); $coords = explode(',', $coords); $coord = new LatLng(['lat' => $coords[0], 'lng' => $coords[1]]); $map = new Map(['center' => $coord, 'zoom' => 15]); $marker = new Marker(['position' => $coord, 'title' => Common::getTitleAdvert($model)]); $map->addOverlay($marker); return $this->render('view_advert', ['model' => $model, 'model_feedback' => $model_feedback, 'user' => $user, 'images' => $images, 'current_user' => $current_user, 'map' => $map]); }
/** * Creates validation rules for $model property * * @param \yii\base\DynamicModel $model */ public function addFormValidators(&$model) { //add validators for basic table filter $model->addRule(['table'], 'required'); $model->addRule(['table'], function () use($model) { return $this->checkTableExists($model); }); //add validators declared in config file foreach (Yii::$app->controller->module->filters as $property => $params) { $model->addRule($property, 'default'); if (!isset($params['rules'])) { continue; } foreach ($params['rules'] as $rule) { $options = isset($rule['options']) ? $rule['options'] : []; $validator = $rule['validator']; if (is_string($validator)) { $model->addRule($property, $validator, $options); } else { $model->addRule($property, function () use($model, $validator, $options) { return call_user_func([$validator['class'], $validator['method']], $model, $options); }); } } } }
public function run() { $data = ['name', 'email', 'text']; $model_feedback = new DynamicModel($data); $model_feedback->addRule('name', 'required'); $model_feedback->addRule('email', 'required'); $model_feedback->addRule('text', 'required'); $model_feedback->addRule('email', 'email'); if (Yii::$app->request->isPost) { if ($model_feedback->load(Yii::$app->request->post()) && $model_feedback->validate()) { Yii::$app->common->sendMail('Subject Advert', $model_feedback->text); } } $current_user = ['email' => '', 'username' => '']; if (!Yii::$app->user->isGuest) { $current_user['email'] = Yii::$app->user->identity->email; $current_user['username'] = Yii::$app->user->identity->username; } return $this->render('feedback', [ 'model_feedback' => $model_feedback, 'current_user' => $current_user ]); }
public function actionData($file = false) { \Yii::$app->response->format = Response::FORMAT_JSON; if (\Yii::$app->request->isPost) { /**@var Module $module */ $module = Module::getInstance(); $model = new DynamicModel(['file' => null]); $model->addRule('file', 'file', ['extensions' => $module->expansions, 'maxSize' => $module->maxSize]); $model->file = UploadedFile::getInstanceByName('image'); if ($model->validate()) { if (!is_dir(\Yii::getAlias($module->uploadDir))) { FileHelper::createDirectory(\Yii::getAlias($module->uploadDir)); } $oldFileName = $model->file->name; $newFileName = $module->isFileNameUnique ? uniqid() . '.' . $model->file->extension : $oldFileName; $newFullFileName = \Yii::getAlias($module->uploadDir) . DIRECTORY_SEPARATOR . $newFileName; if ($model->file->saveAs($newFullFileName)) { return ['id' => $oldFileName, 'url' => \Yii::$app->request->getHostInfo() . str_replace('@webroot', '', $module->uploadDir) . '/' . $newFileName]; } } else { \Yii::$app->response->statusCode = 500; return $model->getFirstError('file'); } } elseif (\Yii::$app->request->isDelete && $file) { return true; } throw new BadRequestHttpException(); }
/** * * @return type * @throws BadRequestHttpException */ public function run() { if (Yii::$app->request->isPost) { if (!empty($this->getParamName) && Yii::$app->getRequest()->get($this->getParamName)) { $this->paramName = Yii::$app->getRequest()->get($this->getParamName); } $file = UploadedFile::getInstanceByName($this->paramName); $model = new DynamicModel(compact('file')); $model->addRule('file', $this->_validator, $this->validatorOptions); if ($model->validate()) { if ($this->unique === true) { $model->file->name = uniqid() . (empty($model->file->extension) ? '' : '.' . $model->file->extension); } $result = $model->file->saveAs($this->path . $model->file->name) ? ['key' => $model->file->name, 'caption' => $model->file->name, 'name' => $model->file->name] : ['error' => 'Can\'t upload file']; } else { $result = ['error' => $model->getErrors()]; } if (Yii::$app->getRequest()->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; } return $result; } else { throw new BadRequestHttpException('Only POST is allowed'); } }
/** * Updates an existing AuthRule model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $dynamicModel = new DynamicModel(['ruleNamespace']); $dynamicModel->addRule(['ruleNamespace'], function ($attribute, $params) use($dynamicModel) { $this->validateClass($dynamicModel, $attribute, ['extends' => \yii\rbac\Rule::className()]); }); $dynamicModel->addRule(['ruleNamespace'], 'required'); if ($model->data && ($ruleNamespace = unserialize($model->data)) !== false) { if (method_exists($ruleNamespace, 'className')) { $dynamicModel->ruleNamespace = $ruleNamespace::className(); } } $post = Yii::$app->request->post(); if ($model->load($post) && $dynamicModel->load($post)) { if ($model->validate() && $dynamicModel->validate()) { $ruleModel = new $dynamicModel->ruleNamespace(); $time = time(); $ruleModel->createdAt = $time; $ruleModel->updatedAt = $time; $model->data = serialize($ruleModel); if ($model->save(false)) { Yii::$app->getSession()->setFlash('success', Adm::t('', 'Data successfully changed!')); return Adm::redirect(['update', 'id' => $model->name]); } } } return $this->render('update', ['model' => $model, 'dynamicModel' => $dynamicModel]); }
public function actionVerify() { $session = Yii::$app->session; $urlKey = $this->filter->buildKey('_url'); $urls = $session->get($urlKey); if (is_array($urls) && isset($urls[0], $urls[1])) { $route = $urls[0]; $returnUrl = $urls[1]; } else { throw new \yii\base\InvalidCallException(); } $key = $this->filter->buildKey($route); $field = 'f' . substr($key, 0, 10); $model = new DynamicModel([$field]); $model->addRule($field, 'required'); if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) { if ($this->filter->isValid($model->{$field}, $route)) { $this->filter->setValid($route); return Yii::$app->getResponse()->redirect($returnUrl); } else { $model->addError($field, $this->filter->message); } } return $this->render($this->viewFile, ['model' => $model, 'field' => $field]); }
public function actionStock() { $debug = ''; $model = new DynamicModel(['vins', 'diller']); $model->addRule('vins', 'string')->addRule('diller', 'integer')->addRule(['diller', 'vins'], 'required'); $list = ArrayHelper::map(Mod\cats\Stock::find()->all(), 'id', 'name'); $prompt = Yii::t('app', 'Select stock'); $arrError = []; if ($model->load(Yii::$app->request->post()) && $model->validate()) { $arrvin = explode("\n", $model->vins); foreach ($arrvin as $vin) { if ($car = Mod\Car::findOne(['vin' => trim($vin)])) { $status = Mod\CarStatus::findOne(['car_id' => $car->id]); $status->stock_id = $model->diller; $status->save(); } else { $arrError[] = $vin . ' не найден VIN'; } } // $debug = print_r($arrError, true); $debug = implode('<br>', $arrError); return $this->render('finish', ['debug' => $debug]); } $arrVars = ['model' => $model, 'list' => $list, 'prompt' => $prompt, 'selLabel' => 'Склад', 'title' => 'Пакетное перемещение']; return $this->render('index', $arrVars); }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $width = $request->post('width', $this->width); $height = $request->post('height', $this->height); $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($width, $height)); if ($image->save($this->path . $model->{$this->uploadParam}->name)) { $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST')); } }
/** * ACTION INDEX */ public function actionIndex() { /* variable content View Employe Author: -ptr.nov- // $searchModel_Dept = new DeptSearch(); //$dataProvider_Dept = $searchModel_Dept->search(Yii::$app->request->queryParams); Yii::$app->Mailer->compose() ->setFrom('*****@*****.**') ->setTo('*****@*****.**') ->setSubject('Message subject') ->setTextBody('Plain text content') //->setHtmlBody('<b>HTML content</b>') ->send(); //return $this->render('index'); */ $form = ActiveForm::begin(); $model = new DynamicModel(['TextBody', 'Subject']); $model->addRule(['TextBody', 'Subject'], 'required'); $ok = 'Test LG ERP FROM HOME .... GOOD NIGHT ALL, SEE U LATER '; $form->field($model, 'Subject')->textInput(); ActiveForm::end(); Yii::$app->mailer->compose()->setFrom(['*****@*****.**' => 'LG-ERP-POSTMAN'])->setTo('*****@*****.**')->setSubject('daily test email')->setTextBody($ok)->send(); /* \Yii::$app->mailer->compose() ->setFrom('*****@*****.**') ->setTo('*****@*****.**') ->setSubject('test subject') ->send(); */ }
/** * @inheritdoc */ public function run() { $result = ['err' => 1, 'msg' => 'swfupload init']; if (Yii::$app->request->isPost) { $data = Yii::$app->request->get('data'); $data = Json::decode(base64_decode($data)); $url = $data['url']; $path = $data['path']; $params = $data['params']; $callback = $data['callback']; $file = UploadedFile::getInstanceByName('FileData'); $model = new DynamicModel(compact('file')); $model->addRule('file', 'image', [])->validate(); if ($model->hasErrors()) { $result['msg'] = $model->getFirstError('file'); } else { if ($model->file->extension) { $model->file->name = uniqid() . '.' . $model->file->extension; } if ($model->file->saveAs($path . $model->file->name)) { $result['err'] = 0; $result['msg'] = 'success'; $result['url'] = $model->file->name; $result['params'] = $params; $result['callback'] = $callback; } else { $result['msg'] = $model->getFirstError('file save error!'); } } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; }
public function testBeginHasErrorAndRequired() { $this->helperModel->addError($this->attributeName, "Error Message"); $this->helperModel->addRule($this->attributeName, 'required'); $expectedValue = '<div class="form-group field-dynamicmodel-attributename required has-error">'; $actualValue = $this->activeField->begin(); $this->assertEquals($expectedValue, $actualValue); }
/** * @param ConfigurableInterface $component * @return DynamicModel */ public function getComponentConfigModel($component) { $editableAttributes = $component->getEditableAttributes(); $model = new DynamicModel(array_keys($editableAttributes)); $model->addRule(array_keys($editableAttributes), 'safe'); foreach ($editableAttributes as $attribute => $settings) { if (isset($settings['rules'])) { foreach ($settings['rules'] as $rule) { if (!is_array($rule)) { $rule = [$rule]; } $model->addRule($attribute, array_shift($rule), $rule); } } } return $model; }
/** * Save photo * * @param \app\models\UserProfile $profile * @param string $photo * @return void */ private function savePhoto($profile, $photo) { $file = $this->makeUploadedFile($photo); $model = new DynamicModel(compact('file')); $model->addRule('file', 'image', $profile->fileRules('photo', true))->validate(); if (!$model->hasErrors()) { $profile->createFile('photo', $file->tempName, $model->file->name); } }
private function buildModel($fb, $data) { $model = new DynamicModel(); for ($i = 0; $i < count($fb->fieldName); $i++) { $name = 'f' . $i; $model->defineAttribute($name, $data[$name]); if ($fb->fieldRequired[$i]) { $model->addRule($name, 'required', ['message' => 'Необходимо заполнить поле "' . $fb->fieldName[$i] . '"']); } else { $model->addRule($name, 'safe'); } } if ($fb->useCaptcha) { $model->defineAttribute('captcha', $data['captcha']); $model->addRule('captcha', 'captcha'); } return $model; }
/** * 上传示例 * * @return string */ public function actionUpload() { $model = new DynamicModel(['image' => '']); // 动态添加验证规则! $model->addRule(['image'], 'file', ['extensions' => 'jpeg,jpg, gif, png']); // $model->addRule(['image',], 'required', ['message' => '亲 上传一个文件呢?',]); // post 请求才可能上传文件 if (Yii::$app->request->getIsPost()) { if ($model->validate()) { // 验证通过了 在上传 /* * 参考官方的解决方案 * @see http://flysystem.thephpleague.com/recipes/ * $file = UploadedFile::getInstanceByName($uploadname); if ($file->error === UPLOAD_ERR_OK) { $stream = fopen($file->tempName, 'r+'); $filesystem->writeStream('uploads/'.$file->name, $stream); fclose($stream); } */ $file = UploadedFile::getInstance($model, 'image'); if ($file->error === UPLOAD_ERR_OK) { $stream = fopen($file->tempName, 'r+'); $fileName = 'files/' . time() . $file->name; Yii::$app->fs->writeStream($fileName, $stream); fclose($stream); $result = ''; // 是否上传成功? if (Yii::$app->fs->has($fileName)) { /** * $file = file_get_contents('d:/a.jpg'); * header('Content-type: image/jpeg'); * echo $file; */ // 图片文件的内容嵌入到img 中: http://stackoverflow.com/search?q=html+image+data+base64 // @see http://stackoverflow.com/questions/1124149/is-embedding-background-image-data-into-css-as-base64-good-or-bad-practice // TODO 这里文件的mime 可以用它文件系统组件来探测! $img = Html::img('data:image/gif;base64,' . base64_encode(Yii::$app->fs->read($fileName)), ['width' => '300px']); // 删除掉所上传的文件 // 轻轻的我走了正如我轻轻的来 挥一挥手 不留下一点垃圾! Yii::$app->fs->delete($fileName); $result = '上传的图片: ' . $img . '<br/>上传成功 文件已被删除了'; } else { $result = '上传失败 '; } $result .= '<br/> ' . Html::a('重新上传', [''], []); // 演示renderContent方法 return $this->renderContent($result); } } } return $this->render('upload', ['model' => $model]); }
public function actionLanguage() { $model = new DynamicModel(['language']); $model->addRule(['language'], 'required'); $model->setAttributes(['language' => Yii::$app->session->get('language', 'en')]); if ($model->load(Yii::$app->request->post()) && $model->validate()) { Yii::$app->session->set('language', $model->language); return $this->redirect(['db-config']); } return $this->render('language', ['languages' => InstallerHelper::getLanguagesArray(), 'model' => $model]); }
public function testValidateWithAddRule() { $email = 'invalid'; $name = 'long name'; $age = ''; $model = new DynamicModel(compact('name', 'email', 'age')); $model->addRule(['email', 'name', 'age'], 'required')->addRule('email', 'email')->addRule('name', 'string', ['max' => 3])->validate(); $this->assertTrue($model->hasErrors()); $this->assertTrue($model->hasErrors('email')); $this->assertTrue($model->hasErrors('name')); $this->assertTrue($model->hasErrors('age')); }
public function run() { $file = UploadedFile::getInstanceByName($this->inputName); if (!$file) { return $this->response(['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]); } $model = new DynamicModel(compact('file')); $model->addRule('file', $this->type, $this->rules)->validate(); if ($model->hasErrors()) { return $this->response(['error' => $model->getFirstError('file')]); } else { return $this->upload($file); } }
/** * Register new theme. * Theme zip uploaded to temporary directory and extracted there. * Check the theme directory and move the first directory of the extracted theme. * If registration is successful, the browser will be redirected to the 'index' page. * * @return string */ public function actionUpload() { $errors = []; $model = new DynamicModel(['file']); $model->addRule(['file'], 'required')->addRule(['file'], 'file', ['extensions' => 'zip']); if (!is_dir($this->_dir)) { FileHelper::createDirectory($this->_dir, 0755); } if (!is_dir($this->_tmp)) { FileHelper::createDirectory($this->_tmp, 0755); } if (!is_dir($this->_thumbDir)) { FileHelper::createDirectory($this->_thumbDir, 0755); } if (($model->file = UploadedFile::getInstance($model, 'file')) && $model->validate()) { $themeTempPath = $this->_tmp . $model->file->name; if (!$model->file->saveAs($themeTempPath)) { return $this->render('upload', ['model' => $model, 'errors' => [Yii::t('writesdown', 'Failed to move uploaded file')]]); } $zipArchive = new \ZipArchive(); $zipArchive->open($themeTempPath); if (!$zipArchive->extractTo($this->_tmp)) { $zipArchive->close(); FileHelper::removeDirectory($this->_tmp); return $this->render('upload', ['model' => $model, 'errors' => [Yii::t('writesdown', 'Failed to extract file.')]]); } $baseDir = substr($zipArchive->getNameIndex(0), 0, strpos($zipArchive->getNameIndex(0), '/')); $zipArchive->close(); if (is_dir($this->_dir . $baseDir)) { FileHelper::removeDirectory($this->_tmp); $errors[] = Yii::t('writesdown', 'Theme with the same directory already exist.'); } else { rename($this->_tmp . $baseDir, $this->_dir . $baseDir); FileHelper::removeDirectory($this->_tmp); if (is_file($this->_dir . $baseDir . '/screenshot.png')) { copy($this->_dir . $baseDir . '/screenshot.png', $this->_thumbDir . $baseDir . '.png'); } foreach (ArrayHelper::getValue($this->getConfig($baseDir), 'upload', []) as $type) { try { Yii::createObject($type); } catch (Exception $e) { } } Yii::$app->getSession()->setFlash('success', Yii::t('writesdown', 'Theme successfully uploaded')); return $this->redirect(['index']); } } return $this->render('upload', ['model' => $model, 'errors' => $errors]); }
/** * Lists all Setting models. * @return mixed */ public function actionIndex() { $tabs = (new Query())->select('group')->from('{{%core_setting}}')->orderBy('key_order')->distinct()->column(); $attributes = (new Query())->select('key')->from('{{%core_setting}}')->orderBy('key_order')->column(); //var_dump($tabs); $model = new DynamicModel($attributes); $settings = []; foreach ($attributes as $attribute) { $setting = Setting::find()->where(['key' => $attribute])->asArray()->one(); $settings[$setting['group']][$attribute] = $setting; $model->{$attribute} = $setting['value']; //$model->la if (!empty($rules = json_decode($setting['rules'], true))) { foreach ($rules as $rule => $conf) { //var_dump($conf); $model->addRule($attribute, $rule, $conf); } } else { $model->addRule($attribute, 'required'); } } if ($model->load(Yii::$app->request->post()) && $model->validate()) { foreach ($attributes as $attribute) { $s = Setting::findOne($attribute); $s->value = $model->{$attribute}; if ($s->save(false)) { Yii::$app->session->setFlash('success', Yii::t('app', 'Settings saved successfully.')); } else { Yii::$app->session->setFlash('error', Yii::t('app', 'Sorry, something went wrong. {ERRORS}.', ['ERRORS' => json_encode($s->errors)])); break; } } return $this->redirect(['index']); } return $this->render('index', ['model' => $model, 'settings' => $settings, 'tabs' => $tabs]); }
/** * Lists all Post models. * @return mixed */ public function actionIndex() { $postSearchForm = new DynamicModel(['search']); $postSearchForm->addRule('search', 'string', ['length' => [3, 255], 'tooShort' => 'Поиск должен содержать минимум 3 символа.']); $query = Post::find()->distinct()->joinWith('categories')->where(['post.status' => 1])->orderBy('created DESC'); $request = Yii::$app->request; $query->filterWhere(['category_id' => $request->getQueryParam('category')]); if ($postSearchForm->load($request->queryParams, '') && $postSearchForm->validate()) { $query->andFilterWhere(['OR', ['LIKE', 'title', $request->getQueryParam('search')], ['LIKE', 'anotation', $request->getQueryParam('search')], ['LIKE', 'text', $request->getQueryParam('search')]]); } $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => 3]); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('index', ['models' => $models, 'pages' => $pages, 'postSearchForm' => $postSearchForm]); }
public function actionIndex() { $dataProvider = new ActiveDataProvider(['query' => Job::find(), 'pagination' => ['pageSize' => 1]]); $model = new DynamicModel(['search_keyword', 'search_location', 'search_type']); $model->addRule('search_type', 'integer')->addRule('search_location', 'string', ['max' => 128])->addRule('search_keyword', 'string', ['max' => 128]); if ($model->load(Yii::$app->request->post())) { switch ($model->search_type) { case Lookup::item_code('SearchType', 'Organizations'): return $this->redirect(['organization/index', 'search_keyword' => $model->search_keyword]); break; case Lookup::item_code('SearchType', 'Opportunities'): return $this->redirect(['job/index', 'search_keyword' => $model->search_keyword]); break; default: throw new NotFoundHttpException('Your search:' . $model->search_keyword); break; } } return $this->render('index', ['model' => $model, 'dataProvider' => $dataProvider]); }
/** * Redactor upload action. * * @param string $name Model name * @param string $attr Model attribute * @param string $type Format type * @return array List of files * @throws BadRequestHttpException * @throws InvalidConfigException */ public function actionRedactorUpload($name, $attr, $type = 'image') { /** @var $module \vladdnepr\ycm\Module */ $module = $this->module; $name = (string) $name; $attribute = (string) $attr; $uploadType = 'image'; $validatorOptions = $module->redactorImageUploadOptions; if ((string) $type == 'file') { $uploadType = 'file'; $validatorOptions = $module->redactorFileUploadOptions; } $attributePath = $module->getAttributePath($name, $attribute); if (!is_dir($attributePath)) { if (!FileHelper::createDirectory($attributePath, $module->uploadPermissions)) { throw new InvalidConfigException('Could not create folder "' . $attributePath . '". Make sure "uploads" folder is writable.'); } } $file = UploadedFile::getInstanceByName('file'); $model = new DynamicModel(compact('file')); $model->addRule('file', $uploadType, $validatorOptions)->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError('file')]; } else { if ($model->file->extension) { $model->file->name = md5($attribute . time() . uniqid(rand(), true)) . '.' . $model->file->extension; } $path = $attributePath . DIRECTORY_SEPARATOR . $model->file->name; if ($model->file->saveAs($path)) { $result = ['filelink' => $module->getAttributeUrl($name, $attribute, $model->file->name)]; if ($uploadType == 'file') { $result['filename'] = $model->file->name; } } else { $result = ['error' => Yii::t('ycm', 'Could not upload file.')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; }
public function run() { $file = UploadedFile::getInstanceByName($this->inputName); if (!$file) { return $this->response(['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]); } $rules = $this->model->fileRules($this->attribute, true); $type = $this->model->fileOption($this->attribute, 'type', 'image'); $model = new DynamicModel(compact('file')); $maxFiles = ArrayHelper::getValue($rules, 'maxFiles'); if ($maxFiles !== null && $maxFiles > 1) { $model->file = [$model->file]; } $model->addRule('file', $type, $rules)->validate(); if ($model->hasErrors()) { return $this->response(['error' => $model->getFirstError('file')]); } if (is_array($model->file)) { $model->file = $model->file[0]; } return $this->save($model->file); }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->paramName); $model = new DynamicModel(compact('file')); $model->addRule('file', $this->_validator, $this->validatorOptions)->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError('file')]; } else { if ($this->unique === true && $model->file->extension) { $model->file->name = uniqid() . '.' . $model->file->extension; } if ($model->file->saveAs($this->path . $model->file->name)) { $result = ['name' => $model->file->name]; } else { $result = ['error' => Widget::t('fileapi', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException('Only POST is allowed'); } }
/** * Upload new theme to the site * * @return string */ public function actionUpload() { $model = new DynamicModel(['theme']); $model->addRule(['theme'], 'required')->addRule(['theme'], 'file', ['extensions' => 'zip']); // Create temporary directory if (!is_dir($this->_themeTempDir)) { FileHelper::createDirectory($this->_themeTempDir, 0755); } // Create theme directory if (!is_dir($this->_themeDir)) { FileHelper::createDirectory($this->_themeDir, 0755); } // Create thumbnail directory if (!is_dir($this->_thumbDir)) { FileHelper::createDirectory($this->_thumbDir, 0755); } if (Yii::$app->request->isPost) { $model->theme = UploadedFile::getInstance($model, 'theme'); if ($model->validate()) { // Theme temporary path $themeTempPath = $this->_themeTempDir . $model->theme->name; // Move theme (zip) to temporary directory if ($model->theme->saveAs($themeTempPath)) { $zipArchive = new \ZipArchive(); $zipArchive->open($themeTempPath); if ($zipArchive->extractTo($this->_themeTempDir)) { $baseDir = substr($zipArchive->getNameIndex(0), 0, strpos($zipArchive->getNameIndex(0), '/')); $zipArchive->close(); unlink($themeTempPath); // Check theme exist in theme directory if (is_dir($this->_themeDir . $baseDir)) { FileHelper::removeDirectory($this->_themeTempDir); Yii::$app->getSession()->setFlash('danger', Yii::t('writesdown', 'Theme with the same directory already exist.')); } else { rename($this->_themeTempDir . $baseDir, $this->_themeDir . $baseDir); if (is_file($this->_themeDir . $baseDir . '/screenshot.png')) { copy($this->_themeDir . $baseDir . '/screenshot.png', $this->_thumbDir . $baseDir . '.png'); } FileHelper::removeDirectory($this->_themeTempDir); Yii::$app->getSession()->setFlash('success', Yii::t('writesdown', 'Theme successfully uploaded')); return $this->redirect(['index']); } } } } } return $this->render('upload', ['model' => $model]); }
public function actionChangeBranch() { $model = new DynamicModel(['selected' => Yii::$app->user->branch]); $model->addRule('selected', 'safe'); $ids = UserToBranch::find()->select('id_branch')->where(['id_user' => Yii::$app->user->id])->column(); $branchs = Branch::findAll(['id_branch' => $ids]); if ($model->load(Yii::$app->request->post())) { Yii::$app->user->branch = $model->selected; } return $this->render('change-branch', ['model' => $model, 'branchs' => $branchs]); }
public function actionViewAdvert($id) { $model = Advert::findOne($id); $data = ['name', 'email', 'text']; $model_feedback = new DynamicModel($data); $model_feedback->addRule('name', 'required'); $model_feedback->addRule('email', 'required'); $model_feedback->addRule('text', 'required'); $model_feedback->addRule('email', 'email'); if (\Yii::$app->request->isPost) { if ($model_feedback->load(\Yii::$app->request->post()) && $model_feedback->validate()) { \Yii::$app->common->sendMail('Subject Advert', $model_feedback->text); } } $user = $model->user; $images = Common::getImageAdvert($model, false); $current_user = ['email' => '', 'username' => '']; if (!\Yii::$app->user->isGuest) { $current_user['email'] = \Yii::$app->user->identity->email; $current_user['username'] = \Yii::$app->user->identity->username; } return $this->render('view_advert', ['model' => $model, 'model_feedback' => $model_feedback, 'user' => $user, 'images' => $images, 'current_user' => $current_user]); }