/**
  * Try to read language from session and cookies
  */
 public function init()
 {
     parent::init();
     $slug = null;
     if ($this->languageSession) {
         $slug = Yii::$app->session->get($this->languageSessionKey);
     }
     if ($slug === null && $this->languageCookie) {
         $slug = Yii::$app->request->getCookies()->getValue($this->languageCookieName);
     }
     $languages = [];
     $selectedLanguage = null;
     foreach ($this->languages as $config) {
         if (is_array($config) && !isset($config['class'])) {
             $config['class'] = Language::className();
         }
         /** @var ILanguage $language */
         $language = \Yii::createObject($config);
         $languages[$language->getId()] = $language;
         if ($slug === $language->getSlug()) {
             $selectedLanguage = $language;
         }
     }
     $this->languages = $languages;
     if ($selectedLanguage === null) {
         $selectedLanguage = reset($languages);
     }
     $this->setLanguage($selectedLanguage);
 }
 protected function optionsModifier($options)
 {
     if (empty($this->component)) {
         throw new InvalidConfigException('The "component" property must be set.');
     }
     /** @var Filesystem $component */
     if (is_string($this->component)) {
         $component = \Yii::$app->get($this->component);
     } else {
         $component = \Yii::createObject($this->component);
     }
     if (!($component instanceof \creocoder\flysystem\Filesystem || $component instanceof Filesystem)) {
         throw new InvalidConfigException('A Filesystem instance is required');
     }
     $options['separator'] = $this->separator;
     $options['filesystem'] = new Filesystem($component->getAdapter());
     $options['path'] = $this->path;
     if (!empty($this->glideURL) && !empty($this->glideKey)) {
         $options['glideURL'] = $this->glideURL;
         $options['glideKey'] = $this->glideKey;
         unset($options['tmbPath']);
         unset($options['tmbURL']);
     }
     if (!empty($this->url)) {
         $options['URL'] = $this->url;
     }
     return $options;
 }
 public function deferEvent($event)
 {
     $class = get_class($this->owner);
     $pk = $this->owner->getPrimaryKey();
     $attributes = $this->owner->getAttributes();
     $scenario = $this->owner->scenario;
     $eventName = $event->name;
     $queue = $this->queue;
     $handler = clone $this;
     $handler->queue = null;
     $handler->owner = null;
     /* @var $queue Queue */
     if ($eventName == ActiveRecord::EVENT_AFTER_DELETE) {
         $queue->post(new \UrbanIndo\Yii2\Queue\Job(['route' => function () use($class, $pk, $attributes, $handler, $eventName, $scenario) {
             $object = \Yii::createObject($class);
             /* @var $object ActiveRecord */
             $object->setAttributes($attributes, false);
             $object->scenario = $scenario;
             $handler->handleEvent($object);
         }]));
     } else {
         $queue->post(new \UrbanIndo\Yii2\Queue\Job(['route' => function () use($class, $pk, $attributes, $handler, $eventName, $scenario) {
             $object = $class::findOne($pk);
             if ($object === null) {
                 throw new \Exception("Model is not found");
             }
             $object->scenario = $scenario;
             /* @var $object ActiveRecord */
             $handler->handleEvent($object);
         }]));
     }
 }
Beispiel #4
0
 public function register()
 {
     if ($this->getIsNewRecord() == false) {
         throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
     }
     if ($this->module->enableConfirmation == false) {
         $this->confirmed_at = time();
     }
     if ($this->module->enableGeneratingPassword) {
         $this->password = Password::generate(8);
     }
     $this->trigger(self::USER_REGISTER_INIT);
     if ($this->save()) {
         $this->trigger(self::USER_REGISTER_DONE);
         if ($this->module->enableConfirmation) {
             $token = \Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]);
             $token->link('user', $this);
             $this->mailer->sendConfirmationMessage($this, $token);
         } else {
             \Yii::$app->user->login($this);
         }
         if ($this->module->enableGeneratingPassword) {
             $this->mailer->sendWelcomeMessage($this);
         }
         \Yii::$app->session->setFlash('info', $this->getFlashMessage());
         \Yii::getLogger()->log('User has been registered', Logger::LEVEL_INFO);
         return true;
     }
     \Yii::getLogger()->log('An error occurred while registering user account', Logger::LEVEL_ERROR);
     return false;
 }
