* @package common
* @version $Id$
* @link http://www.zentao.net
*/
class commonModel extends model
{
public static $requestErrors = array();
/**
* 设置用户配置信息。
* Set config of user.
*
* @access public
* @return void
*/
public function setUserConfig()
{
$this->sendHeader();
$this->setCompany();
$this->setUser();
$this->setApproval();
$this->loadConfigFromDB();
$this->loadCustomFromDB();
if(!$this->checkIP()) return print($this->lang->ipLimited);
}
/**
* 同步执行、项目、项目集的状态。
* Set the status of execution, project, and program to doing.
*
* @param int $objectID
* @access public
* @return void
*/
public function syncPPEStatus(int $objectID)
{
global $app;
$rawModule = $app->rawModule;
if($rawModule == 'task' or $rawModule == 'effort')
{
$taskID = $objectID;
$execution = $this->syncExecutionStatus($taskID);
$project = $this->syncProjectStatus($execution);
$this->syncProgramStatus($project);
}
if($rawModule == 'execution')
{
$executionID = $objectID;
$execution = $this->dao->select('id, project, grade, parent, status, deleted')->from(TABLE_EXECUTION)->where('id')->eq($executionID)->fetch();
$this->syncExecutionByChild($execution);
$project = $this->syncProjectStatus($execution);
$this->syncProgramStatus($project);
}
if($rawModule == 'project')
{
$projectID = $objectID;
$project = $this->dao->select('id, parent, path')->from(TABLE_PROJECT)->where('id')->eq($projectID)->fetch();
$this->syncProgramStatus($project);
}
if($rawModule == 'program' and $this->config->systemMode == 'ALM')
{
$programID = $objectID;
$program = $this->dao->select('id, parent, path')->from(TABLE_PROGRAM)->where('id')->eq($programID)->fetch();
$this->syncProgramStatus($program);
}
}
/**
* 项目开始时,设置项目所属的项目集的状态为进行中。
* Set the status of the program to which theproject is linked as Ongoing.
*
* @param object $project
* @access public
* @return void
*/
public function syncProgramStatus(object $project)
{
if($project->parent == 0) return;
$parentPath = str_replace(",{$project->id},", '', $project->path);
$parentPath = explode(',', trim($parentPath, ','));
$waitList = $this->dao->select('id')->from(TABLE_PROGRAM)
->where('id')->in($parentPath)
->andWhere('status')->eq('wait')
->orderBy('id_desc')
->fetchPairs();
$this->dao->update(TABLE_PROGRAM)->set('status')->eq('doing')->set('realBegan')->eq(helper::now())->where('id')->in($waitList)->exec();
$this->loadModel('action');
foreach($waitList as $programID)
{
$this->action->create('program', $programID, 'syncprogram');
}
}
/**
* 执行开始时,设置执行所属的项目和项目所属的项目集的状态为进行中。
* Set the status of the project to which the execution is linked as Ongoing.
*
* @param object $execution
* @access public
* @return object $project
*/
public function syncProjectStatus(object $execution): object
{
$projectID = $execution->project;
$project = $this->dao->select('*')->from(TABLE_PROJECT)->where('id')->eq($projectID)->fetch();
$today = helper::today();
if($project->status == 'wait')
{
$this->dao->update(TABLE_PROJECT)
->set('status')->eq('doing')
->beginIf(helper::isZeroDate($project->realBegan))->set('realBegan')->eq($today)->fi()
->where('id')->eq($projectID)
->exec();
$this->loadModel('project')->recordFirstEnd($projectID);
$actionType = $project->multiple ? 'syncproject' : 'syncmultipleproject';
$this->loadModel('action')->create('project', $projectID, $actionType);
}
return $project;
}
/**
* 子阶段开始时,设置子阶段所属的父阶段和项目的状态为进行中。
* Set the status of the execution to which the sub execution is linked as Ongoing.
*
* @param object $execution
* @access public
* @return object|false $parentExecution
*/
public function syncExecutionByChild(object $execution): object|false
{
if($execution->grade == 1) return false;
$today = helper::today();
$parentExecution = $this->dao->select('*')->from(TABLE_EXECUTION)->where('id')->eq($execution->parent)->fetch();
if($execution->deleted == '0' and $execution->status == 'doing' and in_array($parentExecution->status, array('wait', 'closed')))
{
$this->dao->update(TABLE_EXECUTION)
->set('status')->eq('doing')
->beginIf(helper::isZeroDate($parentExecution->realBegan))->set('realBegan')->eq($today)->fi()
->where('id')->eq($execution->parent)
->exec();
$this->loadModel('action')->create('execution', $execution->parent, 'syncexecutionbychild');
}
$project = $this->loadModel('project')->getByID($execution->project);
if($project->model == 'waterfall' or $project->model == 'waterfallplus') $this->loadModel('programplan')->computeProgress($execution->id);
return $parentExecution;
}
/**
* 任务开始时,设置任务所属的执行、项目和项目所属的项目集的状态为进行中。
* Set the status of the execution to which the task is linked as Ongoing.
*
* @param int $taskID
* @access public
* @return object $execution
*/
public function syncExecutionStatus(int $taskID): object
{
$execution = $this->dao->select('t1.*')->from(TABLE_EXECUTION)->alias('t1')
->leftJoin(TABLE_TASK)->alias('t2')->on('t1.id=t2.execution')
->where('t2.id')->eq($taskID)
->fetch();
$today = helper::today();
if($execution->status == 'wait')
{
$this->dao->update(TABLE_EXECUTION)->set('status')->eq('doing')->set('realBegan')->eq($today)->where('id')->eq($execution->id)->exec();
$this->loadModel('project')->recordFirstEnd($execution->id);
$this->loadModel('action')->create('execution', $execution->id, 'syncexecution');
if($execution->parent)
{
$execution = $this->dao->select('*')->from(TABLE_EXECUTION)->where('id')->eq($execution->id)->fetch(); // Get updated execution.
$this->syncExecutionByChild($execution);
}
}
return $execution;
}
/**
* 设置HTTP标头。
* Set the header info.
*
* @access public
* @return void
*/
public function sendHeader()
{
helper::header('Content-Type', "text/html; Language={$this->config->charset}");
helper::header('Cache-Control', 'private');
/* Send HTTP header. */
if($this->config->framework->sendXCTO) helper::header('X-Content-Type-Options', 'nosniff');
if($this->config->framework->sendXXP) helper::header('X-XSS-Protection', '1; mode=block');
if($this->config->framework->sendHSTS) helper::header('Strict-Transport-Security', 'max-age=3600; includeSubDomains');
if($this->config->framework->sendRP) helper::header('Referrer-Policy', 'no-referrer-when-downgrade');
if($this->config->framework->sendXPCDP) helper::header('X-Permitted-Cross-Domain-Policies', 'master-only');
if($this->config->framework->sendXDO) helper::header('X-Download-Options', 'noopen');
/* Set Content-Security-Policy header. */
if($this->config->CSPs)
{
foreach($this->config->CSPs as $CSP) helper::header('Content-Security-Policy', "$CSP;");
}
if($this->loadModel('setting')->getItem('owner=system&module=sso&key=turnon'))
{
if(isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == 'on')
{
$session = $this->config->sessionVar . '=' . session_id();
helper::header('Set-Cookie', "$session; SameSite=None; Secure=true", false);
}
}
else
{
if(!empty($this->config->xFrameOptions)) helper::header('X-Frame-Options', $this->config->xFrameOptions);
}
}
/**
* 设置公司信息。
* Set the company.
*
* First, search company by the http host. If not found, search by the default domain. Last, use the first as the default.
* After get the company, save it to session.
* @access public
* @return void
*/
public function setCompany()
{
if($this->session->company)
{
$this->app->company = $this->session->company;
}
else
{
$httpHost = $this->server->http_host;
$company = $this->loadModel('company')->getFirst();
if(!$company) $this->app->triggerError(sprintf($this->lang->error->companyNotFound, $httpHost), __FILE__, __LINE__, true);
$this->session->set('company', $company);
$this->app->company = $company;
}
}
/**
* 设置用户信息。
* Set the user info.
*
* @access public
* @return void
*/
public function setUser()
{
if($this->session->user)
{
if(!$this->app->upgrading) $this->session->user->view = $this->loadModel('user')->grantUserView();
$this->app->user = $this->session->user;
}
elseif($this->app->company->guest || (PHP_SAPI == 'cli' && (!isset($_SERVER['RR_MODE']) || $_SERVER['RR_MODE'] == 'jobs')))
{
$user = new stdClass();
$user->id = 0;
$user->account = 'guest';
$user->realname = 'guest';
$user->dept = 0;
$user->avatar = '';
$user->role = 'guest';
$user->admin = false;
$user->rights = $this->loadModel('user')->authorize('guest');
$user->groups = array('group');
$user->visions = $this->config->vision;
if(!$this->app->upgrading) $user->view = $this->user->grantUserView($user->account, $user->rights['acls']);
$this->session->set('user', $user);
$this->app->user = $this->session->user;
}
}
/**
* 设置审批配置。
* Set approval config.
*
* @access public
* @return void
*/
public function setApproval()
{
$this->config->openedApproval = (in_array($this->config->edition, array('max', 'ipd'))) && ($this->config->vision == 'rnd');
}
/**
* 获取表单的配置项。
* Obtain the config for the form.
*
* @param string $module
* @param string $method
* @static
* @access public
* @return array
*/
public static function formConfig(string $module, string $method): array
{
global $config, $app;
if($config->edition == 'open') return array();
$required = $app->dbQuery("SELECT * FROM " . TABLE_WORKFLOWRULE . " WHERE `type` = 'system' and `rule` = 'notempty'")->fetch();
$fields = $app->control->loadModel('flow')->getExtendFields($module, $method);
$formConfig = array();
$type = 'string';
foreach($fields as $fieldObject)
{
if(strpos($fieldObject->type, 'int') !== false) $type = 'int';
if(strpos($fieldObject->type, 'date') !== false) $type = 'date';
if(in_array($fieldObject->type, array('float', 'decimal'))) $type = 'float';
$formConfig[$fieldObject->field] = array('type' => $type, 'default' => $fieldObject->default, 'control' => $fieldObject->control, 'rules' => $fieldObject->rules);
$formConfig[$fieldObject->field]['required'] = strpos(",{$fieldObject->rules},", ",{$required->id},") !== false;
if(in_array($fieldObject->control, array('multi-select', 'checkbox'))) $formConfig[$fieldObject->field]['filter'] = 'join';
}
return $formConfig;
}
/**
* 从数据库加载配置信息。
* Load configs from database and save it to config->system and config->personal.
*
* @access public
* @return void
*/
public function loadConfigFromDB()
{
/* Get configs of system and current user. */
$account = isset($this->app->user->account) ? $this->app->user->account : '';
if($this->config->db->name) $config = $this->loadModel('setting')->getSysAndPersonalConfig($account);
$this->config->system = isset($config['system']) ? $config['system'] : array();
$this->config->personal = isset($config[$account]) ? $config[$account] : array();
/* Override the items defined in config/config.php and config/my.php. */
if(isset($this->config->system->common)) $this->app->mergeConfig($this->config->system->common, 'common');
if(isset($this->config->personal->common)) $this->app->mergeConfig($this->config->personal->common, 'common');
$this->config->disabledFeatures = $this->config->disabledFeatures . ',' . $this->config->closedFeatures;
}
/**
* 从数据库加载自定义信息。
* Load custom lang from db.
*
* @access public
* @return void
*/
public function loadCustomFromDB()
{
$this->loadModel('custom');
if($this->app->upgrading) return;
if(!$this->config->db->name) return;
$records = $this->custom->getAllLang();
if(!$records) return;
$this->lang->db = new stdclass();
$this->lang->db->custom = $records;
}
/**
* 判断哪些方法不需要鉴权。
* Judge a method of one module is open or not.
*
* @param string $module
* @param string $method
* @access public
* @return bool
*/
public function isOpenMethod(string $module, string $method): bool
{
if(in_array("$module.$method", $this->config->openMethods)) return true;
if($module == 'block' and $method == 'main' and isset($_GET['hash'])) return true;
if($this->loadModel('user')->isLogon() or ($this->app->company->guest and $this->app->user->account == 'guest'))
{
if(stripos($method, 'ajax') !== false) return true;
if($module == 'block') return true;
if($module == 'index' and $method == 'app') return true;
if($module == 'my' and $method == 'guidechangetheme') return true;
if($module == 'product' and $method == 'showerrornone') return true;
if($module == 'misc' and in_array($method, array('downloadclient', 'changelog'))) return true;
if($module == 'tutorial' and in_array($method, array('start', 'index', 'quit', 'wizard'))) return true;
}
return false;
}
/**
* 拒绝访问的页面。
* Deny access.
*
* @param string $module
* @param string $method
* @param bool $reload
* @access public
* @return mixed
*/
public function deny(string $module, string $method, bool $reload = true)
{
if($reload)
{
/* Get authorize again. */
$user = $this->app->user;
$user->rights = $this->loadModel('user')->authorize($user->account);
$user->groups = $this->user->getGroups($user->account);
$user->admin = strpos($this->app->company->admins, ",{$user->account},") !== false;
$this->session->set('user', $user);
$this->app->user = $this->session->user;
if(commonModel::hasPriv($module, $method)) return true;
}
$vars = "module=$module&method=$method";
if(isset($this->server->http_referer))
{
$referer = helper::safe64Encode($this->server->http_referer);
$vars .= "&referer=$referer";
}
$denyLink = helper::createLink('user', 'deny', $vars);
echo json_encode(array('load' => $denyLink));
helper::end();
}
/**
* 输出运行信息。
* Print the run info.
*
* @param mixed $startTime the start time.
* @access public
* @return array the run info array.
*/
public function printRunInfo($startTime)
{
$info['timeUsed'] = round(getTime() - $startTime, 4) * 1000;
$info['memory'] = round(memory_get_peak_usage() / 1024, 1);
$info['querys'] = count(dao::$querys);
vprintf($this->lang->runInfo, $info);
return $info;
}
/**
* 格式化日期,将日期格式化为YYYY-mm-dd,将日期时间格式化为YYYY-mm-dd HH:ii:ss。
* Format the date to YYYY-mm-dd, format the datetime to YYYY-mm-dd HH:ii:ss.
*
* @param string $date
* @param string $type date|datetime|''
* @access public
* @return string
*/
public function formatDate(string $date, string $type = '')
{
if(helper::isZeroDate($date))
{
if($type == 'date') return '0000-00-00';
if($type == 'datetime') return '0000-00-00 00:00:00';
}
$datePattern = '\w{4}(\/|-)\w{1,2}(\/|-)\w{1,2}';
$datetimePattern = $datePattern . ' \w{1,2}\:\w{1,2}\:\w{1,2}';
if(empty($type))
{
if(!preg_match("/$datePattern/", $date) and !preg_match("/$datetimePattern/", $date)) return $date;
if(preg_match("/$datePattern/", $date) === 1) $type = 'date';
if(preg_match("/$datetimePattern/", $date) === 1) $type = 'datetime';
}
if($type == 'date') $format = 'Y-m-d';
if($type == 'datetime') $format = 'Y-m-d H:i:s';
return date($format, strtotime($date));
}
/**
* 创建菜单项链接。
* Create menu item link
*
* @param object $menuItem
*
* @static
* @access public
* @return string
*/
public static function createMenuLink(object $menuItem): string
{
$link = $menuItem->link;
if(is_array($menuItem->link))
{
$vars = isset($menuItem->link['vars']) ? $menuItem->link['vars'] : '';
if(isset($menuItem->tutorial) and $menuItem->tutorial)
{
if(!empty($vars)) $vars = helper::safe64Encode($vars);
$link = helper::createLink('tutorial', 'wizard', "module={$menuItem->link['module']}&method={$menuItem->link['method']}¶ms=$vars");
}
else
{
$link = helper::createLink($menuItem->link['module'], $menuItem->link['method'], $vars);
}
}
return $link;
}
/**
* 获取左侧一级导航。
* Get main nav items list
*
* @param string $moduleName
*
* @static
* @access public
* @return array
*/
public static function getMainNavList(string $moduleName): array
{
global $lang, $app, $config;
$app->loadLang('my');
$menuOrder = $lang->mainNav->menuOrder;
ksort($menuOrder);
$items = array();
$lastItem = end($menuOrder);
$printDivider = false;
foreach($menuOrder as $key => $group)
{
if($group != 'my' && !empty($app->user->rights['acls']['views']) && !isset($app->user->rights['acls']['views'][$group])) continue; // 后台权限分组中没有给导航视图
$nav = $lang->mainNav->$group;
list($title, $currentModule, $currentMethod, $vars) = explode('|', $nav);
/* When last divider is not used in mainNav, use it next menu. */
$printDivider = ($printDivider or ($lastItem != $key) and strpos($lang->dividerMenu, ",{$group},") !== false) ? true : false;
if($printDivider and !empty($items))
{
$items[] = 'divider';
$printDivider = false;
}
$display = false;
/* 1. 有权限则展示导航. */
if(common::hasPriv($currentModule, $currentMethod)) $display = true;
/* 2. 如果没有资产库落地页的权限,则查看是否有资产库其他方法的权限. */
if($currentModule == 'assetlib' && !$display) list($display, $currentMethod) = commonTao::setAssetLibMenu($display, $currentModule, $currentMethod);
/* 3. 可以个性化设置的导航,如果没有落地页的权限,则查看是否有其他落地页的权限。 */
$moduleLinkList = $currentModule . 'LinkList';
if(!$display and isset($lang->my->$moduleLinkList) and $config->vision != 'or') list($display, $currentMethod) = commonTao::setPreferenceMenu($display, $currentModule, $currentMethod);
/* 4. 不可以个性化设置的导航,如果没有落地页的权限,则查看是否有对应app下其他方法的权限. */
if(!$display and isset($lang->$currentModule->menu) and !in_array($currentModule, array('program', 'product', 'project', 'execution', 'demandpool'))) list($display, $currentMethod) = commonTao::setOtherMenu($display, $currentModule, $currentMethod);
/* 5. 如果以上权限都没有,则最后查看是否有该应用下任意一个顶部一级导航的权限。 */
if(!$display and isset($lang->$group->menu)) list($display, $currentModule, $currentMethod) = commonTao::setMenuByGroup($group, $display, $currentModule, $currentMethod);
if(!$display) continue;
/* Assign vars. */
$item = new stdClass();
$item->group = $group;
$item->code = $group;
$item->active = zget($lang->navGroup, $moduleName, '') == $group or $moduleName != 'program' and $moduleName == $group;
$item->title = $title;
$item->moduleName = $currentModule;
$item->methodName = $currentMethod;
$item->vars = $vars;
$isTutorialMode = commonModel::isTutorialMode();
if($isTutorialMode and $currentModule == 'project')
{
if(!empty($vars)) $vars = helper::safe64Encode($vars);
$item->url = helper::createLink('tutorial', 'wizard', "module={$currentModule}&method={$currentMethod}¶ms=$vars", '', 0, 0, 1);
}
else
{
$item->url = helper::createLink($currentModule, $currentMethod, $vars, '', false, 0, 1);
}
$items[] = $item;
}
/* Fix bug 14574. */
if(end($items) == 'divider') array_pop($items);
return $items;
}
/**
* Get active main menu.
*
* @static
* @access public
* @return string
*/
public static function getActiveMainMenu(): string
{
global $app;
$isTutorialMode = commonModel::isTutorialMode();
$currentModule = $app->rawModule;
$currentMethod = $app->rawMethod;
if($isTutorialMode && defined('WIZARD_MODULE')) $currentModule = WIZARD_MODULE;
if($isTutorialMode && defined('WIZARD_METHOD')) $currentMethod = WIZARD_METHOD;
/* Print all main menus. */
$menu = customModel::getMainMenu();
$activeMenu = '';
foreach($menu as $menuItem)
{
if(isset($menuItem->hidden) and $menuItem->hidden and (!isset($menuItem->tutorial) or !$menuItem->tutorial)) continue;
if(empty($menuItem->link)) continue;
/* Init the these vars. */
$alias = isset($menuItem->alias) ? $menuItem->alias : '';
$subModule = isset($menuItem->subModule) ? explode(',', $menuItem->subModule) : array();
$exclude = isset($menuItem->exclude) ? $menuItem->exclude : '';
if($menuItem->name == $currentModule and strpos(",$exclude,", ",$currentModule-$currentMethod,") === false) $activeMenu = $menuItem->name;
if($subModule and in_array($currentModule, $subModule) and strpos(",$exclude,", ",$currentModule-$currentMethod,") === false) $activeMenu = $menuItem->name;
if($menuItem->link)
{
$module = '';
$method = '';
if(is_array($menuItem->link))
{
if(isset($menuItem->link['module'])) $module = $menuItem->link['module'];
if(isset($menuItem->link['method'])) $method = $menuItem->link['method'];
}
if($module == $currentModule and ($method == $currentMethod or strpos(",$alias,", ",$currentMethod,") !== false) and strpos(",$exclude,", ",$currentMethod,") === false) $activeMenu = $menuItem->name;
/* Print drop menus. */
if(isset($menuItem->dropMenu))
{
foreach($menuItem->dropMenu as $dropMenuName => $dropMenuItem)
{
if(empty($dropMenuItem)) continue;
if(isset($dropMenuItem->hidden) and $dropMenuItem->hidden) continue;
/* Parse drop menu link. */
$dropMenuLink = zget($dropMenuItem, 'link', $dropMenuItem);
list($subLabel, $subModule, $subMethod, $subParams) = explode('|', $dropMenuLink);
if(!common::hasPriv($subModule, $subMethod)) continue;
$activeMainMenu = false;
if($currentModule == strtolower($subModule) and $currentMethod == strtolower($subMethod))
{
$activeMainMenu = true;
}
else
{
$subModule = isset($dropMenuItem['subModule']) ? explode(',', $dropMenuItem['subModule']) : array();
$subExclude = isset($dropMenuItem['exclude']) ? $dropMenuItem['exclude'] : $exclude;
if($subModule and in_array($currentModule, $subModule) and strpos(",$subExclude,", ",$currentModule-$currentMethod,") === false) $activeMainMenu = true;
}
if($activeMainMenu) $activeMenu = $dropMenuName;
}
}
}
}
return $activeMenu;
}
/**
* Print icon of split line.
*
* @static
* @access public
* @return void
*/
public static function printDivider()
{
echo " ";
}
/**
* Print icon of comment.
*
* @param string $commentFormLink
* @param object $object
*
* @static
* @access public
* @return mixed
*/
public static function printCommentIcon($commentFormLink, $object = null)
{
global $lang;
if(!commonModel::hasPriv('action', 'comment', $object)) return false;
echo html::commonButton(' ' . $lang->action->create, '', 'btn btn-link pull-right btn-comment');
echo <<