diff --git a/CHANGELOG.md b/CHANGELOG.md index be1c398a..c1d0fcf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added + +- Add notification tags for the fields of the notified item: `##fields..##` for the value, `##lang.fields..##` for the label. A value is only sent to the recipients whose profile can read the block +- Add the fields of tickets, changes and problems, and of the assets linked to a ticket, to the variables of the followup, task and solution templates: `{{ ticket.fields.. }}`, `{{ asset.fields.. }}` + ### Fixed - Remove redundant variable initialization in the question type AJAX controller diff --git a/README.md b/README.md index 12ef0998..873e9c85 100644 --- a/README.md +++ b/README.md @@ -261,6 +261,21 @@ Fields options (mandatory / read only) can be overridden for some item statuses. ![Screenshot](./docs/screenshots/override_by_status.png) +Fields can be used in notification templates of the items having notifications (tickets, changes, problems, projects, etc.), they are listed in the "Tags" tab of the templates: + + * `##fields..##`: value of the field, as displayed in the form (dropdown label, Yes / No, date in the recipient format, etc.) + * `##lang.fields..##`: label of the field, translated in the recipient language + +`` and `` are the system names, they do not change when a label is renamed. A value is only sent to the recipients whose profile can read the block in the entity of the item; it is empty for a recipient without GLPI account. + +The fields of tickets, changes and problems can also be used in followup, task and solution templates, as `{{ ticket.fields.. }}` (or `change.`, `problem.`), as well as the fields of the assets linked to a ticket: + +```twig +{% for asset in ticket.assets %}{{ asset.name }}: {{ asset.fields.. }}{% endfor %} +``` + +They are listed in the documentation of the template variables, with the filter to use for multiple lines text (`nl2br`) and rich text (`raw`). As in the item form, a value is only rendered if the profile of the user applying the template can read the block. When the template is applied by a form (the ticket is created without right checks) or by the cron (followups and reminders of pending reasons, sent to the requester), every value is rendered: this allows a form submitted by a requester to add a private followup with technical data for the technicians. + ## Download Releases can be donwloaded on [GitHub](https://github.com/PluginsGLPI/fields/releases). diff --git a/hook.php b/hook.php index 59ef72bb..e9ecd63f 100644 --- a/hook.php +++ b/hook.php @@ -28,6 +28,8 @@ * ------------------------------------------------------------------------- */ +use Glpi\ContentTemplates\Parameters\ParametersTypes\AttributeParameter; + /** * Plugin install process * @@ -362,3 +364,25 @@ function plugin_item_transfer_fields(array $options): void $container->updateFieldsValues($data, $itemtype, true); } } + +/** + * Fields variables listed in the documentation of the template variables + * + * @return AttributeParameter[] + */ +function plugin_fields_get_content_template_parameter(?string $node_name): array +{ + return PluginFieldsNotificationTag::getTemplateParameters($node_name); +} + +/** + * Fields values of the item on which a followup, task or solution template is used + * + * @param array{node_name: string, id: int} $params + * + * @return array{fields?: array>} + */ +function plugin_fields_get_content_template_value(array $params): array +{ + return PluginFieldsNotificationTag::getTemplateValues($params['node_name'], (int) $params['id']); +} diff --git a/inc/notificationtag.class.php b/inc/notificationtag.class.php new file mode 100644 index 00000000..e2b6cda0 --- /dev/null +++ b/inc/notificationtag.class.php @@ -0,0 +1,521 @@ +. + * ------------------------------------------------------------------------- + * @copyright Copyright (C) 2013-2023 by Fields plugin team. + * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + * @link https://github.com/pluginsGLPI/fields + * ------------------------------------------------------------------------- + */ + +use Glpi\ContentTemplates\Parameters\AssetParameters; +use Glpi\ContentTemplates\Parameters\ParametersTypes\AttributeParameter; +use Glpi\Plugin\Hooks; + +/** + * Fields values in the texts generated by GLPI: + * - notification tags of the notified item: ##fields..## for the value, + * ##lang.fields..## for the label; + * - variables of the followup, task and solution templates: {{ ticket.fields.. }} + * (or change., problem.), {{ asset.fields.. }} for the assets linked to a ticket. + */ +final class PluginFieldsNotificationTag +{ + /** + * Itemtypes of the followup, task and solution templates, by node name of their variables + */ + private const TEMPLATE_ITEMTYPES = [ + 'ticket' => Ticket::class, + 'change' => Change::class, + 'problem' => Problem::class, + ]; + + /** + * Notified itemtype by notification target class + * + * @var array, class-string> + */ + private static array $itemtypes = []; + + /** + * Fields by itemtype and language, a notification being sent to several recipients + * + * @var array>> + */ + private static array $fields_cache = []; + + /** + * @param string[] $itemtypes Itemtypes having containers + */ + public static function registerHooks(array $itemtypes): void + { + /** @var array $PLUGIN_HOOKS */ + /** @var array $CFG_GLPI */ + global $PLUGIN_HOOKS, $CFG_GLPI; + + self::$itemtypes = []; + self::$fields_cache = []; + + // GLPI calls plugin_fields_get_content_template_*() for the plugins registering these hooks + if (array_intersect($itemtypes, [...array_values(self::TEMPLATE_ITEMTYPES), ...$CFG_GLPI['asset_types']]) !== []) { + $PLUGIN_HOOKS[Hooks::GET_CONTENT_TEMPLATE_PARAMETER]['fields'] = true; + $PLUGIN_HOOKS[Hooks::GET_CONTENT_TEMPLATE_VALUE]['fields'] = true; + } + + foreach ($itemtypes as $itemtype) { + $target_class = NotificationTarget::getInstanceClass($itemtype); + // not every itemtype has notifications (Computer, etc.) + if (!class_exists($target_class)) { + continue; + } + + self::$itemtypes[$target_class] = $itemtype; + + // GLPI has no hook to declare tags: ITEM_ADD_TARGETS is the one run by the target + // constructor, so the tags are listed in the "Tags" tab of the notification templates. + $PLUGIN_HOOKS[Hooks::ITEM_ADD_TARGETS]['fields'][$target_class] = self::addTags(...); + $PLUGIN_HOOKS[Hooks::ADD_RECIPIENT_TO_TARGET]['fields'][$target_class] = self::addRecipient(...); + $PLUGIN_HOOKS[Hooks::ITEM_GET_DATA]['fields'][$target_class] = self::addData(...); + } + } + + /** + * Pass the recipient to the template data, so that the values of a container + * are only sent to the users who can read it (see addData()). + * + * The data being computed once by set of recipient options, this computes it by recipient. + */ + public static function addRecipient(NotificationTarget $target): void + { + $users_id = self::getRecipientUserId($target); + if ($users_id === 0 || self::getFields(self::$itemtypes[$target::class] ?? '') === []) { + return; + } + + foreach ($target->target as $key => $infos) { + /** @var array $infos `users_id` is set for GLPI users, but missing from the GLPI PHPDoc */ + if ((int) ($infos['users_id'] ?? 0) === $users_id) { + $target->target[$key]['additionnaloption']['users_id'] = $users_id; + } + } + } + + public static function addTags(NotificationTarget $target): void + { + foreach (self::getFields(self::$itemtypes[$target::class] ?? '') as $field) { + $target->addTagToList([ + 'tag' => self::getTagName($field), + 'label' => $field['container_label'] . ' - ' . $field['label'], + 'value' => true, + ]); + } + } + + public static function addData(NotificationTarget $target): void + { + $item = $target->obj; + // no single item for some events (ex: alerts of the cron) + $has_item = $item instanceof CommonDBTM && !$item->isNewItem(); + + $readable_containers = $has_item + ? self::getReadableContainers( + self::getRecipientUserId($target), + $item->isEntityAssign() ? $item->getEntityID() : 0, + ) + : []; + + $values = []; + foreach (self::getFields(self::$itemtypes[$target::class] ?? '') as $field) { + $container_id = (int) $field['plugin_fields_containers_id']; + if (!array_key_exists($container_id, $values)) { + $values[$container_id] = in_array($container_id, $readable_containers, true) + ? self::getValues($item, $field) + : null; + } + + $tag = self::getTagName($field); + // a tag without value is set anyway, otherwise it would be sent as is + $target->data['##' . $tag . '##'] = $values[$container_id] === null ? '' : self::formatValue($field, $values[$container_id]); + $target->data['##lang.' . $tag . '##'] = $field['label']; + } + } + + /** + * Variables of the followup, task and solution templates (twig), listed in the documentation + * of the variables, see plugin_fields_get_content_template_parameter(): + * {{ ticket.fields.. }} (or change., problem.) for the item, and + * {{ asset.fields.. }} in {% for asset in ticket.assets %} for the linked assets + * + * @return AttributeParameter[] + */ + public static function getTemplateParameters(?string $node_name): array + { + /** @var array $CFG_GLPI */ + global $CFG_GLPI; + + $itemtypes = $node_name === AssetParameters::getDefaultNodeName() + ? $CFG_GLPI['asset_types'] + : [self::TEMPLATE_ITEMTYPES[$node_name] ?? '']; + + $parameters = []; + foreach ($itemtypes as $itemtype) { + foreach (self::getFields($itemtype) as $field) { + $label = $field['container_label'] . ' - ' . $field['label']; + $parameters[] = new AttributeParameter( + sprintf('fields.%s.%s', $field['container_name'], $field['name']), + // a container may be used by several asset types + count($itemtypes) > 1 ? $itemtype::getTypeName(1) . ' - ' . $label : $label, + match ($field['type']) { + // a rich text value is HTML, cleaned by GLPI after the rendering + 'richtext' => 'raw', + 'textarea' => 'nl2br', + default => '', + }, + ); + } + } + + return $parameters; + } + + /** + * Values of the template variables for the item on which the template is used. + * See plugin_fields_get_content_template_value() + * + * A template can be rendered for any user who can read the item (ajax/itilfollowup.php only + * checks this right), so the values of a container are only rendered if the current profile + * can read it, as in the item form. Without right checks (template applied by a form, which + * creates the ticket with Session::callAsSystem()) or by the cron (followups and reminders of + * pending reasons, sent to the requester), every value is rendered: the administrator chooses + * the template. + * + * @return array{fields?: array>, assets?: array>} + */ + public static function getTemplateValues(string $node_name, int $items_id): array + { + /** @var array $CFG_GLPI */ + global $CFG_GLPI; + + $itemtype = self::TEMPLATE_ITEMTYPES[$node_name] ?? null; + if ($itemtype === null || ($item = $itemtype::getById($items_id)) === false) { + return []; + } + + $has_fields = self::getFields($itemtype) !== []; + $assets_with_fields = $item instanceof Ticket + ? array_filter( + $CFG_GLPI['asset_types'], + fn(string $asset_itemtype): bool => self::getFields($asset_itemtype) !== [], + ) + : []; + if (!$has_fields && $assets_with_fields === []) { + return []; + } + + $readable_containers = self::getContainersReadableInTemplates(); + + $values = []; + if ($has_fields) { + $values['fields'] = self::getVariables($item, $readable_containers); + } + + // The values of a plugin replace the ones of GLPI: the linked assets are built as GLPI does + // (see TicketParameters::defineValues()), with their fields in addition. + if ($assets_with_fields !== []) { + $assets = []; + foreach (Item_Ticket::getItemsAssociatedTo(Ticket::class, $item->getID()) as $item_ticket) { + $asset_itemtype = $item_ticket->fields['itemtype']; + if ( + !in_array($asset_itemtype, $CFG_GLPI['asset_types'], true) + || !class_exists($asset_itemtype) + || ($asset = $asset_itemtype::getById($item_ticket->fields['items_id'])) === false + ) { + continue; + } + + $asset_values = (new AssetParameters())->getValues($asset); + if (in_array($asset_itemtype, $assets_with_fields, true)) { + $asset_values['fields'] = self::getVariables($asset, $readable_containers); + } + + $assets[] = $asset_values; + } + + $values['assets'] = $assets; + } + + return $values; + } + + /** + * Containers whose values are rendered in the templates, null for all of them + * + * @return int[]|null + */ + private static function getContainersReadableInTemplates(): ?array + { + if (Session::isRightChecksDisabled() || Session::isCron()) { + return null; + } + + return isset($_SESSION['glpiactiveprofile']['id']) + ? self::getReadableContainersForProfiles([(int) $_SESSION['glpiactiveprofile']['id']]) + : []; + } + + /** + * @param int[]|null $readable_containers Containers whose values are rendered, null for all of them + * + * @return array> Displayed values by container and field name + */ + private static function getVariables(CommonDBTM $item, ?array $readable_containers): array + { + $values = []; + $variables = []; + foreach (self::getFields($item::class) as $field) { + $container_id = (int) $field['plugin_fields_containers_id']; + if (!array_key_exists($container_id, $values)) { + $values[$container_id] = $readable_containers === null || in_array($container_id, $readable_containers, true) + ? self::getValues($item, $field) + : null; + } + + $variables[$field['container_name']][$field['name']] = $values[$container_id] === null + ? '' + : self::formatValue($field, $values[$container_id]); + } + + return $variables; + } + + private static function getRecipientUserId(NotificationTarget $target): int + { + return ($target->recipient_data['itemtype'] ?? null) === User::class + ? (int) ($target->recipient_data['items_id'] ?? 0) + : 0; + } + + /** + * Containers readable by a profile of the user in the entity, none for a recipient + * without GLPI account (email address of a requester, etc.) + * + * @return int[] + */ + private static function getReadableContainers(int $users_id, int $entities_id): array + { + if ($users_id <= 0) { + return []; + } + + $profiles = Profile_User::getUserProfiles( + $users_id, + getEntitiesRestrictCriteria(Profile_User::getTable(), 'entities_id', $entities_id, true), + ); + + return self::getReadableContainersForProfiles(array_values($profiles)); + } + + /** + * @param int[] $profiles + * + * @return int[] + */ + private static function getReadableContainersForProfiles(array $profiles): array + { + /** @var DBmysql $DB */ + global $DB; + + if ($profiles === []) { + return []; + } + + $containers = []; + $iterator = $DB->request([ + 'SELECT' => 'plugin_fields_containers_id', + 'DISTINCT' => true, + 'FROM' => PluginFieldsProfile::getTable(), + 'WHERE' => [ + 'profiles_id' => $profiles, + 'right' => ['>=', READ], + ], + ]); + foreach ($iterator as $data) { + $containers[] = (int) $data['plugin_fields_containers_id']; + } + + return $containers; + } + + /** + * Active fields of the active containers of the itemtype, with translated labels + * + * @return array> + */ + private static function getFields(string $itemtype): array + { + /** @var DBmysql $DB */ + global $DB; + + if ($itemtype === '') { + return []; + } + + $cache_key = $itemtype . '|' . ($_SESSION['glpilanguage'] ?? ''); + if (isset(self::$fields_cache[$cache_key])) { + return self::$fields_cache[$cache_key]; + } + + $containers = []; + foreach ((new PluginFieldsContainer())->find(['is_active' => 1]) as $container) { + $container_itemtypes = PluginFieldsToolbox::decodeJSONItemtypes($container['itemtypes']); + if (is_array($container_itemtypes) && in_array($itemtype, $container_itemtypes, true)) { + $container['label'] = PluginFieldsLabelTranslation::getLabelFor($container + ['itemtype' => PluginFieldsContainer::class]); + $containers[$container['id']] = $container; + } + } + + if ($containers === []) { + return self::$fields_cache[$cache_key] = []; + } + + $fields = []; + $iterator = $DB->request([ + 'FROM' => PluginFieldsField::getTable(), + 'WHERE' => [ + 'plugin_fields_containers_id' => array_keys($containers), + 'is_active' => 1, + 'NOT' => ['type' => 'header'], + ], + 'ORDER' => ['plugin_fields_containers_id', 'ranking'], + ]); + foreach ($iterator as $field) { + $container = $containers[$field['plugin_fields_containers_id']]; + + $field['label'] = PluginFieldsLabelTranslation::getLabelFor($field + ['itemtype' => PluginFieldsField::class]); + $field['container_name'] = $container['name']; + $field['container_label'] = $container['label']; + $field['container_entity'] = $container['entities_id']; + $field['container_recursive'] = $container['is_recursive']; + $field['itemtype'] = $itemtype; + $fields[] = $field; + } + + return self::$fields_cache[$cache_key] = $fields; + } + + private static function getTagName(array $field): string + { + return sprintf('fields.%s.%s', $field['container_name'], $field['name']); + } + + /** + * Values stored by the container of the field for the item, + * empty if none is stored, null if the container does not apply to the item entity + * + * @return array|null + */ + private static function getValues(CommonDBTM $item, array $field): ?array + { + if ($item->isEntityAssign()) { + $entity = $item->getEntityID(); + $container_entities = $field['container_recursive'] + ? getSonsOf(Entity::getTable(), $field['container_entity']) + : [$field['container_entity']]; + if (!in_array($entity, $container_entities)) { + return null; + } + } + + $classname = PluginFieldsContainer::getClassname($field['itemtype'], $field['container_name']); + if (!class_exists($classname)) { + return []; + } + + $values = (new $classname())->find([ + 'plugin_fields_containers_id' => $field['plugin_fields_containers_id'], + 'items_id' => $item->getID(), + ], [], 1); + + return array_shift($values) ?? []; + } + + /** + * Value of the field as displayed to the user + */ + private static function formatValue(array $field, array $values): string + { + $name = $field['name']; + $type = $field['type']; + + if ($type === 'glpi_item') { + $itemtype = $values['itemtype_' . $name] ?? null; + $items_id = (int) ($values['items_id_' . $name] ?? 0); + if (!is_string($itemtype) || !is_a($itemtype, CommonDBTM::class, true) || $items_id <= 0) { + return ''; + } + + $linked_item = $itemtype::getById($items_id); + return $linked_item === false ? '' : $linked_item->getName(); + } + + $value = $values[$type === 'dropdown' ? 'plugin_fields_' . $name . 'dropdowns_id' : $name] ?? null; + // same default value as the search, the current date is not one for an existing item + if (($value === null || $value === '') && $field['default_value'] !== 'now') { + $value = $field['default_value']; + } + + if ($value === null || $value === '') { + return ''; + } + + $dropdown_matches = []; + $dropdown_itemtype = match (true) { + $type === 'dropdown' => PluginFieldsDropdown::getClassname($name), + preg_match('/^dropdown-(?.+)$/i', $type, $dropdown_matches) === 1 => $dropdown_matches['class'], + default => null, + }; + + if ($dropdown_itemtype !== null) { + if (!is_a($dropdown_itemtype, CommonDBTM::class, true)) { + return ''; // itemtype of a disabled plugin + } + + $ids = $field['multiple'] ? json_decode((string) $value, true) : [$value]; + $names = []; + foreach (is_array($ids) ? $ids : [] as $id) { + if ((int) $id > 0) { + $names[] = Dropdown::getDropdownName($dropdown_itemtype::getTable(), (int) $id); + } + } + + return implode(', ', array_filter($names, fn($name) => $name !== '')); + } + + return match ($type) { + 'yesno' => Dropdown::getYesNo((int) $value), + 'date' => (string) Html::convDate((string) $value), + 'datetime' => (string) Html::convDateTime((string) $value), + default => (string) $value, + }; + } +} diff --git a/setup.php b/setup.php index a7e9b379..231613ce 100644 --- a/setup.php +++ b/setup.php @@ -130,6 +130,11 @@ function plugin_init_fields() } } + // Notifications are also sent by the cron, without session + if ($itemtypes !== false) { + PluginFieldsNotificationTag::registerHooks($itemtypes); + } + $PLUGIN_HOOKS[Hooks::ITEM_TRANSFER]['fields'] = 'plugin_item_transfer_fields'; // Register fields question type diff --git a/tests/Units/NotificationTagTest.php b/tests/Units/NotificationTagTest.php new file mode 100644 index 00000000..1d08cb8f --- /dev/null +++ b/tests/Units/NotificationTagTest.php @@ -0,0 +1,603 @@ +. + * ------------------------------------------------------------------------- + * @copyright Copyright (C) 2013-2023 by Fields plugin team. + * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + * @link https://github.com/pluginsGLPI/fields + * ------------------------------------------------------------------------- + */ + +declare(strict_types=1); + +namespace GlpiPlugin\Field\Tests\Units; + +use Change; +use Computer; +use DBmysql; +use Dropdown; +use Entity; +use Glpi\ContentTemplates\ParametersPreset; +use Glpi\ContentTemplates\TemplateManager; +use Glpi\Tests\DbTestCase; +use Glpi\Tests\GLPITestCase; +use GlpiPlugin\Field\Tests\FieldTestTrait; +use ITILFollowup; +use ITILFollowupTemplate; +use NotificationEventMailing; +use NotificationTarget; +use PluginFieldsContainer; +use PluginFieldsDropdown; +use PluginFieldsField; +use PluginFieldsLabelTranslation; +use PluginFieldsProfile; +use Profile; +use Profile_User; +use Session; +use Ticket; +use User; + +require_once __DIR__ . '/../FieldTestCase.php'; + +final class NotificationTagTest extends DbTestCase +{ + use FieldTestTrait; + + private PluginFieldsContainer $container; + + /** @var array Field name by type */ + private array $names = []; + + public function setUp(): void + { + GLPITestCase::setUp(); + $this->login(); + $this->setEntity(0, true); + + $this->container = $this->createFieldContainer([ + 'label' => 'Notified', + 'type' => 'tab', + 'itemtypes' => [Change::class], + 'is_active' => 1, + 'entities_id' => 0, + 'is_recursive' => 1, + ]); + + $fields = [ + 'header' => ['type' => 'header'], + 'text' => ['type' => 'text'], + 'textarea' => ['type' => 'textarea'], + 'richtext' => ['type' => 'richtext'], + 'number' => ['type' => 'number'], + 'url' => ['type' => 'url'], + 'yesno' => ['type' => 'yesno'], + 'date' => ['type' => 'date'], + 'datetime' => ['type' => 'datetime'], + 'dropdown' => ['type' => 'dropdown'], + 'dropdown_multiple' => ['type' => 'dropdown', 'multiple' => 1, 'default_value' => []], + 'user' => ['type' => 'dropdown-User'], + 'users' => ['type' => 'dropdown-User', 'multiple' => 1, 'default_value' => []], + 'item' => ['type' => 'glpi_item', 'allowed_values' => [Computer::class]], + 'inactive' => ['type' => 'text', 'is_active' => 0], + ]; + $ranking = 1; + foreach ($fields as $key => $inputs) { + $field = $this->createField($inputs + [ + 'label' => 'Label ' . $key, + PluginFieldsContainer::getForeignKeyField() => $this->container->getID(), + 'ranking' => $ranking++, + 'is_active' => 1, + 'is_readonly' => 0, + ], ['default_value']); + $this->names[$key] = $field->fields['name']; + } + } + + public function tearDown(): void + { + $this->tearDownFieldTest(); + GLPITestCase::tearDown(); + } + + public function testTagsAreListedForActiveFields(): void + { + $target = NotificationTarget::getInstanceByType(Change::class); + $target->getTags(); + + $values = array_keys($target->tag_descriptions[NotificationTarget::TAG_VALUE]); + $labels = array_keys($target->tag_descriptions[NotificationTarget::TAG_LANGUAGE]); + + foreach (array_diff_key($this->names, ['header' => 0, 'inactive' => 0]) as $name) { + $this->assertContains($this->tag($name), $values); + $this->assertContains($this->langTag($name), $labels); + } + + $this->assertNotContains($this->tag($this->names['header']), $values); + $this->assertNotContains($this->tag($this->names['inactive']), $values); + + $tag = $target->tag_descriptions[NotificationTarget::TAG_VALUE][$this->tag($this->names['text'])]; + $this->assertSame('Notified - Label text', $tag['label']); + } + + public function testValuesAreDisplayedAsInTheForm(): void + { + $dropdown_class = PluginFieldsDropdown::getClassname($this->names['dropdown']); + $alpha = $this->createItem($dropdown_class, ['name' => 'Alpha', 'entities_id' => 0]); + + $multiple_class = PluginFieldsDropdown::getClassname($this->names['dropdown_multiple']); + $one = $this->createItem($multiple_class, ['name' => 'One', 'entities_id' => 0]); + $two = $this->createItem($multiple_class, ['name' => 'Two', 'entities_id' => 0]); + + $user_id = getItemByTypeName(User::class, TU_USER, true); + $tech_id = getItemByTypeName(User::class, 'tech', true); + $computer = $this->createItem(Computer::class, [ + 'name' => 'Linked computer', + 'entities_id' => getItemByTypeName(Entity::class, '_test_root_entity', true), + ]); + $change = $this->createChange(); + + $this->assertTrue($this->container->updateFieldsValues([ + 'plugin_fields_containers_id' => $this->container->getID(), + 'itemtype' => Change::class, + 'items_id' => $change->getID(), + $this->names['text'] => 'Some text', + $this->names['textarea'] => "Line 1\nLine 2", + $this->names['richtext'] => '

