Пример #1
1
 public function run()
 {
     $request = Yii::$app->request;
     $user = Yii::createObject($this->modelClass, ['scenario' => $this->scenario]);
     $profile = Yii::createObject($this->profileClass);
     $roles = [];
     if ($this->roleArray !== null) {
         $roles = call_user_func($this->roleArray, $this);
     }
     $roleArray = ArrayHelper::map($roles, 'name', 'description');
     $statusArray = [];
     if ($this->statusArray !== null) {
         $statusArray = call_user_func($this->statusArray, $this);
     }
     if ($user->load($request->post()) && $profile->load($request->post())) {
         if ($user->validate() && $profile->validate()) {
             $user->populateRelation('profile', $profile);
             if ($user->save(false)) {
                 $this->trigger('success', new Event(['data' => $user]));
                 return $this->controller->redirect(Url::to([$this->updateRoute, 'id' => $user->id]));
             } else {
                 $this->trigger('success', new Event(['data' => Module::t('admin', 'Failed create user')]));
                 return $this->controller->refresh();
             }
         } elseif ($request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return array_merge(ActiveForm::validate($user), ActiveForm::validate($profile));
         }
     }
     return $this->render(compact(['user', 'profile', 'roleArray', 'statusArray']));
 }
Пример #2
0
 public function actionUpload_product()
 {
     if (Yii::$app->request->isAjax) {
         $model = new ProductCategory();
         $Product = new Product();
         $ProductImageRel = new ProductImageRel();
         $ProductCategoryRel = new ProductCategoryRel();
         $model_cat_title = UploadedFile::getInstance($model, 'cat_title');
         $time = time();
         $model_cat_title->saveAs('product_uploads/' . $time . $model_cat_title->baseName . '.' . $model_cat_title->extension);
         if ($model_cat_title) {
             $response = [];
             $Product->title = $_POST['title'];
             $Product->desc = $_POST['desc'];
             $Product->status = 1;
             if ($Product->save()) {
                 $ProductCategoryRel->category_id = $_POST['id'];
                 $ProductCategoryRel->product_id = $Product->id;
                 $ProductImageRel->product_id = $Product->id;
                 $ProductImageRel->image = $time . $model_cat_title->baseName . '.' . $model_cat_title->extension;
                 if ($ProductCategoryRel->save() && $ProductImageRel->save()) {
                     $response['files'][] = ['name' => $time . $model_cat_title->name, 'type' => $model_cat_title->type, 'size' => $model_cat_title->size, 'url' => Url::base() . '/product_uploads/' . $time . $model_cat_title->baseName . '.' . $model_cat_title->extension, 'deleteUrl' => Url::to(['delete_uploaded_file', 'file' => $model_cat_title->baseName . '.' . $model_cat_title->extension]), 'deleteType' => 'DELETE'];
                     $response['base'] = $time . $model_cat_title->baseName;
                     $response['view'] = $this->renderAjax('uploaded_product', ['url' => Url::base() . '/product_uploads/' . $time . $model_cat_title->baseName . '.' . $model_cat_title->extension, 'basename' => $time . $model_cat_title->baseName, 'id' => $ProductImageRel->id, 'model' => $Product]);
                 }
             } else {
                 $response['errors'] = $product->getErrors();
             }
             return json_encode($response);
         }
     }
 }
Пример #3
0
 public function actionRss()
 {
     /** @var News[] $news */
     $news = News::find()->where(['status' => News::STATUS_PUBLIC])->orderBy('id DESC')->limit(50)->all();
     $feed = new Feed();
     $feed->title = 'YiiFeed';
     $feed->link = Url::to('');
     $feed->selfLink = Url::to(['news/rss'], true);
     $feed->description = 'Yii news';
     $feed->language = 'en';
     $feed->setWebMaster('*****@*****.**', 'Alexander Makarov');
     $feed->setManagingEditor('*****@*****.**', 'Alexander Makarov');
     foreach ($news as $post) {
         $item = new Item();
         $item->title = $post->title;
         $item->link = Url::to(['news/view', 'id' => $post->id], true);
         $item->guid = Url::to(['news/view', 'id' => $post->id], true);
         $item->description = HtmlPurifier::process(Markdown::process($post->text));
         if (!empty($post->link)) {
             $item->description .= Html::a(Html::encode($post->link), $post->link);
         }
         $item->pubDate = $post->created_at;
         $item->setAuthor('*****@*****.**', 'YiiFeed');
         $feed->addItem($item);
     }
     $feed->render();
 }
