Exemplo n.º 1
4
 /**
  * @inheritdoc
  */
 public function run()
 {
     $jsOptions = ['clientOptions' => $this->clientOptions];
     $this->options['id'] = 'input-id';
     if ($this->hasModel()) {
         echo Html::activeInput('file', $this->model, $this->attribute, $this->options);
         echo Html::img('#', ['id' => 'cropper-box']);
         echo Html::button('Crop', ['id' => 'cropImage']);
         $input_name = Html::getInputName($this->model, $this->attribute);
         $input_id = Html::getInputId($this->model, $this->attribute);
         echo Html::hiddenInput($input_name . '[file]', '', ['id' => $input_id . '_image']);
         $jsOptions['model'] = $this->model;
         $jsOptions['attribute'] = $this->attribute;
     } else {
         echo Html::fileInput($this->name, $this->value, $this->options);
         echo Html::img('#', ['id' => 'cropper-box']);
         echo Html::button('Crop', ['id' => 'cropImage']);
     }
     if ($this->uploadUrl) {
         $this->uploadUrl = \Yii::getAlias($this->uploadUrl);
     }
     $jsOptions['uploadUrl'] = $this->uploadUrl;
     $jsOptions['uploadCroppedUrl'] = $this->uploadCroppedUrl;
     $jsOptions['changeUrl'] = $this->changeUrl;
     $jsOptions['name'] = $this->name;
     $jsOptions['aspectRatio'] = $this->aspectRatio;
     $this->registerPlugin($jsOptions);
 }
Exemplo n.º 2
0
 public function actionDuiHuan()
 {
     $post = \Yii::$app->request->post();
     $user = \Yii::$app->user->identity;
     $dzUser = (new DzHelper())->getDzUserByUsername($user->username);
     $data = [];
     $bbsUrl = \Yii::getAlias('@bbsUrl');
     $model = ShopProduct::findOne($post['dataId']);
     //实体物品
     if ($post['dataType'] == ShopCategory::findOne(['slug' => 'shi-ti-wu-pin'])->id) {
         return $this->redirect(['shi-wu-order', 'slug' => $model->slug]);
     }
     //判断积分
     if ($model->jifen > $dzUser['credits']) {
         $data['msg'] = '<i class="glyphicon glyphicon-ok"></i> 您当前的积分为 : ' . $dzUser['credits'];
         $data['msg'] .= '<br>';
         $data['msg'] .= '<i class="glyphicon glyphicon-ok"></i> 很遗憾您的积分不够兑换该礼品';
         $data['msg'] .= '<br>';
         $data['msg'] .= "<a href={$bbsUrl} target='_blank'>[去论坛赚积分]</a>";
         return json_encode($data);
     } else {
         //实体物品
         if ($post['dataType'] == ShopCategory::findOne(['slug' => 'shi-ti-wu-pin'])->id) {
             return $this->redirect(['shi-wu-order', 'slug' => $model->slug]);
         }
         //虚拟物品
         if ($post['dataType'] == ShopCategory::findOne(['slug' => 'xu-ni-wu-pin'])->id) {
         }
     }
     $data['msg'] = '<i class="glyphicon glyphicon-ok"></i> 系统异常,请稍后在试!';
     return json_encode($data);
 }
 /**
  * 上传图片的操作
  * @author gaoqing
  * 2016年1月28日
  * @return array 上传成功后,返回图片的相关信息
  */
 public function actionUpload()
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     //设置上传目录
     $path = $this->temp;
     if (!empty($_FILES)) {
         //得到上传的临时文件流
         $tempFile = $_FILES['Filedata']['tmp_name'];
         //允许的文件后缀
         $fileTypes = array('jpg', 'jpeg', 'gif', 'png');
         //得到文件原名
         $fileName = iconv("UTF-8", "GB2312", $_FILES["Filedata"]["name"]);
         $fileParts = pathinfo($_FILES['Filedata']['name']);
         //最后保存服务器地址
         $frontend = \Yii::getAlias("@frontend");
         $fullpath = $frontend . DIRECTORY_SEPARATOR . "web" . DIRECTORY_SEPARATOR . $path;
         if (!file_exists($fullpath) || !is_dir($fullpath)) {
             mkdir($fullpath, 0777);
         }
         $name = strstr($fileName, ".", true);
         $name = md5($name);
         $suffix = strstr($fileName, ".");
         $fileName = $name . $suffix;
         $domain = \Yii::getAlias("@jb_domain");
         if (move_uploaded_file($tempFile, $path . $fileName)) {
             return ['path' => $path, 'name' => $name, 'suffix' => $suffix, 'fileName' => $fileName, 'domain' => $domain];
         }
     }
 }
 public function actionUpload()
 {
     // @todo Update code
     // http://webtips.krajee.com/ajax-based-file-uploads-using-fileinput-plugin/
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         $gallery = Gallery::findOne(Yii::$app->session->get('gallery.gallery-id'));
         $form = new ImageUploadForm();
         $images = UploadedFile::getInstances($form, 'images');
         foreach ($images as $k => $image) {
             $_model = new ImageUploadForm();
             $_model->image = $image;
             if ($_model->validate()) {
                 $path = \Yii::getAlias('@uploadsBasePath') . "/img/{$_model->image->baseName}.{$_model->image->extension}";
                 $_model->image->saveAs($path);
                 // Attach image to model
                 $gallery->attachImage($path);
             } else {
                 foreach ($_model->getErrors('image') as $error) {
                     $gallery->addError('image', $error);
                 }
             }
         }
         if ($form->hasErrors('image')) {
             // @todo Translate
             $response['message'] = count($form->getErrors('image')) . ' of ' . count($images) . ' images not uploaded';
         } else {
             $response['message'] = Yii::t('app', '{n, plural, =1{Image} other{# images}} successfully uploaded', ['n' => count($images)]);
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $response;
     }
 }