Rich text

', + $this->names['number'] => '42', + $this->names['url'] => 'https://example.com/?a=1&b=2', + $this->names['yesno'] => '1', + $this->names['date'] => '2026-11-19', + $this->names['datetime'] => '2026-11-19 10:30:00', + 'plugin_fields_' . $this->names['dropdown'] . 'dropdowns_id' => $alpha->getID(), + 'plugin_fields_' . $this->names['dropdown_multiple'] . 'dropdowns_id' => [$one->getID(), $two->getID()], + $this->names['user'] => $user_id, + $this->names['users'] => [$user_id, $tech_id], + 'itemtype_' . $this->names['item'] => Computer::class, + 'items_id_' . $this->names['item'] => $computer->getID(), + ], Change::class)); + + $data = $this->getData($change); + + $this->assertSame('Some text', $data[$this->tag($this->names['text'])]); + $this->assertSame("Line 1\nLine 2", $data[$this->tag($this->names['textarea'])]); + $this->assertSame('

Rich text

', $data[$this->tag($this->names['richtext'])]); + $this->assertSame('42', $data[$this->tag($this->names['number'])]); + $this->assertSame('https://example.com/?a=1&b=2', $data[$this->tag($this->names['url'])]); + $this->assertSame('Yes', $data[$this->tag($this->names['yesno'])]); + $this->assertSame('2026-11-19', $data[$this->tag($this->names['date'])]); + $this->assertSame('2026-11-19 10:30', $data[$this->tag($this->names['datetime'])]); + $this->assertSame('Alpha', $data[$this->tag($this->names['dropdown'])]); + $this->assertSame('One, Two', $data[$this->tag($this->names['dropdown_multiple'])]); + $this->assertSame( + Dropdown::getDropdownName(User::getTable(), $user_id), + $data[$this->tag($this->names['user'])], + ); + $this->assertSame( + Dropdown::getDropdownName(User::getTable(), $user_id) . ', ' . Dropdown::getDropdownName(User::getTable(), $tech_id), + $data[$this->tag($this->names['users'])], + ); + $this->assertSame('Linked computer', $data[$this->tag($this->names['item'])]); + $this->assertSame('Label text', $data[$this->langTag($this->names['text'])]); + } + + public function testTagsOfAnItemWithoutValuesAreEmpty(): void + { + $data = $this->getData($this->createChange()); + + foreach (array_diff_key($this->names, ['header' => 0, 'inactive' => 0, 'yesno' => 0]) as $name) { + $this->assertSame('', $data[$this->tag($name)], $name); + } + + // a Yes/No field is "No" by default, as in the form + $this->assertSame('No', $data[$this->tag($this->names['yesno'])]); + } + + public function testDefaultValueIsUsedWhenNoValueIsStored(): void + { + $field = $this->createField([ + 'label' => 'Label default', + 'type' => 'yesno', + 'default_value' => '1', + PluginFieldsContainer::getForeignKeyField() => $this->container->getID(), + 'ranking' => 99, + 'is_active' => 1, + 'is_readonly' => 0, + ]); + + $data = $this->getData($this->createChange()); + + $this->assertSame('Yes', $data[$this->tag($field->fields['name'])]); + } + + public function testLabelIsTranslatedInTheRecipientLanguage(): void + { + $field_id = $this->getFieldId($this->names['text']); + $this->createItem(PluginFieldsLabelTranslation::class, [ + 'itemtype' => PluginFieldsField::class, + 'items_id' => $field_id, + 'language' => 'fr_FR', + 'label' => 'Libellé texte', + ]); + $change = $this->createChange(); + + $this->assertSame('Label text', $this->getData($change)[$this->langTag($this->names['text'])]); + + $language = $_SESSION['glpilanguage']; + $_SESSION['glpilanguage'] = 'fr_FR'; + try { + $this->assertSame('Libellé texte', $this->getData($change)[$this->langTag($this->names['text'])]); + } finally { + $_SESSION['glpilanguage'] = $language; + } + } + + public function testContainerOfAnotherEntityGivesEmptyValues(): void + { + $child_entity = getItemByTypeName(Entity::class, '_test_child_1', true); + $this->assertTrue($this->container->update([ + 'id' => $this->container->getID(), + 'entities_id' => $child_entity, + 'is_recursive' => 0, + ])); + $change = $this->createChange(); + + $this->assertTrue($this->container->updateFieldsValues([ + 'plugin_fields_containers_id' => $this->container->getID(), + 'itemtype' => Change::class, + 'items_id' => $change->getID(), + $this->names['text'] => 'Hidden', + ], Change::class)); + + $this->assertSame('', $this->getData($change)[$this->tag($this->names['text'])]); + } + + public function testValuesAreOnlySentToRecipientsAllowedToReadTheContainer(): void + { + /** @var DBmysql $DB */ + global $DB; + + $change = $this->createChange(); + $this->assertTrue($this->container->updateFieldsValues([ + 'plugin_fields_containers_id' => $this->container->getID(), + 'itemtype' => Change::class, + 'items_id' => $change->getID(), + $this->names['text'] => 'Restricted', + ], Change::class)); + + $profiles_id = getItemByTypeName(Profile::class, 'Self-Service', true); + $user = $this->createItem(User::class, ['name' => 'recipient' . $this->getUniqueString()]); + $this->createItem(Profile_User::class, [ + 'users_id' => $user->getID(), + 'profiles_id' => $profiles_id, + 'entities_id' => 0, + 'is_recursive' => 1, + ]); + + $set_right = fn(int $right) => $DB->update(PluginFieldsProfile::getTable(), ['right' => $right], [ + 'profiles_id' => $profiles_id, + 'plugin_fields_containers_id' => $this->container->getID(), + ]); + + $set_right(0); + $data = $this->getData($change, $user->getID()); + $this->assertSame('', $data[$this->tag($this->names['text'])]); + // the label is not confidential + $this->assertSame('Label text', $data[$this->langTag($this->names['text'])]); + + $set_right(READ); + $this->assertSame('Restricted', $this->getData($change, $user->getID())[$this->tag($this->names['text'])]); + + // email address without GLPI account + $this->assertSame('', $this->getData($change, 0)[$this->tag($this->names['text'])]); + } + + public function testRecipientIsPassedToTheTemplateData(): void + { + $users_id = getItemByTypeName(User::class, TU_USER, true); + + $target = NotificationTarget::getInstance($this->createChange(), 'update'); + $target->setEvent(NotificationEventMailing::class); + $target->addToRecipientsList([ + 'users_id' => $users_id, + 'email' => 'recipient@example.com', + 'language' => 'en_GB', + ]); + + $recipients = array_values($target->target); + $this->assertCount(1, $recipients); + $this->assertSame($users_id, $recipients[0]['additionnaloption']['users_id']); + } + + public function testTagsOfAnEventWithoutItemAreEmpty(): void + { + $target = NotificationTarget::getInstanceByType(Change::class, 'update'); + $data = $target->getForTemplate('update', [ + 'additionnaloption' => ['usertype' => NotificationTarget::GLPI_USER], + ]); + + $this->assertSame('', $data[$this->tag($this->names['text'])]); + $this->assertSame('Label text', $data[$this->langTag($this->names['text'])]); + } + + public function testFollowupTemplateRendersFieldsVariables(): void + { + $dropdown_class = PluginFieldsDropdown::getClassname($this->names['dropdown']); + $alpha = $this->createItem($dropdown_class, ['name' => 'Alpha', 'entities_id' => 0]); + + $change = $this->createChange(); + $this->assertTrue($this->container->updateFieldsValues([ + 'plugin_fields_containers_id' => $this->container->getID(), + 'itemtype' => Change::class, + 'items_id' => $change->getID(), + $this->names['text'] => 'Some ', + $this->names['richtext'] => '