Пример #4
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     // set titles
     $this->setCreateTitle(Yii::t('kalibao', 'create_title'));
     $this->setUpdateTitle(Yii::t('kalibao', 'update_title'));
     // models
     $models = $this->getModels();
     // language
     $language = $this->getLanguage();
     // get drop down list methods
     $dropDownList = $this->getDropDownList();
     // upload config
     $uploadConfig['main'] = $this->uploadConfig[(new \ReflectionClass($models['main']))->getName()];
     // set items
     $items = [];
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'id', 'value' => $models['main']->id]);
     }
     $items[] = new InputField(['model' => $models['main'], 'attribute' => 'file', 'type' => 'activeFileInput', 'options' => ['maxlength' => true, 'class' => 'input-advanced-uploader', 'placeholder' => $models['main']->getAttributeLabel('file'), 'data-type-uploader' => $uploadConfig['main']['file']['type'], 'data-file-url' => $models['main']->file != '' ? $uploadConfig['main']['file']['baseUrl'] . '/' . $models['main']->file : '']]);
     $items[] = new InputField(['model' => $models['main'], 'attribute' => 'media_type_id', 'type' => 'activeHiddenInput', 'options' => ['class' => 'form-control input-sm input-ajax-select', 'data-action' => Url::to(['advanced-drop-down-list', 'id' => 'media_type_i18n.title']), 'data-allow-clear' => 1, 'data-placeholder' => Yii::t('kalibao', 'input_select'), 'data-text' => !empty($models['main']->media_type_id) ? MediaTypeI18n::findOne(['media_type_id' => $models['main']->media_type_id, 'i18n_id' => $language])->title : '']]);
     $items[] = new InputField(['model' => $models['i18n'], 'attribute' => 'title', 'type' => 'activeTextInput', 'options' => ['class' => 'form-control input-sm', 'maxlength' => true, 'placeholder' => $models['i18n']->getAttributeLabel('title')]]);
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'created_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->created_at, I18N::getDateFormat())]);
     }
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'updated_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->updated_at, I18N::getDateFormat())]);
     }
     $this->setItems($items);
 }
 public function actionAdd()
 {
     $requestId = yii::$app->request->get('id');
     $id = isset($requestId) ? (int) $requestId : 0;
     $item = $this->GetModel()->GetItem($id);
     if (yii::$app->request->isPost) {
         $pathInfo = Yii::$app->request->pathInfo;
         $fields = Yii::$app->request->post();
         if (isset($fields["main"]["id"])) {
             $id = $fields["main"]["id"];
         } else {
             $id = Yii::$app->request->get('id') ? (int) Yii::$app->request->get('id') : 0;
         }
         $model = $this->GetModel();
         $model->attributes = $fields["main"];
         if ($model->validate()) {
             $insert_id = $model->Add($id, $fields["main"]);
             $this->redirect(Url::to(["/{$pathInfo}", "id" => $insert_id]));
         } else {
             $errors = $model->errors;
             app::PrintPre($errors);
         }
     }
     $interace = $this->MakeInterface($item);
     $this->headerPage = "Новый тип страницы";
     return $this->render('add', ["interface" => $interace, "id" => $id]);
 }
Пример #6
0
 public function init()
 {
     $url = is_array($this->route) ? Url::to($this->route) : Url::to([$this->route, 'term' => 'QUERY']);
     $this->dataset = [['remote' => ['url' => $url, 'wildcard' => 'QUERY'], 'templates' => ['empty' => Html::tag('span', Yii::t('app', 'Hit enter to search'), ['class' => 'empty-search']), 'suggestion' => new JsExpression("Handlebars.compile('{$this->template}')")]]];
     $this->pluginOptions = ['hint' => false];
     parent::init();
 }