Beispiel #5
0
 public function publish($channel, $message)
 {
     if ($this->redis === null) {
         $this->redis = \Yii::createObject(['class' => \kepco\Redis::className(), 'hostname' => $this->redis_server]);
     }
     $this->redis->publish($channel, $message);
 }
Beispiel #6
0
 public function beforeAction($action)
 {
     $device = new MobileDetect();
     $theme = ['class' => 'yii\\base\\Theme', 'basePath' => '@app/themes/basic', 'baseUrl' => '@web/themes/basic', 'pathMap' => ['@app/views' => ['@app/themes/' . ($device->isMobile() ? 'mobile' : 'special'), '@app/themes/basic']]];
     \Yii::$app->getView()->theme = \Yii::createObject($theme);
     return true;
 }
 /**
  * @return \metalguardian\fileProcessor\components\FileTransfer
  * @throws \yii\base\InvalidConfigException
  */
 public static function transfer()
 {
     if (is_null(static::$transfer)) {
         static::$transfer = \Yii::createObject(\metalguardian\fileProcessor\components\FileTransfer::className());
     }
     return static::$transfer;
 }
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @return bool
  * @throws \yii\base\InvalidConfigException
  */
 public function save(\yii\authclient\ClientInterface $Client)
 {
     /** @var Account\backend\Module $Module */
     $Module = \Yii::$app->getModule($this->accountModule);
     $roles = $Module->roles;
     /** @var AccountModel $Account */
     $Account = \Yii::createObject(AccountModel::class);
     $Account->appendClientAttributes($Client);
     $Account->setAttributes(['email' => $this->email]);
     $Account->validate() && $Account->save();
     $AuthResponse = AccountAuthResponseModel::createLog($Client);
     if ($Account->hasErrors()) {
         $AuthResponse->result = Json::encode($Account->getErrors());
     } else {
         $AuthResponse->result = (string) $Account->id;
         $Account->pushSocialLink($Client);
         AuthManager()->assign(RbacFactory::Role($roles['user']), $Account->id);
         $SignInFormModel = \Yii::createObject(SignInForm::class);
         User()->login($Account, $SignInFormModel::REMEMBER_TIME);
     }
     $AuthResponse->validate() && $AuthResponse->save();
     if ($Account->hasErrors()) {
         $this->populateErrors($Account, 'name');
     }
     return !$Account->hasErrors();
 }
 /**
  * @return EditableFactory
  * @throws \yii\base\InvalidConfigException
  */
 public function editable()
 {
     if ($this->editable === null) {
         $this->editable = Yii::createObject(EditableFactory::class, $this->editableConfig);
     }
     return $this->editable;
 }
 public function init()
 {
     parent::init();
     $this->layout = $this->layoutMittente;
     //se sono il widget di destinazione per le scelte delle associazioni
     if (!$this->targetUrl) {
         $this->layout = $this->layoutTarget;
         if (!$this->modelTargetSearch) {
             throw new InvalidConfigException($this->throwErrorMessage('modelTargetSearch'));
         }
         if (!$this->modelTargetSearch['class']) {
             throw new InvalidConfigException($this->throwErrorMessage('modelTargetSearch[class]'));
         }
         if (!$this->modelTargetSearch['action']) {
             throw new InvalidConfigException($this->throwErrorMessage('modelTargetSearch[action]'));
         }
         $this->modelTarget = \Yii::createObject($this->modelTargetSearch['class']);
         $this->modelTargetData = $this->modelTarget->{$this->modelTargetSearch['action']}(\Yii::$app->request->getQueryParams());
     }
     if (!$this->modelData) {
         throw new InvalidConfigException($this->throwErrorMessage('modelData'));
     }
     if (!$this->modelId) {
         throw new InvalidConfigException($this->throwErrorMessage('modelId'));
     }
     if (!$this->model) {
         throw new InvalidConfigException($this->throwErrorMessage('model'));
     }
     $this->modelDataArr = ArrayHelper::map($this->modelData->all(), 'id', 'id');
 }
 /**
  * Initialization
  *
  * @param array $config
  * @return \phantomd\filedaemon\FileProcessing Object
  * @throws InvalidParamException
  */
 public static function init($config)
 {
     if (empty($config)) {
         $message = 'Component error: Could not be empty `config`!';
         \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')');
         throw new InvalidParamException($message);
     }
     $class = null;
     if (false === empty($config['component'])) {
         if (class_exists($config['component'])) {
             $class = $config['component'];
         } else {
             $class = __NAMESPACE__ . '\\' . ucfirst(strtolower((string) $config['component'])) . 'Processing';
         }
     }
     if ($class) {
         if (false === class_exists($class)) {
             $message = "Component error: Not exist - `{$class}`";
             \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')');
             throw new InvalidParamException($message);
         }
         $params = ['class' => $class, 'config' => $config];
         $object = \Yii::createObject($params);
         if ($object instanceof FileProcessing) {
             return $object;
         } else {
             $message = "Component error: `{$class}` must be instance of class `FileProcessing`!";
             \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')');
             throw new InvalidParamException($message);
         }
     }
     return null;
 }
 public function run()
 {
     if ($this->checkAccess) {
         call_user_func($this->checkAccess, $this->id);
     }
     $params = Yii::$app->request->post();
     if (!isset($params['language'])) {
         throw new HttpException(404, Yii::t('cza', 'Language ({s1}) Not Found!', ['s1' => $params['language']]));
     }
     if (isset($params['src_model_id'])) {
         $model = $this->controller->retrieveModel($params['src_model_id']);
     } else {
         throw new HttpException(404, Yii::t('cza', 'Srouce model not found!'));
     }
     $translationModel = $model->getTranslation($params['language']);
     // handle cms media fields
     if ($this->controller instanceof \cza\base\components\controllers\backend\CmsController) {
         $cmsFields = $this->controller->getCmsFields();
         $translationModel->attachBehavior('CmsMediaBehavior', ['class' => CmsMediaBehavior::className(), 'fields' => $cmsFields, 'options' => ['isTranslation' => true]]);
     }
     if ($translationModel->load($params) && $translationModel->save()) {
         $responseData = \cza\base\models\statics\ResponseDatum::getSuccessDatum($_POST, array('message' => Yii::t('cza', 'Operation completed successfully!')));
     } else {
         $responseData = \cza\base\models\statics\ResponseDatum::getErrorDatum($_POST, array('message' => $translationModel->getFirstErrors()));
     }
     return \Yii::createObject(['class' => 'yii\\web\\Response', 'format' => \yii\web\Response::FORMAT_JSON, 'data' => $responseData]);
 }