Rich text

', + 'plugin_fields_' . $this->names['dropdown'] . 'dropdowns_id' => $alpha->getID(), + ], Change::class)); + + $variable = fn(string $key, string $filter = '') => sprintf( + '{{ change.fields.%s.%s%s }}', + $this->container->fields['name'], + $this->names[$key], + $filter, + ); + $template = $this->createItem(ITILFollowupTemplate::class, [ + 'name' => 'Template ' . $this->getUniqueString(), + 'content' => '

' . $variable('text') . ' / ' . $variable('dropdown') . '

' . $variable('richtext', ' | raw'), + ]); + + $this->assertSame( + '

Some <text> / Alpha

Rich text

', + $template->getRenderedContent($change), + ); + + // the current profile cannot read the container: empty values, as in the item form + /** @var DBmysql $DB */ + global $DB; + $DB->update(PluginFieldsProfile::getTable(), ['right' => 0], [ + 'profiles_id' => $_SESSION['glpiactiveprofile']['id'], + 'plugin_fields_containers_id' => $this->container->getID(), + ]); + $this->assertSame('

/

', $template->getRenderedContent($change)); + + // without right checks, as when a form creates the ticket: all the values + $this->assertSame( + '

Some <text> / Alpha

Rich text

', + Session::callAsSystem(fn() => $template->getRenderedContent($change)), + ); + } + + public function testTemplateRenderedForARequesterOnlyShowsReadableContainers(): void + { + $profiles_id = getItemByTypeName(Profile::class, 'Self-Service', true); + /** @var DBmysql $DB */ + global $DB; + $DB->update(PluginFieldsProfile::getTable(), ['right' => 0], [ + 'profiles_id' => $profiles_id, + 'plugin_fields_containers_id' => $this->container->getID(), + ]); + + $change = $this->createChange(); + $this->assertTrue($this->container->updateFieldsValues([ + 'plugin_fields_containers_id' => $this->container->getID(), + 'itemtype' => Change::class, + 'items_id' => $change->getID(), + $this->names['text'] => 'Technical data', + ], Change::class)); + + $template = $this->createItem(ITILFollowupTemplate::class, [ + 'name' => 'Template ' . $this->getUniqueString(), + 'content' => sprintf('

