/**
  * @param $class \yii\db\ActiveRecord|string
  * @return int
  * @throws \yii\elasticsearch\Exception
  */
 public function upload($class)
 {
     $bulk = '';
     $index = Index::index();
     $type = Index::type();
     $timestamp = time();
     /** @var \yii\base\Behavior[] */
     $behaviors = (new $class())->behaviors;
     $query = $class::find();
     array_walk($behaviors, function ($behavior) use($query) {
         if ($behavior instanceof TaggableBehavior) {
             $query->with('tags');
         }
     });
     foreach ($query->each() as $model) {
         /** @var \yii\db\ActiveRecord|\gromver\platform\core\interfaces\model\SearchableInterface|\gromver\platform\core\interfaces\model\ViewableInterface $model */
         $action = Json::encode(["index" => ["_id" => $model->getPrimaryKey(), "_type" => $type, "_index" => $index]]);
         $indexModel = Index::findOne(['model_id' => $model->getPrimaryKey(), 'model_class' => $model->className()]) or $indexModel = new Index();
         $indexModel->model_id = $model->getPrimaryKey();
         $indexModel->model_class = $model->className();
         $indexModel->title = $model->getSearchTitle();
         $indexModel->content = $model->getSearchContent();
         $indexModel->tags = $model->getSearchTags();
         $indexModel->url_backend = $model->getBackendViewLink();
         $indexModel->url_frontend = $model->getFrontendViewLink();
         $indexModel->updated_at = $timestamp;
         ModuleEvent::trigger(Module::EVENT_BEFORE_CREATE_INDEX . $model->className(), new ElasticIndexEvent(['model' => $model, 'index' => $indexModel, 'sender' => $this->module]));
         if ($indexModel->validate()) {
             $bulk .= $action . "\n" . Json::encode($indexModel->toArray()) . "\n";
         }
     }
     $url = [$index, $type, '_bulk'];
     $response = ActiveRecord::getDb()->post($url, [], $bulk);
     $n = 0;
     $errors = [];
     foreach ($response['items'] as $item) {
         if (isset($item['index']['status']) && ($item['index']['status'] == 201 || $item['index']['status'] == 200)) {
             $n++;
         } else {
             $errors[] = $item['index'];
         }
     }
     if (!empty($errors) || isset($response['errors']) && $response['errors']) {
         throw new Exception(__METHOD__ . ' failed inserting ' . $class . ' model records.', $errors);
     }
     return $n;
 }
 /**
  * @return array
  * @throws InvalidConfigException
  * @throws \yii\base\NotSupportedException
  */
 protected function fetchParamsInfo()
 {
     $items = ModuleEvent::trigger(self::EVENT_FETCH_MODULE_PARAMS, new FetchParamsEvent(['sender' => $this]), 'items');
     $result = [];
     foreach ($items as $item) {
         if (is_string($item)) {
             /** @var \gromver\platform\core\components\ParamsObject $item */
             $result[$item::paramsType()] = ['class' => $item];
         } elseif (is_array($item)) {
             /** @var \gromver\platform\core\components\ParamsObject $class */
             $class = $item['class'];
             $result[$class::paramsType()] = $item;
         } else {
             throw new InvalidConfigException(get_class($this) . '::fetchParamsInfo invalid params configuration.');
         }
     }
     return $result;
 }
 /**
  * Собирает правила маршрутизации со всех маршрутизаторов модулей
  * @throws InvalidConfigException
  */
 protected function buildRules()
 {
     //нам нужно собрать все роутеры от модулей и вытащить из них инструкции по маршрутизации
     $routers = ModuleEvent::trigger(self::EVENT_FETCH_MODULE_ROUTERS, new FetchRoutersEvent(['routers' => [], 'sender' => $this]), 'routers');
     // вытаскиваем инструкции из всех роутеров
     foreach ($routers as $routerClass) {
         $router = $this->getRouter($routerClass);
         foreach ($router->createUrlRules() as $rule) {
             @$rule['class'] or $rule['class'] = MenuRouterUrlRuleCreate::className();
             $rule['router'] = $router->className();
             $this->_createUrlRules[] = Yii::createObject($rule);
         }
         foreach ($router->parseUrlRules() as $rule) {
             @$rule['class'] or $rule['class'] = MenuRouterUrlRuleParse::className();
             $rule['router'] = $router->className();
             $this->_parseUrlRules[] = Yii::createObject($rule);
         }
     }
 }
 protected function launch()
 {
     $query = Index::find();
     if (empty($this->models)) {
         $this->models = array_keys(self::models());
     }
     // ищем только по тем моделям которые в списке
     $this->filters[] = ['terms' => ['model_class' => $this->models]];
     // ивент на модификацию фильтров ($this->filters) сторонними модулями
     foreach ($this->models as $modelClass) {
         ModuleEvent::trigger(self::EVENT_BEFORE_SEARCH, new ElasticBeforeSearchEvent(['modelClass' => $modelClass, 'query' => $query, 'sender' => $this]));
     }
     $query->query = ['filtered' => ['filter' => ['and' => ['filters' => $this->filters]]]];
     if (!empty($this->query)) {
         $query->query['filtered']['query']['multi_match'] = ['query' => $this->query, 'fields' => ['title', 'content', 'tags']];
     }
     $query->highlight = $this->highlight;
     echo $this->render($this->layout, ['dataProvider' => new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $this->pageSize]]), 'itemLayout' => $this->itemLayout]);
 }
 /**
  * @param $event \yii\base\Event
  */
 public function searchDeletePage($event)
 {
     ModuleEvent::trigger(self::EVENT_DELETE_PAGE, new SearchBehaviorEvent(['model' => $this->owner]));
 }
 /**
  * Renders the menu.
  */
 public function run()
 {
     if ($this->route === null && Yii::$app->controller !== null) {
         $this->route = Yii::$app->controller->getRoute();
     }
     if ($this->cache) {
         /** @var Cache $cache */
         $this->cache = Instance::ensure($this->cache, Cache::className());
         $cacheKey = [__CLASS__, $this->items];
         if (($this->items = $this->cache->get($cacheKey)) === false) {
             $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new DesktopEvent(['items' => $this->items]), 'items');
             $this->cache->set($cacheKey, $this->items, $this->cacheDuration, $this->cacheDependency);
         }
     } else {
         $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new DesktopEvent(['items' => $this->items]), 'items');
     }
     $this->normalizeItems();
     $options = $this->options;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     echo Html::tag($tag, $this->renderItems($this->columns), $options);
 }
