public function run() { $voting = null; if (is_numeric(HU::post('id_voting'))) { $voting = Voting::model()->onlyActive()->with('answer')->findByPk(HU::post('id_voting')); } if ($voting == null) { //echo CHtml::encode($this->controller->widget('vote.widgets.VoteWidget', null, true)); return; } if (Yii::app()->vote->check($voting->id_voting)) { $answers = $_POST['VotingAnswer']['name']; $cr = new CDbCriteria(); $cr->addColumnCondition(array('id_voting' => $voting->id_voting)); if (is_array($answers)) { $cr->addInCondition('id_voting_answer', $answers); } else { if (is_numeric($answers)) { $cr->addColumnCondition(array('id_voting_answer' => $answers)); } } VotingAnswer::model()->updateCounters(array('count' => 1), $cr); VisitSite::saveCurrentVisit(Voting::ID_OBJECT, $voting->id_voting); Yii::app()->user->setState('vote_' . $voting->id_voting, time()); // перегружаем голосовалку, чтоб обновились показатели счетчиков $voting = Voting::model()->onlyActive()->with('answer')->findByPk($voting->id_voting); } $voteCount = $voting->getSumVote(); echo CHtml::encode($this->controller->renderPartial("vote.widgets.views.statistic", array('voting' => $voting, 'voteCount' => $voteCount)), null, true); }
public function init() { parent::init(); if ($this->isNewRecord) { $this->ip = HU::getUserIp(); } }
/** * Добавление лога в произвольный файл * Фиксируется время, ip, логин в системе * @param string $fileName абсолютный пусть и имя файла лога * @param string $str строка для записи * @param integer $flag оставлен для совместимости TODO */ public static function loging($fileName, $str, $flag = 1, $rn = false) { $exists = true; if (!file_exists($fileName)) { $exists = false; } if ($fp = fopen($fileName, "a")) { //OK. Work with file $s = date("Y.m.d H:i:s") . " ip:" . HU::getUserIp() . ' '; if (Yii::app()->hasModule('user') && !Yii::app()->user->isGuest) { $s .= Yii::app()->user->name; } else { $s .= 'guest'; } $s .= " " . $str . "\r\n"; if ($rn) { $s = "\r\n" . $s; } fwrite($fp, $s); fclose($fp); } if (!$exists) { chmod($fileName, 0777); } }
public function actionIndex() { $model = new ExportForm(); $modelClass = get_class($model); $this->performAjaxValidation($model); if (isset($_POST[$modelClass])) { //HU::dump($_POST);exit; $model->setAttributes($_POST[$modelClass], false); $valid = true; foreach ($_POST[$modelClass] as $i => $item) { if (isset($_POST[$modelClass][$i]) && is_array($_POST[$modelClass][$i])) { $model->checkAttributes[] = $item['checkAttributes']; $model->newObjectParameters[] = $item['newObjectParameters']; $model->objectParameters[] = $item['objectParameters']; } $valid = $model->validate() && $valid; } if ($model->validate() && $valid) { $sqlDump = $model->getDump(); echo $sqlDump; Yii::app()->end(); } else { HU::dump($model->errors); exit; } } $objects = DaObject::model()->findAll(array('condition' => 'table_name IS NOT NULL', 'order' => 'name ASC')); $this->render('index', array('model' => $model, 'objects' => $objects)); }
public function processModel(CEvent $event) { $model = $this->model; $idInstance = $model->getIdInstance(); // Удаляем все модули для данного шаблона SiteModulePlace::model()->resetScope()->deleteAllByAttributes(array('id_module_template' => $idInstance)); // Получаем все модули $modules = $this->modules; foreach ($modules as $m) { $idModule = $m->getIdInstance(); $placePos = HU::post("mod_" . $idModule . "_plc"); $seq = HU::post("mod_" . $idModule . "_seq"); if (!$placePos || $placePos == "onVisible") { continue; } if (!is_numeric($seq)) { $seq = 0; } $place = new SiteModulePlace(); $place->id_module = $idModule; $place->id_module_template = $idInstance; $place->place = $placePos; $place->sequence = $seq; $place->save(); } }
public function afterSave($event) { $className = get_class(VotingAnswer::model()); $postAnswers = HU::post($className, array()); foreach ($this->answers as $answer) { /** * @var $answer VotingAnswer */ if (isset($postAnswers[$answer->id_voting_answer]['name']) && trim($postAnswers[$answer->id_voting_answer]['name']) != '') { $answer->name = trim($postAnswers[$answer->id_voting_answer]['name']); $answer->update(array('name')); } else { $answer->delete(); } } foreach ($postAnswers as $i => $name) { if ($i > 0) { continue; } if (trim($name['name']) == '') { continue; } $answer = BaseActiveRecord::newModel($className, 'backendInsert'); $answer->id_voting = $this->model->id_voting; $answer->name = trim($name['name']); $answer->save(); } }
public function onParameterAvailable(ParameterAvailableEvent $event) { parent::onParameterAvailable($event); if ($event->status == ViewController::ENTITY_STATUS_NOT_VISIBLE) { return; } $param = $event->objectParameter; $name = $param->getFieldName(); if ($name == 'id_php_script') { /** * @var $instance SiteModule */ $instance = $event->model; // Определяем тип создаваемого/редактируемого раздела $static = true; if (!$instance->isNewRecord) { if ($instance->id_php_script != null) { $static = false; } } else { if (HU::get(ObjectUrlRule::PARAM_SYSTEM_MODULE) != null) { $static = false; } } if ($static) { $event->status = ViewController::ENTITY_STATUS_NOT_VISIBLE; } } }
public function onBeforeGrid(BeforeGridEvent $event) { if (isset(Yii::app()->controller->buttons)) { if (Yii::app()->authManager->canCreateInstance($this->idObject, Yii::app()->user->id)) { Yii::app()->controller->buttons = CMap::mergeArray(Yii::app()->controller->buttons, array(array('caption' => '<i class="glyphicon glyphicon-list icon-white"></i> Пакетная загрузка', 'url' => Yii::app()->createUrl('photogallery/backendPhotogallery/index', array('objectId' => HU::get(PhotogalleryPhoto::URL_PARAM_OBJECT), 'instanceId' => HU::get(PhotogalleryPhoto::URL_PARAM_INSTANCE))), 'class' => 'btn-success'))); } } }
public function init() { parent::init(); if ($this->isNewRecord) { $this->create_date = time(); $this->ip = HU::getUserIp(); } }
public static function saveCurrentVisit($idObject, $idInstance, $type = 1) { $vs = new VisitSite(); $vs->id_object = $idObject; $vs->id_instance = $idInstance; $vs->type_visit = $type; $vs->ip = ip2long(HU::getUserIp()); $vs->date = time(); $vs->save(); }
public function init() { parent::init(); if ($this->isNewRecord) { $this->create_date = time(); $this->ip = HU::getUserIp(); $this->is_send = 0; $this->status = self::STATUS_NEW; } }
protected function beforeSave() { if (HU::get(self::URL_PARAM_OBJECT) != null) { $this->id_photogallery_object = HU::get(self::URL_PARAM_OBJECT); } if (HU::get(self::URL_PARAM_INSTANCE) != null) { $this->id_photogallery_instance = HU::get(self::URL_PARAM_INSTANCE); } return parent::beforeSave(); }
public function onProcessPermissionWhere(PermissionWhereEvent $event) { if ($idObject = intval(HU::get(self::URL_PARAM_OBJECT))) { $event->criteria->addCondition('id_object = :id_object_comment'); $event->criteria->params[':id_object_comment'] = $idObject; } if ($idInstance = intval(HU::get(self::URL_PARAM_INSTANCE))) { $event->criteria->addCondition('id_instance = :id_instance_comment'); $event->criteria->params[':id_instance_comment'] = $idInstance; } }
public function onProcessPermissionWhere(PermissionWhereEvent $event) { $idObject = intval(HU::get(self::URL_PARAM_OBJECT)); $idInstance = intval(HU::get(self::URL_PARAM_INSTANCE)); $where = $event->where; if ($idObject && $idInstance) { $where = HText::addCondition($where, 'id_object = :id_object_banner AND id_instance = :id_instance_banner'); $event->params[':id_object_banner'] = $idObject; $event->params[':id_instance_banner'] = $idInstance; } $event->where = $where; }
public function processModel(CEvent $event) { $phpScript = $this->phpScript; $phpScriptType = $phpScript->phpScript; $paramsConfig = $phpScriptType->getParametersConfig(); $key = $this->getElementName(); foreach ($paramsConfig as $name => $config) { $val = HU::post($key . '_' . $name); $phpScript->setParameterValue($name, $val); } $phpScript->save(); $this->model->{$this->attributeName} = $phpScript->id_php_script; }
public function check($idVote) { if ($this->checkByCookie) { $t = Yii::app()->user->getState('vote_' . $idVote); if ($t != null && is_numeric($t) && $t + $this->expiredTimout * 3600 > time()) { return false; } } if ($this->checkByIp) { $ip = HU::getUserIp(); return VisitSite::check(Voting::ID_OBJECT, $idVote, 1, $ip, $this->expiredTimout * 3600, $this->numVoteIp); } return true; }
public function processModel(CEvent $event) { $roles = HU::post('roles', array()); foreach ($this->currentRoles as $role) { if (!in_array($role, $roles)) { Yii::app()->authManager->revoke($role, $this->model->id_user); } } foreach ($roles as $role) { if (!in_array($role, $this->currentRoles)) { Yii::app()->authManager->assign($role, $this->model->id_user); } } }
public function onProcessPermissionWhere(PermissionWhereEvent $event) { //Формирование условия отбора $pkey = HU::get(ObjectUrlRule::PARAM_OBJECT_PARENT); $where = $event->where; if ($pkey == "") { //$where .= "id_object IS NULL OR id_object IN(SELECT id_object FROM da_object WHERE object_type<>".DA_OBJECT_TYPE_HEIR.")"; $where = HText::addCondition($where, "id_module_parent IS NULL"); } else { //$where .= "id_object IN(SELECT id_object FROM da_object WHERE object_type=".DA_OBJECT_TYPE_HEIR." AND table_name=$pkey)"; $where = HText::addCondition($where, "id_module_parent=" . $pkey); } $event->where = $where; }
public function processModel(CEvent $event) { $postData = HU::post($this->getElementName(), array()); $selectedData = $this->getSelectedData(); foreach ($selectedData as $id => $name) { if (!in_array($id, $postData)) { Yii::app()->db->createCommand()->delete($this->many2manyTable, $this->relationField . '=:relField AND ' . $this->secondaryField . '=:secField', array(':relField' => $this->model->getIdInstance(), ':secField' => $id)); } } foreach ($postData as $key => $id) { if (!isset($selectedData[$id])) { Yii::app()->db->createCommand()->insert($this->many2manyTable, array($this->relationField => $this->model->getIdInstance(), $this->secondaryField => $id)); } } }
public function createInstance(CEvent $event) { $objectId = HU::get('ownerObjectId'); $instanceId = HU::get('ownerInstanceId'); if (!($objectId && $instanceId)) { throw new CHttpException(400, 'Bad request.'); } $formModel = $event->sender->getFormModel(); $ownerModel = $this->loadOwnerObjectModel($objectId, $instanceId); $photo = new PhotogalleryPhoto('backendInsert'); $photo->id_photogallery_object = $ownerModel->getIdObject(); $photo->id_photogallery_instance = $ownerModel->getIdInstance(); $photo->save(false); $formModel->instanceId = $photo->id_photogallery_photo; $formModel->objectId = $photo->getIdObject(); $formModel->tmpId = null; }
public function processModel(CEvent $event) { /** * @var $model DaObject */ $model = $this->model; $idObject = $model->getIdInstance(); $idView = null; if (HU::post("create_rep") == 1) { //Создать представление с введённым именем $name = trim(HU::post("create_rep_name")); $view = null; if ($name != "") { $view = new DaObjectView(); $id = $idObject . '-view-main'; while (DaObjectView::model()->exists('id_object_view=:id', array(':id' => $id))) { $id = $idObject . '-view-view' . rand(1, 100); } $view->id_object_view = $id; $view->name = $name; $view->id_object = $idObject; $parent = $model->getFieldByType(DataType::ID_PARENT); if ($parent != null) { $view->id_parent = $parent; } //Сортировка $view->sql_order_by = $model->getOrderBy(); $view->save(); $idView = $view->getIdInstance(); } } $columnsForm = HU::post('column'); if (count($columnsForm)) { if (is_null($idView)) { //Свойства стоят, представления нет, приписываем имеющемуся //Если у объекта есть единственное представление, приписываем отмеченные галочки ему $view = DaObjectView::model()->findAll('id_object=:id', array(':id' => $idObject)); if (count($view) != 1) { return; } $idView = $view[0]->getIdInstance(); } //Уже приписанные представлению колонки $already = array(); $columns = DaObjectViewColumn::model()->findAll('id_object_view=:id', array(':id' => $idView)); foreach ($columns as $c) { $already[] = $c->id_object_parameter; } foreach ($columnsForm as $col) { if (in_array($col, $already)) { continue; } $p = $model->getParameterObjectByIdParameter($col); if ($p == null) { continue; } $column = new DaObjectViewColumn(); $column->id_object_view_column = $idView . '-' . str_replace('_', '-', $p->getFieldName()); $column->id_object_view = $idView; $column->id_object = $idObject; $column->id_object_parameter = $p->getIdParameter(); $column->caption = $p->getCaption(); $column->id_data_type = $p->getType(); $column->field_name = $p->getFieldName(); $column->save(); } } }
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 actionAutocomplete() { $query = HU::post('query'); $idObject = HU::post('idObject'); $object = DaObject::getById($idObject); $idCaptionField = $object == null ? null : $object->id_field_caption; if ($idCaptionField == null) { return json_encode(array()); } $parameter = $object->getParameterObjectByIdParameter($idCaptionField); $captionField = $parameter->getFieldName(); $where = $captionField . ' LIKE :q'; $data = $object->getModel()->findAll(array('condition' => $where, 'params' => array(':q' => $query . '%'), 'limit' => 10)); $result = array(); foreach ($data as $instance) { /** * @var $instance DaActiveRecord */ array_push($result, array("label" => $instance->getInstanceCaption(), "value" => $instance->getIdInstance())); } echo json_encode($result); }
public function processModel(CEvent $event) { $permissionsNew = HU::post('setPermission') == null ? array() : HU::post('setPermission'); $idObject = $this->model->getIdInstance(); $oldIdObject = $this->model->getPkBeforeSave(); $roles = Yii::app()->authManager->getAuthItems(CAuthItem::TYPE_ROLE); if ($idObject != $oldIdObject) { $items = Yii::app()->authManager->getAuthItemByIdObject($oldIdObject); foreach ($items as $name => $item) { Yii::app()->authManager->removeAuthItem($name); } } $permissionsOld = array(); if ($idObject != '') { $permissions = array(DaDbAuthManager::OPERATION_VIEW => 'просмотра', DaDbAuthManager::OPERATION_EDIT => 'изменения', DaDbAuthManager::OPERATION_DELETE => 'удаления', DaDbAuthManager::OPERATION_CREATE => 'создания'); foreach ($roles as $roleName => $role) { /** * @var CAuthItem $role */ foreach ($permissions as $permId => $perm) { $op = Yii::app()->authManager->getAuthItemObject($permId, $idObject); if ($op != null && Yii::app()->authManager->hasItemChild($roleName, $op->getName())) { $permissionsOld[] = $roleName . '-' . $permId; } } } } $object = DaObject::getById($idObject); $createPermissions = array_diff($permissionsNew, $permissionsOld); foreach ($createPermissions as $info) { list($roleName, $action) = explode('-', $info); if (!isset($permissions[$action])) { continue; } $op = Yii::app()->authManager->getAuthItemObject($action, $idObject); if ($op == null) { $op = Yii::app()->authManager->createOperationForObject($action, $idObject, 'Операция ' . $permissions[$action] . ' для объекта ' . $object->getName()); } $role = Yii::app()->authManager->getAuthItem($roleName); if (!Yii::app()->authManager->hasItemChild($role->getName(), $op->getName())) { $role->addChild($op->getName()); } } $deletePermissions = array_diff($permissionsOld, $permissionsNew); foreach ($deletePermissions as $info) { list($roleName, $action) = explode('-', $info); if (!isset($permissions[$action])) { continue; } $op = Yii::app()->authManager->getAuthItemObject($action, $idObject); if ($op == null) { continue; } Yii::app()->authManager->removeItemChild($roleName, $op->getName()); } // права на общий доступ работы с объектом (доступ к объекту в общем меню) foreach ($roles as $roleName => $role) { /** * @var CAuthItem $role */ $exists = false; foreach ($permissions as $permId => $perm) { $op = Yii::app()->authManager->getAuthItemObject($permId, $idObject); if ($op != null && Yii::app()->authManager->hasItemChild($roleName, $op->getName())) { $exists = true; break; } } $op = Yii::app()->authManager->getAuthItemObject(DaDbAuthManager::OPERATION_LIST, $idObject); if ($exists) { // создаем if ($op == null) { $op = Yii::app()->authManager->createOperationForObject(DaDbAuthManager::OPERATION_LIST, $idObject, 'Просмотр списка данных объекта ' . $object->getName()); } if (!Yii::app()->authManager->hasItemChild($role->getName(), $op->getName())) { $role->addChild($op->getName()); } } else { if ($op != null && !$exists) { // удаляем if (Yii::app()->authManager->hasItemChild($role->getName(), $op->getName())) { Yii::app()->authManager->removeItemChild($roleName, $op->getName()); } } } } }
public function init() { parent::init(); $this->ask_date = time(); $this->ip = HU::getUserIp(); }
protected function formatLogMessage($message, $level, $category, $time) { $user = Yii::app()->user; $userName = $user == null ? 'guest' : $user->name; return parent::formatLogMessage('[' . HU::getUserIp() . '] ' . $userName . ' ' . $message, $level, $category, $time); }
/** * Рекурсивное удаление файлов и папок * * @param string Путь к директории, которую надо удалить * @param boolean Удалять ли директорию $dir в конце * @param boolean Вести лог при работе функции * @return boolean */ public static function removeDirectoryRecursive($dir, $removeSelf = true, $log = false, $errorEnable = true, $excludeFiles = array()) { if ($dir == null) { return false; } // если кто-то вызовет метод с пустым значением, то метод затерет все данные на диске $dir = self::addSlashPath($dir); if (strpos(self::normalizePath($dir), self::normalizePath(realpath(Yii::getPathOfAlias('webroot')))) === false) { // и ещё защита, чтоб случано не удалили файлы, которые расположены выше корня сайта return false; } if (!($handle = opendir($dir))) { if ($log) { HU::log_da('Не удалось открыть дирикторию (' . $dir . ')'); } return false; } while ($entry = readdir($handle)) { if ($entry == ".." || $entry == ".") { continue; } if (is_dir($dir . $entry)) { self::removeDirectoryRecursive($dir . $entry, true, $log); } else { if (in_array($entry, $excludeFiles) || in_array($dir . $entry, $excludeFiles)) { continue; } if (!unlink($dir . $entry)) { if ($log) { HU::log_da('Не удалось удалить файл (' . $dir . $entry . ')'); } } } } closedir($handle); if ($removeSelf) { if ($errorEnable && !rmdir($dir) || !$errorEnable && !@rmdir($dir)) { if ($log) { HU::log_da('Не удалось удалить дирикторию (' . $dir . ')'); } return false; } } return true; }
$table .= '<thead><tr>'; foreach ($row as $k => $v) { $table .= '<th>' . $k . '</th>'; } $table .= '</tr></thead><tbody>'; } $table .= '<tr>'; foreach ($row as $k => $v) { $table .= '<td>' . $v . '</td>'; } $table .= '</tr>'; } $table .= '</tbody></table>'; echo $table; } else { $_POST['sql'] = str_replace("\r", '', HU::post('sql')); $delimiter = ';'; if (preg_match('~\\ndelimiter(.*)\\n~iUs', $_POST['sql'], $reg)) { $delimiter = trim($reg[1]); $_POST['sql'] = preg_replace('~\\ndelimiter(.*)\\n~iUs', "\n", $_POST['sql']); } $_POST['sql'] = preg_replace('~--.*\\n~iUs', "\n", $_POST['sql']); $sqlArray = explode("{$delimiter}\n", $_POST['sql']); $errors = array(); $affected = 0; foreach ($sqlArray as $k => $sqlQuery) { if (trim($sqlQuery) == null) { unset($sqlArray[$k]); continue; } $affected += Yii::app()->db->createCommand($sqlQuery)->execute();
public function getFormValue() { return HU::postModelAttr($this->model, $this->attributeName); }
} else { if (HU::get("mode") == "3") { $allFiles = File::model()->findAll('id_parent_file IS NULL AND id_file_type=' . File::FILE_IMAGE); $c = 0; foreach ($allFiles as $file) { if ($file->resizeImage()) { $c++; if ($fileResultStr2 == "") { $fileResultStr2 .= "<br>Были обработаны следующие картинки: <br>"; } $fileResultStr2 .= $file->getUrlPath() . "<br>"; } } Yii::app()->clientScript->registerScript('admin.special.cacheClear.yii', 'alert("Процедура завершена, обработано изображений: ' . $c . '");'); } else { if (HU::get("mode") == "4") { $path = Yii::app()->assetManager->basePath; HFile::removeDirectoryRecursive($path, false, false, false, array('.gitignore')); Yii::app()->request->redirect('/admin/page/89/'); } } } } $countImage = File::model()->count('id_parent_file IS NULL AND id_file_type=' . File::FILE_IMAGE); ?> <fieldset class="form-horizontal"> <legend>Служебные файлы (кэш и превью)</legend> <div class="form-group"> <label class="control-label col-lg-4">Кэш стилей и js-файлов</label> <div class="controls col-lg-8">