示例#1
0
 public function actionIndex()
 {
     /**
      * @var DaActiveRecord $model
      * @var DaObject $object
      */
     $object = Yii::app()->backend->object;
     $idObject = $object->id_object;
     $model = null;
     $id_v = HU::get(ObjectUrlRule::PARAM_ACTION_VIEW);
     $id = HU::post('id_instance');
     if ($id == null) {
         $id = HU::get(ObjectUrlRule::PARAM_OBJECT_INSTANCE);
     }
     if ($id == null && $id_v == null) {
         throw new CHttpException(400, 'Bad Request');
     }
     $statusProcess = intval(HU::post('submit_form', ViewController::MODE_VIEW));
     if (!in_array($statusProcess, array(ViewController::MODE_VIEW, ViewController::MODE_SAVE_AND_CLOSE, ViewController::MODE_ACCEPT, ViewController::MODE_SAVE_AND_CREATE_NEW))) {
         throw new CHttpException(400, 'Bad Request');
     }
     $readOnlyInstance = false;
     if ($id != null) {
         if ($id == -1) {
             if (!Yii::app()->authManager->canCreateInstance($idObject, Yii::app()->user->id)) {
                 throw new CHttpException(403, 'Нет прав на создание');
             }
             $id = null;
         } else {
             // Редактируют, проверяем доступность текущему пользователю
             if (!Yii::app()->authManager->checkObjectInstance(DaDbAuthManager::OPERATION_EDIT, Yii::app()->user->id, $idObject, $id)) {
                 throw new CHttpException(403, 'Нет прав на редактирование или объект не существует');
             }
         }
     } else {
         if ($id_v != null) {
             if ($id_v == -1) {
                 throw new CHttpException(403);
             } else {
                 if (!Yii::app()->authManager->checkObjectInstance(DaDbAuthManager::OPERATION_VIEW, Yii::app()->user->id, $idObject, $id_v)) {
                     throw new CHttpException(403, "Нет прав на просмотр");
                 }
                 $id = $id_v;
                 $readOnlyInstance = true;
             }
         }
     }
     if ($id != null) {
         $model = $object->getModel()->findByIdInstance($id);
         if ($model == null) {
             throw new CHttpException(404);
         }
         $model->setScenario('backendUpdate');
     } else {
         $model = $object->getModel(true);
         $model->setIsNewRecord(true);
         $model->setScenario('backendInsert');
     }
     $visualElementArray = array();
     $event = new InstanceAvailableEvent($this, $model);
     $this->raiseEvent(ViewController::EVENT_ON_INSTANCE_AVAILABLE, $event);
     $available = $event->status;
     if ($available == ViewController::ENTITY_STATUS_NOT_VISIBLE) {
         //Если нет прав на просмотр, то уходим
         return;
         // TODO
     }
     if ($available == ViewController::ENTITY_STATUS_READ_ONLY) {
         $readOnlyInstance = true;
     }
     $parameters = $object->parameters;
     foreach ($parameters as $objectParameter) {
         /**
          * @var $objectParameter ObjectParameter
          */
         // Детальная обработка:
         // Если свойство является группирующем, то устанавливаем значение по умолчанию
         if ($model->isNewRecord && HU::get(ObjectUrlRule::PARAM_GROUP_PARAMETER) == $objectParameter->getIdParameter()) {
             $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_GROUP_INSTANCE);
         }
         // Установка значений свойств экземпляра по умолчанию
         if ($objectParameter->getType() == DataType::SEQUENCE) {
             if ($model->isNewRecord) {
                 $model->{$objectParameter->getFieldName()} = 0;
             }
         } else {
             if ($objectParameter->getType() == DataType::ID_PARENT) {
                 if ($model->isNewRecord) {
                     // TODO - сделать проверку, что пользователь может создавать раздел в переданном ИД паренте
                     $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_OBJECT_PARENT);
                 }
                 if ($objectParameter->getAdditionalParameter() != 1) {
                     continue;
                 }
             }
         }
         if (!$objectParameter->isVisible()) {
             continue;
         }
         $event = new ParameterAvailableEvent($this, $model, $objectParameter);
         $this->raiseEvent(ViewController::EVENT_ON_PARAMETER_AVAILABLE, $event);
         $availableStatus = $event->status;
         if ($availableStatus == ViewController::ENTITY_STATUS_NOT_VISIBLE) {
             //Невидим
             continue;
         }
         $event = new CreateVisualElementEvent($this, $model, $objectParameter);
         $this->raiseEvent(ViewController::EVENT_ON_CREATE_VISUAL_ELEMENT, $event);
         $visualElement = $event->visualElement;
         // Если свойство является группирующем, то пропускаем его.
         /*if ($visualElement == null && HU::get(ObjectUrlRule::PARAM_GROUP_PARAMETER) == $objectParameter->getIdParameter()) {
                 $visualElement = Yii::app()->controller->createWidget('backend.widgets.hiddenField.HiddenFieldWidget', array(
                   'model' => $model,
                   'attributeName' => $objectParameter->getFieldName(),
                 ));
         
                 $visualElementArray[] = $visualElement;
                 $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_GROUP_INSTANCE);
                 continue;
               }*/
         if ($visualElement == null) {
             $visualElement = VisualElementFactory::getVisualElement($model, $objectParameter);
         }
         if ($visualElement == null) {
             continue;
         }
         if ($availableStatus == ViewController::ENTITY_STATUS_READ_ONLY || $readOnlyInstance) {
             //Только для чтения
             $visualElement->setReadOnly(true);
         }
         if ($objectParameter->getFieldName() != null && $model instanceof DaInstance && $visualElement instanceof VisualElementBaseWidget) {
             $model->addValidator(CValidator::createValidator('safe', $model, $objectParameter->getFieldName()));
         }
         $visualElementArray[] = $visualElement;
     }
     // закончили обрабатывать свойства
     $modelClass = get_class($model);
     if (isset($_POST[$modelClass]) || isset($_POST['submit_form'])) {
         if (isset($_POST[$modelClass])) {
             $model->attributes = $_POST[$modelClass];
         }
         $event = new PostFormEvent($this, $model);
         $this->raiseEvent(ViewController::EVENT_ON_POST_FORM, $event);
         Yii::import('ygin.modules.search.components.SearchComponent', true);
         if ($model->isNewRecord) {
             // insert
             if ($model->save()) {
                 SearchComponent::replaceIndex($model);
                 //$instance->updateObjectInstanceInfo(1);
                 $newIdInstance = $model->getIdInstance(false);
                 $seqKey = $object->getFieldByType(DataType::SEQUENCE);
                 if ($seqKey != null) {
                     $pk = $object->getFieldByType(DataType::PRIMARY_KEY);
                     $max = Yii::app()->db->createCommand('SELECT MAX(' . $seqKey . ') FROM ' . $object->table_name)->queryScalar();
                     $sql = 'UPDATE ' . $object->table_name . ' SET ' . $seqKey . ' = :max WHERE ' . $pk . '=:id';
                     Yii::app()->db->createCommand($sql)->execute(array(':max' => $max + 1, ':id' => $newIdInstance));
                 }
                 Yii::log('Добавлен новый экземпляр (' . $object->getName() . ') id=' . $newIdInstance, CLogger::LEVEL_INFO, 'backend.model.insert');
             } else {
                 $statusProcess = ViewController::MODE_ERROR;
             }
         } else {
             if ($model->save()) {
                 SearchComponent::replaceIndex($model);
                 //$instance->updateObjectInstanceInfo(2);
                 Yii::log('Изменение (' . $object->getName() . ') id=' . $model->getIdInstance(), CLogger::LEVEL_INFO, 'backend.model.update');
             } else {
                 $statusProcess = ViewController::MODE_ERROR;
             }
         }
     }
     if ($statusProcess == ViewController::MODE_ERROR || $statusProcess == ViewController::MODE_VIEW) {
         $this->render('/view', array('model' => $model, 'visualElementArray' => $visualElementArray));
     } else {
         if ($statusProcess == ViewController::MODE_ACCEPT) {
             $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_VIEW, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => $model->getIdInstance()));
             $this->redirect($url);
         } else {
             if ($statusProcess == ViewController::MODE_SAVE_AND_CLOSE) {
                 $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(), array(ObjectUrlRule::PARAM_OBJECT_INSTANCE, ObjectUrlRule::PARAM_ACTION_VIEW));
                 $this->redirect($url);
             } else {
                 if ($statusProcess == ViewController::MODE_SAVE_AND_CREATE_NEW) {
                     $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_VIEW, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => -1));
                     $this->redirect($url);
                 }
             }
         }
     }
 }
 public function actionRun()
 {
     $iv = new Interviews();
     $iv->owner = Yii::app()->user->id;
     $iv->name = Yii::app()->getRequest()->getPost('name');
     $iv->title = Yii::app()->getRequest()->getPost('title');
     $iv->status = 1;
     $qs = Yii::app()->getRequest()->getPost('q');
     $answs = Yii::app()->getRequest()->getPost('a');
     $quests = array();
     foreach ($qs as $k => $v) {
         $cq = array();
         $cq['question'] = $v;
         foreach ($answs[$k] as $kk => $vv) {
             $cq['answs'][] = $vv;
         }
         array_push($quests, $cq);
     }
     $iv->questions = json_encode($quests);
     $targ = array();
     $targ['country'] = intVal(trim(Yii::app()->getRequest()->getPost('country_id', 0)));
     $targ['cities'] = Yii::app()->getRequest()->getPost('city', array());
     if (!is_array($targ['cities'])) {
         $targ['cities'] = array();
     }
     $targ['gender'] = intVal(Yii::app()->getRequest()->getPost('gender', -1));
     $targ['family_state'] = Yii::app()->getRequest()->getPost('fs', array());
     if (!is_array($targ['family_state'])) {
         $targ['family_state'] = array();
     }
     $targ['age_from'] = intVal(Yii::app()->getRequest()->getPost('age_from', 0));
     $targ['age_to'] = intVal(Yii::app()->getRequest()->getPost('age_to', 0));
     $targ['school'] = trim(Yii::app()->getRequest()->getPost('school', ''));
     $targ['class'] = trim(Yii::app()->getRequest()->getPost('class', ''));
     $targ['schoolyear'] = intVal(Yii::app()->getRequest()->getPost('schoolyear', 0));
     $targ['uni'] = trim(Yii::app()->getRequest()->getPost('uni', ''));
     $targ['fac'] = trim(Yii::app()->getRequest()->getPost('fac', ''));
     $targ['uniyear'] = intVal(Yii::app()->getRequest()->getPost('uniyear', 0));
     $targ['workplace'] = trim(Yii::app()->getRequest()->getPost('workplace', ''));
     $targ['workstate'] = trim(Yii::app()->getRequest()->getPost('workstate', ''));
     $iv->targeting = json_encode($targ);
     $iv->price = intVal(Yii::app()->getRequest()->getPost('cost', 0));
     $iv->limit = intVal(Yii::app()->getRequest()->getPost('limit', 0));
     $iv->spent = 0;
     $iv->crt = 0;
     $iv->shows = 0;
     $iv->activity_log = json_encode(array('' . time() => 'create', '' . time() => 'start'));
     if ($iv->is_exist()) {
         $name = $iv->name . '_';
         $i = -1;
         do {
             $i++;
             $iv->name = $name . $i;
         } while ($iv->is_exist());
     }
     //YiiBase::trace($iv->name);
     $success = $iv->save();
     foreach ($quests as $k => $v) {
         $qqq = new InterviewQuestions();
         $qqq->interview_id = $iv->primaryKey;
         $qqq->question = $k;
         $qqq->question_text = $v['question'];
         $qqq->answers = json_encode($v['answs']);
         if (!$qqq->save()) {
             $errs = $qqq->getErrors();
             foreach ($errs as $ev) {
                 foreach ($ev as $evv) {
                     YiiBase::trace($evv);
                 }
             }
         }
     }
     $search = new SearchComponent();
     $udr = $search->targetFinder();
     foreach ($udr as $row) {
         $addon = new AdvertStack();
         $addon->user_id = $row['user_id'];
         $addon->type = 1;
         $addon->content_id = $iv->primaryKey;
         $addon->date_added = time();
         $addon->save();
     }
     if ($success) {
         $this->redirect('//advert/interview/my');
     } else {
         $errs = $iv->getErrors();
         foreach ($errs as $v) {
             foreach ($v as $vv) {
                 YiiBase::trace($vv);
             }
         }
     }
 }