{{ change.fields.%s.%s }}

', $this->container->fields['name'], $this->names['text']), + ]); + + // as rendered by ajax/itilfollowup.php for a requester, who can read the change but not the container + $this->login('post-only', 'postonly'); + $this->assertSame('Self-Service', $_SESSION['glpiactiveprofile']['name']); + $this->assertSame('

', $template->getRenderedContent($change)); + } + + public function testFollowupTemplateAppliedOnTicketCreationWithoutRightChecks(): void + { + $computer_container = $this->createFieldContainer([ + 'label' => 'Admin', + 'type' => 'tab', + 'itemtypes' => [Computer::class], + 'is_active' => 1, + 'entities_id' => 0, + 'is_recursive' => 1, + ]); + $ip_field = $this->createField([ + 'label' => 'IP Admin', + 'type' => 'text', + PluginFieldsContainer::getForeignKeyField() => $computer_container->getID(), + 'ranking' => 1, + 'is_active' => 1, + 'is_readonly' => 0, + ]); + + $entities_id = getItemByTypeName(Entity::class, '_test_root_entity', true); + $computer = $this->createItem(Computer::class, ['name' => 'Server', 'entities_id' => $entities_id]); + $this->assertTrue($computer_container->updateFieldsValues([ + 'plugin_fields_containers_id' => $computer_container->getID(), + 'itemtype' => Computer::class, + 'items_id' => $computer->getID(), + $ip_field->fields['name'] => '192.0.2.10', + ], Computer::class)); + + $template = $this->createItem(ITILFollowupTemplate::class, [ + 'name' => 'Template ' . $this->getUniqueString(), + 'is_private' => 1, + 'content' => sprintf( + '{%% for asset in ticket.assets %%}