Пример #7
0
    public function run()
    {
        //Если данные по доставке закешированы просто рисуем их иначе делаем ajax запрос, чтобы заполнился кеш
        if (\Yii::$app->v3toysSettings->isCurrentShippingCache) {
            return $this->render($this->viewFile);
        } else {
            $js = \yii\helpers\Json::encode(['backend' => \yii\helpers\Url::to('/v3toys/cart/get-current-shipping')]);
            $this->view->registerJs(<<<JS
    (function(sx, \$, _)
    {
        sx.classes.GetShipping = sx.classes.Component.extend({

            _onDomReady: function()
            {
                var self = this;

                _.delay(function()
                {
                    sx.ajax.preparePostQuery(self.get('backend')).execute();
                }, 500);
            }
        });

        new sx.classes.GetShipping({$js});

    })(sx, sx.\$, sx._);
JS
);
        }
    }
 public function up()
 {
     mb_internal_encoding("UTF-8");
     $tableOptions = $this->db->driverName === 'mysql' ? 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB' : null;
     $this->createTable('{{%wysiwyg}}', ['id' => Schema::primaryKey(), 'name' => Schema::string()->notNull(), 'class_name' => Schema::string()->notNull(), 'params' => Schema::text(), 'configuration_model' => Schema::string()], $tableOptions);
     $this->insert('{{%wysiwyg}}', ['name' => 'Imperavi', 'class_name' => 'vova07\\imperavi\\Widget', 'params' => Json::encode(['settings' => ['replaceDivs' => false, 'minHeight' => 200, 'paragraphize' => false, 'pastePlainText' => true, 'buttonSource' => true, 'imageManagerJson' => Url::to(['/backend/dashboard/imperavi-images-get']), 'plugins' => ['table', 'fontsize', 'fontfamily', 'fontcolor', 'video', 'imagemanager'], 'replaceStyles' => [], 'replaceTags' => [], 'deniedTags' => [], 'removeEmpty' => [], 'imageUpload' => Url::to(['/backend/dashboard/imperavi-image-upload'])]]), 'configuration_model' => 'app\\modules\\core\\models\\WysiwygConfiguration\\Imperavi']);
 }
Пример #9
0
 /**
  * 上传商品图片
  */
 public function actionProductpic()
 {
     $user_id = \Yii::$app->user->getId();
     $p_params = Yii::$app->request->get();
     $product = Product::findOne($p_params['id']);
     if (!$product) {
         throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
     }
     $picture = new UploadForm();
     $picture->file = UploadedFile::getInstance($product, 'product_s_img');
     if ($picture->file !== null && $picture->validate()) {
         Yii::$app->response->getHeaders()->set('Vary', 'Accept');
         Yii::$app->response->format = Response::FORMAT_JSON;
         $response = [];
         if ($picture->productSave()) {
             $response['files'][] = ['name' => $picture->file->name, 'type' => $picture->file->type, 'size' => $picture->file->size, 'url' => '/' . $picture->getImageUrl(), 'thumbnailUrl' => '/' . $picture->getOImageUrl(), 'deleteUrl' => Url::to(['/uploadfile/deletepropic', 'id' => $picture->getID()]), 'deleteType' => 'POST'];
         } else {
             $response[] = ['error' => Yii::t('app', '上传错误')];
         }
         @unlink($picture->file->tempName);
     } else {
         if ($picture->hasErrors()) {
             $response[] = ['error' => '上传错误'];
         } else {
             throw new HttpException(500, Yii::t('app', '上传错误'));
         }
     }
     return $response;
 }
Пример #10
0
 /**
  * Returns file url for requested size.
  * @param            $path - path to file from DB
  * @param string     $size - image size
  * @param bool|false $absoluteUrl
  * @return string
  */
 public static function makeUrl($path, $size = 'original', $absoluteUrl = false)
 {
     if (preg_match('/^(http:\\/\\/|https:\\/\\/|\\/\\/).*/', $path)) {
         return $path;
     }
     return Url::to(self::normalizePath(self::$uploadDir . $size . $path, '/'), $absoluteUrl);
 }