Exemplo n.º 5
0
 public function init()
 {
     $this->basePath = $_SERVER['DOCUMENT_ROOT'] . \Yii::getAlias('@web') . '/ueditor';
     //设置资源所处的目录
     $this->baseUrl = Yii::getAlias('@web') . '/ueditor';
     //echo $this->baseUrl; die;
 }
Exemplo n.º 6
0
 /**
  * Bootstrap method to be called during application bootstrap stage.
  *
  * @param Application $app the application currently running
  */
 public function bootstrap($app)
 {
     /**
      * @var Module $gii
      */
     \Yii::setAlias('@carono', '@vendor/carono/yii2-components');
     if ($app instanceof \yii\console\Application) {
         $commands = ['city' => 'CityController', 'currency' => 'CurrencyController', 'dumper' => 'DumperController', 'carono' => 'CaronoController'];
         foreach ($commands as $name => $command) {
             $name = file_exists(\Yii::getAlias("@app/commands/{$command}.php")) ? "carono" . ucfirst($name) : $name;
             $app->controllerMap[$name] = 'carono\\components\\commands\\' . $command;
         }
         if (!isset($app->controllerMap['giix'])) {
             if (($gii = $app->getModule('gii')) && isset($gii->generators["giiant-model"])) {
                 if (!isset($gii->generators["giiant-model"]["templates"])) {
                     if (is_array($gii->generators["giiant-model"])) {
                         $gii->generators["giiant-model"]["templates"] = [];
                     } else {
                         $gii->generators["giiant-model"] = ["class" => 'schmunk42\\giiant\\generators\\model\\Generator', "templates" => []];
                     }
                 }
                 $template = '@vendor/carono/yii2-components/templates/giiant-model';
                 $gii->generators["giiant-model"]["templates"]["caronoModel"] = $template;
                 $app->controllerMap['giix'] = 'carono\\components\\commands\\GiixController';
             }
         }
     }
 }
Exemplo n.º 7
0
 /**
  * @return SxGeo
  */
 public function getSxGeo()
 {
     if ($this->_sxGeo === null) {
         $this->_sxGeo = new SxGeo(\Yii::getAlias($this->database), $this->accessMode);
     }
     return $this->_sxGeo;
 }
Exemplo n.º 8
0
 public function init()
 {
     parent::init();
     $this->layoutPath = \Yii::getAlias('@app/moduls/admin/views/layouts/');
     $this->layout = 'admin';
     // custom initialization code goes here
 }
Exemplo n.º 9
0
 public function init()
 {
     parent::init();
     if (!file_exists(\Yii::getAlias('@bower/history.js/scripts/bundled/html5/native.history.js'))) {
         throw new InvalidConfigException('You must include `bower-asset/history.js` package in your composer.json configuration file.');
     }
 }
Exemplo n.º 10
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $this->uploadDir = !empty(\Yii::$app->getModule('core')->fileUploadPath) ? \Yii::$app->getModule('core')->fileUploadPath : $this->uploadDir;
     $this->uploadDir = FileHelper::normalizePath(\Yii::getAlias($this->uploadDir));
     $this->additionalRenderData['uploadDir'] = $this->uploadDir;
 }