Beispiel #13
0
 /**
  * Tests the `LogTarget::jsonSerialize` method.
  */
 public function testJsonSerialize()
 {
     $client = \Yii::createObject(['class' => Client::class, 'password' => 'secret', 'username' => 'anonymous']);
     $data = (new LogTarget(['client' => $client]))->jsonSerialize();
     $this->assertObjectHasAttribute('enabled', $data);
     $this->assertTrue($data->enabled);
 }
Beispiel #14
0
 public static function get($id)
 {
     $query = is_numeric($id) ? ['clientid' => $id] : ['email' => $id];
     $response = self::getWhmcs()->call('getclientsdetails', $query, false);
     \Yii::trace(VarDumper::dumpAsString($response), __METHOD__);
     return \Yii::createObject(self::className(), [$response]);
 }
 public function testLogin()
 {
     $this->form = \Yii::createObject(LoginForm::className());
     $this->specify('should not allow logging in blocked users', function () {
         $user = $this->getFixture('user')->getModel('blocked');
         $this->form->setAttributes(['login' => $user->email, 'password' => 'qwerty']);
         verify($this->form->validate())->false();
         verify($this->form->getErrors('login'))->contains('Your account has been blocked');
     });
     $this->specify('should not allow logging in unconfirmed users', function () {
         \Yii::$app->getModule('user')->enableConfirmation = true;
         \Yii::$app->getModule('user')->enableUnconfirmedLogin = false;
         $user = $this->getFixture('user')->getModel('user');
         $this->form->setAttributes(['login' => $user->email, 'password' => 'qwerty']);
         verify($this->form->validate())->true();
         $user = $this->getFixture('user')->getModel('unconfirmed');
         $this->form->setAttributes(['login' => $user->email, 'password' => 'unconfirmed']);
         verify($this->form->validate())->false();
     });
     $this->specify('should log the user in with correct credentials', function () {
         $user = $this->getFixture('user')->getModel('user');
         $this->form->setAttributes(['login' => $user->email, 'password' => 'wrong']);
         verify($this->form->validate())->false();
         $this->form->setAttributes(['login' => $user->email, 'password' => 'qwerty']);
         verify($this->form->validate())->true();
     });
 }