Exemple #7
0
 /**
  * Renders the menu.
  */
 public function run()
 {
     $event = new MenuItemRoutesEvent(['items' => $this->items]);
     ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, $event);
     $this->items = $event->items;
     $this->normalizeItems();
     $options = $this->options;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     echo Html::tag($tag, $this->renderItems($this->columns), $options);
 }
Exemple #8
0
 /**
  * @return array
  */
 public function getMenuItemLayouts()
 {
     return ModuleEvent::trigger(self::EVENT_MENU_ITEM_LAYOUTS, new MenuItemLayoutsModuleEvent(['items' => $this->_menuItemLayouts]), 'items');
 }
Exemple #9
0
 /**
  * @inheritdoc
  */
 public function deletePage($event)
 {
     $index = Index::find()->where(['model_id' => $event->model->getPrimaryKey(), 'model_class' => $event->model->className()])->one();
     ModuleEvent::trigger(self::EVENT_BEFORE_DELETE_INDEX, new ElasticIndexEvent(['model' => $event->model, 'index' => $index, 'sender' => $this]));
     if ($index) {
         $index->delete();
     }
 }
Exemple #10
0
 public function afterSave($insert, $changedAttributes)
 {
     parent::afterSave($insert, $changedAttributes);
     if (is_array($this->_roles)) {
         ModuleEvent::trigger(self::EVENT_BEFORE_USER_ROLES_SAVE, new BeforeRolesSaveEvent(['sender' => $this]));
         $newRoles = $this->_roles;
         $this->_roles = null;
     } else {
         return;
     }
     $oldRoles = $this->getRoles();
     $toAssign = array_diff($newRoles, $oldRoles);
     $toRevoke = array_diff($oldRoles, $newRoles);
     $auth = Yii::$app->authManager;
     foreach ($toAssign as $role) {
         $auth->assign($auth->getRole($role), $this->id);
     }
     foreach ($toRevoke as $role) {
         $auth->revoke($auth->getRole($role), $this->id);
     }
 }
 protected function launch()
 {
     $query = Index::find();
     $indexTable = Index::tableName();
     if (!empty($this->_words)) {
         $searchWords = Yii::$app->db->quoteValue(implode(' ', $this->_words));
         $query->select(["{$indexTable}.*", 'relevance' => "(MATCH ({$indexTable}.title, {$indexTable}.content) AGAINST ({$searchWords}) + (MATCH ({$indexTable}.tags) AGAINST ({$searchWords}) * 0.3))"])->where("MATCH ({$indexTable}.title, {$indexTable}.content) AGAINST ({$searchWords}) OR MATCH ({$indexTable}.tags) AGAINST ({$searchWords})")->orderBy("relevance DESC");
     } else {
         // empty search
         $query->select("{$indexTable}.*")->orderBy("{$indexTable}.updated_at DESC");
     }
     if (empty($this->models)) {
         $this->models = array_keys(self::models());
     }
     // ищем только по тем моделям которые в списке
     $query->andWhere(['model_class' => $this->models]);
     // ивент на модификацию запроса сторонними модулями
     foreach ($this->models as $modelClass) {
         ModuleEvent::trigger(self::EVENT_BEFORE_SEARCH . $modelClass, new SqlBeforeSearchEvent(['query' => $query, 'sender' => $this]));
     }
     echo $this->render($this->layout, ['dataProvider' => new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $this->pageSize]]), 'itemLayout' => $this->itemLayout]);
 }
 /**
  * @return array
  */
 public static function models()
 {
     return ModuleEvent::trigger(static::EVENT_FETCH_SEARCHABLE_MODELS, new SearchableModelsEvent(['items' => []]), 'items');
 }
 public static function url()
 {
     return ModuleEvent::trigger(static::EVENT_FETCH_ENDPOINTS, new SearchEndpointsEvent(['items' => []]), 'items');
 }