Exemplo n.º 11
0
 /**
  * Send email.
  *
  * @param bool $isTest
  *
  * @return bool
  *
  * @throws ObjectException
  * @throws InvalidParamException
  * @throws TransportException
  */
 public function send($isTest = false)
 {
     $massmail = MassMail::findByObjectId($this->object_id);
     if ($massmail && $massmail->is_send) {
         throw new ObjectException('Email has been already sent.');
     }
     if (!$massmail) {
         $massmail = new MassMail();
         $massmail->object_id = $this->object_id;
         $massmail->subject = $this->title;
         $massmail->to = $this->email;
         $massmail->message = file_get_contents(Yii::getAlias('@runtime/massmail/blank_email.html'));
         $massmail->created_at = time();
     }
     if (!$massmail->save()) {
         throw new ObjectException('Model save errors: ' . $this->getErrors($massmail));
     }
     $massmail->is_send = (new TransportMassMail($massmail))->send($isTest);
     if (!$massmail->is_send) {
         throw new ObjectException('Email not send, see logs.');
     }
     if ($massmail->is_send) {
         $massmail->sent_at = time();
     }
     $massmail->save();
     return true;
 }
Exemplo n.º 12
0
 /**
  * Start cron tasks
  * @param string $taskCommand
  * @throws \yii\base\InvalidConfigException
  */
 public function actionStart($taskCommand = null)
 {
     /**
      * @var $cron Crontab
      */
     $cron = $this->module->get($this->module->nameComponent);
     $cron->eraseJobs();
     $common_params = $this->module->params;
     if (!empty($this->module->tasks)) {
         if ($taskCommand && isset($this->module->tasks[$taskCommand])) {
             $task = $this->module->tasks[$taskCommand];
             $params = ArrayHelper::merge(ArrayHelper::getValue($task, 'params', []), $common_params);
             $cron->addApplicationJob(\Yii::getAlias('@app') . '/../yii', $task['command'], $params, ArrayHelper::getValue($task, 'min'), ArrayHelper::getValue($task, 'hour'), ArrayHelper::getValue($task, 'day'), ArrayHelper::getValue($task, 'month'), ArrayHelper::getValue($task, 'dayofweek'), $this->module->cronGroup);
         } else {
             foreach ($this->module->tasks as $commandName => $task) {
                 $params = ArrayHelper::merge(ArrayHelper::getValue($task, 'params', []), $common_params);
                 $cron->addApplicationJob(\Yii::getAlias('@app') . '/../yii', $task['command'], $params, ArrayHelper::getValue($task, 'min'), ArrayHelper::getValue($task, 'hour'), ArrayHelper::getValue($task, 'day'), ArrayHelper::getValue($task, 'month'), ArrayHelper::getValue($task, 'dayofweek'), $this->module->cronGroup);
             }
         }
         $cron->saveCronFile();
         // save to my_crontab cronfile
         $cron->saveToCrontab();
         // adds all my_crontab jobs to system (replacing previous my_crontab jobs)
         echo $this->ansiFormat('Cron Tasks started.' . PHP_EOL, Console::FG_GREEN);
     } else {
         echo $this->ansiFormat('Cron do not have Tasks.' . PHP_EOL, Console::FG_GREEN);
     }
 }
 public function attach($owner)
 {
     //ok
     parent::attach($owner);
     if (!is_array($this->attributes) || empty($this->attributes)) {
         throw new InvalidParamException('Invalid or empty attributes array.');
     } else {
         foreach ($this->attributes as $attribute => $config) {
             if (!isset($config['path']) || empty($config['path'])) {
                 throw new InvalidParamException('Path must be set for all attributes.');
             }
             if (!isset($config['temp_path']) || empty($config['temp_path'])) {
                 throw new InvalidParamException('Temporary path must be set for all attributes.');
             }
             if (!isset($config['url']) || empty($config['url'])) {
                 $config['url'] = $this->publish($config['path']);
             }
             $this->attributes[$attribute]['path'] = FileHelper::normalizePath(Yii::getAlias($config['path'])) . DIRECTORY_SEPARATOR;
             $this->attributes[$attribute]['temp_path'] = FileHelper::normalizePath(Yii::getAlias($config['temp_path'])) . DIRECTORY_SEPARATOR;
             $this->attributes[$attribute]['url'] = rtrim($config['url'], '/') . '/';
             $validator = Validator::createValidator('string', $this->owner, $attribute);
             $this->owner->validators[] = $validator;
             unset($validator);
         }
     }
 }
 public function up()
 {
     $data = (include Yii::getAlias('@common') . '/data/test-adverts.php');
     $i = 0;
     while ($i++ !== 3) {
         foreach ($data as $one) {
             $advert = new Advert();
             $advert->detachBehavior('timestamp');
             $advert->setAttributes($one);
             $advert->user_id = rand(1, 50);
             $advert->created_at = time() - 3600 * 24 * rand(1, 31) - 3600 * rand(1, 24) + rand(1, 3600);
             $advert->updated_at = $advert->created_at;
             $advert->term_at = $advert->created_at + 3600 * 24 * rand(1, 31);
             if ($advert->save()) {
                 echo "Advert for user №{$advert->user_id} created\n";
             } else {
                 print_r($advert->getErrors());
             }
         }
     }
     foreach (User::find()->all() as $user) {
         $profile = new Profile();
         $profile->user_id = $user->id;
         $profile->name = $user->username;
         if ($profile->save()) {
             echo "Profile of \"{$user->username}\" created\n";
         } else {
             print_r($profile->getErrors());
         }
     }
 }
