diff --git a/CHANGELOG.md b/CHANGELOG.md index 70b1d41b..355eb4bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Make the plugin compatible with the Content Security Policy +### Fixed + +- Faster dashboards and report pages: report configurations and rights are read once per page +- Faster "Backlogs", "Computers by OS", "Tickets per service", "Ticket status by technician" and "Computers by entity" reports, with the same results +- Fewer queries on every GLPI page and on the core statistics page + ## [1.10.4] - 2026-11-04 ### Fixed diff --git a/ajax/common.tabs.php b/ajax/common.tabs.php index 525b5dd0..0faf390e 100644 --- a/ajax/common.tabs.php +++ b/ajax/common.tabs.php @@ -33,5 +33,8 @@ Session::checkLoginUser(); +// the tab only reads the session: release its lock for the other requests of the user +session_write_close(); + $common = new PluginMreportingCommon(); $common->showCentral($_REQUEST); diff --git a/inc/baseclass.class.php b/inc/baseclass.class.php index 1ef7b64e..d005f0ea 100644 --- a/inc/baseclass.class.php +++ b/inc/baseclass.class.php @@ -210,4 +210,19 @@ public function __construct($config = []) $config['randname'], ); } + + /** + * SQL expression of the end of the selected period ('Y-m-d 23:59:59') containing a date field, + * the same value as criteria_list_date / criteria_list_date2 give for `date` / `solvedate`. + * + * @param string $field quoted column name, e.g. `glpi_tickets`.`date` + */ + protected function getPeriodEndSql(string $field): string + { + return match ($this->period_interval) { + 'WEEK' => "DATE_FORMAT($field + INTERVAL (6 - WEEKDAY($field)) DAY, '{$this->period_datetime}')", + 'MONTH' => "CONCAT(LAST_DAY(DATE_FORMAT($field, '{$this->period_datetime}')), ' 23:59:59')", + default => "DATE_FORMAT($field, '{$this->period_datetime}')", + }; + } } diff --git a/inc/common.class.php b/inc/common.class.php index 2052c0e4..3f479053 100644 --- a/inc/common.class.php +++ b/inc/common.class.php @@ -110,6 +110,12 @@ public static function getMenuContent() */ public static function parseAllClasses($inc_dir) { + // the files are read once per request: getAllReports() and the config list call this several times + static $cache = []; + if (isset($cache[$inc_dir])) { + return $cache[$inc_dir]; + } + $classes = []; $matches = []; @@ -130,7 +136,7 @@ public static function parseAllClasses($inc_dir) } } - return $classes; + return $cache[$inc_dir] = $classes; } /** @@ -209,15 +215,16 @@ public function getAllReports($with_url = true, $params = []) $reports[$classname]['functions'][$i]['short_classname'] = $scn; $reports[$classname]['functions'][$i]['is_active'] = false; - $config = new PluginMreportingConfig(); - if ($config->getFromDBByFunctionAndClassname($f_name, $classname)) { - if ($config->fields['is_active'] == 1) { + // configs and rights come from per-request caches: one query each instead of 4 per report + $config_fields = PluginMreportingConfig::getCachedConfig($f_name, $classname); + if ($config_fields !== null) { + if ($config_fields['is_active'] == 1) { $reports[$classname]['functions'][$i]['is_active'] = true; - $reports[$classname]['functions'][$i]['id'] = $config->fields['id']; + $reports[$classname]['functions'][$i]['id'] = $config_fields['id']; } $reports[$classname]['functions'][$i]['right'] = READ; if (isset($_SESSION['glpiactiveprofile'])) { - $reports[$classname]['functions'][$i]['right'] = PluginMreportingProfile::canViewReports($_SESSION['glpiactiveprofile']['id'], $config->fields['id']); + $reports[$classname]['functions'][$i]['right'] = PluginMreportingProfile::canViewReports($_SESSION['glpiactiveprofile']['id'], $config_fields['id']); } } diff --git a/inc/config.class.php b/inc/config.class.php index 52a77636..89c2897c 100644 --- a/inc/config.class.php +++ b/inc/config.class.php @@ -66,6 +66,15 @@ class PluginMreportingConfig extends CommonDBTM { public static $rightname = 'config'; + /** + * Every report config, keyed by lowercase "classname|name" (the database comparison ignores case), + * loaded with one query the first time a read-only lookup needs it during the request. + * false marks a key matching several configs, which getFromDBByCrit() refuses too. + * + * @var array|false>|null + */ + private static ?array $configs_cache = null; + public static function getTypeName($nb = 0) { return __s('Configuration', 'mreporting'); @@ -271,6 +280,50 @@ public function getFromDBByFunctionAndClassname($function, $classname) ]); } + /** + * Fields of the config of a report, for read-only lookups: every config is loaded with one query per request. + * + * @return array|null null when no config, or several configs, match + */ + public static function getCachedConfig(string $function, string $classname): ?array + { + /** @var DBmysql $DB */ + global $DB; + + if (self::$configs_cache === null) { + self::$configs_cache = []; + foreach ($DB->request(['FROM' => self::getTable()]) as $row) { + $key = strtolower($row['classname'] . '|' . $row['name']); + self::$configs_cache[$key] = isset(self::$configs_cache[$key]) ? false : $row; + } + } + + return (self::$configs_cache[strtolower($classname . '|' . $function)] ?? null) ?: null; + } + + public static function resetConfigCache(): void + { + self::$configs_cache = null; + } + + public function post_addItem() + { + self::resetConfigCache(); + parent::post_addItem(); + } + + public function post_updateItem($history = true) + { + self::resetConfigCache(); + parent::post_updateItem($history); + } + + public function post_purgeItem() + { + self::resetConfigCache(); + parent::post_purgeItem(); + } + /** * add First config Link *@return void @@ -873,17 +926,18 @@ public static function initConfigParams($name, $classname) 'graphtype' => 'SVG', ]; - $self = new self(); - if ($self->getFromDBByFunctionAndClassname($name, $classname)) { - $crit['area'] = $self->fields['show_area']; - $crit['spline'] = $self->fields['spline']; - $crit['show_label'] = $self->fields['show_label']; - $crit['flip_data'] = $self->fields['flip_data']; - $crit['unit'] = $self->fields['unit']; - $crit['delay'] = $self->fields['default_delay']; - $crit['condition'] = $self->fields['condition']; - $crit['show_graph'] = $self->fields['show_graph']; - $crit['graphtype'] = $self->fields['graphtype']; + // read about 5 times per displayed report: served by the per-request cache + $fields = self::getCachedConfig($name, $classname); + if ($fields !== null) { + $crit['area'] = $fields['show_area']; + $crit['spline'] = $fields['spline']; + $crit['show_label'] = $fields['show_label']; + $crit['flip_data'] = $fields['flip_data']; + $crit['unit'] = $fields['unit']; + $crit['delay'] = $fields['default_delay']; + $crit['condition'] = $fields['condition']; + $crit['show_graph'] = $fields['show_graph']; + $crit['graphtype'] = $fields['graphtype']; $crit['randname'] = $classname . $name; } @@ -912,9 +966,9 @@ public static function showGraphConfigValue($name, $classname) // DEBUG_MREPORTING is constant. It is true if debug mode is enabled, false otherwise. For PHPStan, this constant is always true or false. /* @phpstan-ignore-next-line */ - $self = new self(); - if ($self->getFromDBByFunctionAndClassname($name, $classname)) { - return $self->fields['show_graph']; + $fields = self::getCachedConfig($name, $classname); + if ($fields !== null) { + return $fields['show_graph']; } return false; diff --git a/inc/helpdesk.class.php b/inc/helpdesk.class.php index b64ba093..8faeb0ae 100644 --- a/inc/helpdesk.class.php +++ b/inc/helpdesk.class.php @@ -474,31 +474,17 @@ public function reportHgbarTicketNumberByService($config = []) $delay = PluginMreportingCommon::getCriteriaDate('glpi_tickets.date', $config['delay'], $config['randname']); foreach ($this->filters as $class => $filter) { - $query = [ - 'SELECT' => [ - Ticket::getTable() . '.id', - ], - 'FROM' => Ticket::getTable(), - 'WHERE' => [ - Ticket::getTable() . '.type' => 1, - ], - ]; - - $result = $DB->request($query); $datas['labels2'][$filter['label']] = $filter['label']; - $ticket_ids = []; - foreach ($result as $ticket) { - $ticket_ids[] = $ticket['id']; - } - + // tickets that are not of type 1; `type` is NOT NULL, so this is the former + // "id NOT IN (ids of every type 1 ticket)" without loading and sending back every id $query = [ 'COUNT' => 'count', 'FROM' => Ticket::getTable(), 'WHERE' => [ [ 'NOT' => [ - Ticket::getTable() . '.id' => $ticket_ids, + Ticket::getTable() . '.type' => 1, ], ], Ticket::getTable() . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), @@ -885,11 +871,13 @@ public function reportVstackbarTicketStatusByTechnician($config = []) //get technician list $technicians = []; + // one row per technician, not per assignment $query = [ 'SELECT' => [ new QueryExpression("CONCAT(" . User::getTable() . ".firstname, ' ', " . User::getTable() . ".realname) as fullname"), User::getTable() . ".name as username", ], + 'DISTINCT' => true, 'FROM' => Ticket::getTable(), 'INNER JOIN' => [ Ticket_User::getTable() => [ diff --git a/inc/helpdeskplus.class.php b/inc/helpdeskplus.class.php index 3fa9ca7c..a477d988 100644 --- a/inc/helpdeskplus.class.php +++ b/inc/helpdeskplus.class.php @@ -324,57 +324,71 @@ public function reportGlineBacklogs($config = []) $begin = date($this->period_sort_php, $time1); $end = date($this->period_sort_php, $time2); - $subqueries = []; + $ticket_table = Ticket::getTable(); + $date_end = $this->getPeriodEndSql(DBmysql::quoteName($ticket_table . '.date')); + $solve_end = $this->getPeriodEndSql(DBmysql::quoteName($ticket_table . '.solvedate')); - $subqueries[] = [ - 'SELECT' => [$this->criteria_list_date], - 'DISTINCT' => true, - 'FROM' => Ticket::getTable(), - ]; - - $subqueries[] = [ - 'SELECT' => [$this->criteria_list_date2], - 'DISTINCT' => true, - 'FROM' => Ticket::getTable(), - ]; + // Period ends to display: every period holding the creation or the resolution of any ticket, + // inside the selected interval. The bounds, one period wider than the interval, only let the index skip rows. + $low = date('Y-m-d H:i:s', strtotime('-1 ' . $this->period_interval, $time1)); + $high = date('Y-m-d 23:59:59', strtotime('+1 ' . $this->period_interval, $time2)); - $union = new QueryUnion($subqueries, false, 'list_date_union'); - - $list_date_table = [ - 'SELECT' => ['period_l'], - 'FROM' => $union, - 'DISTINCT' => true, - ]; + $list_date = new QueryUnion([ + [ + 'SELECT' => [new QueryExpression("$date_end AS period_l")], + 'FROM' => $ticket_table, + 'WHERE' => [ + $ticket_table . '.date' => ['>=', $low], + [$ticket_table . '.date' => ['<=', $high]], + ], + ], + [ + 'SELECT' => [new QueryExpression("$solve_end AS period_l")], + 'FROM' => $ticket_table, + 'WHERE' => [ + $ticket_table . '.solvedate' => ['>=', $low], + [$ticket_table . '.solvedate' => ['<=', $high]], + ], + ], + ], true, 'list_date'); - $query = [ + $periods = $DB->request([ 'SELECT' => [ - new QueryExpression("DATE_FORMAT(list_date.period_l, '{$this->period_sort}') as period"), - new QueryExpression("DATE_FORMAT(list_date.period_l, '{$this->period_label}') as period_name"), - new QueryExpression("COUNT(DISTINCT " . Ticket::getTable() . ".id) as nb"), + 'period_l', + new QueryExpression('DATE_FORMAT(list_date.period_l, ' . $DB->quoteValue($this->period_sort) . ') AS period'), + new QueryExpression('DATE_FORMAT(list_date.period_l, ' . $DB->quoteValue($this->period_label) . ') AS period_name'), ], - 'FROM' => new QuerySubQuery($list_date_table, 'list_date'), - 'LEFT JOIN' => array_merge( - [ - Ticket::getTable() => [ - 'AND' => [ - Ticket::getTable() . '.date' => ['<=', new QueryExpression('list_date.period_l')], - 'OR' => [ - Ticket::getTable() . '.solvedate' => ['>', new QueryExpression('list_date.period_l')], - new QueryExpression(Ticket::getTable() . '.solvedate IS NULL'), - ], - ], - ], - ], - $this->criteria_join_tu, - $this->criteria_join_gt, - $this->criteria_join_gtr, - ), + 'FROM' => $list_date, + 'WHERE' => [ + new QueryExpression('DATE_FORMAT(list_date.period_l, ' . $DB->quoteValue($this->period_sort) . ') >= ' . $DB->quoteValue($begin)), + new QueryExpression('DATE_FORMAT(list_date.period_l, ' . $DB->quoteValue($this->period_sort) . ') <= ' . $DB->quoteValue($end)), + ], + 'ORDER' => ['period_l'], + ]); + + // A ticket is in the backlog at a period end when it was opened before and not solved before: + // backlog = tickets opened up to the period end - tickets opened and solved up to the period end. + // Both are counted once per period over the whole history, then accumulated in PHP. + // The actor joins are LEFT JOINs: they only change the counted tickets when their filter is set, + // so they are added only then (the distinct count is the same without them). + $backlog_joins = []; + if ($this->criteria_user_assign !== []) { + $backlog_joins = array_merge($backlog_joins, $this->criteria_join_tu); + } + if ($this->criteria_group_assign !== []) { + $backlog_joins = array_merge($backlog_joins, $this->criteria_join_gt); + } + if ($this->criteria_group_request !== []) { + $backlog_joins = array_merge($backlog_joins, $this->criteria_join_gtr); + } + + $count_criteria = [ + 'FROM' => $ticket_table, + 'LEFT JOIN' => $backlog_joins, 'WHERE' => array_merge( [ - Ticket::getTable() . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), - Ticket::getTable() . '.is_deleted' => 0, - new QueryExpression("DATE_FORMAT(list_date.period_l, '{$this->period_sort}') >= '$begin'"), - new QueryExpression("DATE_FORMAT(list_date.period_l, '{$this->period_sort}') <= '$end'"), + $ticket_table . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), + $ticket_table . '.is_deleted' => 0, ], $this->criteria_type, $this->criteria_group_assign, @@ -382,14 +396,48 @@ public function reportGlineBacklogs($config = []) $this->criteria_user_assign, $this->criteria_itilcat, ), - 'GROUPBY' => ['period'], + 'GROUPBY' => ['period_l'], + 'ORDER' => ['period_l'], ]; + $count_distinct = new QueryExpression('COUNT(DISTINCT ' . DBmysql::quoteName($ticket_table . '.id') . ') AS nb'); + + $opened = []; + $opened_criteria = $count_criteria; + $opened_criteria['SELECT'] = [new QueryExpression("$date_end AS period_l"), $count_distinct]; + $opened_criteria['WHERE'][] = ['NOT' => [$ticket_table . '.date' => null]]; + foreach ($DB->request($opened_criteria) as $data) { + $opened[] = [$data['period_l'], (int) $data['nb']]; + } - $result = $DB->request($query); + // a ticket solved before its creation date leaves the backlog at its creation period + $solved = []; + $solved_criteria = $count_criteria; + $solved_criteria['SELECT'] = [new QueryExpression("GREATEST($date_end, $solve_end) AS period_l"), $count_distinct]; + $solved_criteria['WHERE'][] = ['NOT' => [$ticket_table . '.date' => null]]; + $solved_criteria['WHERE'][] = ['NOT' => [$ticket_table . '.solvedate' => null]]; + foreach ($DB->request($solved_criteria) as $data) { + $solved[] = [$data['period_l'], (int) $data['nb']]; + } - foreach ($result as $data) { - $tab[$data['period']]['backlog'] = $data['nb']; - $tab[$data['period']]['period_name'] = $data['period_name']; + $opened_total = 0; + $solved_total = 0; + $opened_index = 0; + $solved_index = 0; + foreach ($periods as $data) { + while ($opened_index < count($opened) && $opened[$opened_index][0] <= $data['period_l']) { + $opened_total += $opened[$opened_index][1]; + $opened_index++; + } + while ($solved_index < count($solved) && $solved[$solved_index][0] <= $data['period_l']) { + $solved_total += $solved[$solved_index][1]; + $solved_index++; + } + + // periods without any ticket in the backlog are not displayed, as before + if ($opened_total - $solved_total > 0) { + $tab[$data['period']]['backlog'] = $opened_total - $solved_total; + $tab[$data['period']]['period_name'] = $data['period_name']; + } } } diff --git a/inc/inventory.class.php b/inc/inventory.class.php index 15527366..16a43f0c 100644 --- a/inc/inventory.class.php +++ b/inc/inventory.class.php @@ -425,75 +425,11 @@ public function computersByOS($config = []) 'Android' => 'Android', 'HP-UX' => 'HP-UX', ]; - $notlike = []; - - $queries = []; - - $subquery = [ - 'SELECT' => [ - new QueryExpression("COUNT(*)"), - ], - 'FROM' => Computer::getTable(), - 'LEFT JOIN' => [ - Item_OperatingSystem::getTable() => [ - 'ON' => [ - Item_OperatingSystem::getTable() . '.items_id', - Computer::getTable() . '.id', - ], - ], - OperatingSystem::getTable() => [ - 'ON' => [ - OperatingSystem::getTable() . '.id', - Item_OperatingSystem::getTable() . '.operatingsystems_id', - ], - ], - ], - 'WHERE' => array_merge([ - Computer::getTable() . '.is_deleted' => 0, - Computer::getTable() . '.is_template' => 0, - Item_OperatingSystem::getTable() . '.itemtype' => 'Computer', - Computer::getTable() . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), - ], $criteria_states), - ]; - - foreach ($oses as $os => $search) { - $queries[] = [ - 'SELECT' => [ - new QueryExpression("'$os'" . " AS OS"), - new QueryExpression("COUNT(*) * 100 / " . new QuerySubQuery($subquery, 'Percent')), - ], - 'COUNT' => 'Total', - 'FROM' => Computer::getTable(), - 'LEFT JOIN' => [ - Item_OperatingSystem::getTable() => [ - 'ON' => [ - Item_OperatingSystem::getTable() . '.items_id', - Computer::getTable() . '.id', - ], - ], - OperatingSystem::getTable() => [ - 'ON' => [ - OperatingSystem::getTable() . '.id', - Item_OperatingSystem::getTable() . '.operatingsystems_id', - ], - ], - ], - 'WHERE' => array_merge([ - Item_OperatingSystem::getTable() . '.itemtype' => 'Computer', - Computer::getTable() . '.is_deleted' => 0, - Computer::getTable() . '.is_template' => 0, - new QueryExpression(OperatingSystem::getTable() . ".name REGEXP '" . $search . "'"), - Computer::getTable() . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), - ], $criteria_states), - ]; - - $notlike[] = new QueryExpression(OperatingSystem::getTable() . ".name NOT REGEXP '" . $search . "'"); - } - - $queries[] = [ + // one query counting the OS links per OS name; the families are matched in PHP. + // A name can match several families and is counted in each of them; 'Others' gets the names matching none. + $result = $DB->request([ 'SELECT' => [ - new QueryExpression("'" . __s('Others') . "' AS OS"), - new QueryExpression("COUNT(*) * 100 / " . new QuerySubQuery($subquery, 'Percent')), + OperatingSystem::getTable() . '.name AS os_name', ], 'COUNT' => 'Total', 'FROM' => Computer::getTable(), @@ -516,19 +452,40 @@ public function computersByOS($config = []) Computer::getTable() . '.is_deleted' => 0, Computer::getTable() . '.is_template' => 0, Computer::getTable() . '.entities_id' => PluginMreportingCommon::formatWhereEntitiesArray($this->where_entities), - $notlike, ], $criteria_states), - 'ORDER' => ['Total DESC'], - ]; + 'GROUPBY' => ['os_name'], + ]); + + $all_computers = 0; + $totals = array_fill_keys(array_keys($oses), 0); + $others = 0; + foreach ($result as $row) { + $all_computers += (int) $row['Total']; + // a missing OS name matches no family and is not an 'Other' either + if ($row['os_name'] === null) { + continue; + } - $query = new QueryUnion($queries); - $result = $DB->request($query); + $matched = false; + foreach ($oses as $os => $search) { + // case-insensitive, as the REGEXP of the database collation + if (preg_match('/' . $search . '/i', $row['os_name']) === 1) { + $totals[$os] += (int) $row['Total']; + $matched = true; + } + } + if (!$matched) { + $others += (int) $row['Total']; + } + } + $totals[__s('Others')] = $others; $datas = []; - foreach ($result as $computer) { - $percent = round(floatval($computer['Percent']), 2); - if ($computer['Total']) { - $datas['datas'][$computer['OS'] . " ($percent %)"] = $computer['Total']; + foreach ($totals as $os => $total) { + if ($total) { + // the database rounded the division to 4 decimals before this rounding + $percent = round(round($total * 100 / $all_computers, 4), 2); + $datas['datas'][$os . " ($percent %)"] = $total; } } @@ -1121,28 +1078,31 @@ public function reportHbarComputersByEntity($config = []) foreach ($result as $data) { $entities_first_level[$data['id']] = $data['name']; } + // computers counted per entity in one query, then summed over each displayed entity and its sons + $computers_per_entity = []; + $result = $DB->request([ + 'SELECT' => [Computer::getTable() . '.entities_id'], + 'COUNT' => 'Total', + 'FROM' => Computer::getTable(), + 'WHERE' => [ + Computer::getTable() . '.is_deleted' => 0, + Computer::getTable() . '.is_template' => 0, + ], + 'GROUPBY' => [Computer::getTable() . '.entities_id'], + ]); + foreach ($result as $row) { + $computers_per_entity[$row['entities_id']] = (int) $row['Total']; + } + $entities = []; foreach ($entities_first_level as $entities_id => $entities_name) { - if ($entities_id == $_SESSION['glpiactive_entity']) { - $restrict = " = '" . $entities_id . "'"; - } else { - $restrict = 'IN (' . implode(',', getSonsOf('glpi_entities', $entities_id)) . ')'; + $total = 0; + foreach (getSonsOf(Entity::getTable(), $entities_id) as $sons_id) { + $total += $computers_per_entity[$sons_id] ?? 0; } - $query = [ - 'COUNT' => 'Total', - 'FROM' => Computer::getTable(), - 'WHERE' => [ - Computer::getTable() . '.entities_id' => getSonsOf(Entity::getTable(), $entities_id), - Computer::getTable() . '.is_deleted' => 0, - Computer::getTable() . '.is_template' => 0, - ], - ]; - $result = $DB->request($query); - foreach ($result as $computer) { - $datas['tmp'][$entities_name . ' (pourcentage %)'] = $computer['Total']; - $entities[$entities_name . ' (pourcentage %)'] = $entities_id; - } + $datas['tmp'][$entities_name . ' (pourcentage %)'] = $total; + $entities[$entities_name . ' (pourcentage %)'] = $entities_id; } $total = array_sum($datas['tmp']); foreach ($datas['tmp'] as $key => $value) { diff --git a/inc/profile.class.php b/inc/profile.class.php index 9abf61b1..b0e4bc43 100644 --- a/inc/profile.class.php +++ b/inc/profile.class.php @@ -229,6 +229,9 @@ private static function addMissingRights(array $profiles_ids, array $reports_ids } } } + + // the inserts bypass post_addItem() + self::resetRightsCache(); } /** @@ -452,16 +455,57 @@ public function findReportByProfiles($profil_id) return $prof; } + /** + * Rights of each profile on each report, loaded with one query per profile the first time they are read in the request. + * + * @var array> + */ + private static array $rights_cache = []; + + public static function resetRightsCache(): void + { + self::$rights_cache = []; + } + public static function canViewReports($profil_id, $report_id) { - $prof = new self(); - $res = $prof->getFromDBByCrit( - [ - 'profiles_id' => $profil_id, - 'reports' => $report_id, - ], - ); - return $res && $prof->fields['right'] == READ; + /** @var DBmysql $DB */ + global $DB; + + // called for every report by getAllReports(): one query for the profile instead of 2 per report + if (!isset(self::$rights_cache[$profil_id])) { + self::$rights_cache[$profil_id] = []; + $result = $DB->request([ + 'SELECT' => ['reports', 'right'], + 'FROM' => self::getTable(), + 'WHERE' => ['profiles_id' => $profil_id], + ]); + foreach ($result as $row) { + self::$rights_cache[$profil_id][$row['reports']] = $row['right']; + } + } + + // (profiles_id, reports) is unique: at most one right per report + return array_key_exists($report_id, self::$rights_cache[$profil_id]) + && self::$rights_cache[$profil_id][$report_id] == READ; + } + + public function post_addItem() + { + self::resetRightsCache(); + parent::post_addItem(); + } + + public function post_updateItem($history = true) + { + self::resetRightsCache(); + parent::post_updateItem($history); + } + + public function post_purgeItem() + { + self::resetRightsCache(); + parent::post_purgeItem(); } // Hook done on add item case diff --git a/setup.php b/setup.php index 4496a688..2fd212e0 100644 --- a/setup.php +++ b/setup.php @@ -75,109 +75,111 @@ function plugin_init_mreporting() $PLUGIN_HOOKS['csrf_compliant']['mreporting'] = true; - if (Plugin::isPluginActive('mreporting')) { - // *Direct* access to rapport file (from e-mail) : - if (isset($_GET['redirect']) && str_contains($_GET['redirect'], 'plugin_mreporting')) { - $filename = basename(str_replace('plugin_mreporting_', '', $_GET['redirect'])); - if (preg_match('/^[\w\-.]+$/', $filename)) { - Html::redirect($CFG_GLPI['root_doc'] . '/files/_plugins/mreporting/notifications/' . $filename); - } + // Plugin::load() also runs this function while the plugin is being installed, when its tables do not exist yet. + // The list of active plugins is kept in memory by the core: no query, unlike Plugin::isPluginActive() during init. + if (!in_array('mreporting', Plugin::getPlugins(), true)) { + return; + } + + // *Direct* access to rapport file (from e-mail) : + if (isset($_GET['redirect']) && str_contains($_GET['redirect'], 'plugin_mreporting')) { + $filename = basename(str_replace('plugin_mreporting_', '', $_GET['redirect'])); + if (preg_match('/^[\w\-.]+$/', $filename)) { + Html::redirect($CFG_GLPI['root_doc'] . '/files/_plugins/mreporting/notifications/' . $filename); } + } - //Load additionnal language files in needed - includeAdditionalLanguageFiles(); - - if (Session::getCurrentInterface()) { - /* Profile */ - $PLUGIN_HOOKS['change_profile']['mreporting'] = ['PluginMreportingProfile', - 'changeProfile', - ]; - $PLUGIN_HOOKS['redirect_page']['mreporting'] = 'front/download.php'; - - Plugin::registerClass( - 'PluginMreportingNotification', - ['notificationtemplates_types' => true], - ); - - Plugin::registerClass( - 'PluginMreportingDashboard', - ['addtabon' => ['Central']], - ); - - Plugin::registerClass( - 'PluginMreportingProfile', - ['addtabon' => 'Profile'], - ); - - Plugin::registerClass( - 'PluginMreportingPreference', - ['addtabon' => 'Preference'], - ); - - $mreporting_profile = new PluginMreportingProfile(); - $reports_profiles = $mreporting_profile->find( - [ - 'profiles_id' => $_SESSION['glpiactiveprofile']['id'], - 'right' => READ, - ], - ); - - /* Menu */ - $PLUGIN_HOOKS['config_page']['mreporting'] = 'front/config.php'; - if (count($reports_profiles) > 0) { - $PLUGIN_HOOKS['menu_toadd']['mreporting'] = ['tools' => 'PluginMreportingCommon']; - } + //Load additionnal language files in needed + includeAdditionalLanguageFiles(); + + // counted once per request, only the count is needed + $can_access_reports = null; + + if (Session::getCurrentInterface()) { + /* Profile */ + $PLUGIN_HOOKS['change_profile']['mreporting'] = ['PluginMreportingProfile', + 'changeProfile', + ]; + $PLUGIN_HOOKS['redirect_page']['mreporting'] = 'front/download.php'; + + Plugin::registerClass( + 'PluginMreportingNotification', + ['notificationtemplates_types' => true], + ); + + Plugin::registerClass( + 'PluginMreportingDashboard', + ['addtabon' => ['Central']], + ); + + Plugin::registerClass( + 'PluginMreportingProfile', + ['addtabon' => 'Profile'], + ); + + Plugin::registerClass( + 'PluginMreportingPreference', + ['addtabon' => 'Preference'], + ); + + $can_access_reports = PluginMreportingCommon::canAccessAtLeastOneReport($_SESSION['glpiactiveprofile']['id']) > 0; + + /* Menu */ + $PLUGIN_HOOKS['config_page']['mreporting'] = 'front/config.php'; + if ($can_access_reports) { + $PLUGIN_HOOKS['menu_toadd']['mreporting'] = ['tools' => 'PluginMreportingCommon']; + } - /* Show Reports in standart stats page */ - if (preg_match('#front/stat.*\.php#', $_SERVER['REQUEST_URI'])) { - $mreporting_common = new PluginMreportingCommon(); - $reports = $mreporting_common->getAllReports(); - if ($reports !== false) { - foreach ($reports as $report) { - foreach ($report['functions'] as $func) { - $PLUGIN_HOOKS['stats']['mreporting'][$func['min_url_graph']] = $func['title']; - } + /* Show Reports in standart stats page */ + if (preg_match('#front/stat.*\.php#', $_SERVER['REQUEST_URI'])) { + $mreporting_common = new PluginMreportingCommon(); + $reports = $mreporting_common->getAllReports(); + if ($reports !== false) { + foreach ($reports as $report) { + foreach ($report['functions'] as $func) { + $PLUGIN_HOOKS['stats']['mreporting'][$func['min_url_graph']] = $func['title']; } } } - - $PLUGIN_HOOKS['pre_item_purge']['mreporting'] - = ['Profile' => ['PluginMreportingProfile', 'purgeProfiles'], - 'PluginMreportingConfig' => ['PluginMreportingProfile', 'purgeProfilesByReports'], - ]; - $PLUGIN_HOOKS['item_add']['mreporting'] - = ['Profile' => ['PluginMreportingProfile', 'addProfiles'], - 'PluginMreportingConfig' => ['PluginMreportingProfile', 'addReport'], - ]; } - if (isset($_SESSION['glpiactiveprofile']['id']) && $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { - if (PluginMreportingCommon::canAccessAtLeastOneReport($_SESSION['glpiactiveprofile']['id'])) { - $PLUGIN_HOOKS['add_javascript']['mreporting'][] = 'js/helpdesk-menu.js'; //This need Ext js lib ! - $PLUGIN_HOOKS['helpdesk_menu_entry']['mreporting'] = false; - } - } else { - $PLUGIN_HOOKS['helpdesk_menu_entry']['mreporting'] = true; - } + $PLUGIN_HOOKS['pre_item_purge']['mreporting'] + = ['Profile' => ['PluginMreportingProfile', 'purgeProfiles'], + 'PluginMreportingConfig' => ['PluginMreportingProfile', 'purgeProfilesByReports'], + ]; + $PLUGIN_HOOKS['item_add']['mreporting'] + = ['Profile' => ['PluginMreportingProfile', 'addProfiles'], + 'PluginMreportingConfig' => ['PluginMreportingProfile', 'addReport'], + ]; + } - if (str_contains($_SERVER['REQUEST_URI'] ?? '', '/mreporting/')) { - // Add specific files to add to the header : javascript - $PLUGIN_HOOKS['add_javascript']['mreporting'] = [ - 'lib/protovis/protovis.js', - 'lib/jquery.tipsy/jquery.tipsy.js', - 'lib/jquery.tipsy/tipsy.js', - ]; - - //Add specific files to add to the header : css - $PLUGIN_HOOKS['add_css']['mreporting'] = [ - 'css/mreporting.css', - 'lib/jquery.tipsy/jquery.tipsy.css', - ]; + if (isset($_SESSION['glpiactiveprofile']['id']) && $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { + $can_access_reports ??= PluginMreportingCommon::canAccessAtLeastOneReport($_SESSION['glpiactiveprofile']['id']) > 0; + if ($can_access_reports) { + $PLUGIN_HOOKS['add_javascript']['mreporting'][] = 'js/helpdesk-menu.js'; //This need Ext js lib ! + $PLUGIN_HOOKS['helpdesk_menu_entry']['mreporting'] = false; } + } else { + $PLUGIN_HOOKS['helpdesk_menu_entry']['mreporting'] = true; + } - if (DEBUG_MREPORTING && isset($_SESSION['glpimenu'])) { - unset($_SESSION['glpimenu']); - } + if (str_contains($_SERVER['REQUEST_URI'] ?? '', '/mreporting/')) { + // Add specific files to add to the header : javascript + $PLUGIN_HOOKS['add_javascript']['mreporting'] = [ + 'lib/protovis/protovis.js', + 'lib/jquery.tipsy/jquery.tipsy.js', + 'lib/jquery.tipsy/tipsy.js', + ]; + + //Add specific files to add to the header : css + $PLUGIN_HOOKS['add_css']['mreporting'] = [ + 'css/mreporting.css', + 'lib/jquery.tipsy/jquery.tipsy.css', + ]; + } + + if (DEBUG_MREPORTING && isset($_SESSION['glpimenu'])) { + unset($_SESSION['glpimenu']); } }