示例#3
0
<?php

if (HU::get("start") == "1") {
    SearchComponent::recreateIndex();
    echo '<p>Процедура завершена</p>';
} else {
    if (HU::get("start") == "2") {
        Yii::app()->db->createCommand('REPAIR TABLE da_search_data')->execute();
        echo '<p>Процедура завершена</p>';
    }
}
?>
<form method="get" submit="">
	<input type="hidden" name="start" value="1">
	<button type="submit" class="btn btn-default">Запустить пересоздание поискового индекса</button>
</form>
<br>
<form method="get" submit="">
	<input type="hidden" name="start" value="2">
	<button type="submit" class="btn btn-default">Починить таблицу da_search_data</button>
</form>
示例#4
0
 public static function replaceData($idObject, $idInstance, $idLang, $data)
 {
     $valueItog = SearchComponent::processValue($data);
     $prs = Yii::app()->db->createCommand()->select('id_object')->from('da_search_data')->where('id_object = :obj AND id_instance = :inst AND id_lang = :lang', array(':obj' => $idObject, ':inst' => $idInstance, ':lang' => $idLang))->queryAll();
     $exists = count($prs) == 1;
     if ($exists) {
         if ($valueItog == "") {
             $sql = 'DELETE FROM da_search_data WHERE id_object = :idObject AND id_instance = :idInstance AND id_lang = :idLang';
             $com = Yii::app()->db->createCommand($sql);
             $com->execute(array(':idObject' => $idObject, ':idInstance' => $idInstance, ':idLang' => $idLang));
         } else {
             $sql = 'UPDATE da_search_data SET value=:value WHERE id_object=:idObject AND id_instance=:idInstance AND id_lang=:idLang';
             $com = Yii::app()->db->createCommand($sql);
             $com->execute(array(':value' => $valueItog, ':idObject' => $idObject, ':idInstance' => $idInstance, ':idLang' => $idLang));
         }
     } else {
         if ($valueItog != "") {
             $sql = 'INSERT INTO da_search_data(id_object, id_instance, id_lang, value) VALUES(:idObject, :idInstance, :idLang, :value)';
             $com = Yii::app()->db->createCommand($sql);
             $com->execute(array(':value' => $valueItog, ':idObject' => $idObject, ':idInstance' => $idInstance, ':idLang' => $idLang));
         }
     }
 }