Exemplo n.º 15
0
 public function actionIndex()
 {
     $file = UploadedFile::getInstanceByName('imgFile');
     $basePath = dirname(\Yii::getAlias('@common'));
     $date = date("Y{$this->separator}m", time());
     $uploadPath = "../uploads/Attachment/{$date}";
     if (!is_dir($basePath . "/" . $uploadPath)) {
         FileHelper::createDirectory($basePath . "/" . $uploadPath);
     }
     if (preg_match('/(\\.[\\S\\s]+)$/', $file->name, $match)) {
         $filename = md5(uniqid(rand())) . $match[1];
     } else {
         $filename = $file->name;
     }
     $uploadData = ['type' => $file->type, 'name' => $filename, 'size' => $file->size, 'path' => "/" . $uploadPath, 'module' => null, 'controller' => null, 'action' => null, 'user_id' => \Yii::$app->user->isGuest ? 0 : \Yii::$app->user->identity->id];
     $module = \Yii::$app->controller->module;
     Upload::$db = $module->db;
     $model = new Upload();
     $model->setAttributes($uploadData);
     $model->validate();
     if ($model->save() && $file->saveAs($basePath . '/' . $uploadPath . '/' . $filename)) {
         return Json::encode(array('error' => 0, 'url' => "/" . $uploadPath . '/' . $filename, 'id' => $model->id, 'name' => $file->name));
     } else {
         return Json::encode(array('error' => 1, 'msg' => Json::encode($model->getErrors())));
     }
 }
Exemplo n.º 16
0
 /**
  * Reloads all bundles by going through all installed bundles and refilling cache file
  */
 public function reloadBundles()
 {
     $this->bundles = [];
     if ($this->coreBundlesLocation !== false) {
         $normalizedCoreBundles = HasFilesystemRepresentation::normalizePath(Yii::getAlias($this->coreBundlesLocation));
         $coreBundles = ['bundle', 'core', 'visual-builder'];
         foreach ($coreBundles as $bundle) {
             $this->loadBundle($normalizedCoreBundles . $bundle);
         }
     }
     // load third-party bundles
     $finder = new Finder();
     try {
         $finder->directories()->in(HasFilesystemRepresentation::normalizePath(Yii::getAlias($this->bundlesLocation)) . $this->bundleLocationLookup)->ignoreUnreadableDirs()->followLinks()->sortByName()->depth('== 0');
         foreach ($finder as $directory) {
             /** @var SplFileInfo $directory */
             $this->loadBundle(dirname($directory->getRealPath()));
         }
     } catch (\InvalidArgumentException $e) {
     }
     $finder = null;
     unset($finder);
     gc_collect_cycles();
     $this->updateBundlesCache();
 }
Exemplo n.º 17
0
    private static function _quoteReplace($entity, $attributes = array())
    {
        $baseUrl = \Yii::$app->params['newsSocialUrl'];
        $title = $entity->title;
        $titleEncode = urlencode($title);
        $image = $entity->getPreviewUrl();
        $urlPath = $baseUrl . FPUtil::getLink($entity);
        $url = urlencode($urlPath);
        $baseUrl = \Yii::getAlias('@web');
        $str = <<<EOT
\t\t<!-- QUOTE BLOCK -->
    <section class="quote-block">
        <h2 class="hide">{$title}</h2>
        <img src="{$image}" class="img-responsive quote-block__image" />
        <div class="quote-block__social">
            <a href="https://www.facebook.com/sharer/sharer.php?app_id=299133566841790&sdk=joey&u={$url}&display=popup&ref=plugin&src=share_button" class="quote-block__social__item" target="_blank">
                <i class="fa fa-facebook"></i>
            </a>
            <a href="https://plus.google.com/share?url={$url}" class="quote-block__social__item" target="_blank">
                <i class="fa fa-google-plus"></i>
            </a>
            <a href="https://twitter.com/intent/tweet?hashtags=ThaiPBSNews&original_referer={$url}&ref_src=twsrc%5Etfw&text={$titleEncode}&tw_p=tweetbutton&url={$url}&via=ThaiPBSNews" class="quote-block__social__item" target="_blank">
                <i class="fa fa-twitter"></i>
            </a>
            <a href="http://line.me/R/msg/text/?{$url}" class="quote-block__social__item" target="_blank">
                <img src="{$baseUrl}/images/linebutton_bl.png" width="20" height="20" class="normal" alt="LINE it!" />
                <img src="{$baseUrl}/images/linebutton_wh.png" width="20" height="20" class="hover" alt="LINE it!" />
            </a>

        </div>
    </section>
    <!--/ QUOTE BLOCK -->
EOT;
        return $str;
    }