Пример #11
0
 function run()
 {
     foreach ($this->data as $n => $v) {
         if (isset($this->{$n})) {
             $this->{$n} = $v;
         }
     }
     $this->view->registerCssFile('http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css');
     $link = $this->link;
     if (is_array($link)) {
         $link = Url::to($link);
     }
     if ($this->link_text === null) {
         $this->link_text = \Yii::t('app', 'More info');
     }
     $html = "<!-- small box -->\n";
     $html .= "<div class=\"col-lg-3 col-xs-6\">\n";
     $html .= "  <div class=\"small-box {$this->color}\">\n";
     $html .= "    <div class=\"inner\">";
     $html .= Html::tag('h3', $this->count . Html::tag('sup', $this->count_type, ['style' => "font-size: 20px"]));
     $html .= Html::tag('p', $this->text);
     $html .= "</div>\n";
     $html .= "    <div class=\"icon\">";
     $html .= Html::tag('i', '', ['class' => 'ion ' . $this->icon]);
     $html .= "</div>\n";
     $html .= "    ";
     $html .= Html::a($this->link_text . " <i class=\"fa fa-arrow-circle-right\"></i>", $link, ['class' => 'small-box-footer']);
     $html .= "  </div>";
     $html .= "</div>";
     return $html;
 }
Пример #12
0
 public function actionAdd()
 {
     $id = !empty(yii::$app->request->get('id')) ? yii::$app->request->get('id') : 0;
     $this->titlePage = "Добавление элемента на страницу блог";
     $this->headerPage = "Новый элемент";
     $item = $this->GetModel()->GetItem($id);
     if ($item) {
         $this->titlePage = $item["name"];
         $this->headerPage = "Редактирование элемента - " . $item["name"];
     }
     if (yii::$app->request->isPost) {
         $pathInfo = Yii::$app->request->pathInfo;
         $fields = Yii::$app->request->post();
         if (isset($fields["main"]["id"])) {
             $id = $fields["main"]["id"];
         } else {
             $id = Yii::$app->request->get('id') ? (int) Yii::$app->request->get('id') : 0;
         }
         $model_properties = new ModelProperties();
         $model = $this->GetModel();
         $model->attributes = $fields["main"];
         if ($model->validate()) {
             $insert_id = $model->Add($id, $fields["main"]);
             $model_properties->Add($insert_id, $fields['properties']);
             $this->redirect(Url::to(["/{$pathInfo}", "id" => $insert_id]));
         } else {
             $errors = $model->errors;
             app::PrintPre($errors);
         }
     }
     $interface = $this->MakeInterface($item, 21);
     return $this->render('add', array("interface" => $interface, "data" => $item));
 }
Пример #13
0
 public function actionCreate()
 {
     $productOrder = $this->getModel(Yii::$app->request->post('orderId'));
     $chargeForm = new ChargeForm();
     $chargeForm->order_no = $productOrder->id;
     $chargeForm->amount = $productOrder->payAmount;
     /**
      * @see Channel
      */
     $chargeForm->channel = Channel::ALIPAY_PC_DIRECT;
     $chargeForm->currency = 'cny';
     $chargeForm->client_ip = Yii::$app->getRequest()->userIP;
     $chargeForm->subject = sprintf("为订单ID为#%s的订单付款。", $productOrder->id);
     $chargeForm->body = sprintf('订单总价为 %s, 联系方式为 %s, 联系地址为 %s', $productOrder->total_price, $productOrder->contact, $productOrder->address);
     $chargeForm->extra = ['success_url' => Url::to(['success-sync-callback'], true)];
     if ($response = $chargeForm->create()) {
         $productOrder->out_order_no = $response->order_no;
         $productOrder->charge_id = $response->id;
         if ($productOrder->save()) {
             return $response->__toArray(true);
         }
     } elseif ($chargeForm->hasErrors()) {
         return $chargeForm->getErrors();
     }
     throw new ServerErrorHttpException();
 }