{{ asset.fields.%s.%s }}

{%% endfor %%}', + $computer_container->fields['name'], + $ip_field->fields['name'], + ), + ]); + + // the current profile (a requester) cannot read the container + $profiles_id = getItemByTypeName(Profile::class, 'Self-Service', true); + /** @var DBmysql $DB */ + global $DB; + $DB->update(PluginFieldsProfile::getTable(), ['right' => 0], [ + 'profiles_id' => $profiles_id, + 'plugin_fields_containers_id' => $computer_container->getID(), + ]); + $this->login('post-only', 'postonly'); + $this->setEntity($entities_id, true); + + // as Glpi\Form\Destination\AbstractCommonITILFormDestination::createDestinationItems() does + $tickets_id = Session::callAsSystem(fn() => (new Ticket())->add([ + 'name' => 'Ticket ' . $this->getUniqueString(), + 'content' => 'Content', + 'entities_id' => $entities_id, + 'items_id' => [Computer::class => [$computer->getID()]], + '_itilfollowuptemplates_id' => [$template->getID()], + ])); + $this->assertGreaterThan(0, $tickets_id); + + $followup = new ITILFollowup(); + $this->assertTrue($followup->getFromDBByCrit(['itemtype' => Ticket::class, 'items_id' => $tickets_id])); + $this->assertSame('