Exemplo n.º 18
0
 public static function isBackend()
 {
     if (!self::isBackendAliasSet()) {
         throw new InvalidConfigException("'backendName' alias not defined!\n\n Please create it in '/common/config/bootstrap.php' with your backend app's name.\n\n Example: Yii::setAlias('@backendName', 'app-backend');");
     }
     return \Yii::$app->id == \Yii::getAlias('@backendName') ? true : false;
 }
Exemplo n.º 19
0
 public function uninstall($code)
 {
     $row = (new \yii\db\Query())->select(['id', 'shipping_name', 'print_bg'])->from(self::tableName())->where(['shipping_code' => $code])->limit(1)->one();
     if (!$row) {
         return true;
     }
     $shipping_id = $row['id'];
     $shipping_name = $row['shipping_name'];
     //获取配送地区id
     $rows = (new \yii\db\Query())->select(['id'])->from(ShippingArea::tableName())->where(['shipping_id' => $shipping_id])->all();
     $all = UtilD::getCol($rows);
     $in = UtilD::db_create_in(join(',', $all));
     $conn = \Yii::$app->getDb();
     $transaction = $conn->beginTransaction();
     try {
         $sql1 = "DELETE FROM " . AreaRegion::tableName() . " WHERE shipping_area_id " . $in;
         $sql2 = "DELETE FROM " . ShippingArea::tableName() . " WHERE id=" . $shipping_id;
         $sql3 = "DELETE FROM " . Shipping::tableName() . " WHERE id=" . $shipping_id;
         $conn->createCommand($sql1)->execute();
         $conn->createCommand($sql2)->execute();
         $conn->createCommand($sql3)->execute();
         $transaction->commit();
     } catch (\Exception $e) {
         $transaction->rollBack();
         return false;
     }
     //删除上传的非默认快递单
     if ($row['print_bg'] != '' && !UtilD::is_print_bg_default($row['print_bg'])) {
         @unlink(\Yii::getAlias('@web') . DIRECTORY_SEPARATOR . $row['print_bg']);
     }
     AdminLog::admin_log(addslashes($shipping_name), 'uninstall', 'shipping');
     return true;
 }
 public function up()
 {
     // Create folders for media manager
     $webroot = Yii::getAlias('@app/web');
     foreach (['upload', 'files'] as $folder) {
         $path = $webroot . '/' . $folder;
         if (!file_exists($path)) {
             echo "mkdir('{$path}', 0777)...";
             if (mkdir($path, 0777, true)) {
                 echo "done.\n";
             } else {
                 echo "failed.\n";
             }
         }
     }
     // Creates the default platform config
     /** @var \gromver\platform\core\modules\main\models\MainParams $params */
     $params = Yii::$app->paramsManager->main;
     $model = new \gromver\models\ObjectModel(\gromver\platform\core\modules\main\models\MainParams::className());
     $model->setAttributes($params->toArray());
     //$supportModel = $model->supportEmail;
     echo 'Setup application config: ' . PHP_EOL;
     $this->readStdinUser('Site Name (My Site)', $model, 'siteName', 'My Site');
     $this->readStdinUser('Admin Email (admin@example.com)', $model, 'adminEmail', '*****@*****.**');
     // todo заполнение email данных саппорта
     //$this->readStdinUser('Support Email (support@example.com)', $supportModel, 'supportEmail', '*****@*****.**');
     //$this->readStdinUser('Support Name (My Site Support)', $supportModel, 'supportName', 'My Site Support');
     if ($model->validate()) {
         \gromver\platform\core\modules\main\models\MainParams::create($model->toArray())->save();
     }
     echo 'Setup complete.' . PHP_EOL;
 }