Пример #14
0
 public function actionUpload($model, $primaryKey)
 {
     $results = [];
     $modelImage = new Image();
     $modelImage->model = $model;
     $modelImage->primaryKey = $primaryKey;
     $filePath = $modelImage->getFilePath();
     if (Yii::$app->request->isPost) {
         $modelImage->file = UploadedFile::getInstance($modelImage, 'file');
         if ($modelImage->file && $modelImage->validate()) {
             $filename = $modelImage->file->name;
             $modelImage->src = $filename;
             $modelImage->position = $modelImage->nextPosition;
             $modelImage->save();
             $image = \Yii::$app->image->load($modelImage->file->tempName);
             $image->resize(2592, 1728, \yii\image\drivers\Image::AUTO);
             if ($image->save($filePath . '/' . $filename)) {
                 $imagePath = $filePath . '/' . $filename;
                 $result = ['name' => $filename, 'size' => filesize($filePath . '/' . $filename), 'url' => $imagePath, 'thumbnailUrl' => $modelImage->resize('100x100'), 'deleteUrl' => Url::to(['/core/image/delete', 'id' => $modelImage->id]), 'deleteType' => "DELETE"];
                 $results[] = $result;
             }
         } else {
             $results[] = (object) [$modelImage->file->name => false, 'error' => strip_tags(Html::error($modelImage, 'file')), 'extension' => $modelImage->file->extension, 'type' => $modelImage->file->type];
         }
     }
     echo json_encode((object) ['files' => $results]);
 }
Пример #15
0
 public function actionIndex()
 {
     $admin = Administrator::find()->all();
     $this->var['breadcumb'] = [Url::to(["administrator/manager"]) => "Quản lý cấp quyền quản trị"];
     $this->var['table_name'] = 'Quản lý cấp quyền quản trị';
     return $this->render('auth', ['data' => $admin]);
 }
Пример #16
0
 /**
  * Runs the action.
  */
 public function run()
 {
     // Character type ... defaults to non alphabetical characters
     $session = Yii::$app->session;
     $session->open();
     $name = $this->getSessionKey();
     if ($session[$name . 'type'] !== null && $session[$name . 'type'] === 'abc') {
         $this->useMbChars = false;
     }
     $refresh = Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR);
     $toggle = Yii::$app->request->getQueryParam(self::TOGGLE_GET_VAR);
     if ($refresh !== null || $toggle !== null) {
         if ($toggle !== null) {
             $this->useMbChars = !$this->useMbChars;
         }
         // AJAX request for regenerating code
         $code = $this->getVerifyCode(true);
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ['hash1' => $this->generateValidationHash($code), 'hash2' => $this->generateValidationHash(strtolower($code)), 'url' => Url::to([$this->id, 'v' => uniqid()])];
     } else {
         $this->setHttpHeaders();
         Yii::$app->response->format = Response::FORMAT_RAW;
         return $this->renderImage($this->getVerifyCode());
     }
 }
Пример #17
0
 public function init()
 {
     $this->controllerMap = ['elfinder' => ['class' => 'mihaildev\\elfinder\\Controller', 'access' => ['@'], 'disabledCommands' => ['netmount'], 'roots' => [['baseUrl' => $this->mediaUrl, 'basePath' => $this->mediaPath, 'path' => '', 'name' => 'Global']]]];
     $this->modules = ['settings' => ['class' => 'plathir\\settings\\Module', 'modulename' => 'blog'], 'treemanager' => ['class' => '\\kartik\\tree\\Module', 'treeViewSettings' => ['nodeActions' => [\kartik\tree\Module::NODE_MANAGE => Url::to(['/blog/categorytree/manage']), \kartik\tree\Module::NODE_SAVE => Url::to(['/blog/categorytree/save']), \kartik\tree\Module::NODE_REMOVE => Url::to(['/blog/categorytree/remove']), \kartik\tree\Module::NODE_MOVE => Url::to(['/blog/categorytree/move'])], 'nodeView' => '/categorytree/_form']]];
     parent::init();
     // custom initialization code goes here
 }