Beispiel #16
0
 public function init()
 {
     parent::init();
     $this->module = \kepco\Module::getInstance();
     $this->client = new \GuzzleHttp\Client(['base_uri' => 'http://srm.kepco.net/', 'cookies' => true, 'allow_redirects' => false, 'headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Cookie' => $this->cookie, 'X-CSRF-TOKEN' => $this->token]]);
     $this->sub = \Yii::createObject(['class' => \kepco\Redis::className(), 'hostname' => $this->module->redis_server]);
 }
 /**
  * @inheritdoc
  */
 protected function loadAttributes(\dektrium\user\models\User $user)
 {
     $user->setAttributes(['email' => $this->email, 'username' => $this->username, 'password' => $this->password]);
     $profile = \Yii::createObject(Profile::className());
     $profile->setAttributes(['name' => ucwords(strtolower($this->firstname)) . " " . ucwords(strtolower($this->lastname)), 'firstname' => ucwords(strtolower($this->firstname)), 'lastname' => ucwords(strtolower($this->lastname)), 'birthday' => $this->birthday, 'terms' => $this->terms]);
     $user->setProfile($profile);
 }
 /**
  * @param  DataEntityProvider[] $providers
  * @param  ActionData           $actionData
  * @param  array                $packed
  * @param  array                $providedKeys
  *
  * @return mixed
  */
 public static function process($providers, &$actionData, &$packed, &$providedKeys)
 {
     $result = [];
     $providedKeys = [];
     foreach ($providers as $i => $provider) {
         $profileKey = "DataProviderProcessor: {$i}";
         Yii::beginProfile($profileKey);
         //! @todo Add check for correct class names here
         /** @var DataEntityProvider $instance */
         $instance = Yii::createObject($provider);
         $providerResult = $instance->getEntities($actionData);
         $keys = [];
         array_walk($providerResult, function ($materials, $regionKey) use(&$keys) {
             $result = [];
             array_walk($materials, function ($data, $materialIndex) use(&$result) {
                 $result[$materialIndex] = array_keys($data);
             });
             $keys[$regionKey] = $result;
         });
         $providedKeys[$i] = $keys;
         $result = ArrayHelper::merge($result, $providerResult);
         $packed[$i] = $instance->pack();
         Yii::endProfile($profileKey);
     }
     return $result;
 }
Beispiel #19
0
 public function prepareDatabase($config, $fixture, $open = true)
 {
     if (!isset($config['class'])) {
         $config['class'] = 'yii\\db\\Connection';
     }
     /* @var $db \yii\db\Connection */
     $db = \Yii::createObject($config);
     if (!$open) {
         return $db;
     }
     $db->open();
     if ($fixture !== null) {
         if ($this->driverName === 'oci') {
             list($drops, $creates) = explode('/* STATEMENTS */', file_get_contents($fixture), 2);
             list($statements, $triggers, $data) = explode('/* TRIGGERS */', $creates, 3);
             $lines = array_merge(explode('--', $drops), explode(';', $statements), explode('/', $triggers), explode(';', $data));
         } else {
             $lines = explode(';', file_get_contents($fixture));
         }
         foreach ($lines as $line) {
             if (trim($line) !== '') {
                 $db->pdo->exec($line);
             }
         }
     }
     return $db;
 }
Beispiel #20
0
 public function build()
 {
     $control = parent::build();
     $activeObject = Yii::createObject($this->config, [$request]);
     $control['data'] = $activeObject->run();
     return $control;
 }
Beispiel #21
0
 public static function updateUser($user_id, $data = null)
 {
     $user = User::findOne($user_id);
     $user->scenario = 'settings';
     $profile = $user->profile;
     $oldEmail = $user->email;
     if ($user->load(['User' => $data]) && $user->validate()) {
         if ($user->email != $oldEmail) {
             $user->unconfirmed_email = $user->email;
             $user->email = $oldEmail;
             $token = \Yii::createObject(['class' => Token::className(), 'user_id' => $user->id, 'type' => Token::TYPE_CONFIRM_NEW_EMAIL]);
             $token->save(false);
             $mailer = Yii::createObject(['class' => Mailer::className(), 'reconfirmationSubject' => 'Mail confirmation']);
             $mailer->sendReconfirmationMessage($user, $token);
         }
         if (!$profile) {
             $profile = Yii::createObject(['class' => Profile::className(), 'user_id' => $user->id]);
             $profile->save();
         }
         $profile->load(['Profile' => $data]);
         $profile->save();
         $user->save();
     } else {
         self::error($user);
     }
     return self::clearUserData($user);
 }