Exemplo n.º 21
0
 public function testCommon()
 {
     $url = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=1K5pS0Rz6KrM0n-ju_CBm0DZxFkKyoyJd3Orhhk3MYz4&exportFormat=xlsx';
     $path = Yii::getAlias('@tests/_output/AdvancedImporter.xlsx');
     file_put_contents($path, file_get_contents($url));
     $importer = new Importer(['filePath' => $path, 'sheetNames' => ['Data'], 'standardModelsConfig' => [['className' => Test::className(), 'labels' => ['Test', 'Tests'], 'standardAttributesConfig' => [['name' => 'type', 'valueReplacement' => Test::getTypesList()], ['name' => 'description', 'valueReplacement' => function ($value) {
         return $value ? Html::tag('p', $value) : '';
     }], ['name' => 'author_id', 'valueReplacement' => function ($value) {
         return Author::find()->select('id')->where(['name' => $value]);
     }]]], ['className' => Question::className(), 'labels' => ['Question', 'Questions']], ['className' => Answer::className(), 'labels' => ['Answer', 'Answers']]]]);
     $result = $importer->run();
     $this->assertEquals($importer->error, null);
     $this->assertEquals($result, true);
     $this->assertEquals(Test::find()->count(), 5);
     $this->assertEquals(Test::findOne(1)->attributes, ['id' => 1, 'name' => 'Basic test', 'type' => 2, 'description' => '<p>This is the basic test</p>', 'author_id' => 2]);
     $this->assertEquals(Test::findOne(2)->attributes, ['id' => 2, 'name' => 'Common test', 'type' => 1, 'description' => '', 'author_id' => 1]);
     $this->assertEquals(Test::findOne(3)->attributes, ['id' => 3, 'name' => 'Programming test', 'type' => 2, 'description' => '', 'author_id' => 2]);
     $this->assertEquals(Test::findOne(4)->attributes, ['id' => 4, 'name' => 'Language test', 'type' => 1, 'description' => '', 'author_id' => 1]);
     $this->assertEquals(Test::findOne(5)->attributes, ['id' => 5, 'name' => 'Science test', 'type' => 1, 'description' => '', 'author_id' => 1]);
     $this->assertEquals(Question::find()->count(), 5);
     $this->assertEquals(Question::findOne(1)->attributes, ['id' => 1, 'test_id' => 1, 'content' => "What's your name?", 'sort' => 1]);
     $this->assertEquals(Question::findOne(2)->attributes, ['id' => 2, 'test_id' => 1, 'content' => 'How old are you?', 'sort' => 2]);
     $this->assertEquals(Question::findOne(3)->attributes, ['id' => 3, 'test_id' => 5, 'content' => "What's your name?", 'sort' => 1]);
     $this->assertEquals(Question::findOne(4)->attributes, ['id' => 4, 'test_id' => 5, 'content' => 'How old are you?', 'sort' => 2]);
     $this->assertEquals(Question::findOne(5)->attributes, ['id' => 5, 'test_id' => 1, 'content' => 'Yes or no?', 'sort' => 1]);
     $this->assertEquals(Answer::find()->count(), 2);
     $this->assertEquals(Answer::findOne(1)->attributes, ['id' => 1, 'question_id' => 5, 'content' => 'Yes', 'sort' => 1]);
     $this->assertEquals(Answer::findOne(2)->attributes, ['id' => 2, 'question_id' => 5, 'content' => 'No', 'sort' => 2]);
 }
Exemplo n.º 22
0
 /**
  * @return array
  */
 protected function getYiiConfiguration()
 {
     if (YII_ENV == 'test') {
         return ['basePath' => \Yii::getAlias('@tests')];
     }
     return parent::getYiiConfiguration();
 }
Exemplo n.º 23
0
 public function init()
 {
     parent::init();
     if (!$this->executePath) {
         $this->executePath = \Yii::getAlias('@app');
     }
 }
Exemplo n.º 24
0
 public function init()
 {
     parent::init();
     if (!file_exists(\Yii::getAlias('@bower/sticky/jquery.sticky.js'))) {
         throw new InvalidConfigException('You must include `bower-asset/sticky` package in your composer.json configuration file.');
     }
 }
 public function actionUpload()
 {
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         $slider = Slider::findOne($post['sliderId']);
         $form = new ImageUploadForm();
         $images = UploadedFile::getInstances($form, 'images');
         foreach ($images as $k => $image) {
             $_model = new ImageUploadForm();
             $_model->image = $image;
             if ($_model->validate()) {
                 $path = \Yii::getAlias('@uploadsBasePath') . "/img/{$_model->image->baseName}.{$_model->image->extension}";
                 $_model->image->saveAs($path);
                 // Attach image to model
                 $slider->attachImage($path);
             } else {
                 foreach ($_model->getErrors('image') as $error) {
                     $slider->addError('image', $error);
                 }
             }
         }
         if ($form->hasErrors('image')) {
             $form->addError('image', count($form->getErrors('image')) . ' of ' . count($images) . ' images not uploaded');
         } else {
             Yii::$app->session->setFlash('image-success', Yii::t('app', 'Images successfully uploaded', ['Image' => Yii::t('app', 'Image'), 'images' => Yii::t('app', 'images'), 'n' => count($images)]));
         }
         return $this->redirect(['index?sliderId=' . $post['sliderId']]);
     }
 }