Пример #18
0
 /**
  * Returns the options for the ajax form JS widget.
  * @return array the options
  */
 protected function getClientOptions()
 {
     $options = ['resetOnSuccess' => $this->resetOnSuccess, 'requireReset' => $this->requireReset, 'failCallback' => $this->failCallback, 'action' => Url::to($this->action)];
     return array_filter($options, function ($value) {
         return $value !== null;
     });
 }
Пример #19
0
 /**
  * Initializes the widget.
  */
 public function init()
 {
     parent::init();
     if (empty($this->id)) {
         $this->id = $this->hasModel() ? Html::getInputId($this->model, $this->attribute) : $this->getId();
     }
     if (empty($this->name)) {
         $this->name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->id;
     }
     if (empty($this->value) && $this->hasModel() && $this->model->hasAttribute($this->attribute)) {
         $this->value = $this->model->getAttribute($this->attribute);
     }
     if (!$this->autoHeightEnable) {
         if (empty($this->width)) {
             $this->width = '100%';
         }
         if (empty($this->height)) {
             $this->height = '350';
         }
     }
     $options = ['id' => $this->id, 'style' => 'width:100%;height:350px'];
     $this->options = array_merge($options, $this->options);
     $jsOptions = ['serverUrl' => Url::to(['ueditor', 'type' => 'ueditor']), 'autoHeightEnable' => $this->autoHeightEnable, 'autoFloatEnable' => true, 'textarea' => $this->name];
     $this->jsOptions = array_merge($jsOptions, $this->jsOptions);
 }
Пример #20
0
 /**
  * @param $fileName
  * @return string
  */
 public function getUrl($fileName)
 {
     if (!$this->webAccessUrl) {
         throw new InvalidConfigException('Invalid config $webAccessUrl. Web access is disabled.');
     }
     return Url::to($this->uploadUrl . '/' . $fileName);
 }
Пример #21
0
 /**
  * @return string $template
  * @return mixed
  */
 public function actions($template = '{update} {delete}')
 {
     $this->columns = array_merge($this->columns, [['class' => ActionColumn::className(), 'controller' => SELF::CONTROLLER, 'template' => $template, 'buttons' => ['update' => function ($url, $model, $key) {
         return Html::a('<i class="fa fa-pencil"></i>', false, ['value' => Url::to([SELF::CONTROLLER . '/update', 'id' => $model->id]), 'title' => 'Update', 'class' => 'showModalButton']);
     }], 'contentOptions' => ['class' => 'text-right']]]);
     return $this;
 }
Пример #22
0
 /**
  * Composes client auth URL.
  * @param ClientInterface $provider external auth client instance.
  * @return string auth URL.
  */
 public function createClientUrl($provider)
 {
     $this->autoRender = false;
     $url = $this->getBaseAuthUrl();
     $url[$this->clientIdGetParamName] = $provider->getId();
     return Url::to($url);
 }
Пример #23
0
 public static function Breadcrumbs($params)
 {
     $links = [];
     if (isset($params['marka'])) {
         $url = Url::to('/autocatalogs');
         $links[] = ['label' => 'Автокаталог', 'url' => $url];
     }
     if (isset($params['region'])) {
         $url .= '/' . $params['marka'] . '/' . $params['region'];
         $links[] = ['label' => $params['marka'], 'url' => $url];
     }
     if (isset($params['family'])) {
         $url .= '/' . $params['family'];
         $links[] = ['label' => $params['family'], 'url' => $url];
     }
     if (isset($params['cat_code'])) {
         $url .= '/' . $params['cat_code'] . '/' . base64_encode($params['option']);
         $links[] = ['label' => $params['cat_code'], 'url' => $url];
     }
     if (isset($params['cat_folder'])) {
         $url .= '/' . $params['cat_folder'];
         $links[] = ['label' => $params['cat_folder'], 'url' => $url];
     }
     if (isset($params['sect'])) {
         $url .= '/' . $params['sect'];
         $links[] = ['label' => $params['sect'], 'url' => $url];
     }
     if (isset($params['sub_sect'])) {
         $url .= '/' . $params['sub_sect'];
         $links[] = ['label' => $params['sub_sect'], 'url' => $url];
     }
     return $links;
 }
