Source
xxxxxxxxxx
* @return array|null Item data at specified time of first data before specified time. null if data is not found.
<?php
/*
** 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/>.
**/
/**
* Class to perform low level history related actions.
*/
class CHistoryManager {
/**
* @var bool
*/
private $primary_keys_enabled = false;
/**
* Whether to enable optimizations that make use of PRIMARY KEY (itemid, clock, ns) on the history tables.
*
* @param bool $enabled
*
* @return CHistoryManager
*/
public function setPrimaryKeysEnabled(bool $enabled = true): CHistoryManager {
$this->primary_keys_enabled = $enabled;
return $this;
}
/**
* Returns a subset of $items having history data within the $period of time.
*
* @param array $items An array of items with the 'itemid' and 'value_type' properties.
* @param int $period The maximum period of time to search for history values within.
*
* @return array An array with items IDs as keys and the original item data as values.
*/
public function getItemsHavingValues(array $items, $period = null) {
$items = zbx_toHash($items, 'itemid');
$results = [];
$grouped_items = $this->getItemsGroupedByStorage($items);
if (array_key_exists(ZBX_HISTORY_SOURCE_ELASTIC, $grouped_items)) {
$results += $this->getLastValuesFromElasticsearch($grouped_items[ZBX_HISTORY_SOURCE_ELASTIC], 1, $period);
}
if (array_key_exists(ZBX_HISTORY_SOURCE_SQL, $grouped_items)) {
$results += $this->getItemsHavingValuesFromSql($grouped_items[ZBX_HISTORY_SOURCE_SQL], $period);
}
return array_intersect_key($items, $results);
}
/**
* SQL specific implementation of getItemsHavingValues.
*
* @see CHistoryManager::getItemsHavingValues
*/
private function getItemsHavingValuesFromSql(array $items, $period = null) {
$results = [];
if (CHousekeepingHelper::get(CHousekeepingHelper::HK_HISTORY_GLOBAL) == 1) {
$hk_history = timeUnitToSeconds(CHousekeepingHelper::get(CHousekeepingHelper::HK_HISTORY));
$period = $period !== null ? min($period, $hk_history) : $hk_history;
}
if ($period !== null) {
$period = time() - $period;
}
$items = zbx_toHash($items, 'itemid');
$itemids_by_type = [];
foreach ($items as $itemid => $item) {
$itemids_by_type[$item['value_type']][] = $itemid;
}
foreach ($itemids_by_type as $type => $type_itemids) {
$type_results = DBfetchColumn(DBselect(