Exemple #14
0
 /**
  * @inheritdoc
  */
 public function afterSave($insert, $changedAttributes)
 {
     parent::afterSave($insert, $changedAttributes);
     // сохраняем/удаляем роли
     if (is_array($this->_roles)) {
         ModuleEvent::trigger(self::EVENT_BEFORE_USER_ROLES_SAVE, new BeforeRolesSaveEvent(['sender' => $this]));
         $newRoles = $this->_roles;
         $this->_roles = null;
         $oldRoles = $this->getRoles();
         $toAssign = array_diff($newRoles, $oldRoles);
         $toRevoke = array_diff($oldRoles, $newRoles);
         $auth = Yii::$app->authManager;
         foreach ($toAssign as $role) {
             $auth->assign($auth->getRole($role), $this->id);
         }
         foreach ($toRevoke as $role) {
             $auth->revoke($auth->getRole($role), $this->id);
         }
     }
     // сохраняем/удаляем параметры пользователя
     $params = $this->params;
     foreach ($params as $name => $param) {
         if (is_null($param->value)) {
             if (!$param->isNewRecord) {
                 // удаляем параметр из БД
                 $param->delete();
             }
         } else {
             $param->user_id = $this->id;
             $param->save();
         }
     }
 }
 /**
  * @inheritdoc
  */
 public function bootstrap($app)
 {
     $app->set($this->id, $this);
     $this->_moduleConfigDependency = new ExpressionDependency(['expression' => '\\Yii::$app->getModulesHash()']);
     DbState::bootstrap();
     Yii::$container->set('gromver\\models\\fields\\EditorField', ['controller' => 'grom/media/manager', 'editorOptions' => ['filebrowserBrowseUrl' => ['/grom/menu/backend/item/ckeditor-select'], 'extraPlugins' => 'codesnippet']]);
     Yii::$container->set('gromver\\models\\fields\\MediaField', ['controller' => 'grom/media/manager']);
     Yii::$container->set('gromver\\modulequery\\ModuleQuery', ['cache' => $app->cache, 'cacheDependency' => $this->_moduleConfigDependency]);
     Yii::$container->set('gromver\\platform\\basic\\components\\MenuMap', ['cache' => $app->cache, 'cacheDependency' => DbState::dependency(MenuItem::tableName())]);
     Yii::$container->set('gromver\\platform\\basic\\components\\MenuUrlRule', ['cache' => $app->cache, 'cacheDependency' => $this->_moduleConfigDependency]);
     Yii::$container->set('gromver\\platform\\basic\\modules\\main\\widgets\\Desktop', ['cache' => $app->cache, 'cacheDependency' => $this->_moduleConfigDependency]);
     /** @var MenuManager $manager */
     $rules['auth'] = 'grom/auth/default/login';
     $rules['admin'] = 'grom/backend/default/index';
     if (is_array($this->blockedUrlRules) && count($this->blockedUrlRules)) {
         foreach ($this->blockedUrlRules as $rule) {
             $rules[$rule] = 'grom/default/page-not-found';
             //блокируем доступ напрямую
         }
     }
     $app->urlManager->addRules($rules, false);
     //вставляем в начало списка
     $app->set('menuManager', \Yii::createObject(MenuManager::className()));
     // пропускаем \gromver\models\fields\events\ListItemsEvent событие, через ModuleEvent - не факт, что нужно, но почему бы и нет
     Event::on('\\gromver\\models\\fields\\ListField', 'fetchItems', function ($event) {
         /** @var $event \gromver\models\fields\events\ListItemsEvent */
         ModuleEvent::trigger(self::EVENT_FETCH_LIST_ITEMS, new ListItemsModuleEvent(['sender' => $event]));
     });
     ModuleQuery::instance()->implement('\\gromver\\platform\\common\\interfaces\\BootstrapInterface')->invoke('bootstrap', [$app]);
 }