Пример #24
0
 public function actionIndex()
 {
     $session = Yii::$app->session;
     $user = $session->get('user');
     $examTemplates = ExamTemplate::findByMajorJobAndProvince($user['majorJobId'], $user['provinceId']);
     $totalNumber = count($examTemplates);
     if ($totalNumber == 0) {
         $url = Url::to(['site/test-library-not-found']);
         header("Location:{$url}");
         exit;
     }
     $rand = rand(1, $totalNumber);
     $examTemplate = $examTemplates[$rand - 1];
     $session->set('examTemplate', $examTemplate);
     //存入session,在考试结束后计算分数要用到
     $examTemplateDetails = ExamTemplateDetail::findByExamTemplate($examTemplate['examTemplateId']);
     $examTemplateDetails = ExamTemplateDetail::remakeArray($examTemplateDetails);
     $testLibraries = TestLibrary::findByTemplateDetails($examTemplateDetails, $user);
     $majorJob = MajorJob::findNameByMajorJobId($user['majorJobId']);
     //将一些必要参数存入session,方便后续页面调用
     $session->set('testLibraries', $testLibraries);
     //所有同类型题目
     $session->set('totalNumber', count($testLibraries));
     //总题数
     $session->set('testTitle', "模拟考试");
     //测试标题
     $session->set('majorJob', $majorJob);
     //测试岗位
     return $this->render('index', ['testLibraries' => $testLibraries]);
 }
Пример #25
0
 public function api_get($id_slug)
 {
     if (($text = $this->findText($id_slug)) === null) {
         return $this->notFound($id_slug);
     }
     return LIVE_EDIT ? API::liveEdit($text['text'], Url::to(['/admin/text/a/edit/', 'id' => $text['text_id']])) : $text['text'];
 }
