From b7eccbbe7465cb03b14080431d41415555aa20d8 Mon Sep 17 00:00:00 2001 From: MyvTsv Date: Fri, 13 Nov 2026 16:29:27 +0100 Subject: [PATCH 1/2] fix(core): reduce SQL queries on forms, init and the tag Associated items tab --- CHANGELOG.md | 1 + ajax/get_entity_tags.php | 3 + inc/config.class.php | 36 ++++ inc/tag.class.php | 279 +++++++++++++++++++++------ inc/tagitem.class.php | 95 ++++----- setup.php | 40 ++-- tests/TagTestCase.php | 10 + tests/Units/TagItemTest.php | 42 ++++ tests/Units/TagMassiveActionTest.php | 27 +++ tests/Units/TagTest.php | 25 +++ 10 files changed, 441 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 509c3e4..19cca25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fix tag search criterion matching items of other types sharing the same ID - Fix error when updating a ticket without creation date (e.g. entity transfer) - Fix tags left in a deleted entity: declare their entity relation so it is checked and replaced on entity deletion +- Improve performance: no more database queries on each page load, fewer queries when displaying an item with many tags, faster "Associated items" tab of a tag (new index on the tag of the links), lighter entity tags and tag save requests ## [2.14.8] - 2026-09-30 diff --git a/ajax/get_entity_tags.php b/ajax/get_entity_tags.php index 8d1d00c..fdc6875 100644 --- a/ajax/get_entity_tags.php +++ b/ajax/get_entity_tags.php @@ -38,4 +38,7 @@ throw new BadRequestHttpException(); } +// Only reads the session: release its lock so the other calls of the page are not serialized behind this one +Session::writeClose(); + echo PluginTagTag::getTagForEntityName($_REQUEST['name']); diff --git a/inc/config.class.php b/inc/config.class.php index 8a6e0cb..3b68277 100644 --- a/inc/config.class.php +++ b/inc/config.class.php @@ -32,6 +32,41 @@ class PluginTagConfig extends CommonDBTM { protected static $notable = true; + /** + * Configured location of the tags field, memoized for the current request. + */ + private static ?string $tags_location = null; + + /** + * Get the configured location of the tags field in item forms. + * + * @return string '1' for the bottom of the form, '0' for the top (default) + */ + public static function getTagsLocation(): string + { + return self::$tags_location ??= (string) (Config::getConfigurationValues('plugin:Tag', ['tags_location'])['tags_location'] ?? '0'); + } + + /** + * Forget the memoized location. + */ + public static function resetTagsLocation(): void + { + self::$tags_location = null; + } + + /** + * Called by core when the configuration form of the plugin is saved (`config_class` input). + * + * @param array $input submitted configuration values + * @return array + */ + public static function configUpdate($input) + { + self::resetTagsLocation(); + return $input; + } + public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { @@ -95,6 +130,7 @@ public static function uninstall() { $config = Config::getConfigurationValues('plugin:Tag'); Config::deleteConfigurationValues('plugin:Tag', array_keys($config)); + self::resetTagsLocation(); return true; } } diff --git a/inc/tag.class.php b/inc/tag.class.php index fc1f37d..c220ef8 100644 --- a/inc/tag.class.php +++ b/inc/tag.class.php @@ -46,6 +46,27 @@ class PluginTagTag extends CommonDropdown public static $rightname = 'plugin_tag_tag'; + /** + * Itemtypes of the active tags, memoized for the current request. + * + * @var array{use_global_tag: bool, itemtypes: array}|null + */ + private static ?array $active_tags_itemtypes = null; + + /** + * Items whose form already displays the tags field in the current request. + * + * @var WeakMap|null + */ + private static ?WeakMap $displayed_items = null; + + /** + * Colors of the tags available in the tags field, by search criteria (itemtype and entity restriction), memoized for the current request. + * + * @var array> + */ + private static array $available_tags_colors = []; + public static function getTypeName($nb = 1) { return _sn('Tag', 'Tags', $nb, 'tag'); @@ -88,19 +109,81 @@ public static function canItemtype($itemtype = '') return false; } - $tags = new self(); - $types_menu = []; + $active_itemtypes = self::getActiveTagsItemtypes(); + + return $active_itemtypes['use_global_tag'] || isset($active_itemtypes['itemtypes'][$itemtype]); + } + + /** + * Get the itemtypes the active tags apply to, read once per request. + * + * @return array{use_global_tag: bool, itemtypes: array} + */ + private static function getActiveTagsItemtypes(): array + { + /** @var DBmysql $DB */ + global $DB; + + if (self::$active_tags_itemtypes !== null) { + return self::$active_tags_itemtypes; + } + + $itemtypes = []; $use_global_tag = false; - foreach ($tags->find(['is_active' => 1]) as $tag) { - if (!empty($tag['type_menu'])) { - $types_menu = array_merge($types_menu, json_decode((string) $tag['type_menu'])); - } else { + $iterator = $DB->request([ + 'SELECT' => ['type_menu'], + 'FROM' => self::getTable(), + 'WHERE' => ['is_active' => 1], + ]); + foreach ($iterator as $tag) { + if (empty($tag['type_menu'])) { $use_global_tag = true; + continue; + } + + foreach ((array) json_decode((string) $tag['type_menu'], true) as $tag_itemtype) { + // Only itemtype names: nested or malformed values can never match an itemtype + if (is_scalar($tag_itemtype)) { + $itemtypes[(string) $tag_itemtype] = true; + } } } - return $use_global_tag || in_array($itemtype, $types_menu); + return self::$active_tags_itemtypes = [ + 'use_global_tag' => $use_global_tag, + 'itemtypes' => $itemtypes, + ]; + } + + /** + * Forget the itemtypes of the active tags and the tags available in the tags fields. + * + * Called after a tag is added, updated or purged through PluginTagTag; code writing + * `glpi_plugin_tag_tags` directly (migration, tests rolling back a transaction) must call it. + */ + public static function resetActiveTagsItemtypes(): void + { + self::$active_tags_itemtypes = null; + self::$available_tags_colors = []; + } + + public function post_addItem() + { + self::resetActiveTagsItemtypes(); + parent::post_addItem(); + } + + public function post_updateItem($history = true) + { + self::resetActiveTagsItemtypes(); + parent::post_updateItem($history); + } + + public function post_purgeItem() + { + self::resetActiveTagsItemtypes(); + parent::post_purgeItem(); } public function showForm($ID, $options = []) @@ -199,6 +282,8 @@ public static function install(Migration $migration) $itemtypes = $CFG_GLPI['plugin_tag_itemtypes'][$data['type_menu']] ?? []; $DB->update($table, ['type_menu' => json_encode($itemtypes)], ['id' => $data['id']]); } + + self::resetActiveTagsItemtypes(); } } @@ -244,6 +329,8 @@ public static function uninstall() $migration = new Migration(PLUGIN_TAG_VERSION); $migration->dropTable(getTableForItemType(self::class)); + self::resetActiveTagsItemtypes(); + return true; } @@ -504,11 +591,13 @@ public static function parseItemtype($itemtype, $id = 0) * * Depending on the config settings, this will either show at the top or bottom of the forms. * - * @param array $params should contains theses keys: - * - item the CommonDBTM object + * @param array $params should contains theses keys: + * - item the CommonDBTM object + * @param bool|null $at_bottom true or false to display the field only when it is configured at the bottom + * or at the top of the forms, null to display it whatever the configuration * @return bool|null False if the form was not shown. Otherwise nothing is returned and the form is displayed. */ - public static function showForItem($params = []) + public static function showForItem($params = [], ?bool $at_bottom = null) { if (!self::canView()) { return false; @@ -521,24 +610,62 @@ public static function showForItem($params = []) $item = $params['item']; $itemtype = $item::class; - if (self::canItemtype($itemtype)) { - // manage values after a redirect (ex ticket creation, after a cat change) - $value = ''; - if (isset($item->input['_plugin_tag_tag_values'])) { - $value = $item->input['_plugin_tag_tag_values']; - } + if (!self::canItemtype($itemtype)) { + return null; + } + + // Read the configured location only for forms that can show tags + if ($at_bottom !== null && (PluginTagConfig::getTagsLocation() === '1') !== $at_bottom) { + return null; + } + + // A form calling the same hook twice (core template branches, other plugins) + // must not get a second tags field with the same input name + self::$displayed_items ??= new WeakMap(); + if (isset(self::$displayed_items[$item])) { + return null; + } - self::showTagDropdown([ - 'itemtype' => $itemtype, - 'id' => $item->getId(), - 'value' => $value, - ]); + self::$displayed_items[$item] = true; + + // manage values after a redirect (ex ticket creation, after a cat change) + $value = ''; + if (isset($item->input['_plugin_tag_tag_values'])) { + $value = $item->input['_plugin_tag_tag_values']; } + + self::showTagDropdown([ + 'itemtype' => $itemtype, + 'id' => $item->getId(), + 'value' => $value, + ]); } return null; } + /** + * `pre_item_form` hook: display the tags field when it is configured at the top of the forms. + * + * @param array $params see showForItem() + * @return bool|null + */ + public static function showForItemAtTop($params = []) + { + return self::showForItem($params, false); + } + + /** + * `post_item_form` hook: display the tags field when it is configured at the bottom of the forms. + * + * @param array $params see showForItem() + * @return bool|null + */ + public static function showForItemAtBottom($params = []) + { + return self::showForItem($params, true); + } + /** * Display the current tags before the Kanban item content. * @@ -664,8 +791,7 @@ public static function showTagDropdown($params = []) $obj = new $itemtype(); - $tag = new self(); - $tag_item = new PluginTagTagItem(); + $tag = new self(); if (isset($params['id'])) { $obj->getFromDB($params['id']); @@ -675,19 +801,6 @@ public static function showTagDropdown($params = []) $obj->getEmpty(); } - $values = []; - if (!$obj->isNewItem()) { - foreach ( - $tag_item->find(['items_id' => $params['id'], 'itemtype' => $itemtype]) as $found_item - ) { - $values[] = $found_item['plugin_tag_tags_id']; - } - } elseif (is_string($params['value'])) { - $values = empty($params['value']) ? [] : explode(',', $params['value']); - } elseif (is_array($params['value'])) { - $values = $params['value']; - } - /** @var DBmysql $DB */ global $DB; @@ -704,26 +817,53 @@ public static function showTagDropdown($params = []) $where += getEntitiesRestrictCriteria('', '', '', true); } - $available_tags = $tag->find($where, 'name'); - foreach ($available_tags as $tag_data) { - $available_tags_color[$tag_data['id']] = $tag_data['color'] ?: '#DDDDDD'; + // Several tags fields with the same criteria on one page (item and sub-forms) share the same list + $available_tags_key = md5(serialize($where)); + if (!isset(self::$available_tags_colors[$available_tags_key])) { + self::$available_tags_colors[$available_tags_key] = []; + foreach ($tag->find($where, 'name') as $tag_data) { + self::$available_tags_colors[$available_tags_key][$tag_data['id']] = $tag_data['color'] ?: '#DDDDDD'; + } } + $available_tags_color = self::$available_tags_colors[$available_tags_key]; + + // Tags linked to the item, ignoring links to tags that no longer exist, in one query (none for a new item) $selected_tags = []; - $select_tags = $tag_item->find(['items_id' => $params['id'], 'itemtype' => $itemtype]); - foreach ($select_tags as $tag_item_data) { - $tag_data = $tag->getFromDB($tag_item_data['plugin_tag_tags_id']); - if ($tag_data) { + if (!$obj->isNewItem()) { + $selected_iterator = $DB->request([ + 'SELECT' => [PluginTagTagItem::getTable() . '.plugin_tag_tags_id'], + 'FROM' => PluginTagTagItem::getTable(), + 'INNER JOIN' => [ + self::getTable() => [ + 'FKEY' => [ + self::getTable() => 'id', + PluginTagTagItem::getTable() => 'plugin_tag_tags_id', + ], + ], + ], + 'WHERE' => [ + PluginTagTagItem::getTable() . '.items_id' => $params['id'], + PluginTagTagItem::getTable() . '.itemtype' => $itemtype, + ], + 'ORDERBY' => PluginTagTagItem::getTable() . '.id', + ]); + foreach ($selected_iterator as $tag_item_data) { $selected_tags[] = $tag_item_data['plugin_tag_tags_id']; } } $rand = mt_rand(); - $can_update_all = array_filter($params['items_ids'], function ($value) use ($obj) { - $obj->getFromDB($value); - return !$obj->canUpdateItem(); - }) === []; + // Massive action: stop at the first selected item that cannot be updated + $can_update_all = true; + foreach ($params['items_ids'] as $selected_id) { + $obj->getFromDB($selected_id); + if (!$obj->canUpdateItem()) { + $can_update_all = false; + break; + } + } $readOnly = !$tag::canUpdate() || ($obj->isNewItem() && !$obj->canCreateItem()) @@ -741,13 +881,11 @@ public static function showTagDropdown($params = []) $extra_class = "mb-3"; } - $tag_location = Config::getConfigurationValues('plugin:Tag')['tags_location'] ?? 0; - TemplateRenderer::getInstance()->display('@tag/tag_dropdown.html.twig', [ 'extra_class' => $extra_class ?? '', 'selected_tags' => $selected_tags, 'condition' => $where, - 'tags_color' => $available_tags_color ?? [], + 'tags_color' => $available_tags_color, 'rand' => $rand, 'readOnly' => $readOnly, 'can_create' => $can_create, @@ -761,7 +899,6 @@ public static function showTagDropdown($params = []) 'is_form' => $obj instanceof Form, 'is_new_item' => $obj->isNewItem(), 'tag_search_url' => self::getSearchURL(), - 'tag_location' => $tag_location, ]); } @@ -773,27 +910,49 @@ public static function getTagForEntityName($completename = "") $out = ""; if ($entities_id >= 0) { - $tag_item = new PluginTagTagItem(); - foreach ($tag_item->find(['items_id' => $entities_id, 'itemtype' => 'Entity']) as $found_item) { - $out .= PluginTagTag::getSingleTag($found_item['plugin_tag_tags_id']); + /** @var DBmysql $DB */ + global $DB; + + // Tags of the entity with their name and color, in one query + $iterator = $DB->request([ + 'SELECT' => [self::getTable() . '.name', self::getTable() . '.color'], + 'FROM' => PluginTagTagItem::getTable(), + 'INNER JOIN' => [ + self::getTable() => [ + 'FKEY' => [ + self::getTable() => 'id', + PluginTagTagItem::getTable() => 'plugin_tag_tags_id', + ], + ], + ], + 'WHERE' => [ + PluginTagTagItem::getTable() . '.items_id' => $entities_id, + PluginTagTagItem::getTable() . '.itemtype' => 'Entity', + ], + 'ORDERBY' => PluginTagTagItem::getTable() . '.id', + ]); + foreach ($iterator as $tag_data) { + $out .= self::renderSingleTag($tag_data); } } return $out; } - public static function getSingleTag($tag_id, $separator = '') + /** + * Render a tag badge. + * + * @param array $tag_data tag fields, at least `name` and `color` + */ + private static function renderSingleTag(array $tag_data): string { - $plugintagtag = new self(); - $plugintagtag->getFromDB($tag_id); - - $color = $plugintagtag->fields["color"] ?: '#DDDDDD'; + $color = ($tag_data['color'] ?? '') ?: '#DDDDDD'; $inv_color = idealTextColor($color); $style = sprintf('background-color: %s; color: %s', $color, $inv_color); return "" - . $separator . htmlentities((string) $plugintagtag->fields['name'], ENT_QUOTES, "UTF-8") . ''; + . htmlentities((string) ($tag_data['name'] ?? ''), ENT_QUOTES, "UTF-8") . ''; } public function prepareInputForAdd($input) diff --git a/inc/tagitem.class.php b/inc/tagitem.class.php index f843496..0fcc1a4 100644 --- a/inc/tagitem.class.php +++ b/inc/tagitem.class.php @@ -102,7 +102,8 @@ public static function install(Migration $migration) `items_id` INT {$default_key_sign} NOT NULL DEFAULT '1', `itemtype` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`), - UNIQUE INDEX `unicity` (`itemtype`, `items_id`, `plugin_tag_tags_id`) + UNIQUE INDEX `unicity` (`itemtype`, `items_id`, `plugin_tag_tags_id`), + KEY `plugin_tag_tags_id` (`plugin_tag_tags_id`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC; SQL; $DB->doQuery($query); @@ -116,6 +117,8 @@ public static function install(Migration $migration) 'unicity', 'UNIQUE INDEX', ); + // lookups by tag (associated items, tab counter, tag purge) must not scan the whole table + $migration->addKey($table, 'plugin_tag_tags_id'); $migration->migrationOneTable($table); self::updateRuleActionTable($migration); @@ -181,18 +184,9 @@ public static function showForTag(PluginTagTag $tag) $result[] = $data; } - $it2 = $DB->request([ - 'SELECT' => ['itemtype', 'items_id'], - 'FROM' => $table, - 'WHERE' => ['plugin_tag_tags_id' => $instID], - ]); - $result2 = []; - foreach ($it2 as $data) { - $result2[] = $data; - } - - $number = count($result); - $rand = mt_rand(); + $number = count($result); + $rand = mt_rand(); + $entity_names = []; if ($canedit) { echo "
"; @@ -262,8 +256,6 @@ public static function showForTag(PluginTagTag $tag) continue; } - $item_id = $result2[$i]['items_id']; - if ($item->canView()) { $column = (stripos((string) $itemtype, 'item_device') !== false) ? '' @@ -333,10 +325,8 @@ public static function showForTag(PluginTagTag $tag) break; default: if (is_a($itemtype, CommonDBTM::class, true)) { - $obj = new $itemtype(); - $obj->getFromDB($item_id); - - if (isset($obj->fields['entities_id'])) { + // Read the entity from the item table when it has one, instead of loading an item + if ($DB->fieldExists($itemtable, 'entities_id')) { $criteria['SELECT'][] = 'glpi_entities.id AS entity'; $criteria['LEFT JOIN'] = [ 'glpi_entities' => [ @@ -357,7 +347,25 @@ public static function showForTag(PluginTagTag $tag) $linked_iterator = $DB->request($criteria); + // Type label, the same for every row of this itemtype, computed on the first displayed row + $type_label = null; + foreach ($linked_iterator as $data) { + if ($type_label === null) { + // Show plugin name (is to delete remove any ambiguity) + $type_label = ''; + $pieces = preg_split('/(?=[A-Z])/', (string) $itemtype); + if ($pieces[1] == 'Plugin') { + $plugin_name = $pieces[2]; + if (function_exists("plugin_version_" . $plugin_name)) { // For security + $tab = call_user_func("plugin_version_" . $plugin_name); + $type_label = $tab["name"] . " : "; + } + } + + $type_label .= $item->getTypeName(1); + } + if ($itemtype == 'Softwarelicense') { $soft = new Software(); $soft->getFromDB($data['softwares_id']); @@ -415,33 +423,21 @@ public static function showForTag(PluginTagTag $tag) echo ""; } - echo ""; - - // Show plugin name (is to delete remove any ambiguity) : - $pieces = preg_split('/(?=[A-Z])/', (string) $itemtype); - if ($pieces[1] == 'Plugin') { - $plugin_name = $pieces[2]; - if (function_exists("plugin_version_" . $plugin_name)) { // For security - $tab = call_user_func("plugin_version_" . $plugin_name); - echo $tab["name"] . " : "; - } - } - - echo $item->getTypeName(1) . ""; + echo "" . $type_label . ""; echo "" . $name . ""; echo ""; $entity = $data['entity']; - //for Plugins : - if ($data["entity"] == -1) { - $item->getFromDB($data['id']); - if (isset($item->fields["entities_id"])) { - $entity = $item->fields["entities_id"]; - } + // Rows selected with "-1 AS entity": the row already holds the item columns ($itemtable.*), + // read entities_id from it instead of loading the item + if ($entity == -1 && isset($data['entities_id'])) { + $entity = $data['entities_id']; } - echo htmlescape(Dropdown::getDropdownName("glpi_entities", $entity)); + // Many linked items share a few entities: resolve each entity name once + $entity_names[$entity] ??= Dropdown::getDropdownName("glpi_entities", $entity); + echo htmlescape($entity_names[$entity]); echo ""; echo "" . (isset($data["serial"]) ? htmlescape($data["serial"]) : "-") . ""; @@ -471,6 +467,8 @@ public static function showForTag(PluginTagTag $tag) */ public static function updateItem(CommonDBTM $item, bool $delete_existing_tags = true) { + /** @var DBmysql $DB */ + global $DB; if ( $item->getID() @@ -546,10 +544,16 @@ public static function updateItem(CommonDBTM $item, bool $delete_existing_tags = } // process actions - $existing_tags_ids = array_column( - $tag_item->find(['items_id' => $item->getID(), 'itemtype' => $item->getType()]), - 'plugin_tag_tags_id', - ); + $existing_tags_ids = []; + $existing_iterator = $DB->request([ + 'SELECT' => ['plugin_tag_tags_id'], + 'FROM' => self::getTable(), + 'WHERE' => ['items_id' => $item->getID(), 'itemtype' => $item->getType()], + ]); + foreach ($existing_iterator as $existing_tag) { + $existing_tags_ids[] = $existing_tag['plugin_tag_tags_id']; + } + $added_tags_ids = array_diff($tag_values, $existing_tags_ids); $removed_tags_ids = $delete_existing_tags ? array_diff($existing_tags_ids, $tag_values) : []; if (!Session::isCron()) { @@ -565,9 +569,10 @@ public static function updateItem(CommonDBTM $item, bool $delete_existing_tags = ]); } - foreach ($removed_tags_ids as $tag_id) { + // unlink all the removed tags with one lookup + if ($removed_tags_ids !== []) { $tag_item->deleteByCriteria([ - 'plugin_tag_tags_id' => $tag_id, + 'plugin_tag_tags_id' => array_values($removed_tags_ids), "items_id" => $item->getID(), "itemtype" => $item->getType(), ]); diff --git a/setup.php b/setup.php index db53983..06cc180 100644 --- a/setup.php +++ b/setup.php @@ -63,7 +63,7 @@ function plugin_init_tag() $PLUGIN_HOOKS['csrf_compliant']['tag'] = true; - if (Plugin::isPluginActive("tag")) { + if (plugin_tag_is_plugin_active("tag")) { // define list of itemtype which can be associated with tags $CFG_GLPI['plugin_tag_itemtypes'] = [ __s('Assets') => [ @@ -88,17 +88,17 @@ function plugin_init_tag() $CFG_GLPI['plugin_tag_itemtypes'][__s('Setup')][] = 'Webhook'; } - if (Plugin::isPluginActive('appliances')) { + if (plugin_tag_is_plugin_active('appliances')) { $CFG_GLPI['plugin_tag_itemtypes'][__s('Assets')][] = 'PluginAppliancesAppliance'; } // Plugin Webapplication - if (Plugin::isPluginActive('webapplications') && class_exists(Webapplication::class)) { + if (plugin_tag_is_plugin_active('webapplications') && class_exists(Webapplication::class)) { $CFG_GLPI['plugin_tag_itemtypes'][__s('Assets')][] = Webapplication::class; } // Plugin fusioninventory - if (Plugin::isPluginActive('fusioninventory')) { + if (plugin_tag_is_plugin_active('fusioninventory')) { $CFG_GLPI['plugin_tag_itemtypes'][__s('FusionInventory')][] = 'PluginFusioninventoryTask'; } @@ -112,7 +112,7 @@ function plugin_init_tag() $PLUGIN_HOOKS['use_massive_action']['tag'] = true; // Plugin uninstall : after uninstall action - if (Plugin::isPluginActive("uninstall")) { + if (plugin_tag_is_plugin_active("uninstall")) { //to prevent null global variable load plugin if needed if ($UNINSTALL_TYPES == null) { Plugin::load('uninstall'); @@ -123,13 +123,10 @@ function plugin_init_tag() } } - // insert tag dropdown into all possible itemtypes - $location = Config::getConfigurationValues('plugin:Tag')['tags_location'] ?? 0; - if ($location === '1') { - $PLUGIN_HOOKS['post_item_form']['tag'] = ['PluginTagTag', 'showForItem']; - } else { - $PLUGIN_HOOKS['pre_item_form']['tag'] = ['PluginTagTag', 'showForItem']; - } + // insert tag dropdown into all possible itemtypes, at the top or at the bottom of the form: + // the configured location is read only when a form is displayed, not on every request + $PLUGIN_HOOKS['pre_item_form']['tag'] = ['PluginTagTag', 'showForItemAtTop']; + $PLUGIN_HOOKS['post_item_form']['tag'] = ['PluginTagTag', 'showForItemAtBottom']; $PLUGIN_HOOKS['pre_kanban_content']['tag'] = ['PluginTagTag', 'preKanbanContent']; $common_kanban_filters = [ @@ -215,6 +212,25 @@ function idealTextColor($hexTripletColor) return (((255 - $bgDelta) < $nThreshold) ? "#000000" : "#ffffff"); } +/** + * Check whether a plugin is active, without querying the database once GLPI has booted its plugins. + * + * While plugins initialize, `Plugin::isPluginActive()` reads `glpi_plugins` on each call (2 queries). + * `Plugin::getPlugins()` holds the plugins booted in the ACTIVATED state, already filtered with + * `Plugin::isLoadable()`, and core removes a plugin from it when it is unloaded: it is the state + * `isPluginActive()` reads from the database. When no plugin has been booted (contexts that load + * plugins without booting them), fall back to `Plugin::isPluginActive()`. + */ +function plugin_tag_is_plugin_active(string $plugin_key): bool +{ + $activated_plugins = Plugin::getPlugins(); + if ($activated_plugins === []) { + return Plugin::isPluginActive($plugin_key); + } + + return in_array(strtolower($plugin_key), array_map(strtolower(...), $activated_plugins), true); +} + function plugin_tag_geturl(): string { /** @var array $CFG_GLPI */ diff --git a/tests/TagTestCase.php b/tests/TagTestCase.php index 34b520f..d4bf067 100644 --- a/tests/TagTestCase.php +++ b/tests/TagTestCase.php @@ -32,6 +32,7 @@ use CommonDBTM; use Glpi\Tests\DbTestCase; +use PluginTagConfig; use PluginTagTag; use PluginTagTagItem; use Profile_User; @@ -39,6 +40,15 @@ abstract class TagTestCase extends DbTestCase { + public function setUp(): void + { + parent::setUp(); + + // Each test rolls back its transaction: forget what the previous one memoized + PluginTagTag::resetActiveTagsItemtypes(); + PluginTagConfig::resetTagsLocation(); + } + protected function logOut() { $ctime = $_SESSION['glpi_currenttime']; diff --git a/tests/Units/TagItemTest.php b/tests/Units/TagItemTest.php index 6e6da3c..b376b04 100644 --- a/tests/Units/TagItemTest.php +++ b/tests/Units/TagItemTest.php @@ -31,11 +31,14 @@ namespace GlpiPlugin\Tag\Tests\Units; use Computer; +use Dropdown; use Glpi\Exception\Http\AccessDeniedHttpException; use GlpiPlugin\Tag\Controller\TagItemController; use GlpiPlugin\Tag\Tests\TagTestCase; use PluginTagTag; use PluginTagTagItem; +use RuleTicket; +use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\HttpFoundation\Request; use Ticket; @@ -156,6 +159,45 @@ public function testShowForTagEncodesLinkedItemValues(): void $this->assertStringContainsString(htmlescape($raw_name), $output); } + public function testShowForTagDisplaysEntityOfLinkedRules(): void + { + global $DB; + + $this->login(); + + $tagID = $this->createTag('RuleTag', ['RuleTicket']); + $entity_id = getItemByTypeName('Entity', '_test_child_1', true); + $rule = $this->createItem(RuleTicket::class, [ + 'name' => 'Tagged rule', + 'sub_type' => RuleTicket::class, + 'match' => 'AND', + 'is_active' => 1, + 'entities_id' => $entity_id, + ]); + // Rules share the glpi_rules table: the entity column is read from it + $DB->insert(PluginTagTagItem::getTable(), [ + 'plugin_tag_tags_id' => $tagID, + 'itemtype' => RuleTicket::class, + 'items_id' => $rule->getID(), + ]); + + $tag = new PluginTagTag(); + $this->assertTrue($tag->getFromDB($tagID)); + + ob_start(); + PluginTagTagItem::showForTag($tag); + $output = ob_get_clean(); + + $row = (new Crawler($output))->filter('tr')->reduce( + fn(Crawler $tr) => str_contains($tr->text(), 'Tagged rule'), + ); + $this->assertCount(1, $row); + $this->assertStringContainsString( + Dropdown::getDropdownName('glpi_entities', $entity_id), + $row->text(), + ); + } + public function testTagAssociationCreatesLink(): void { $this->loginAs(self::TECH_USER); diff --git a/tests/Units/TagMassiveActionTest.php b/tests/Units/TagMassiveActionTest.php index 4d250e1..036fe1c 100644 --- a/tests/Units/TagMassiveActionTest.php +++ b/tests/Units/TagMassiveActionTest.php @@ -30,8 +30,10 @@ namespace GlpiPlugin\Tag\Tests\Units; +use Computer; use GlpiPlugin\Tag\Tests\TagTestCase; use PluginTagTag; +use Symfony\Component\DomCrawler\Crawler; use function Safe\ob_get_clean; use function Safe\ob_start; @@ -99,4 +101,29 @@ public function testMassiveActionHookIgnoresOtherFields(): void $this->assertFalse($handled); $this->assertSame('', $html); } + + public function testMassiveActionTagDropdownIsBuiltForTheSelectedItems(): void + { + $this->login(); + $this->createTag('MassiveActionTag', ['Computer']); + $computer = $this->createItem(Computer::class, [ + 'name' => 'Computer updated through a massive action', + 'entities_id' => $this->getTestRootEntity(true), + ]); + + ob_start(); + PluginTagTag::showTagDropdown([ + 'itemtype' => Computer::class, + 'items_ids' => [$computer->getID()], + ]); + $html = ob_get_clean(); + + // The rights and the layout come from the selected items (update), not from an empty new item (create) + $crawler = new Crawler($html); + $select = $crawler->filter('select[name="_plugin_tag_tag_values[]"]'); + $this->assertCount(1, $select); + $this->assertNull($select->attr('disabled')); + $this->assertCount(1, $crawler->filter('div.col-xxl-9')); + $this->assertCount(0, $crawler->filter('div.col-xxl-12')); + } } diff --git a/tests/Units/TagTest.php b/tests/Units/TagTest.php index 7d32149..b069c3f 100644 --- a/tests/Units/TagTest.php +++ b/tests/Units/TagTest.php @@ -256,4 +256,29 @@ public function testTagIsMovedWhenItsEntityIsReplaced(): void $this->assertTrue($tag->getFromDB($tag->getID())); $this->assertSame($root_id, $tag->fields['entities_id']); } + + public function testShowForItemDisplaysTheTagsFieldOncePerItem(): void + { + $this->loginAs(['login' => 'glpi', 'pass' => 'glpi']); + $this->createTag('OncePerItemTag'); + + $ticket = $this->createItem(Ticket::class, [ + 'name' => 'Ticket with a form hook called twice', + 'content' => 'Ticket with a form hook called twice', + 'entities_id' => $this->getTestRootEntity(true), + ]); + $other_ticket = Ticket::getById($ticket->getID()); + + ob_start(); + PluginTagTag::showForItem(['item' => $ticket]); + PluginTagTag::showForItem(['item' => $ticket]); + $same_item_html = ob_get_clean(); + + ob_start(); + PluginTagTag::showForItem(['item' => $other_ticket]); + $other_item_html = ob_get_clean(); + + $this->assertCount(1, (new Crawler($same_item_html))->filter('select[name="_plugin_tag_tag_values[]"]')); + $this->assertCount(1, (new Crawler($other_item_html))->filter('select[name="_plugin_tag_tag_values[]"]')); + } } From d79088f52b5a6ed093daa362d59fe2deeff7cfb0 Mon Sep 17 00:00:00 2001 From: MyvTsv Date: Wed, 25 Nov 2026 15:28:34 +0100 Subject: [PATCH 2/2] review --- inc/tag.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/inc/tag.class.php b/inc/tag.class.php index c220ef8..fc7c975 100644 --- a/inc/tag.class.php +++ b/inc/tag.class.php @@ -846,7 +846,7 @@ public static function showTagDropdown($params = []) PluginTagTagItem::getTable() . '.items_id' => $params['id'], PluginTagTagItem::getTable() . '.itemtype' => $itemtype, ], - 'ORDERBY' => PluginTagTagItem::getTable() . '.id', + 'ORDERBY' => PluginTagTagItem::getTable() . '.plugin_tag_tags_id', ]); foreach ($selected_iterator as $tag_item_data) { $selected_tags[] = $tag_item_data['plugin_tag_tags_id']; @@ -929,7 +929,7 @@ public static function getTagForEntityName($completename = "") PluginTagTagItem::getTable() . '.items_id' => $entities_id, PluginTagTagItem::getTable() . '.itemtype' => 'Entity', ], - 'ORDERBY' => PluginTagTagItem::getTable() . '.id', + 'ORDERBY' => PluginTagTagItem::getTable() . '.plugin_tag_tags_id', ]); foreach ($iterator as $tag_data) { $out .= self::renderSingleTag($tag_data);