ElixirVault/www/system-brs-core/sys/sysPermissions/inc/sysPermissionsController.php

733 lines
24 KiB
PHP

<?php
namespace BRSystems\Core\Sys\sysPermissions\inc;
use BRSystems\Core\Cms\cmsClassificators\inc\cmsClassificatorsModule;
use BRSystems\Core\Library\cCore\cCore;
use BRSystems\Core\Library\cJSON\cJSON;
use BRSystems\Core\Library\cValidator\cValidator;
/**
* sysPermissions Controller
*
* @category sysPermissions Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @since Version 2.0
*/
class sysPermissionsController 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 sysPermissionsModule();
$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 sysPermissions Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 = array();
if($filter_json){
$filter = cJSON::decode($filter_json, true);
}
$this->oView->MODULE_TITLE = $this->gM("CMS 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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;
}else{
cJSON::sendError();
}
}
return false;
}
/**
* Function to get table record data for edit mode
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysPermissions Controller
* @param int $id - record id
* @return array of data
*/
public function editCmsTableRecord($id) {
if($id){
$PP = $this->module->getRecordDataById($id);
if(date('d-m-Y', $PP['p_created']) == date('d-m-Y')){
$PP['p_created'] = date('H:i', $PP['p_created']);
}else{
$PP['p_created'] = date($this->CMSDateFormat, $PP['p_created']);
}
if(date('d-m-Y', $PP['p_modified']) == date('d-m-Y')){
$PP['p_modified'] = date('H:i', $PP['p_modified']);
}else{
$PP['p_modified'] = date($this->CMSDateFormat, $PP['p_modified']);
}
$this->oView->PPR = $PP;
}
$cls = new cmsClassificatorsModule();
$this->oView->PT = $cls->getClTypes($cls::CT_TYPE_PERMISSION_GROUPS);
// 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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['pbase']['p_type'])?1: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 <mareks.keiss@brsystems.lv>
* @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' => 0,
'p_description' => $sDesc,
'p_blocked' => $bBlocked,
'p_modified' => $iTime,
'p_created' => $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,
'group_created' => $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, 'site_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 <mareks.keiss@brsystems.lv>
* @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 site_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']})";
// If linked group, we save group id and gen. insert query for links
if(!empty($v['groups_id'])){
$vGroupsIds[$v['groups_id']] = $v['groups_id'];
$sSqlPt2 .= ",\n (0, {$v['groups_id']}, {$v['id']})";
}
}
$sSqlInsertPermissions .= substr($sSqlPt1, 1) . ";";
if(strlen($sSqlPt2)){
$sSqlInsertLinks = "INSERT INTO site_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 site_users_groups (id, group_name, group_description, 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_modified']}, {$v['group_created']})";
$sSqlInsertGroup .= substr($sSqlPt3, 1) . ";";
}
}
$sSqlPermDelete = "";
$sSqlGroupsDelete = "";
$sSqlDeleteLinks1 = "";
$sSqlDeleteLinks2 = "";
if(count($vPermissionsIds)){
$sSqlPermDelete = "DELETE FROM site_permissions WHERE id IN (". implode (", ", $vPermissionsIds) .");";
$sSqlDeleteLinks1 = "DELETE FROM site_users_permissions WHERE permissions_id IN (". implode (", ", $vPermissionsIds) .");";
}
if(count($vGroupsIds)){
$sSqlGroupsDelete = "DELETE FROM site_users_groups WHERE id IN (". implode (", ", $vGroupsIds) .");";
$sSqlDeleteLinks2 = "DELETE FROM site_users_permissions WHERE 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions Controller
* @return array of data
* @version 1.1
*/
public function getTableFields() {
if(!$this->oUser->chkPermission('SYS_PERMISSIONS_SHOW_MANAGEMENT', false, false)){
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',
'db_field' => 'pp.id',
'type' => 'input',
),
"p_name" => array(
'sort' => true,
'search' => true,
'title' => $this->gM("Permission title"),
'class' => 'w30',
'db_field' => 'pp.p_name',
'type' => 'input',
),
"p_description" => array(
'sort' => true,
'search' => true,
'title' => $this->gM("Description"),
'class' => 'w30',
'db_field' => array ('pp.p_description', 'mc.cl_name'),
'db_link' => 'OR',
'type' => 'input',
),
"type_name" => array(
'sort' => true,
'search' => false,
'title' => $this->gM("Type"),
'class' => 'w16',
'db_field' => 'mc.cl_name',
'type' => 'input',
),
"status" => array(
'sort' => false,
'search' => false,
'title' => $this->gM("Blocked"),
'class' => 'w7 center',
'field' => 'p_blocked',
'db_field' => 'pp.p_blocked',
'type' => 'dropBox',
'data' => $statusData,
'default' => '',
),
"buttons" => array(
'sort' => false,
'class' => 'w20',
'title' => $this->gM("Actions"),
'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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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' => ''
),
'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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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 <mareks.keiss@brsystems.lv>
* @category sysPermissions 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')
)
);
}
}