Пример #26
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     // set titles
     $this->setCreateTitle(Yii::t('kalibao.backend', 'variable_variable_create_title'));
     $this->setUpdateTitle(Yii::t('kalibao.backend', 'variable_variable_update_title'));
     // models
     $models = $this->getModels();
     // language
     $language = $this->getLanguage();
     // get drop down list methods
     $dropDownList = $this->getDropDownList();
     // upload config
     $uploadConfig['main'] = $this->uploadConfig[(new \ReflectionClass($models['main']))->getName()];
     // set items
     $items = [];
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'id', 'value' => $models['main']->id]);
     }
     $items[] = new InputField(['model' => $models['main'], 'attribute' => 'variable_group_id', 'type' => 'activeHiddenInput', 'options' => ['class' => 'form-control input-sm input-ajax-select', 'data-action' => Url::to(['advanced-drop-down-list', 'id' => 'variable_group_i18n.title']), 'data-allow-clear' => 1, 'data-placeholder' => Yii::t('kalibao', 'input_select'), 'data-add-action' => Url::to('/variable/variable-group/create'), 'data-update-action' => Url::to('/variable/variable-group/update'), 'data-update-argument' => 'id', 'data-related-field' => '.link_variable_group_title', 'data-text' => !empty($models['main']->variable_group_id) ? VariableGroupI18n::findOne(['variable_group_id' => $models['main']->variable_group_id, 'i18n_id' => $language])->title : '']]);
     $items[] = new InputField(['model' => $models['main'], 'attribute' => 'name', 'type' => 'activeTextInput', 'options' => ['class' => 'form-control input-sm', 'maxlength' => true, 'placeholder' => $models['main']->getAttributeLabel('name')]]);
     $items[] = new InputField(['model' => $models['main'], 'attribute' => 'val', 'type' => 'activeTextInput', 'options' => ['class' => 'form-control input-sm', 'maxlength' => true, 'placeholder' => $models['main']->getAttributeLabel('val')]]);
     $items[] = new InputField(['model' => $models['i18n'], 'attribute' => 'description', 'type' => 'activeTextarea', 'options' => ['class' => 'form-control input-sm', 'data-ckeditor-language' => $language]]);
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'created_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->created_at, I18N::getDateFormat())]);
     }
     if (!$models['main']->isNewRecord) {
         $items[] = new SimpleValueField(['model' => $models['main'], 'attribute' => 'updated_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->updated_at, I18N::getDateFormat())]);
     }
     $this->setItems($items);
 }
Пример #27
0
 /**
  * 
  * @param \yii\authclient\ClientInterface $client
  * @return type
  */
 public function successCallback($client)
 {
     // TODO: Group FK's to one local user.
     //       Otherwise, if we log in via FB and another time via google, we
     //       end up with two local accounts.
     if (!$this->action instanceof \yii\authclient\AuthAction) {
         throw new \yii\base\InvalidCallException("successCallback is only meant to be executed by AuthAction!");
     }
     $attributes = $client->getUserAttributes();
     $externalUser = new AuthForm();
     $externalUser->authProvider = $client->getName();
     $externalUser->externalUserId = array_key_exists('id', $attributes) ? $attributes['id'] : null;
     if ($externalUser->validate()) {
         Yii::info('AuthForm validated.');
         if ($externalUser->isRegistered()) {
             Yii::info('ExternalUser is registered. Logging in and redirecting to game/index.');
             $externalUser->login();
             return $this->action->redirect(Url::to(['site/index'], true));
         } else {
             throw new \yii\base\InvalidCallException("Can't login non-registered user '{$externalUser->externalUserId}@{$externalUser->authProvider}'!");
         }
     } else {
         // TODO error. Throw, display actionError?
         Yii::info('AuthForm couldn\'t be validated. Errors: ' . print_r($externalUser->errors, true));
         Yii::info('Client attributes: ' . print_r($attributes, true));
     }
 }
Пример #28
0
 public function getFullSiteUrl()
 {
     $slug = isset($this->slug) ? $this->slug : $this->name;
     $route = Url::to([$this->tableName() . '/index', 'slug' => $slug]);
     $domain = Url::base(true);
     return $domain . $route;
 }
Пример #29
0
    public function actionApprove()
    {
        $user = User::findOne(['id' => (int) Yii::$app->request->get('id')]);
        if ($user == null) {
            throw new HttpException(404, Yii::t('AdminModule.controllers_ApprovalController', 'User not found!'));
        }
        $model = new ApproveUserForm();
        $model->subject = Yii::t('AdminModule.controllers_ApprovalController', "Account Request for '{displayName}' has been approved.", array('{displayName}' => Html::encode($user->displayName)));
        $model->message = Yii::t('AdminModule.controllers_ApprovalController', 'Hello {displayName},<br><br>

   your account has been activated.<br><br>

   Click here to login:<br>
   <a href=\'{loginURL}\'>{loginURL}</a><br><br>

   Kind Regards<br>
   {AdminName}<br><br>', array('{displayName}' => Html::encode($user->displayName), '{loginURL}' => Url::to(["/user/auth/login"], true), '{AdminName}' => Yii::$app->user->getIdentity()->displayName));
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->send($user->email);
            $user->status = User::STATUS_ENABLED;
            $user->save();
            $user->setUpApproved();
            return $this->redirect(['index']);
        }
        return $this->render('approve', ['model' => $user, 'approveFormModel' => $model]);
    }
Пример #30
0
    public function registerClientScripts()
    {
        HighchartsAsset::registerWithOptions($this->view, ['modules' => $this->modules, 'theme' => $this->theme]);
        $options = Json::encode($this->clientOptions);
        if ($this->jsonUrl) {
            $url = Url::to($this->jsonUrl);
            $js = <<<JS
var {$this->id};
\$.getJSON('{$url}', function(data) {
    var options = {$options};
    options.series = [{data: data}];
    {$this->id} = new Highcharts.Chart(options);
});
JS;
        } elseif ($this->jsonSeriesUrl) {
            $url = Url::to($this->jsonSeriesUrl);
            $js = <<<JS
var {$this->id};
\$.getJSON('{$url}', function(data) {
    var options = {$options};
    options.series = data;
    {$this->id} = new Highcharts.Chart(options);
});
JS;
        } else {
            $js = <<<JS
var {$this->id} = new Highcharts.Chart({$options});
JS;
        }
        $this->view->registerJs($js);
    }