Beispiel #22
0
 public function init()
 {
     if (!$this->provider) {
         throw new InvalidConfigException('Provider must be declared.');
     }
     $this->_provider = \Yii::createObject($this->provider);
 }
Beispiel #23
0
 public function init()
 {
     $settingModel = \Yii::createObject(SettingFiles::className())->findOne(['setting_code' => self::settingCode]);
     if ($settingModel) {
         $this->scale = $settingModel->value;
     }
 }
Beispiel #24
0
 public function actionLogin()
 {
     if (!\Yii::$app->user->isGuest) {
         $this->goHome();
     }
     $model = \Yii::createObject(LoginForm::className());
     $this->performAjaxValidation($model);
     if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
         $app = Yii::$app->id;
         //backend access only for users with some roles
         if ($app == 'backend') {
             if (!$this->hasBackendAccess($model->login)) {
                 $user = $this->getUser($model->login);
                 if (!empty($user)) {
                     $model->addError('app', 'This user is not authorized for administration');
                     $app = 'frontend';
                 } else {
                     Yii::$app->getUser()->logout();
                     return $this->goBack();
                 }
             }
         }
         $redirect = "@baseUrl" . ucfirst($app);
         return $this->redirect(Yii::getAlias($redirect));
     }
     return $this->render('login', ['model' => $model, 'module' => $this->module]);
 }
Beispiel #25
0
 public function init()
 {
     parent::init();
     $this->module = \ebidlh\Module::getInstance();
     $this->pub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $this->module->redis_server]);
     $this->sub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $this->module->redis_server]);
 }
 public function safeDown()
 {
     $controller = Yii::$app->controller;
     $model = \Yii::createObject(LoginForm::className());
     do {
         if ($model->hasErrors()) {
             $this->showErrors($model);
         }
         // get username
         $username = $controller->prompt($controller->ansiFormat("\tUsername: "******"\tPassword: "******"\n";
         $model->login = $username;
         $model->password = $password;
     } while (!$model->validate());
     $user = User::findOne(['username' => $username]);
     if (empty($user)) {
         throw new \yii\console\Exception("Unable to find user {$username}");
     }
     $this->delete('{{%auth_assignment}}', ['item_name' => 'admin', 'user_id' => $user->primaryKey]);
     $user->delete();
 }
Beispiel #27
0
 /**
  * @return string
  */
 public function actionIndex()
 {
     /** @var FeedItemModel $ItemModel */
     $ItemModel = \Yii::createObject(FeedItemModel::class);
     $ItemEditForm = \Yii::createObject(['class' => Feed\backend\forms\ItemEditForm::class, 'Item' => $ItemModel]);
     return $this->render('index', ['ItemEditForm' => $ItemEditForm]);
 }
 public function loadAttributes(User $user)
 {
     $user->setAttributes($this->attributes);
     $profile = \Yii::createObject(Profile::className());
     $profile->setAttributes(['name' => $this->name]);
     $user->setProfile($profile);
 }
 /**
  * @param $id
  * @return string
  * @throws InvalidConfigException
  * @throws \yii\web\HttpException
  */
 public function run($id)
 {
     $this->model = CmsContentElement::findOne(['id' => $id]);
     //Пробуем рендерить view для текущего типа страницы
     if ($this->model) {
         $cmsContent = $this->model->cmsContent;
         if ($cmsContent) {
             if ($cmsContent->viewFile) {
                 $this->view = $cmsContent->viewFile;
             } else {
                 $this->view = $cmsContent->code;
             }
             if ($cmsContent->access_check_element == 'Y') {
                 /**
                  * @var $filter CmsAccessControl
                  */
                 $filter = \Yii::createObject(['class' => CmsAccessControl::className(), 'only' => [$this->id], 'rules' => [['allow' => true, 'matchCallback' => function ($rule, $action) {
                     //Если такая привилегия заведена, нужно ее проверять.
                     if ($permission = \Yii::$app->authManager->getPermission($this->model->permissionName)) {
                         if (!\Yii::$app->user->can($permission->name)) {
                             return false;
                         }
                     }
                     return true;
                 }]]]);
                 $result = $filter->beforeAction($this);
             }
         }
     }
     return $this->_go();
 }
 /**
  * Lists all FinanceRecord models.
  * @return mixed
  */
 public function actionIndex()
 {
     Url::remember('', 'actions-redirect');
     $searchModel = \Yii::createObject(FinanceSearch::className());
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
 }