public function remove() { if (!empty($this->model)) { $keyName = $this->model->primary; $this->model->remove(K_Db_Select::create()->where(array($keyName => $this->data[$keyName]))); } }
public function get($tag, $attr = 'content') { $tag = trim($tag); $attrName = 'widget_' . $attr; if (empty($tag)) { return; } $unlimCache = K_Cache_Manager::get('unlim'); $blockCacheID = 'widget_' . $tag; if ($unlimCache->test($blockCacheID)) { $cacheData = $unlimCache->load($blockCacheID); if (isset($cacheData[$attrName])) { echo $cacheData[$attrName]; } } else { K_Loader::load('widgets', APP_PATH . '/default/model/'); $widgetsTable = new widgetsModel(); $widgetInfo = $widgetsTable->fetchRow(K_Db_Select::create()->where(array('widget_tag' => $tag))->limit(1)); if (count($widgetInfo)) { $unlimCache->save($blockCacheID, $widgetInfo); if (isset($widgetInfo[$attrName])) { echo $widgetInfo[$attrName]; } } } }
protected function roleExistsUpdate(&$text, $fieldName) { $result = $this->fetchRow(K_Db_Select::create()->where(array('and' => array($fieldName => $text, 'not' => array('role_id' => $this->data['role_id']))))); if (count($result)) { $this->errors[$fieldName] = 'Роль с таким названием или ACL key уже есть в системе'; return false; } return true; }
public function indexAction() { $commentModel = new Admin_Model_Comment(); $this->view->comments = $commentModel->fetchAll(K_Db_Select::create()->where(array('comment_status' => 'опубликован'))->order('comment_date DESC')); $capchaText = K_Secur::genCapchaText(); $this->view->capacha64 = K_Secur::genCapcha($capchaText); K_Auth::setUserKey('capchaText', $capchaText); K_Auth::setUserKey('capchaTime', time()); }
protected function ruleExistsUpdate(&$text, $fieldName) { $result = $this->fetchRow(K_Db_Select::create()->where(array('and' => array('tree_rule_role_id' => $this->data['tree_rule_role_id'], 'tree_rule_resource_id' => $this->data['tree_rule_resource_id'], 'tree_rule_privilege_id' => $text, 'not' => array('tree_rule_id' => $this->data['tree_rule_id']))))); if (count($result)) { $this->errors[$fieldName] = 'Доступ с таким сочетанием ресурса и привелегии уже есть в системе'; return false; } return true; }
protected function userExistsUpdate(&$text, $fieldName) { $result = $this->fetchRow(K_Db_Select::create()->where(array('and' => array($fieldName => $text, 'not' => array('user_id' => $this->data['user_id']))))); if (count($result)) { $this->errors[$fieldName] = 'Пользователь с таким email`ом или логином уже зарегестрирован'; return false; } return true; }
protected function blogNotExists(&$text, $fieldName) { $blogModel = new Type_Model_Blog(); $result = $blogModel->fetchRow(K_Db_Select::create()->where(array('type_blog_id' => $text))); if ($result && count($result)) { return true; } $this->errors[$fieldName] = 'NEWS_ID_ERROR'; return false; }
public function delAction() { $userModel = new Admin_Model_User(); $user_id = intval($_POST['delusrid']); $userModel->removeID($user_id); $userRolesModel = new Admin_Model_UserRole(); $userRolesModel->remove(K_Db_Select::create()->where(array('usrol_user_id' => $user_id))); $returnJson = array('error' => false, 'msg' => '<strong>OK:</strong>Пользователь удалён'); $this->putJSON($returnJson); }
protected function userTruePass(&$text, $fieldName) { $oldPassword = md5(md5($text . K_Registry::get('Configure.salt'))); $result = $this->fetchRow(K_Db_Select::create()->where(array($fieldName => $oldPassword))); if (!count($result)) { $this->errors[$fieldName] = 'неправильный действующий пароль'; return false; } return true; }
protected function clientExists(&$text, $fieldName) { $clientModel = new Admin_Model_Client(); $result = $clientModel->fetchRow(K_Db_Select::create()->where(array('client_id' => $text))); if (count($result)) { return true; } $this->errors[$fieldName] = 'Такого клиента не существует'; return false; }
public function delAction() { $roleModel = new Admin_Model_role(); $role_id = $_POST['delroleid']; $roleModel->removeID($role_id); $userRolesModel = new Admin_Model_UserRole(); $userRolesModel->remove(K_Db_Select::create()->where(array('usrol_role_id' => $role_id))); $ruleModel = new Admin_Model_Rule(); $ruleModel->remove(K_Db_Select::create()->where(array('rule_role_id' => $role_id))); $returnJson = array('error' => false, 'msg' => '<strong>OK:</strong>Роль удалёна'); $this->putJSON($returnJson); }
public function loadAction() { $type_form = new Admin_Model_Form(); $form_key = $this->getParam('key'); $form_data = $type_form->fetchRow(K_Db_Select::create()->where("type_form_id={$form_key}")); if ($form_data) { K_Loader::load('formbuilder', APP_PATH . '/plugins'); $form_builder = new Formbuilder(unserialize($form_data['type_form_content'])); $this->putAjax($form_builder->render_json()); } else { $this->putAjax('ERROR'); } }
private function getNews() { $result = array(); $newsTable = new Default_Model_News(); $newsList = $newsTable->find(K_Db_Select::create()->_join('authors', '`news`.`news_author_id` = `authors`.`author_id`', 'inner')->_join('categories', '`news`.`news_category_id` = `categories`.`category_id`', 'inner')->order('news_id ASC')); if (count($newsList)) { foreach ($newsList as $item) { $resultLink = $item->toArray(); $resultLink['news_date'] = date('Y.m.d H:i:s', $resultLink['news_added_time']); $result[] = $resultLink; } } return $result; }
public static function costPerMounth() { self::init(); $client = new Admin_Model_Client(); $orgClientsCountResult = $client->fetchAll(K_Db_Select::create('client_level')->where(array('client_organization' => K_Auth::getUserInfo('organization')))); $orgAdminsCount = 0; $orgUsersCount = 0; foreach ($orgClientsCountResult as $v) { if ($v['client_level'] == 'admin') { $orgAdminsCount++; } else { $orgUsersCount++; } } return $orgAdminsCount * self::$_adminCost + $orgUsersCount * self::$_userCost; }
public function indexAction() { $auth_error = false; //Если авторизован отпровляем в админку if (K_Access::acl()->isAllowed(K_Auth::getRoles(), 'admin')) { K_Request::redirect("/admin"); } if (isset($_POST['btnauth'])) { $login = K_Arr::get($_POST, 'login', false); if ($login and strlen($login) < 100) { $password = K_Arr::get($_POST, 'password', false); if ($password) { $password_hash = md5(md5($password . K_Registry::get('Configure.salt'))); $user_model = new Admin_Model_User(); $user_arr = $user_model->find(K_Db_Select::create()->fields('user_id, user_name, user_login , user_email')->where(array('and' => array('user_login' => $login, "user_password" => $password_hash)))->limit(1)); if (is_array($user_arr) && count($user_arr)) { $user = $user_arr[0]->toArray(); $user_role = new Admin_Model_UserRole(); // находим все роли пользователя $user_roles_arr = $user_role->fetchAssoc('role_acl_key', 'SELECT r.role_acl_key FROM (`users_roles`)inner join `role` as r on usrol_role_id=r.role_id WHERE usrol_user_id = "' . $user['user_id'] . '"'); foreach ($user_roles_arr as $v) { $user_roles[] = $v["role_acl_key"]; } //Загружаем роли в класc авторизации // var_dump ($user); //даже если у пользователя нет ролей даём ему роль guests if (!isset($user_roles)) { $user_roles = array('guests'); } K_Auth::authorize($user, $user_roles); K_Request::redirect("/admin"); } else { $auth_error = true; } } else { $auth_error = true; } } else { $auth_error = true; } } $this->view->error_msg = ''; if ($auth_error) { $this->view->error_msg = "Ошибка авторизации, неверный логин или пароль"; } }
public function urlTest(&$text, $fieldName) { if (mb_strlen($text, 'UTF-8') > 255) { $this->errors[$fieldName] = 'Максимальный размер поля 255 символов'; return false; } if (mb_strlen($text, 'UTF-8') < 2) { $this->errors[$fieldName] = 'Минимальный размер поля 2 символа'; return false; } if (!$this->allowDuplicate) { // test on duplicate $result = $this->fetchRow(K_Db_Select::create()->where(array('url_url' => $text))); if (count($result)) { $this->errors[$fieldName] = 'Найден дубликат поля'; return false; } } return true; }
public function completedFormAction() { $clientFormData = new Admin_Model_ClientFormData(); $clientFormDataKey = $this->getParam('key'); $data = $clientFormData->fetchRow(K_Db_Select::create()->where(array('clientform_data_id' => $clientFormDataKey))); //вытягиваем структуру формы. $formData = Gcontroller::loadclientFormStructure($data['clientform_data_type']); $formStructure = json_decode($formData['form_structure']); $formStructure = K_Tree_Types::objectToArray($formStructure); //выбираем пары имя, label foreach ($formStructure as $v) { if (isset($v['values']['name']) && isset($v['values']['label'])) { $name = $v['values']['name']; $lable = $v['values']['label']; $fields[$name] = $lable; } } if ($data) { $formDataHtml = ''; $fromDataObj = unserialize($data['clientform_data_content']); foreach ($fromDataObj as $k => $v) { if (is_array($v)) { $value = implode(', ', $v); } else { $value = $v; } $formDataHtml .= '<tr><td>' . $fields[$k] . '</td><td>' . $value . '</td></tr>'; } $this->putAjax('<table class="table-skeleton">' . $formDataHtml . '</table>'); } else { $this->putAjax('ERROR'); } }
protected function tagsGUI() { $this->tabs['tags'] = 'Теги'; $tagsOptions = ''; $tagsInputs = ''; $tags = K_TreeQuery::crt('/blogtags/')->type('blogtag')->go(); $blogTagsMode = new Admin_Model_BlogTag(); $blogTags = $blogTagsMode->fetchAssoc('bt_tag_id', K_Db_Select::create()->where(array('bt_blog_id' => $this->nodeData['tree_id']))); $blogTagsIds = array_keys($blogTags); foreach ($tags as $v) { $tagsOptions .= '<option value="' . $v['tree_id'] . '" >' . ($v['name'] ? htmlspecialchars($v['name']) : 'Нет названия') . '</option>'; if (in_array($v['tree_id'], $blogTagsIds)) { $tagsInputs .= '<input style="display:none" name="tags[]" value="' . $v['tree_id'] . '">'; $tagsSelOptions .= '<option value="' . $v['tree_id'] . '" >' . ($v['name'] ? htmlspecialchars($v['name']) : 'Нет названия') . '</option>'; } } return <<<HTML <div class="b-padded mainForm"> <div id="flash-msg-nNote" class="nNote hideit" style="display: none;"><p></p></div> <form action="/admin/blogs/settags/" class="ajax-form" method="post"> <div class="rowElem noborder admin-form-row"> <label> Добавить новый тег: </label> <div class="formRight"> <input type="text" name="new-teg" id="add-new-tag-name" /> </div> <div class="fix"></div> <input type="button" value="Добавить" id="add-new-tag" class="b-button greyishBtn submitForm"> </div> <div class="fix"></div> <table class="sel-tags-table" > <tr> <td> <select class="blog-tags" id="sel-tags-start" multiple="on"> {$tagsOptions} </select> </td> <td> <select name="tags[]" id="sel-tags" class="tags-select" multiple="on"> {$tagsSelOptions} </select> </td> <tr> </table> <div id="sel-tags-int"> {$tagsInputs} </div> <input type="hidden" name="this_key" value="{$this->nodeData['tree_id']}" /> <input type="submit" value="Сохранить теги" id="save_button" class="b-button greyishBtn submitForm"> </form> </div> HTML; }
public function exporttypeAction() { $typeId = $this->getParam('typeid'); $typeModel = new Admin_Model_Type(); $typeRow = $typeModel->fetchRow(K_Db_Select::create()->where(array('type_id' => $typeId))); $typeRow = $typeRow->toArray(); $typeName = $typeRow['type_name']; $configArray = array('typeName' => $typeName); $query = new K_Db_Query(); $typeTable = $query->q('SHOW CREATE TABLE type_' . $typeName . ';'); $zip = new ZipArchive(); //создаём папку если такой нет. if (!file_exists(ROOT_PATH . '/cache/typestmp/')) { mkdir(ROOT_PATH . '/cache/temp/', 0777, true); } if ($zip->open(ROOT_PATH . '/www/upload/typestmp/' . $typeName . '.zip', ZipArchive::CREATE) === true) { // php файлы $zip->addFile(ROOT_PATH . '/application/type/model/' . $typeName . '.php', $typeName . '_model.php'); /// Добавление модели типа $zip->addFile(ROOT_PATH . '/application/type/controller/' . $typeName . '.php', $typeName . '_controller.php'); /// Добавление контроллера типа $zip->addFile(ROOT_PATH . '/application/admin/controller/gui/' . $typeName . '.php', $typeName . '_gui.php'); /// Добавление GUI типа // иконка $zip->addFile(ROOT_PATH . '/www/adm/img/tree/' . $typeName . '.png', $typeName . '.png'); /// Добавление иконки типа // данные $zip->addFromString('config.json', json_encode($configArray)); // конфигурационный файл $zip->addFromString('typerow.json', json_encode($typeRow)); // строка типа из таблицы типов $zip->addFromString('typetable.sql', $typeTable[0]['Create Table']); // структура таблицы типа $zip->close(); } else { echo 'Не могу создать архив!'; } K_Request::redirect('/upload/typestmp/' . $typeName . '.zip'); }
/** * @function remove - óäàëåíèå çàïèñåé ïî óñëîâèþ where * @param $sql - óñëîâèå íà óäàëåíèå çàïèñåé */ public function remove($sql) { if ($sql instanceof K_Db_Select) { $sql->from($this->name); } elseif (empty($sql)) { $sql = K_Db_Select::create()->from($this->name); } $this->db->query('DELETE FROM ' . $this->name . ' WHERE ' . $sql->getCompiledWhere()); }
public static function countChilds($pid) { $treeTable = new K_Tree_Model(); return $treeTable->count(K_Db_Select::create()->where(array('tree_pid' => $pid))); }
public static function add($typeName, $typeDesc, $fields, $allowedChildren, $allowedParents, $module = 'type', $generateClasses = true, $formbuilderStructure = false, $createHMVC = false, $seo = false) { $typesTable = new K_Tree_Types_Model(); if (!preg_match('/[a-z0-9.-]+/s', $typeName)) { throw new Exception('Wrong type name: ' . $typeName); } if (!is_array($fields) || empty($fields)) { if (json_decode($fields) != null) { $fields = json_decode($fields); $fields = self::objectToArray($fields); } else { $fields = array(); //throw new Exception('Cannot create empty type: '.$typeName); } } if (!is_array($allowedChildren)) { $allowedChildren = (array) $allowedChildren; foreach ($allowedChildren as $key => $value) { if ($value == 'Все') { $allowedChildren[$key] = 'all'; } if ($value == 'Нет') { $allowedChildren = array(); break; } } //throw new Exception('Childrens must be array: '.$typeName); } if (!is_array($allowedParents)) { $allowedParents = (array) $allowedParents; foreach ($allowedParents as $key => $value) { if ($value == 'Все') { $allowedParents[$key] = 'all'; } if ($value == 'Нет') { $allowedParents = array(); break; } } //throw new Exception('Parents must be array: '.$typeName); } if (!is_dir(APP_PATH . '/' . $module)) { throw new Exception('Wrong module directory: ' . $typeName); } $pageExists = $typesTable->count(K_Db_Select::create()->where('`type_name` = "' . $typeName . '"')); if ($pageExists > 0) { throw new Exception('Current type already exists: ' . $typeName); } $time = time(); $insertIntoTypesData = array('type_name' => $typeName, 'type_desc' => $typeDesc, 'type_fields' => serialize($formbuilderStructure), 'types_module' => $module, 'type_added' => $time, 'type_modified' => $time); $insertId = $typesTable->save($insertIntoTypesData); $newTableName = 'type_' . $typeName; $seoFields = array('title', 'keys', 'h1', 'desc'); $sql = 'CREATE TABLE IF NOT EXISTS`' . $newTableName . '` ( `' . $newTableName . '_id` INT UNSIGNED NOT NULL ,`' . $newTableName . '_pid` INT UNSIGNED NOT NULL,'; // если сео тип то добавляем поля с префиксом SEO foreach ($fields as $fieldId => $field) { if ($field['type'] == 'submit' || $field['type'] == 'reset') { continue; } $sql .= '`' . $newTableName . '_' . $field['values']['name'] . '` ' . self::setType($field['type'], $field['vlds']) . ' NOT NULL ,'; } // если сео тип то добавляем поля с префиксом SEO if ($seo) { foreach ($seoFields as $field) { $sql .= '`' . 'seo' . '_' . $field . '` VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,'; } } $sql .= 'PRIMARY KEY (`' . $newTableName . '_id`) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;'; $query = new K_Db_Query(); $query->q($sql); if ($generateClasses) { self::generateModel($typeName, $module); self::generateController($typeName, $module, $allowedChildren, $allowedParents, $fields); self::generateGUI($typeName, $module, $allowedChildren, $allowedParents, $fields, $seo); } if ($createHMVC) { self::generateTypeBlockController($typeName, array('type' => ucfirst($typeName))); self::generateTypeBlockTemplates($typeName); } }
/** * Remove page info * @param Array $data where array */ public function remove($data) { $cacheID = null; if (isset($data['url_url']) && !empty($data['url_url'])) { $cacheID = 'url_' . md5(trim(mb_strtolower($data['url_url'], 'utf-8'))); } if (isset($data['url_params_json']) && is_array($data['url_params_json'])) { $data['url_params_json'] = json_encode($data['url_params_json']); } $unlimCache = K_Cache_Manager::get('unlim'); if (!empty($cacheID)) { if ($unlimCache->test($cacheID)) { $unlimCache->remove($cacheID); } } $this->rewriteUrlsTable->remove(K_Db_Select::create()->where($data)); }
protected function organizationIdNotExists(&$text, $fieldName) { $organizationModel = new Admin_Model_Organization(); $result = $organizationModel->fetchRow(K_Db_Select::create()->where(array('organization_id' => $text))); if ($result && count($result)) { return true; } $this->errors[$fieldName] = 'Такой организации не сеществует'; return false; }
public static function onDelete($data) { $commentModel = new Admin_Model_Comment(); $commentModel->remove(K_Db_Select::create()->where(array('comment_new' => $data['tree_id']))); }