Exemplo n.º 26
0
 /**
  * @return string the composer lock full file path
  */
 public function getComposerLockPath()
 {
     if ($this->_composer_lock_path == null) {
         $this->_composer_lock_path = \Yii::getAlias('@root') . '/composer.lock';
     }
     return $this->_composer_lock_path;
 }
 public function safeUp()
 {
     $this->insert('{{%user}}', ['id' => 1, 'username' => 'webmaster', 'email' => '*****@*****.**', 'password_hash' => Yii::$app->getSecurity()->generatePasswordHash('webmaster'), 'auth_key' => Yii::$app->getSecurity()->generateRandomString(), 'access_token' => Yii::$app->getSecurity()->generateRandomString(40), 'status' => User::STATUS_ACTIVE, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%user}}', ['id' => 2, 'username' => 'manager', 'email' => '*****@*****.**', 'password_hash' => Yii::$app->getSecurity()->generatePasswordHash('manager'), 'auth_key' => Yii::$app->getSecurity()->generateRandomString(), 'access_token' => Yii::$app->getSecurity()->generateRandomString(40), 'status' => User::STATUS_ACTIVE, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%user}}', ['id' => 3, 'username' => 'user', 'email' => '*****@*****.**', 'password_hash' => Yii::$app->getSecurity()->generatePasswordHash('user'), 'auth_key' => Yii::$app->getSecurity()->generateRandomString(), 'access_token' => Yii::$app->getSecurity()->generateRandomString(40), 'status' => User::STATUS_ACTIVE, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%user_profile}}', ['user_id' => 1, 'locale' => Yii::$app->sourceLanguage, 'firstname' => 'John', 'lastname' => 'Doe']);
     $this->insert('{{%user_profile}}', ['user_id' => 2, 'locale' => Yii::$app->sourceLanguage]);
     $this->insert('{{%user_profile}}', ['user_id' => 3, 'locale' => Yii::$app->sourceLanguage]);
     $this->insert('{{%page}}', ['slug' => 'about', 'title' => 'About', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'status' => \common\models\Page::STATUS_PUBLISHED, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%article_category}}', ['id' => 1, 'slug' => 'news', 'title' => 'News', 'status' => \common\models\ArticleCategory::STATUS_ACTIVE, 'created_at' => time()]);
     $this->insert('{{%widget_menu}}', ['key' => 'frontend-index', 'title' => 'Frontend index menu', 'items' => json_encode([['label' => 'Get started with Yii2', 'url' => 'http://www.yiiframework.com', 'options' => ['tag' => 'span'], 'template' => '<a href="{url}" class="btn btn-lg btn-success">{label}</a>'], ['label' => 'Yii2 Starter Kit on GitHub', 'url' => 'https://github.com/trntv/yii2-starter-kit', 'options' => ['tag' => 'span'], 'template' => '<a href="{url}" class="btn btn-lg btn-primary">{label}</a>'], ['label' => 'Find a bug?', 'url' => 'https://github.com/trntv/yii2-starter-kit/issues', 'options' => ['tag' => 'span'], 'template' => '<a href="{url}" class="btn btn-lg btn-danger">{label}</a>']], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'status' => \common\models\WidgetMenu::STATUS_ACTIVE]);
     $this->insert('{{%widget_text}}', ['key' => 'backend_welcome', 'title' => 'Welcome to backend', 'body' => '<p>Welcome to Yii2 Starter Kit Dashboard</p>', 'status' => 1, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%widget_text}}', ['key' => 'ads-example', 'title' => 'Google Ads Example Block', 'body' => '<div class="lead">
             <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
             <ins class="adsbygoogle"
                  style="display:block"
                  data-ad-client="ca-pub-9505937224921657"
                  data-ad-slot="2264361777"
                  data-ad-format="auto"></ins>
             <script>
             (adsbygoogle = window.adsbygoogle || []).push({});
             </script>
         </div>', 'status' => 0, 'created_at' => time(), 'updated_at' => time()]);
     $this->insert('{{%widget_carousel}}', ['id' => 1, 'key' => 'index', 'status' => \common\models\WidgetCarousel::STATUS_ACTIVE]);
     $this->insert('{{%widget_carousel_item}}', ['carousel_id' => 1, 'base_url' => Yii::getAlias('@frontendUrl'), 'path' => 'img/yii2-starter-kit.gif', 'type' => 'image/gif', 'url' => '/', 'status' => 1]);
     $this->insert('{{%key_storage_item}}', ['key' => 'backend.theme-skin', 'value' => 'skin-blue', 'comment' => 'skin-blue, skin-black, skin-purple, skin-green, skin-red, skin-yellow']);
     $this->insert('{{%key_storage_item}}', ['key' => 'backend.layout-fixed', 'value' => 0]);
     $this->insert('{{%key_storage_item}}', ['key' => 'backend.layout-boxed', 'value' => 0]);
     $this->insert('{{%key_storage_item}}', ['key' => 'backend.layout-collapsed-sidebar', 'value' => 0]);
     $this->insert('{{%key_storage_item}}', ['key' => 'frontend.maintenance', 'value' => 'disabled', 'comment' => 'Set it to "true" to turn on maintenance mode']);
 }
 public function safeUp()
 {
     $app = Yii::$app;
     $app->setModule('user', ['class' => 'dektrium\\user\\Module']);
     if (!isset($app->get('i18n')->translations['user*'])) {
         $app->get('i18n')->translations['user*'] = ['class' => \yii\i18n\PhpMessageSource::className(), 'basePath' => Yii::getAlias('@dektrium/user/migrations')];
     }
     $controller = Yii::$app->controller;
     $user = new User(['scenario' => 'register']);
     echo $controller->ansiFormat("\n\n ==> Create Admin User\n", \yii\helpers\Console::FG_CYAN);
     do {
         if ($user->hasErrors()) {
             $this->showErrors($user);
         }
         // get email
         $email = $controller->prompt($controller->ansiFormat("\tE-mail: ", \yii\helpers\Console::FG_BLUE));
         // get username
         $username = $controller->prompt($controller->ansiFormat("\tUsername: "******"\tPassword: "******"\n";
         $affectedRows = Yii::$app->db->createCommand()->insert('{{%user}}', ['username' => (string) $username, 'email' => $email, 'password_hash' => Password::hash($password), 'confirmed_at' => new Expression('UNIX_TIMESTAMP()')])->execute();
     } while ($affectedRows < 1);
     do {
         // get realname
         $name = $controller->prompt($controller->ansiFormat("\tFull name: ", \yii\helpers\Console::FG_BLUE));
         echo "\n\n";
     } while (empty($name));
     $userPrimaryKey = User::findOne(['email' => $email])->primaryKey;
     $this->update('{{%profile}}', ['name' => $name], 'user_id=:user_id', [':user_id' => $userPrimaryKey]);
     $this->insert('{{%auth_assignment}}', ['item_name' => 'admin', 'user_id' => $userPrimaryKey, 'created_at' => new Expression('UNIX_TIMESTAMP()')]);
 }
Exemplo n.º 29
0
 public function actionUpload()
 {
     $model = new UploadForm();
     if (Yii::$app->request->isPost) {
         $model->file = UploadedFile::getInstances($model, 'file');
         if ($model->file && $model->validate()) {
             foreach ($model->file as $file) {
                 $model_script = new Sqlscript();
                 $save_name = '';
                 if (strtolower($file->extension) === 'txt' || strtolower($file->extension) === 'sql') {
                     $path = \Yii::getAlias('@webroot') . "/scripts/";
                     $fname = iconv('UTF-8', 'tis-620', $file->name);
                     // win
                     $save_name = $path . $fname;
                     $file->saveAs($save_name);
                     $model_script->topic = iconv('tis-620', 'UTF-8', $fname);
                     $model_script->sql_script = iconv('tis-620', 'UTF-8', file_get_contents($save_name));
                     $model_script->user = Yii::$app->user->identity->username;
                     $model_script->d_update = date('Y-m-d H:i:s');
                 }
                 $model_script->save();
             }
             return $this->redirect(['sqlscript/index']);
         }
     }
     return $this->render('upload', ['model' => $model]);
 }
 public function up()
 {
     // Creates folders for media manager
     $webroot = Yii::getAlias('@app/web');
     foreach (['upload', 'files'] as $folder) {
         $path = $webroot . '/' . $folder;
         if (!file_exists($path)) {
             echo "mkdir('{$path}', 0777)...";
             if (mkdir($path, 0777, true)) {
                 echo "done.\n";
             } else {
                 echo "failed.\n";
             }
         }
     }
     // Creates the default platform config
     /** @var \gromver\platform\basic\console\modules\main\Module $main */
     $cmf = Yii::$app->grom;
     $paramsPath = Yii::getAlias($cmf->paramsPath);
     $paramsFile = $paramsPath . DIRECTORY_SEPARATOR . 'params.php';
     $params = $cmf->params;
     $model = new \gromver\models\ObjectModel(\gromver\platform\basic\modules\main\models\PlatformParams::className());
     $model->setAttributes($params);
     echo 'Setup application config: ' . PHP_EOL;
     $this->readStdinUser('Site Name (My Site)', $model, 'siteName', 'My Site');
     $this->readStdinUser('Admin Email (admin@email.com)', $model, 'adminEmail', '*****@*****.**');
     $this->readStdinUser('Support Email (support@email.com)', $model, 'supportEmail', '*****@*****.**');
     if ($model->validate()) {
         \yii\helpers\FileHelper::createDirectory($paramsPath);
         file_put_contents($paramsFile, '<?php return ' . var_export($model->toArray(), true) . ';');
         @chmod($paramsFile, 0777);
     }
     echo 'Setup complete.' . PHP_EOL;
 }