192.0.2.10

', $followup->fields['content']); + } + + public function testFollowupTemplateRendersFieldsOfLinkedAssets(): void + { + $computer_container = $this->createFieldContainer([ + 'label' => 'Admin', + 'type' => 'tab', + 'itemtypes' => [Computer::class], + 'is_active' => 1, + 'entities_id' => 0, + 'is_recursive' => 1, + ]); + $ip_field = $this->createField([ + 'label' => 'IP Admin', + 'type' => 'text', + PluginFieldsContainer::getForeignKeyField() => $computer_container->getID(), + 'ranking' => 1, + 'is_active' => 1, + 'is_readonly' => 0, + ]); + + $entities_id = getItemByTypeName(Entity::class, '_test_root_entity', true); + $with_ip = $this->createItem(Computer::class, ['name' => 'Server 1', 'entities_id' => $entities_id]); + $without_ip = $this->createItem(Computer::class, ['name' => 'Server 2', 'entities_id' => $entities_id]); + $this->assertTrue($computer_container->updateFieldsValues([ + 'plugin_fields_containers_id' => $computer_container->getID(), + 'itemtype' => Computer::class, + 'items_id' => $with_ip->getID(), + $ip_field->fields['name'] => '192.0.2.10', + ], Computer::class)); + + $ticket = $this->createItem(Ticket::class, [ + 'name' => 'Ticket ' . $this->getUniqueString(), + 'content' => 'Content', + 'entities_id' => $entities_id, + 'items_id' => [Computer::class => [$with_ip->getID(), $without_ip->getID()]], + ], ['items_id']); + + $template = $this->createItem(ITILFollowupTemplate::class, [ + 'name' => 'Template ' . $this->getUniqueString(), + 'content' => sprintf( + '{%% for asset in ticket.assets %%}

