* @since Version 2.0 */ class cmsPermissionsController extends cCore { public $dir; public $name; public $module; /** * Class constructor */ public function __construct($uriData, $dir, $name) { $this->dir = $dir; $this->name = $name; parent :: __construct($uriData); $this->module = new cmsPermissionsModule(); $this->oView->setTemplateDir($this->dir . "/tmpl/"); if(!$this->oView->cacheUsed()){ $this->oView->setJs(getCurrentFolder($this->dir) . '/js/' . $this->name . '.js'); $this->oView->setCss(getCurrentFolder($this->dir) . '/css/' . $this->name . '.css'); } // Set JS module init title $this->oView->setAsJSON(cCore::JS_MOD, ucfirst($name)); } /** * Function to show main form in the module * * @category cmsPermissions Controller * @author Mareks Keišs * @returns bool true */ public function run($initEditMode = false){ $this->oView->TABLE = true; $this->oView->setAsJSON('initEdit', $initEditMode); $this->oView->setAsJSON('baseUrl', $this->gL()); $this->oView->setAsJSON('gM', $this->getTranslations()); $this->oView->setAsJSON('vcfg', $this->getValCfg()); $this->oView->display(); } /** * Function to create cms table & return for direct & ajax input * * @author Mareks Keišs * @category cmsPermissions Controller * @param int $page - page to display * @param string $filter_json - (optional) filter json string * @param bool $headers - flag whether to send header data or not * @return array of data * @version 1.1 */ public function createCmsTable($page = 1, $filter_json = '', $headers = false) { $pages = 0; $filter = (strlen($filter_json) ? cJSON::decode($filter_json, true) : array()); $this->oView->MODULE_TITLE = $this->gM("PUB permissions"); if(!!$filter && is_array($filter)) $this->oView->DEFAULT_SEARCH_VALUES = prepForDisplayHtml($filter); $this->oView->LIST_HEADER = reOrderTableFields($this->getTableFields(), $this->oUser->oCfg->getTableProperty($this->name)); $this->oView->LIST_DATA = $this->getModuleData($page, $filter, $pages); $this->oView->LIST_ACTIONS = $this->getTableActions(); $data = array( 'data' => $this->oView->genHelperView('cmsc/table/data-table'), 'pcount' => $pages, 'rlimit' => $this->cmsTableRecordsPerPage ); // Send data to client if($headers) $data['header'] = $this->oView->genHelperView('cmsc/table/data-table-search'); return $data; } /** * Function to get module data * * @author Mareks Keišs * @category cmsPermissions Controller * @param int $page * @param array $filter * @param int $pages * @return array of data * @version 1.1 */ public function getModuleData($page = 1, $filter = array(), &$pages) { $where = "AND 1"; $sort = "pp.id DESC"; $offset = (($page?$page:1)-1) * $this->cmsTableRecordsPerPage; $tFields = $this->getTableFields(); // Create sort by if(getP('sortBy')) $sort = $this->module->db->genOrderByQuery(getP('sortBy'), getP('sortWay'), $tFields); // Create where clause if(count($filter)) $where = $this->module->db->genSearchFieldQuery($filter, $tFields); $subWhere = ""; $data = $this->module->getModuleRecords($where . $subWhere, $sort, $offset, $this->cmsTableRecordsPerPage); $this->oView->ROWS = $rows = $this->module->db->getSelectedRecordsCount(); $pages = floor($rows / $this->cmsTableRecordsPerPage) + ($rows%$this->cmsTableRecordsPerPage?1:0); return $data; } /** * Function to disable / enable enum records marked in table * * @author Mareks Keišs * @category cmsPermissions Controller * @param array $baseField - base field to handle * @param string $rows - passed user ids in JSON string * @return array of data */ public function changeEnumFields($baseField, $rows) { if($baseField && $rows = cJSON::decode($rows, true)){ $baseField = substr($baseField, 2); $fields = $this->getTableFields(); if(isset($fields[$baseField]['db_field'])){ if($this->module->changeRecordsStatus($this->module->db->prepData($rows), $fields[$baseField]['db_field'])){ return true; } } } cJSON::sendError(); return false; } /** * Function to delete records marked in table * * @author Mareks Keišs * @category cmsPermissions Controller * @param string $rows - passed user ids in JSON string * @return array of data */ public function delete($rows) { if($rows = cJSON::decode($rows, true)){ if($this->module->deleteRecords($this->module->db->prepData($rows))) return true; cJSON::sendError(); } return false; } /** * Function to get table record data for edit mode * * @author Mareks Keišs * @category cmsPermissions Controller * @param int $id - record id * @return array of data */ public function editCmsTableRecord($id) { if($id){ $vData = $this->module->getRecordDataById($id); if($vData['p_created']){ if(date('d-m-Y', $vData['p_created']) == date('d-m-Y')){ $vData['p_created'] = date('H:i', $vData['p_created']); }else{ $vData['p_created'] = date($this->CMSDateFormat, $vData['p_created']); } } if(date('d-m-Y', $vData['p_modified']) == date('d-m-Y')){ $vData['p_modified'] = date('H:i', $vData['p_modified']); }else{ $vData['p_modified'] = date($this->CMSDateFormat, $vData['p_modified']); } $this->oView->PPR = $vData; } $this->oView->PT = $this->module->getClassificators(); // Load user groups $vGroups = array(); if($gr = $this->module->getPermissionGroups($id)){ if(count($gr)){ foreach($gr as $v){ $v['group_name'] = ucfirst(strtolower(str_replace('_', ' ', $v['group_name']))); $vGroups[] = $v; } } } $this->oView->GROUPS = $vGroups; return array( 'show' => array('buttons_top' => false, 'buttons_bottom' => true), 'btn' => $this->getFormButtons(), 'html' => $this->oView->genTemplate('permissionEdit'), ); } /** * Function to quick add permissions * * @author Aivars Žukovskis * @category cmsPermissions Controller * @return array of data */ public function quickAddPermissions() { return array( 'show' => array('buttons_top' => false, 'buttons_bottom' => true), 'btn' => $this->getFormButtons(), 'html' => $this->oView->genTemplate('quickAdd'), ); } /** * Function to save Record data * * @author Mareks Keišs * @category cmsPermissions Controller * @param int $recordId - record id * @param string $fields - param JSON string * @return array of data */ public function saveRecordData($recordId, $fields) { if($fields){ $fields = $this->getSubmittedDataAsArray($fields); } // Start save process if($fields){ // Validate fields $valid = new cValidator($this); $errors = $valid->checkArray($fields, $this->getValCfg()); if($errors !== true){ cJSON::sendError(array('data' => $errors)); } // We have quick add if(!empty($fields['pbase']['quickAdd'])){ $this->quickAddSave($fields); }else{ $update = array( 'p_name' => $fields['pbase']['p_name'], 'p_type_id' => (!empty($fields['psettings']['p_type_id']) ? $fields['psettings']['p_type_id'] : 0), 'p_description' => $fields['pbase']['p_description'], 'p_blocked' => (!empty($fields['psettings']['p_blocked']) ? 1 : 0), 'p_modified' => time(), ); if(!$recordId) $update['p_created'] = time(); // Update user groups data $vInsert = array(); if(!empty($fields['groups'])){ foreach($fields['groups'] as $k => $v){ if($v == "1"){ $vInsert[] = array( 'user_id' => 0, 'groups_id' => substr($k, 1), 'permissions_id' => &$recordId, ); } } } // Update / Insert record data $oldId = $recordId; if($recordId = $this->module->saveRecordDataById($recordId, $update)){ // Rewrite permissions linked to groups $this->module->rewriteLinkedPermissions($recordId, $vInsert); cJSON::sendOk($oldId?"":array('newid' => $recordId)); } cJSON::sendError(); } } } /** * Function to save quick add form * * @author Aivars Žukovskis * @category cmsPermissions Controller * @param array $vFields - fields for save * @return array of data * @version 1.1 */ public function quickAddSave($vFields) { if(!empty($vFields) && is_array($vFields)){ if($vFields['pbase']['quickAdd'] != 1) cJSON::sendError($this->gM('Error on save, probably already saved!')); $vDefaultPermissions = array('EDIT', 'ADD_NEW', 'DELETE', 'SHOW_MANAGEMENT'); $vMultiInsert = array(); $vMultiInsertLinks = array(); $vPb = &$vFields['pbase']; if(strlen($vPb['p_additional'])){ $vAdds = array_filter(explode(",", preg_replace('/\s+/', '', $vPb['p_additional']))); if(!empty($vAdds) && is_array($vAdds)){ foreach($vAdds as $v) $vDefaultPermissions[] = strtoupper($v); } } $sName = (substr($vPb['p_name'], -1) == '_' ? $vPb['p_name'] : $vPb['p_name'] . "_"); $groupId = 0; // Reserve permissions ids && delete temp row after $rowsToInsert = count($vDefaultPermissions); $lastId = $this->module->rsvTableRows($rowsToInsert + 1) - $rowsToInsert; $this->module->deleteTempRows(); $iTime = time(); foreach($vDefaultPermissions as $v){ $sDesc = "Permission to %PP% in %DD%"; $sDesc = str_replace(array('%PP%', '%DD%'), array(strtolower(preg_replace('/_/', ' ' ,$v)), $vPb['p_description']), $sDesc); $bBlocked = (isset($fields['psettings']['p_blocked']) ? 1 : 0); $vMultiInsert[] = array( 'id' => $lastId, 'p_name' => $sName . $v, 'p_type_id' => (!empty($fields['psettings']['p_type_id']) ? $fields['psettings']['p_type_id'] : 0), 'p_description' => $sDesc, 'p_blocked' => $bBlocked, 'p_modified' => $iTime, ); $vMultiInsertLinks[] = array( 'user_id' => 0, 'groups_id' => &$groupId, 'permissions_id' => $lastId++ ); } unset($vPb); // Create group insert $sName = substr($sName, 0, strlen($sName) -1); $vGroupInsert = array( 'group_name' => $sName, 'group_description' => "Full permission for " . strtolower(preg_replace('/_/', ' ' ,$sName)), 'group_blocked' => 0, 'group_modified' => $iTime, ); // Insert permissions if($this->module->insertMulti($vMultiInsert)){ // Insert group if($groupId = $this->module->insertGroup($vGroupInsert)){ // Insert permissions links to group $this->module->insertMulti($vMultiInsertLinks, 'mod_users_permissions'); }else cJSON::sendError($this->gM('Error to insert permission group')); cJSON::sendOk(); }else{ cJSON::sendError($this->gM('Error to insert permissions')); } } } /** * Function to create table headers + search * * @author Mareks Keišs * @category cmsPermissions Controller * @param string $ids json string * @return array of data * @version 1.1 */ public function generateInsertSql($ids) { if(!!$ids) $ids = json_decode($ids, true); $vData = $this->module->getPermissionDataForSqlExport($ids); if(!empty($vData) && is_array($vData)){ $sSqlInsertPermissions = "INSERT INTO mod_permissions (id, p_name, p_type_id, p_description, p_blocked, p_modified, p_created) VALUES"; $sSqlInsertLinks = ""; $sSqlInsertGroup = ""; $sSqlPt1 = ""; $sSqlPt2 = ""; $vGroupsIds = array(); $vPermissionsIds = array(); foreach($vData as $v){ // Save id for later use $vPermissionsIds[$v['id']] = $v['id']; // Gen. insert query string $sSqlPt1 .= ",\n ({$v['id']}, '{$v['p_name']}', '{$v['p_type_id']}', '{$v['p_description']}', '{$v['p_blocked']}', {$v['p_modified']}, {$v['p_created']})"; } // Get all links for permissions vs group id $vLinkData = $this->module->getPermission2GroupLinkDataForSqlExport($ids); if(!!$vLinkData){ foreach($vLinkData as $k=>$v){ $vGroupsIds[] = $k; foreach($v as $vv){ $sSqlPt2 .= ",\n (0, {$k}, {$vv})"; } } } $sSqlInsertPermissions .= substr($sSqlPt1, 1) . ";"; if(strlen($sSqlPt2)){ $sSqlInsertLinks = "INSERT INTO mod_users_permissions (user_id, groups_id, permissions_id) VALUES"; $sSqlInsertLinks .= substr($sSqlPt2, 1) . ";"; // Get all groups data $vGroupsData = $this->module->getGroupsDataForSqlExport($vGroupsIds); if(!empty($vGroupsData) && is_array($vGroupsData)){ $sSqlPt3 = ""; $sSqlInsertGroup = "INSERT INTO mod_permissions_groups (id, group_name, group_description, group_type, group_blocked, group_modified, group_created) VALUES"; foreach($vGroupsData as $v) $sSqlPt3 .= ",\n ({$v['id']}, '{$v['group_name']}', '{$v['group_description']}', '{$v['group_blocked']}', '{$v['group_blocked']}', {$v['group_modified']}, {$v['group_created']})"; $sSqlInsertGroup .= substr($sSqlPt3, 1) . ";"; } } $sSqlPermDelete = ""; $sSqlGroupsDelete = ""; $sSqlDeleteLinks1 = ""; $sSqlDeleteLinks2 = ""; if(count($vPermissionsIds)){ $sSqlPermDelete = "DELETE FROM mod_permissions WHERE id IN (". implode (", ", $vPermissionsIds) .");"; $sSqlDeleteLinks1 = "DELETE FROM mod_users_permissions WHERE user_id = 0 AND permissions_id IN (". implode (", ", $vPermissionsIds) .");"; } if(count($vGroupsIds)){ $sSqlGroupsDelete = "DELETE FROM mod_permissions_groups WHERE id IN (". implode (", ", $vGroupsIds) .");"; $sSqlDeleteLinks2 = "DELETE FROM mod_users_permissions WHERE user_id = 0 AND groups_id IN (". implode (", ", $vGroupsIds) .");"; } return array( 'sql' => array( 'sDeletePer' => $sSqlPermDelete, 'sDeleteGr' => $sSqlGroupsDelete, 'sDeleteLinks1' => $sSqlDeleteLinks1, 'sDeleteLinks2' => $sSqlDeleteLinks2, 'sGroups' => $sSqlInsertGroup, 'sInsert' => $sSqlInsertPermissions, 'sLinks' => $sSqlInsertLinks, ) ); } return false; } /** * Function to create table headers + search * * @author Mareks Keišs * @category cmsPermissions Controller * @return array of data * @version 1.1 */ public function getTableFields() { if(!$this->chkP('CMS_APP_PERMISSIONS_SHOW_MANAGEMENT')){ return false; } $statusData = array( '' => array( 'title' => $this->gM("Select") ), 0 => array( 'title' => $this->gM("Active") ), 1 => array( 'title' => $this->gM("Inactive") ) ); $tFields = array( "checkbox" => array( 'sort' => false, 'title' => '', 'class' => 'w4 center rchk' ), "id" => array( 'sort' => true, 'search' => true, 'title' => $this->gM("ID"), 'class' => 'w8 center sortDesc sort', 'db_field' => 'pp.id', 'type' => 'input', ), "p_name" => array( 'sort' => true, 'search' => true, 'title' => $this->gM("Permission title"), 'class' => 'w36', 'db_field' => 'pp.p_name', 'type' => 'input', ), "p_description" => array( 'sort' => true, 'search' => true, 'title' => $this->gM("Description"), 'class' => 'w42', 'db_field' => 'pp.p_description', 'type' => 'input', ), "type_name" => array( 'sort' => true, 'search' => true, 'title' => $this->gM("Type"), 'class' => 'w16', 'db_field' => 'pp.p_type', 'type' => 'input', ), "status" => array( 'sort' => false, 'search' => false, 'title' => $this->gM("Blocked"), 'class' => 'w9 center', 'field' => 'p_blocked', 'db_field' => 'pp.p_blocked', 'type' => 'dropBox', 'data' => $statusData, 'default' => '', //'checkbox' => true, ), "status" => array( 'sort' => false, 'search' => false, 'title' => $this->gM("Blocked"), 'class' => 'w9 center', 'field' => 'p_blocked', 'db_field' => 'pp.p_blocked', 'type' => 'dropBox', 'data' => $statusData, 'default' => '', //'checkbox' => true, ), "buttons" => array( 'sort' => false, 'title' => $this->gM("Actions"), 'class' => 'w20', 'btnset' => array( 'ledit' => array( 'edit' => true, 'title' => $this->gM("Edit"), ), 'ldelete' => array( 'title' => $this->gM("Delete"), ) ) ) ); if(!$this->chkP('SYS_SHOW_TABLE_IDS')) unset($tFields['id']); return $tFields; } /** * Function to get js translations for view * * @author Mareks Keišs * @category cmsPermissions Controller * @return array of data */ public function getTranslations(){ return array( 'yes' => $this->gM('Yes'), 'no' => $this->gM('No'), 'delTitle' => $this->gM('Delete permissions?'), 'delMessage' => $this->gM('Selected permissions will be permanently deleted and cannot be recovered. Confirm delete?'), 'buttonYes' => $this->gM('Delete selected permission'), 'buttonCancel' => $this->gM('Cancel operation'), ); } /** * Function to get table actions * * @author Mareks Keišs * @category cmsPermissions Controller * @return array of data */ public function getTableActions(){ $actions = array( 'inew' => array( 'lbl' => $this->gM("Add new"), 'icon' => 'nico-add' ), 'iquickadd' => array( 'lbl' => $this->gM("Quick add"), 'icon' => 'nico-add' ), 'igensql' => array( 'lbl' => $this->gM("Gen. sql"), 'icon' => '' ), 'sepline', 'istatus' => array( 'lbl' => $this->gM("Change item status"), ), 'sepline', 'idelete' => array( 'lbl' => $this->gM("Delete selected"), 'icon' => 'nico-delete' ), ); // Reformat drop down reformatDropDown($actions, false); return $actions; } /** * Function to get js validator cfg * * @author Mareks Keišs * @category cmsPermissions Controller * @return array of data */ public function getValCfg(){ $compWarn = $this->gM('Please fill in the field!'); return array( 'p_name' => array( cValidator::P_TYPE => cValidator::TY_STR, cValidator::P_COMP => 1, cValidator::P_TEST => array(cValidator::CHK_STR), 'comp-warning' => $compWarn ), 'p_description' => array( cValidator::P_TYPE => cValidator::TY_STR, cValidator::P_COMP => 1, cValidator::P_TEST => array(cValidator::CHK_STR), 'comp-warning' => $compWarn ), 'p_type' => array( cValidator::P_TYPE => cValidator::TY_STR, cValidator::P_COMP => 0, cValidator::P_TEST => array(cValidator::CHK_STR), 'comp-warning' => $compWarn ), /* FOR QUICK ADD */ 'p_additional' => array( cValidator::P_TYPE => cValidator::TY_STR, cValidator::P_COMP => 0, cValidator::P_TEST => array(cValidator::CHK_STR), 'comp-warning' => $compWarn ), ); } /** * Function to get form buttons * * @author Mareks Keišs * @category cmsPermissions Controller * @return array of data */ public function getFormButtons(){ return array( 1 => array( 'id' => 'fsave', 'lbl' => $this->gM('Save') ), 2 => array( 'id' => 'fcancel', 'lbl' => $this->gM('Cancel') ) ); } }