/** @function query алиас для query * @param $sql - выполнить sql запрос */ public static function one($sql, $key, $noDbRow = false) { $q = new K_Db_Query(); $r = $q->q($sql, $noDbRow); if (!$r) { return false; } return $r[0][$key]; }
/** @function dTypeNodes удаляет все ноды определённого типа * @param $type - название типа ноды которую надо удалить */ public static function dTypeNodes($type) { /// Удаление всех нод определённого типа с вложенными детьми этих нод $query = new K_Db_Query(); $typeNodes = $query->q('SELECT tree_id FROM tree WHERE tree_type=' . K_DB_Quote::quote($type), true); foreach ($typeNodes as $v) { K_Tree::delete($v['tree_id']); } }
public function loadCompletedFormsAction() { $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } $formData = Gcontroller::loadclientFormStructure(trim($_POST['tree_link'])); /* $clientFormData = $typeClientForm->fetchRow( K_Db_Select::create()->where( "type_clientform_id=$clientFormKey" ) ); $this->view->formStructure=unserialize( $clientFormData['type_clientform_content'] );*/ $formStructure = json_decode($formData['form_structure']); $formStructure = K_Tree_Types::objectToArray($formStructure); $fieldCount = 0; foreach ($formStructure as $v) { if (isset($v['values']['name']) && isset($v['values']['label'])) { $colsKeys[] = $v['values']['name']; $fieldCount++; } if ($fieldCount > 3) { break; } } $query = new K_Db_Query(); $sql = "SELECT * FROM clientform_data WHERE clientform_data_type=" . K_Db_Quote::quote(trim($_POST['tree_link'])) . " ORDER by clientform_data_date DESC LIMIT {$start}, {$onPage}"; $formsRes = $query->q($sql); $sql = "SELECT count(*) as countItems from clientform_data WHERE clientform_data_type=" . K_Db_Quote::quote(trim($_POST['tree_link'])); $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $forms = array(); foreach ($formsRes as $v) { $formData = array(); $id = $v['clientform_data_id']; $formData[] = $v['clientform_data_date']; $data = unserialize($v['clientform_data_content']); $data = K_Tree_Types::objectToArray($data); foreach ($colsKeys as $n) { $formData[] = isset($data[$n]) ? $data[$n] : 'off'; } $formData['id'] = $id; $forms[] = $formData; } $returnJson = array('error' => false, 'items' => $forms, 'countItems' => $countItems); $this->putJSON($returnJson); }
protected function rolesAction() { $this->view->title = 'Просмотр ролей'; $this->view->headers = array(array('title' => 'Роли'), array('title' => 'Пользователи', 'href' => '/admin/acl/')); $query = new K_Db_Query(); $sql = "SELECT DISTINCT r.*, p.role_name AS parent, (SELECT count(*) as rule_count FROM rule WHERE rule_role_id=r.role_id) as rule_count FROM role AS r LEFT JOIN role AS p ON r.role_status = 1 AND p.role_status = 1 AND r.role_parent_id = p.role_id ORDER BY r.role_level"; $this->view->roles = $query->q($sql); $sql = "SELECT DISTINCT resource_name,resource_id FROM resource ORDER BY resource_id"; $this->view->resurses = $query->q($sql); $sql = "SELECT DISTINCT privilege_name,privilege_id FROM privilege ORDER BY privilege_id"; $this->view->privileges = $query->q($sql); $tree = new K_Tree(); $this->view->treeResurses = $tree->getAllTree(); $this->render('roles'); }
/** * Возвращяет итемы опрделённого типа * * @param $opt - либо массив, либо id искомого итема * @param $type - тип, искомого итема * @param $stripFields - удалять название таблицы из в выдаче * * Возможна форма записи аргументов как массив, оставшиеся аргументы не указываються * * $opt=array( * 'type'= 'manager', * 'offset'= fasle, * 'limit'= 2, * 'random'= true * 'order'= 'date_publication' * ) * */ public static function getItems($opt, $type, $stripFields = true) { // для поддержки сокращённого типа вызова if (!is_array($opt)) { $opt = array('id' => $opt, 'type' => $type, 'offset' => false, 'limit' => false, 'random' => false, 'order' => false, 'strip' => $stripFields); } else { $opt = array_merge(array('offset' => false, 'limit' => false, 'random' => false, 'strip' => true, 'joins' => false, 'where' => false), $opt); } //var_dump($opt); $offset = $opt['offset']; $query = new K_Db_Query(); if ($opt['random']) { $result = $query->q('SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `type_' . $opt['type'] . '` '); if (!$opt['limit']) { $opt['limit'] = 1; } } $whereStr = ''; if ($opt['id']) { $whereStr = 'WHERE ty.type_' . $opt['type'] . '_id = ' . $opt['id']; } else { if ($opt['where']) { $whereStr = 'WHERE ' . $opt['where']; } } if ($opt['limit']) { $limitStr = ' LIMIT ' . ($offset ? $offset . ',' : '') . $opt['limit']; } if ($opt['order']) { $orederStr = ' ORDER BY `type_' . $opt['type'] . '_' . $opt['order'] . ' '; } /// echo ('SELECT ty.* FROM `type_'.$opt['type'].'` ty '.$whereStr.$limitStr); $result = $query->q('SELECT ty.* FROM `type_' . $opt['type'] . '` ty ' . $whereStr . $orederStr . $limitStr); if ($opt['strip']) { $rData = self::stripTypeFields($result, $opt['type']); } else { $rData = $result; } // var_dump($result); return $rData; }
public function loadAction() { $userModel = new Admin_Model_User(); $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); $filter = $_POST['filter']; if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } $where = 'WHERE 1=1'; if ($filter) { $where = "WHERE user_name like " . K_Db_Quote::quote($filter . '%'); } $query = new K_Db_Query(); $sql = "SELECT SQL_CALC_FOUND_ROWS u.*, (SELECT GROUP_CONCAT(role_name SEPARATOR ', ') as user_roles FROM users_roles ur left join role on ur.usrol_role_id=role_id WHERE ur.usrol_user_id = u.user_id) as user_roles FROM users u \n {$where} order by user_name LIMIT {$start}, {$onPage}"; $usersRes = $query->q($sql); $sql = "SELECT FOUND_ROWS() as countItems;"; $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $users = array(); foreach ($usersRes as $v) { $id = $v['user_id']; $userRow['name'] = $v['user_name']; $userRow['login'] = $v['user_login']; $userRow['email'] = $v['user_email']; $userRow['roles'] = $v['user_roles'] == null ? '' : $v['user_roles']; $users[$id] = $userRow; } $returnJson = array('error' => false, 'items' => $users, 'countItems' => $countItems); $this->putJSON($returnJson); }
public function updateElementAction() { $this->disableRender = true; $values = array(); $treeTable = new K_Tree_Model(); $elementId = $this->getParam('id'); $node = K_tree::getNode($elementId); $typeModelName = 'Type_Model_' . ucfirst($node['tree_type']); $typeModel = new $typeModelName(); $query = new K_Db_Query(); $columns = $query->q('SHOW COLUMNS FROM `type_' . $node['tree_type'] . '`'); foreach ($columns as $c_key => $column) { $columns[$c_key] = $column->toArray(); foreach ($_POST as $p_key => $value) { if ('type_' . $node['tree_type'] . '_' . $p_key == $columns[$c_key]['Field']) { $values['type_' . $node['tree_type'] . '_' . $p_key] = $value; } elseif ($columns[$c_key]['Field'] == 'type_' . $node['tree_type'] . '_aaccess') { $values['type_' . $node['tree_type'] . '_aaccess'] = ''; } } } $form = new K_Form(); $uploadDir = WWW_PATH . '/upload'; $typeFiles = $form->getFiles(); $typesModel = new K_Tree_Types_Model(); $typeData = $typesModel->select('type_fields')->where('`type_name`="' . $node['tree_type'] . '"')->fetchRow(); $typeData = $typeData->toArray(); $typeData = unserialize($typeData['type_fields']); $typeData = json_decode($typeData['form_structure']); if ($form->hasFiles()) { $typeFiles = $form->getFiles(); } foreach ($typeData as $key => $value) { /* если необходимо добавлять текущее время к дате if($value->values->name == 'date'){ $dates = K_date::dateParse($_POST['date']); $values['type_' . $node['tree_type'] . '_date'] = date('Y-m-d',$dates['ts']) .' '.date('G:i:s',time()); } */ // var_dump($typeFiles); if ($value->type == 'file' || $value->type == 'multifile') { if ($value->type == 'multifile') { $currentTypeData = $typeModel->select()->where('`type_' . $node['tree_type'] . '_id`=' . (int) $node['tree_id'])->fetchRow(); $currentTypeData = $currentTypeData->toArray(); // массив файлов сохранённый в базе; if ($filesArray = unserialize($currentTypeData['type_' . $node['tree_type'] . '_' . $value->values->name])) { $i = 0; $fcount = count($filesArray); for ($i = 0; $i < $fcount; $i++) { $isDelete = false; if ($_POST[$value->values->name . '_delete_' . $i] || $typeFiles[$value->values->name . '_f_' . $i]) { $currentLastLoadedFile = $uploadDir . '/' . $filesArray[$i]['f']; if (is_file($currentLastLoadedFile)) { unlink($currentLastLoadedFile); } unset($filesArray[$i]); $isDelete = true; } if (!$isDelete && $_POST[$value->values->name . '_t_' . $i]) { $filesArray[$i]['t'] = $_POST[$value->values->name . '_t_' . $i]; } } } foreach ($typeFiles as $k => $v) { if (preg_match('/^' . $value->values->name . '_f_([0-9]*)$/s', $k, $m)) { if (is_dir($uploadDir)) { $pathData = $form->moveUploadedFile($k, $uploadDir, md5(time() . rand()), true); /* if ($value->values->filter) { $filters = explode('|', $value->values->filter); foreach ($filters as $filter) { $filter = explode(':', $filter); if ($filter[0] == 'image') { $pathData['path'] = '/images/'.$pathData['filename'].'&'.$filter[1]; } } }*/ } else { $this->putAjax('Директории для загрузки не существует "' . $k . '"!'); } if ($pathData) { $fileOne['f'] = $pathData['filename']; if (!empty($_POST[$value->values->name . '_t_' . $m[1]])) { $fileName = $_POST[$value->values->name . '_t_' . $m[1]]; } else { $fileName = $v['name']; } $fileOne['t'] = $fileName; $filesArray[] = $fileOne; } else { $this->putAjax('Не удалось загрузить файл "' . $k . '"!'); } } } //упорядочим массив $filesArrayOrdered = array(); foreach ($filesArray as $v) { if (isset($v)) { $filesArrayOrdered[] = $v; } } $values['type_' . $node['tree_type'] . '_' . $value->values->name] = count($filesArrayOrdered) ? serialize($filesArrayOrdered) : ''; } else { if ($_POST[$value->values->name . '_delete']) { $currentTypeData = $typeModel->select()->where('`type_' . $node['tree_type'] . '_id`=' . (int) $node['tree_id'])->fetchRow(); $currentTypeData = $currentTypeData->toArray(); $currentLastLoadedFile = $uploadDir . '/' . $currentTypeData['type_' . $node['tree_type'] . '_' . $value->values->name]; if (is_file($currentLastLoadedFile)) { unlink($currentLastLoadedFile); } $values['type_' . $node['tree_type'] . '_' . $value->values->name] = ''; } else { if ($form->hasFiles() && isset($typeFiles[$value->values->name])) { if (is_dir($uploadDir)) { $currentTypeData = $typeModel->select()->where('`type_' . $node['tree_type'] . '_id`=' . (int) $node['tree_id'])->fetchRow(); $currentTypeData = $currentTypeData->toArray(); $currentLastLoadedFile = $uploadDir . '/' . $currentTypeData['type_' . $node['tree_type'] . '_' . $value->values->name]; if (is_file($currentLastLoadedFile)) { unlink($currentLastLoadedFile); } $pathData = $form->moveUploadedFile($value->values->name, $uploadDir, md5(time() . rand()), true); /* if ($value->values->filter) { $filters = explode('|', $value->values->filter); foreach ($filters as $filter) { $filter = explode(':', $filter); if ($filter[0] == 'image') { $pathData['path'] = '/images/'.$pathData['filename'].'&'.$filter[1]; } } }*/ } else { $this->putAjax('Директории для загрузки не существует "' . $value->values->name . '"!'); } if ($pathData) { $values['type_' . $node['tree_type'] . '_' . $value->values->name] = $pathData['filename']; } else { $this->putAjax('Не удалось загрузить файл "' . $value->values->name . '"!'); } } else { if ($value->values->filter == 'required' && !isset($typeFiles[$value->values->name])) { $this->putAjax('Файл "' . $value->values->name . '" не был загружен!'); } else { if (!$values['type_' . $node['tree_type'] . '_' . $value->values->name]) { unset($values['type_' . $node['tree_type'] . '_' . $value->values->name]); } } } } } } } $typeModel->update($values, '`type_' . $node['tree_type'] . '_id`=' . (int) $elementId); echo 'Данные сохранены! <script type="text/javascript"> $(document).ready(function(){ setTimeout(function(){ loadTabs(' . (int) $elementId . '); }, 2000); }); </script> '; }
public function loadAction() { $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); $searche = $_POST['filter']; $blogId = intval($_POST['blogid']); if ($dateStart = K_Date::dateParse($_POST['date-start'])) { $dateStart = mktime(0, 0, 0, $dateStart['m'], $dateStart['d'], $dateStart['y']); } if ($dateStop = K_Date::dateParse($_POST['date-stop'])) { $dateStop = mktime(23, 59, 59, $dateStop['m'], $dateStop['d'], $dateStop['y']); } if (is_numeric($_POST['price-start'])) { $priceStart = $_POST['price-start']; } if (is_numeric($_POST['price-stop'])) { $priceStop = $_POST['price-stop']; } if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } $where = ''; // перечень полей из пост запроса для проверки $fields = array('id' => 'o.id', 'idc1' => 'o.idc1', 'type' => 'o.type', 'filial' => 'o.filial', 'adres' => 'o.adres', 'comnati' => 'o.comnati'); $where = K_Afunc::where($fields, $_POST); // var_dump($where); // цена объекта if ($priceStart && $priceStop) { if ($priceStart > $priceStop) { $where[] = "UNIX_TIMESTAMP(o.price) >= " . K_Db_Quote::quote($priceStart); } else { $where[] = "(UNIX_TIMESTAMP(o.price) BETWEEN " . K_Db_Quote::quote($priceStart) . " AND " . K_Db_Quote::quote($priceStop) . ")"; } } else { if ($priceStart) { $where[] = "UNIX_TIMESTAMP(o.price) >= " . K_Db_Quote::quote($priceStart); } else { if ($priceStop) { $where[] = "UNIX_TIMESTAMP(o.price) <= " . K_Db_Quote::quote($priceStop); } } } // дата публикации объекта if ($dateStart && $dateStop) { if ($dateStart > $dateStop) { $where[] = "UNIX_TIMESTAMP(o.date_publication) >= " . K_Db_Quote::quote($dateStart); } else { $where[] = "(UNIX_TIMESTAMP(o.date_publication) BETWEEN " . K_Db_Quote::quote($dateStart) . " AND " . K_Db_Quote::quote($dateStop) . ")"; } } else { if ($dateStart) { $where[] = "UNIX_TIMESTAMP(o.date_publication) >= " . K_Db_Quote::quote($dateStart); } else { if ($dateStop) { $where[] = "UNIX_TIMESTAMP(o.date_publication) <= " . K_Db_Quote::quote($dateStop); } } } if ($where && count($where)) { $where = ' WHERE ' . implode(' AND ', $where); } $query = new K_Db_Query(); $sql = "SELECT SQL_CALC_FOUND_ROWS o.*, b.symbol letter, t.name typename, t.color color, o.branchID filial_info, b.symbol letter, b.phone, b.address, b.email, b.title filial FROM `obj_objects` o\n \n LEFT JOIN obj_rooms r ON r.id = o.id \n LEFT JOIN obj_types t ON t.id = o.type \n LEFT JOIN obj_branches b ON b.id = o.branchID \n \n {$where} ORDER BY date_publication DESC LIMIT {$start}, {$onPage}"; $itemsRes = $query->q($sql); $sql = "SELECT FOUND_ROWS() as countItems;"; $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $items = array(); // сделать вывод планировок. // var_dump($itemRow); $this->view->objectRow = $itemRow; foreach ($itemsRes as $v) { $itemRow['id'] = $v['id']; $itemRow['id1c'] = $v['id1c']; $itemRow['type'] = $v['typename']; $itemRow['filial'] = strip_tags(htmlspecialchars($v['filial'])); $itemRow['adress'] = strip_tags($v['city'] . ' ' . $v['city'] . ' ' . $v['street']); $itemRow['rooms'] = strip_tags(htmlentities($v['rooms'])); $itemRow['price'] = $v['price']; $itemRow['color'] = strtoupper($v['color']); $items[] = $itemRow; } $returnJson = array('error' => false, 'items' => $items, 'countItems' => $countItems); $this->putJSON($returnJson); }
public static function update($typeName, $desc, $fields, $formbuilderStructure = false) { if (!is_array($fields) || empty($fields)) { if (json_decode($fields) != null) { $fields = json_decode($fields); $fields = self::objectToArray($fields); } else { throw new Exception('Cannot modify fields in: ' . $typeName); } } $typesTable = new K_Tree_Types_Model(); $typesTable->update(array('type_desc' => $desc, 'type_fields' => serialize($formbuilderStructure), 'type_modified' => time()), '`type_name` = "' . $typeName . '"'); $query = new K_Db_Query(); $columns = $query->q('SHOW COLUMNS FROM `type_' . $typeName . '`'); $rightFields = array(); $usedFields = array(0 => 'type_' . $typeName . '_id'); $i = 0; foreach ($fields as $fieldId => $field) { if ($field['type'] == 'submit' || $field['type'] == 'reset') { continue; } $rightFields[$i] = 'type_' . $typeName . '_' . $field['values']['name']; $rightFieldParams[$i] = $field; $i++; } $idExists = false; foreach ($columns as $key => $column) { $columns[$key] = $column->toArray(); if (!in_array($columns[$key]['Field'], $rightFields) && $columns[$key]['Field'] != 'type_' . $typeName . '_id' && $columns[$key]['Field'] != 'type_' . $typeName . '_pid') { $query->q('ALTER TABLE `type_' . $typeName . '` DROP `' . $columns[$key]['Field'] . '`'); } else { $usedFields[] = $columns[$key]['Field']; } if ($columns[$key]['Field'] == 'type_' . $typeName . '_id') { $idExists = true; } } if (!$idExists) { $query->q('ALTER TABLE `type_' . $typeName . '` ADD `type_' . $typeName . '_id` INT UNSIGNED NOT NULL FIRST'); } foreach ($rightFields as $key => $value) { if (!in_array($value, $usedFields)) { $usedFieldsValues = $usedFields; echo $qui = 'ALTER TABLE `type_' . $typeName . '` ADD `' . $value . '` ' . self::setType($rightFieldParams[$key]['type'], $rightFieldParams[$key]['vlds']) . ' NOT NULL AFTER `' . end($usedFieldsValues) . '`'; $query->q($qui); $usedFields[] = 'type_' . $typeName . '_' . $value; } } return true; }
$nodeParentsArr[] = $key; $beforeMove = implode('/', $nodeParentsArr); if (K_Tree::move($key, $baseKey, $position == 'last' ? 'top' : $position)) { //рессурс после перемещения $nodeParentsArr = K_Tree::getParents($key); $nodeParentsArr[] = $key; $afterMove = implode('/', $nodeParentsArr); // если рессурсы отличаються то перезагружаем ветку ACL if ($afterMove != $beforeMove) { //удаляем старую ветку рессурсов K_access::aclTree()->remove($beforeMove); $node = K_Tree::getNode($key); $query = new K_Db_Query(); $sql = "SELECT DISTINCT tree_rule.tree_rule_id as tree_ruleId, tree_rule.tree_rule_resource_id, tree_rule.tree_rule_type as tree_ruleType, role.role_acl_key as role, privilege.privilege_name as privilege \r FROM tree_rule, role, tree, privilege \r WHERE tree.tree_lkey >= " . (int) $node['tree_lkey'] . " AND tree.tree_rkey <= " . (int) $node['tree_rkey'] . " \r and tree_rule.tree_rule_status = 1 \r and role.role_status = 1 \r and privilege.privilege_status = 1 \r and tree_rule.tree_rule_role_id = role.role_id \r and tree_rule.tree_rule_resource_id = tree.tree_id \r and tree_rule.tree_rule_privilege_id = privilege.privilege_id \r ORDER BY tree_rule.tree_rule_order"; $allRules = $query->q($sql); K_Access::aclTreeReloadBrunch($allRules); } echo '{ "status" : 1}'; } else { echo 'false'; } } } } public function removeAction() { $this->disableRender = true; $nodeId = (int) $this->getParam('id'); $returnJson = array(); $node = K_Tree::getNode($nodeId); if ($node['tree_bloked'] == '1') { $returnJson['status'] = false; $this->putJSON($returnJson); } if (K_access::accessTree($nodeId, array('addremove'), true) && K_CupTree::dNodes($nodeId)) {
public function loadAction() { $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); $searche = $_POST['filter']; $newId = intval($_POST['newid']); if ($dateStart = K_Date::dateParse($_POST['date-start'])) { $dateStart = mktime(0, 0, 0, $dateStart['m'], $dateStart['d'], $dateStart['y']); } if ($dateStop = K_Date::dateParse($_POST['date-stop'])) { $dateStop = mktime(23, 59, 59, $dateStop['m'], $dateStop['d'], $dateStop['y']); } if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } if ($dateStart && $dateStop) { if ($dateStart > $dateStop) { $where[] = "UNIX_TIMESTAMP(comment_date) >= " . K_Db_Quote::quote($dateStart); } else { $where[] = "(UNIX_TIMESTAMP(comment_date) BETWEEN " . K_Db_Quote::quote($dateStart) . " AND " . K_Db_Quote::quote($dateStop) . ")"; } } else { if ($dateStart) { $where[] = "UNIX_TIMESTAMP(comment_date) >= " . K_Db_Quote::quote($dateStart); } else { if ($dateStop) { $where[] = "UNIX_TIMESTAMP(comment_date) <= " . K_Db_Quote::quote($dateStop); } } } if ($newId) { $where[] = " comment_new = " . K_Db_Quote::quote($newId); } if ($searche) { $where[] = " (comment_name like " . K_Db_Quote::quote($searche . '%') . " OR comment_email like " . K_Db_Quote::quote($searche . '%') . ")"; } if ($_POST['comments-status']) { $where[] = " comment_status = " . K_Db_Quote::quote($_POST['comments-status']); } if ($where && count($where)) { $where = ' WHERE ' . implode(' AND ', $where); } $query = new K_Db_Query(); $sql = "SELECT SQL_CALC_FOUND_ROWS * from comments {$where} order by comment_date DESC LIMIT {$start}, {$onPage}"; $itemsRes = $query->q($sql); $sql = "SELECT FOUND_ROWS() as countItems;"; $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $items = array(); foreach ($itemsRes as $v) { $itemRow['id'] = $v['comment_id']; $itemRow['date'] = $v['comment_date']; $itemRow['name'] = strip_tags(htmlspecialchars($v['comment_name'])); $itemRow['content'] = strip_tags(htmlspecialchars($v['comment_content'])); $itemRow['status'] = $v['comment_status']; $itemRow['ip'] = long2ip($v['comment_ip']); $items[] = $itemRow; } $returnJson = array('error' => false, 'items' => $items, 'countItems' => $countItems); $this->putJSON($returnJson); }
public static function reStoreTreeKeys($freeKey = 0, $pid = 0) { $query = new K_Db_Query(); if (!is_numeric($pid) || !is_numeric($freeKey)) { return false; } $r = $query->q("select tree_id from tree where tree_pid=" . $pid); if (count($r) > 0) { foreach ($r as $f) { $id = $f['tree_id']; $rightKey = self::reStoreTreeKeys($freeKey + 1, $id); if ($rightKey === false) { return false; } $qr = "UPDATE tree SET tree_lkey=" . $freeKey . ", tree_rkey=" . $rightKey . " WHERE tree_id=" . $id; $query->q($qr); $freeKey = $rightKey + 1; } } return $freeKey; }
public function loadAction() { $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); $searche = $_POST['filter']; $newId = intval($_POST['newid']); if ($dateStart = K_Date::dateParse($_POST['date-start'])) { $dateStart = mktime(0, 0, 0, $dateStart['m'], $dateStart['d'], $dateStart['y']); } if ($dateStop = K_Date::dateParse($_POST['date-stop'])) { $dateStop = mktime(23, 59, 59, $dateStop['m'], $dateStop['d'], $dateStop['y']); } if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } if ($dateStart && $dateStop) { if ($dateStart > $dateStop) { $where[] = "UNIX_TIMESTAMP(type_news_date) >= " . K_Db_Quote::quote($dateStart); } else { $where[] = "(UNIX_TIMESTAMP(type_news_date) BETWEEN " . K_Db_Quote::quote($dateStart) . " AND " . K_Db_Quote::quote($dateStop) . ")"; } } else { if ($dateStart) { $where[] = "UNIX_TIMESTAMP(type_news_date) >= " . K_Db_Quote::quote($dateStart); } else { if ($dateStop) { $where[] = "UNIX_TIMESTAMP(type_news_date) <= " . K_Db_Quote::quote($dateStop); } } } if ($_POST['news-lang']) { $where[] = " type_news_lang = " . K_Db_Quote::quote($_POST['news-lang']); } if ($section = intval($_POST['section'])) { $where[] = " tree_pid = " . K_Db_Quote::quote($section); } if ($searche && mb_strlen($searche) > 2) { if ($searche) { $where[] = "(type_news_title LIKE " . K_Db_Quote::quote('%' . $searche . '%') . ' OR type_news_author LIKE ' . K_Db_Quote::quote($searche . '%') . ")"; } } if ($where && count($where)) { $where = ' WHERE ' . implode(' AND ', $where); } $query = new K_Db_Query(); $sql = "SELECT SQL_CALC_FOUND_ROWS type_news.*,type_section_ua_name from type_news\n LEFT JOIN tree ON tree_id = type_news_id \n LEFT JOIN type_section ON type_section_id = tree_pid \n {$where} order by type_news_date DESC LIMIT {$start}, {$onPage}"; $itemsRes = $query->q($sql); $sql = "SELECT FOUND_ROWS() as countItems;"; $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $items = array(); foreach ($itemsRes as $v) { $itemRow['id'] = $v['type_news_id']; $itemRow['date'] = $v['type_news_date']; $itemRow['title'] = strip_tags(htmlspecialchars($v['type_news_title'])); $itemRow['lang'] = strip_tags($v['type_news_lang']); $itemRow['section'] = strip_tags($v['type_section_ua_name']); $itemRow['author'] = strip_tags(htmlentities($v['type_news_author'])); $items[] = $itemRow; } $returnJson = array('error' => false, 'items' => $items, 'countItems' => $countItems); $this->putJSON($returnJson); }
public function loadAction() { $userModel = new Admin_Model_User(); $page = intval($_POST['page']); $onPage = intval($_POST['onPage']); $filter = $_POST['filter']; if ($page) { if (!$onPage) { $onPage = 10; } $start = $page * $onPage - $onPage; } else { $start = 0; $page = 1; $onPage = 10; } $where = 'WHERE 1=1'; if ($filter) { $where = "WHERE r.role_name like " . K_Db_Quote::quote($filter . '%'); } $query = new K_Db_Query(); $sql = "SELECT SQL_CALC_FOUND_ROWS r.*, p.role_name AS parent, (SELECT count(*) as rule_count FROM rule WHERE rule_role_id=r.role_id) as rule_count FROM role AS r LEFT JOIN role AS p ON r.role_status = 1 AND p.role_status = 1 AND r.role_parent_id = p.role_id {$where} ORDER BY r.role_level LIMIT {$start}, {$onPage}"; //$sql = "SELECT SQL_CALC_FOUND_ROWS u.*, (SELECT GROUP_CONCAT(role_name SEPARATOR ', ') as user_roles FROM users_roles ur left join role on ur.usrol_role_id=role_id WHERE ur.usrol_user_id = u.user_id) as user_roles FROM users u // $where order by user_name LIMIT $start, $onPage"; $rolseRes = $query->q($sql); $sql = "SELECT FOUND_ROWS() as countItems;"; $countItems = $query->q($sql); $countItems = $countItems[0]['countItems']; $roles = array(); foreach ($rolseRes as $v) { $id = $v['role_id']; $roleRow['name'] = $v['role_name']; $roleRow['role_acl_key'] = $v['role_acl_key']; $roleRow['parentid'] = $v['role_parent_id'] == null ? '' : $v['role_parent_id']; $roleRow['parentname'] = $v['parent'] == null ? 'Нет предка' : $v['parent']; $roleRow['rule_count'] = $v['rule_count']; $roles[$id] = $roleRow; } $returnJson = array('error' => false, 'items' => $roles, 'countItems' => $countItems); $this->putJSON($returnJson); }
public function updateElementAction() { $this->disableRender = true; $values = array(); $treeTable = new K_Tree_Model(); $elementId = $this->getParam('id'); $node = K_tree::getNode($elementId); $typeModelName = 'Type_Model_' . ucfirst($node['tree_type']); $typeModel = new $typeModelName(); $query = new K_Db_Query(); $columns = $query->q('SHOW COLUMNS FROM `type_' . $node['tree_type'] . '`'); foreach ($columns as $c_key => $column) { $columns[$c_key] = $column->toArray(); foreach ($_POST as $p_key => $value) { if ('type_' . $node['tree_type'] . '_' . $p_key == $columns[$c_key]['Field']) { $values['type_' . $node['tree_type'] . '_' . $p_key] = $value; } elseif ($columns[$c_key]['Field'] == 'type_' . $node['tree_type'] . '_aaccess') { $values['type_' . $node['tree_type'] . '_aaccess'] = ''; } } } $form = new K_Form(); $uploadDir = WWW_PATH . '/upload'; $typeFiles = $form->getFiles(); $typesModel = new K_Tree_Types_Model(); $typeData = $typesModel->select('type_fields')->where('`type_name`="' . $node['tree_type'] . '"')->fetchRow(); $typeData = $typeData->toArray(); $typeData = unserialize($typeData['type_fields']); $typeData = json_decode($typeData['form_structure']); if ($form->hasFiles()) { $typeFiles = $form->getFiles(); } foreach ($typeData as $key => $value) { if ($value->type == 'file') { if ($_POST[$value->values->name . '_delete']) { $currentTypeData = $typeModel->select()->where('`type_' . $node['tree_type'] . '_id`=' . (int) $node['tree_id'])->fetchRow(); $currentTypeData = $currentTypeData->toArray(); $currentLastLoadedFile = $uploadDir . '/' . $currentTypeData['type_' . $node['tree_type'] . '_' . $value->values->name]; if (is_file($currentLastLoadedFile)) { unlink($currentLastLoadedFile); } $values['type_' . $node['tree_type'] . '_' . $value->values->name] = ''; } else { if ($form->hasFiles() && isset($typeFiles[$value->values->name])) { if (is_dir($uploadDir)) { $currentTypeData = $typeModel->select()->where('`type_' . $node['tree_type'] . '_id`=' . (int) $node['tree_id'])->fetchRow(); $currentTypeData = $currentTypeData->toArray(); $currentLastLoadedFile = $uploadDir . '/' . $currentTypeData['type_' . $node['tree_type'] . '_' . $value->values->name]; if (is_file($currentLastLoadedFile)) { unlink($currentLastLoadedFile); } $pathData = $form->moveUploadedFile($value->values->name, $uploadDir, md5(time() . rand()), true); /* if ($value->values->filter) { $filters = explode('|', $value->values->filter); foreach ($filters as $filter) { $filter = explode(':', $filter); if ($filter[0] == 'image') { $pathData['path'] = '/images/'.$pathData['filename'].'&'.$filter[1]; } } }*/ } else { $this->putAjax('Директории для загрузки не существует "' . $value->values->name . '"!'); } if ($pathData) { $values['type_' . $node['tree_type'] . '_' . $value->values->name] = $pathData['filename']; } else { $this->putAjax('Не удалось загрузить файл "' . $value->values->name . '"!'); } } elseif ($value->values->filter == 'required' && !isset($typeFiles[$value->values->name])) { $this->putAjax('Файл "' . $value->values->name . '" не был загружен!'); } else { if (!$values['type_' . $node['tree_type'] . '_' . $value->values->name]) { unset($values['type_' . $node['tree_type'] . '_' . $value->values->name]); } } } } } $typeModel->update($values, '`type_' . $node['tree_type'] . '_id`=' . (int) $elementId); echo 'Данные сохранены! <script type="text/javascript"> setTimeout(function(){ $("a.jstree-clicked").click(); } }); </script> '; }
public static function loadAclTree($reload = false) { //create Acl Obj self::$aclTree = new K_Acl(); if (!$reload) { /*// зугрузка сразу всего ACL $unlimCache = K_Cache_Manager::get('unlim'); if($unlimCache->test('ATR')) { self::$aclTree = $unlimCache->load('ATR'); return; }*/ // если во время раздельной загрузки возникли проблемы то пересоздадим обьект ACL и продолжим загрузку обычно if (self::loadAclArrays('ATR', self::$aclTree)) { return; } else { self::$aclTree = new K_Acl(); } } $query = new K_Db_Query(); $sql = "SELECT DISTINCT r.role_acl_key AS role, p.role_acl_key AS parent FROM role AS r LEFT JOIN role AS p ON r.role_status = 1 AND p.role_status = 1 AND r.role_parent_id = p.role_id ORDER BY r.role_level"; $allroles = $query->q($sql); foreach ($allroles as $v) { if ($v['parent'] == null) { self::$aclTree->addRole(new K_Acl_Role($v['role'])); } else { self::$aclTree->addRole(new K_Acl_Role($v['role']), $v['parent']); } } //add rules $sql = "SELECT DISTINCT tree_rule.tree_rule_id as tree_ruleId, tree_rule.tree_rule_resource_id, tree_rule.tree_rule_type as tree_ruleType, role.role_acl_key as role, privilege.privilege_name as privilege \n FROM tree_rule, role, tree, privilege \n WHERE tree_rule.tree_rule_status = 1 \n and role.role_status = 1 \n and privilege.privilege_status = 1 \n and tree_rule.tree_rule_role_id = role.role_id \n and tree_rule.tree_rule_resource_id = tree.tree_id \n and tree_rule.tree_rule_privilege_id = privilege.privilege_id \n ORDER BY tree_rule.tree_rule_order"; $allRules = $query->q($sql); self::aclTreeloadRules($allRules); }
public static function getType($type, $conditions, $join) { $typesModel = new K_Tree_Types_Model(); if ($conditions) { foreach ($conditions as $k => $v) { $wA[] = " type_{$type}" . '_' . "{$k}='{$v}' "; } } $w = implode('and ', $wA); $query = new K_Db_Query(); foreach ($join as $k => $v) { $kTable = 'type_' . $k; $jTablesA[] = "{$kTable}.*"; $jJoin[] = " LEFT JOIN {$kTable} ON {$kTable}.{$kTable}" . "_id=type_{$type}" . '_' . "{$v} "; } $jJoin = implode(' ', $jJoin); $jTables = ',' . implode(',', $jTablesA); // echo 'SELECT * '.$jTables.' FROM type_'.$type.' '.$jJoin.' where '.$w; $result = $query->q('SELECT * ' . $jTables . ' FROM type_' . $type . ' ' . $jJoin . ' where ' . $w); foreach ($result as $key => $value) { $result[$key] = $value->toArray(); foreach ($result[$key] as $typeField => $typeValue) { $rData[$key][str_replace('type_' . $type . '_', '', $typeField)] = $typeValue; } } return $rData; }
/** Выбирает ветку ноды со всей её инфой ,которая храниться в смежных таблицах типов * * */ public static function gNodes($opt, $limit = false, $parentNodeData = false) { // Этап 1 формирование настроек для выполнения // для поддержки старого упрощенного варианта if (!is_array($opt)) { $opt = array("id" => $opt, "limit" => $limit); } $opt = array_merge(array("id" => 0, "limit" => false, "offset" => 0, "types" => false, "condit" => '', 'filter' => false, "idIndex" => false, "joins" => false, "group" => false, "order" => false, "more" => array('cascade' => false, "childs" => false, "test" => false, 'meta', 'count' => false, 'orderby' => "ASC", "aliases" => false)), $opt); $rtypes = array(); $rtypesTables = array(); $rtypesAll = array(); $query = new K_Db_Query(); if (!$parentNodeData) { $parentNodeData = K_Tree::getNode($opt["id"]); } //Этап 2 выборка и формирование списка типов с которыми будем работать if (!$opt['types']) { if ($opt['more']['childs']) { /* if (is_numeric($opt["id"])){ $pid=$opt["id"]; } else{ $node=K_Tree::getNode($opt["id"]); $pid=$node['tree_id']; }*/ $q = 'SELECT DISTINCT tree_type FROM tree where tree_pid="' . $parentNodeData['tree_id'] . '" ORDER BY tree_lkey ASC limit 1'; $result = $query->q($q); } else { $q = 'SELECT DISTINCT tree_type FROM `tree` WHERE `tree_lkey`>=' . $parentNodeData['tree_lkey'] . ' AND `tree_rkey`<=' . $parentNodeData['tree_rkey'] . ' ' . ($opt['filter'] ? ' AND tree_type="' . $opt['filter'] . '"' : '') . ' ORDER BY `tree_lkey` ASC ' . ($opt["limit"] ? ' LIMIT ' . $opt["limit"] : ''); $result = $query->q($q); } $usedTypes = array(); for ($i = 0; $i < sizeof($result); $i++) { $data[$i] = $result[$i]->toArray(); if (!in_array($data[$i]['tree_type'], $usedTypes)) { $usedTypes[] = $data[$i]['tree_type']; } } // K_debug::get()->dump($usedTypes); //этап 3 выборка итемов требуемых типов $allResults = array(); $rData = array(); $i = 1; $topLevel = true; $casCadeStart = false; $casCadeIds = array(); // при каскаде убираем тип папка, он только будет мишать if ($opt['more']['cascade'] && ($usedTypes[0] = 'folder')) { array_shift($usedTypes); } } else { $usedTypes = $opt['types']; } foreach ($usedTypes as $type) { //каскадная выборка(сперва выбираються ноды верхнего порядка по типу, к ним применяються условия, потом по pid выбираються ноды следующиего уровня) $inStr = ''; if ($opt['more']['cascade'] && count($casCadeIds)) { $casCadeIdsIn = implode(',', $casCadeIds); $inStr = ' AND tr.tree_pid IN (' . $casCadeIdsIn . ')'; } if (in_array($type, $usedTypes)) { $rtypes[] = $type; $rtypesTables = '`type_' . $type . '` AS ty '; $rtypesAll = 'ty.*'; $tp = $type; //дополнительные условия для выборки $rtypesWhere = '`tr`.`tree_id`=ty.type_' . $type . '_id' . ($opt['condit'][$type] ? $opt['condit'][$type] : ''); // if ($conditions)echo 'SELECT `tr`.*, '.$rtypesAll.' FROM `tree` AS `tr`, '.$rtypesTables.' WHERE '.$rtypesWhere.' AND `tr`.`tree_lkey`>='.$parentNodeData['tree_lkey'].' AND `tr`.`tree_rkey`<='.$parentNodeData['tree_rkey'].' ORDER BY `tr`.`tree_lkey` ASC '.($limit ? ' LIMIT '.$limit : ''); // array('tour'=>array('resort'=>'to_city','hotel'=>'hotel','country'=>'country')); //array('price'=>array('pid'=>array('max'=>'price'))); $agreg = ''; $group = ''; // группировки по типу, найти минимальное, максимальное, сумму для определённого типа if ($opt['group'][$tp]) { $grp = $opt['group'][$tp]; foreach ($grp as $k => $v) { $kCell = 'type_' . $tp . '_' . $k; $group[] = " group by {$k}"; foreach ($v as $t => $y) { $agreg[] = "{$t}(" . 'ty.type_' . $tp . '_' . "{$y})"; } $agreg = ',' . implode(', ', $agreg); $group = implode(' ', $group); } } //дополнительные джойны, для каждого типа, в дальнейшем cделать их автоматическими $jJoin = ''; $jTables = ''; if ($opt['joins'][$tp]) { foreach ($opt['joins'][$tp] as $k => $v) { $kTable = 'type_' . $k; $jTablesA[] = "{$kTable}.*"; $jJoin[] = " LEFT JOIN {$kTable} ON {$kTable}.{$kTable}" . "_id=ty.type_{$tp}" . '_' . "{$v} "; } $jJoin = implode(' ', $jJoin); $jTables = ',' . implode(',', $jTablesA); } $limitStr = ''; if (!$opt['more']['count']) { $topLevel = false; } // при каскадной выборке лимит работает только для верхнего типа if ($opt['more']['cascade']) { if ($topLevel) { $limitStr = $opt['limit'] ? ' LIMIT ' . $opt['offset'] . ', ' . $opt['limit'] : ''; } } else { // при простой выборке лимит делиться на все типы по чучуть if (count($usedTypes) > 1) { $typeCount = count($usedTypes); $limitForType = floor($opt['limit'] / $typeCount); $offsetForType = floor($opt['offset'] / $typeCount); if ($topLevel) { // разницу добавим к верхнему уровню:К ПРИМЕРУ 10 разобьёться на троих так 4 3 3 $limitForType += $opt['limit'] - $limitForType * $typeCount; $offsetForType += $opt['offset'] - $offsetForType * $typeCount; } $limitStr = $limitForType ? ' LIMIT ' . $offsetForType . ', ' . $limitForType : ''; } else { if ($opt['limit']) { $limitStr = ' LIMIT ' . $opt['offset'] . ', ' . $opt['limit']; } } } // сортировка, если её нет то сортируеться по левому ключу if ($opt['order'][$tp]) { if (is_string($opt['order'][$tp])) { $opt['order'][$tp] = array($opt['order'][$tp]); } $orderArr = array(); if (is_string($opt['more']['orderby'])) { $opt['more']['orderby'] = array($opt['more']['orderby']); } $ior = 0; foreach ($opt['order'][$tp] as $v) { $orderArr[] = 'ty.' . 'type_' . $tp . '_' . $v . ' ' . $opt['more']['orderby'][$ior]; $ior++; } $orderFields = implode(',', $orderArr); $orderBY = ' ORDER BY ' . $orderFields . ' '; } else { $orderBY = ' ORDER BY `tr`.`tree_lkey` ASC '; } //основной запроc, $qv = 'SELECT' . ($limitStr ? ' SQL_CALC_FOUND_ROWS ' : '') . ' `tr`.*, ' . $rtypesAll . ' ' . $jTables . ' ' . $agreg . ' FROM `tree` AS `tr`, ' . $rtypesTables . ' ' . $jJoin . ' WHERE ' . $rtypesWhere . ' AND `tr`.`tree_lkey`>=' . $parentNodeData['tree_lkey'] . ' AND `tr`.`tree_rkey`<=' . $parentNodeData['tree_rkey'] . ' ' . $inStr . ' ' . $group . $orderBY . $limitStr; $result = $query->q($qv); if ($limitStr) { $сountResult = $query->q("SELECT FOUND_ROWS() as cItems;"); $countItems += $сountResult[0]['cItems']; } if ($opt['more']['test']) { K_debug::get()->addMessage($countItems); } if ($opt['more']['test']) { K_debug::get()->addMessage($qv); } $casCadeIds = array(); foreach ($result as $key => $value) { $result[$key] = $value->toArray(); $aResults = array(); foreach ($result[$key] as $typeField => $typeValue) { $aResults[str_replace('type_' . $type . '_', '', $typeField)] = $typeValue; // K_debug::get()->dump($key); } if ($opt['more']['aliases'] == true && $aResults['tree_type'] == 'alias') { $aliases[$aResults['tree_lkey']] = $aResults['elementid']; // var_dump( $aResults); } $allResults[$aResults['tree_lkey']] = $aResults; //каскадная выборка(сперва выбираються ноды верхнего порядка по типу, к ним применяються условия, потом по pid выбираються ноды следующиего уровня) // сохраним id нод if ($opt['more']['cascade']) { $casCadeIds[] = $aResults["tree_id"]; } $i++; } if ($opt['more']['cascade'] && !count($casCadeIds)) { break; } //$allResults = array_merge($allResults, $rData); $topLevel = false; } } //Этап 4 постобработка, получение данных в нужном нам виде ,подключение алиасов /** * @todo группировка итемов по типу и вывод в массив * * **/ //K_debug::get()->dump($rAllResults); //проверка на алиасы, если они есть выбираем все элементы по алиасам и заменяем ими алиасы // var_dump($aliases); $aliasesIdsStr = implode(',', array_unique($aliases)); if (count($aliases) && $aliasesIdsStr) { //Узнаём все типы алиасов $q = 'SELECT DISTINCT tree_type FROM tree where tree_id IN(' . implode(',', $aliases) . ')'; $aliasesTypesResult = $query->q($q); //массив таблиц из которых будем выбирать foreach ($aliasesTypesResult as $v) { $aliasesTypes[] = $v['tree_type']; $aliasesTypesTables[] = 'type_' . $v['tree_type']; $aliasesTypesTablesWhere[] = 'type_' . $v['tree_type'] . '.' . 'type_' . $v['tree_type'] . '_id = tree.tree_id'; } //массив условий для выбора типов $qv = 'SELECT * FROM tree, ' . implode(',', $aliasesTypesTables) . ' WHERE tree.tree_id IN(' . implode(',', $aliases) . ') AND ' . implode(',', $aliasesTypesTablesWhere); $aliasesResult = $query->q($qv); foreach ($aliasesResult as $v) { $aliasesResultKeyId[$v['tree_id']] = K_Cupitems::stripFieldsArr($v, 'type_' . $v['tree_type']); } //var_dump($aliasesResultKeyId); foreach ($allResults as $v) { if ($v['tree_type'] == 'alias') { $elementid = $aliases[$v['tree_lkey']]; unset($allResults[$v['tree_lkey']]['tree_type']); $aliasElementResult = array_merge($aliasesResultKeyId[$elementid], $allResults[$v['tree_lkey']]); $allResults[$v['tree_lkey']] = $aliasElementResult; //$aliasesResultKeyId[$elementid]; // array_merge($aliasesResultKeyId[$elementid],$allResults[$v['tree_lkey']]); // var_dump($aliasesResultKeyId[$elementid]); } } } //сортируем по левому ключу: if (!$opt['order']) { ksort($allResults); } $claer = true; if ($opt['group']) { // если есть группировка // нумеруем индексы по id $rrAllResults = array(); foreach ($allResults as $key => $value) { $rrAllResults[$value['tree_id']] = $value; } $allResults = $rrAllResults; // K_debug::get()->dump($allResults); $rAllResults = array(); foreach ($allResults as $key => $value) { //если была группировка по этому типу то в массиве ответа к родительским нодам прикрепляем детей в виде индекса node_childs $tp = $value['tree_type']; if ($opt['group'][$tp]) { $tId = $value['tree_pid']; // K_debug::get()->dump($tId); $allResults[$tId]['node_childs'][] = $value['tree_id']; // K_debug::get()->dump($rAllResults[$tId]['node_childs']); } } $claer = false; } //если есть необходимость переназвать иднексы называем их по одному из полей ноды if ($opt['idIndex']) { $allResults; foreach ($allResults as $value) { if ($opt['idIndex']) { $tId = $value['tree_id']; if (is_string($idIndex)) { $tId = $value[$opt['idIndex']]; } $rAllResults[$tId] = $value; } } $claer = false; } // если всё чисто то просто пронумеруем все элементы выборки по порядку if ($claer) { $i = 0; foreach ($allResults as $value) { $rAllResults[$i] = $value; $i++; } } if ($opt['more']['test']) { K_debug::get()->dump($rAllResults); } if ($opt['more']['meta']) { return array($rAllResults, $parentNodeData); } if ($opt['more']['count']) { return array($rAllResults, $countItems); } return $rAllResults; }