Source
<?php declare(strict_types = 0);
/*
** Copyright (C) 2001-2025 Zabbix SIA
**
** This program is free software: you can redistribute it and/or modify it under the terms of
** the GNU Affero General Public License as published by the Free Software Foundation, version 3.
**
** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License along with this program.
** If not, see <https://www.gnu.org/licenses/>.
**/
/**
* Helper class containing methods for operations with hosts.
*/
class CApiHostHelper {
/**
* Get all parent templates recursively for given hosts and/or templates.
*
* @param array $hostids Mandatory, not empty. Host or template id's for whom you are searching parents.
*
* @throws APIException if templates are looped.
*
* @return array List with two arrays: host to parent templates template map, list of all parent templates.
*/
public static function getParentTemplates(array $hostids): array {
$hosts_templates = [];
$step_hostids = array_flip($hostids);
do {
$step_hostids = array_keys($step_hostids);
foreach ($step_hostids as $hostid) {
$hosts_templates[$hostid]['parents'] = [];
}
$templateids = [];
$db_host_templates = DBselect(
'SELECT ht.hostid,ht.templateid'.
' FROM hosts_templates ht'.
' WHERE '.dbConditionInt('ht.hostid', $step_hostids)
);
while ($db_host_template = DBfetch($db_host_templates)) {
$hosts_templates[$db_host_template['hostid']]['parents'][$db_host_template['templateid']] = true;
$templateids[$db_host_template['templateid']] = true;
}
// Only unprocessed templates will be populated.
$step_hostids = [];
foreach (array_keys($templateids) as $templateid) {
if (!array_key_exists($templateid, $hosts_templates)) {
$step_hostids[$templateid] = true;
}
}
} while ($step_hostids);
$all_templateids = array_keys(array_diff_key($hosts_templates, array_flip($hostids)));