{{ asset.name }}: {{ asset.fields.%s.%s }}

{%% endfor %%}', + $computer_container->fields['name'], + $ip_field->fields['name'], + ), + ]); + + $this->assertSame( + '

Server 1: 192.0.2.10

Server 2:

', + $template->getRenderedContent($ticket), + ); + } + + public function testTemplateVariablesAreDocumented(): void + { + $documentation = TemplateManager::generateMarkdownDocumentation(ParametersPreset::ITIL_CHILD_TEMPLATE); + + $this->assertStringContainsString( + // usage as written by GLPI, with an empty filter + sprintf('{{ change.fields.%s.%s }}', $this->container->fields['name'], $this->names['text']), + $documentation, + ); + $this->assertStringContainsString('Notified - Label text', $documentation); + $this->assertStringContainsString( + sprintf('{{ change.fields.%s.%s \\| nl2br }}', $this->container->fields['name'], $this->names['textarea']), + $documentation, + ); + $this->assertStringContainsString( + // pipe escaped in the markdown table + sprintf('{{ change.fields.%s.%s \\| raw }}', $this->container->fields['name'], $this->names['richtext']), + $documentation, + ); + // only for the itemtypes of the containers + $this->assertStringNotContainsString('ticket.fields.', $documentation); + // asset types without fields container: no asset variables + $this->assertStringNotContainsString('asset.fields.', $documentation); + } + + private function createChange(): Change + { + return $this->createItem(Change::class, [ + 'name' => 'Change ' . $this->getUniqueString(), + 'content' => 'Content', + 'entities_id' => 0, + ]); + } + + /** + * Template data for a recipient, the super-admin test user by default, 0 for an email address + * + * @return array + */ + private function getData(Change $change, ?int $users_id = null): array + { + $users_id ??= getItemByTypeName(User::class, TU_USER, true); + + $target = NotificationTarget::getInstance($change, 'update'); + $additionnaloption = ['usertype' => NotificationTarget::GLPI_USER]; + if ($users_id > 0) { + // set by PluginFieldsNotificationTag::addRecipient() when the recipient is added + $additionnaloption['users_id'] = $users_id; + } + + return $target->getForTemplate('update', ['additionnaloption' => $additionnaloption]); + } + + private function getFieldId(string $name): int + { + $field = new PluginFieldsField(); + $this->assertTrue($field->getFromDBByCrit(['name' => $name])); + + return $field->getID(); + } + + private function tag(string $name): string + { + return sprintf('##fields.%s.%s##', $this->container->fields['name'], $name); + } + + private function langTag(string $name): string + { + return sprintf('##lang.fields.%s.%s##', $this->container->fields['name'], $name); + } +}