示例#5
0
 public function actionIndex()
 {
     // объекты, по которым идет поиск
     // SELECT DISTINCT a.id_object, a.name FROM `da_object` a JOIN da_object_parameters b ON a.id_object = b.id_object WHERE b.search =1
     $query = HU::get('query');
     $error = null;
     $searchResult = array();
     $total = 0;
     try {
         $search = new SearchComponent();
         $search->logQuery = true;
         $search->criteria = $this->criteria;
         $paginator = new CPagination();
         $paginator->setPageSize($this->module->pageSize);
         $paginator->validateCurrentPage = false;
         $search->paginator = $paginator;
         $searchMode = SearchComponent::SEARCH_MODE_SOFT;
         if ($this->module->searchModeEnable) {
             $searchMode = HU::get('search_mode', SearchComponent::SEARCH_MODE_SOFT);
         }
         $search->setSearchMode($searchMode);
         $search->setMinQuery($this->module->queryMin);
         $search->setMaxQuery($this->module->queryMax);
         $search->setLenPreviewText($this->module->lengthPreview);
         $search->setHighlightTemplate($this->module->highlight);
         // TODO доработать поиск. Чтоб учитывалось отключение и подключение плагинов
         /*if (!Yii::app()->hasModule('news')) {
             $notSearch[] =
           }*/
         $search->setObjectNotSearchList($this->module->objectNotSearch);
         // объекты, по которым пока не поддерживается работа
         $search->setObjectSearchList($this->module->objectSearchList);
         $searchResult = $search->startSearch($query);
         $total = $search->getTotalResult();
     } catch (ErrorException $e) {
         $error = $e->getMessage();
     }
     $results = array();
     foreach ($searchResult as $cur) {
         $results[$cur->id_object][$cur->id_instance] = $cur->id_instance;
     }
     $menu = Menu::getAll();
     foreach (array_keys($results) as $idObject) {
         $data = array();
         $model = null;
         switch ($idObject) {
             case Menu::ID_OBJECT:
                 foreach ($results[$idObject] as $id) {
                     $item = $menu->getById($id);
                     if ($item != null) {
                         $data[] = $item;
                     }
                 }
                 break;
                 /*        case News::ID_OBJECT:
                           $model = News::model();
                           break;
                         case Product::ID_OBJECT:
                           $model = Product::model();
                           break;
                         case ProductCategory::ID_OBJECT:
                           $model = ProductCategory::model();
                           break;*/
             /*        case News::ID_OBJECT:
                       $model = News::model();
                       break;
                     case Product::ID_OBJECT:
                       $model = Product::model();
                       break;
                     case ProductCategory::ID_OBJECT:
                       $model = ProductCategory::model();
                       break;*/
             default:
                 $object = DaObject::getById($idObject, false);
                 $model = $object->getModel();
                 if (!$model instanceof ISearchable) {
                     throw new Exception("Ошибка поиска данных по объекту " . $idObject . ", обратитесь к разработчикам.");
                 }
         }
         if ($model != null) {
             $cr = new CDbCriteria();
             $cr->addInCondition($model->getPKName(), $results[$idObject]);
             $data = $model->findAll($cr);
         }
         $results[$idObject] = array();
         foreach ($data as $r) {
             $results[$idObject][$r->getPrimaryKey()] = $r;
         }
     }
     foreach ($searchResult as $cur) {
         if (isset($results[$cur->id_object][$cur->id_instance])) {
             $model = $results[$cur->id_object][$cur->id_instance];
             $cur->model = $model;
             $cur->link = $model->getSearchUrl();
             $cur->title = $model->getSearchTitle();
             /*        switch ($cur->id_object) {
                       case Menu::ID_OBJECT:
                         $cur->link = $model->getUrl();
                         $cur->title = $model->name;
                         break;
                       case News::ID_OBJECT:
                         $cur->link = $model->getUrl();
                         $cur->title = $model->title;
                         break;
                       case Product::ID_OBJECT:
                         $cur->link = $model->getUrl();
                         $cur->title = $model->name;
                         break;
                       case ProductCategory::ID_OBJECT:
                         $cur->link = $model->getUrl();
                         $cur->title = 'Группа товаров: '.$model->name;
                         break;
                     }*/
         }
     }
     $this->render('/index', array('query' => $query, 'error' => $error, 'searchResult' => $searchResult, 'total' => $total, 'paginator' => $search->paginator, 'searchMode' => $searchMode));
 }