repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonSession.class.php
centreon/www/class/centreonSession.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonSession */ class CentreonSession { /** * @param int $flag */ public static function start($flag = 0): void { session_start(); if ($flag) { session_write_close(); } } /** * @return void */ public static function stop(): void { // destroy the session session_unset(); session_destroy(); } /** * @return void */ public static function restart(): void { static::stop(); self::start(); // regenerate the session id value session_regenerate_id(true); } /** * Write value in php session and close it * * @param string $key session attribute * @param mixed $value session value to save */ public static function writeSessionClose($key, $value): void { session_start(); $_SESSION[$key] = $value; session_write_close(); } /** * @param mixed $registerVar */ public function unregisterVar($registerVar): void { unset($_SESSION[$registerVar]); } /** * @param mixed $registerVar */ public function registerVar($registerVar): void { if (! isset($_SESSION[$registerVar])) { $_SESSION[$registerVar] = ${$registerVar}; } } /** * Check user session status * * @param string $sessionId Session id to check * @param CentreonDB $db * @throws PDOException * @return bool */ public static function checkSession($sessionId, CentreonDB $db): bool { if (empty($sessionId)) { return false; } $prepare = $db->prepare('SELECT `session_id` FROM session WHERE `session_id` = :session_id'); $prepare->bindValue(':session_id', $sessionId, PDO::PARAM_STR); $prepare->execute(); return $prepare->fetch(PDO::FETCH_ASSOC) !== false; } /** * Update session to keep alive * * @param CentreonDB $pearDB * * @throws PDOException * @return bool If the session is updated or not */ public function updateSession($pearDB): bool { $sessionUpdated = false; session_start(); $sessionId = session_id(); if (self::checkSession($sessionId, $pearDB)) { try { $sessionStatement = $pearDB->prepare( 'UPDATE `session` SET `last_reload` = :lastReload, `ip_address` = :ipAddress WHERE `session_id` = :sessionId' ); $sessionStatement->bindValue(':lastReload', time(), PDO::PARAM_INT); $sessionStatement->bindValue(':ipAddress', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); $sessionStatement->bindValue(':sessionId', $sessionId, PDO::PARAM_STR); $sessionStatement->execute(); $sessionExpire = 120; $optionResult = $pearDB->query( "SELECT `value` FROM `options` WHERE `key` = 'session_expire'" ); if (($option = $optionResult->fetch()) && ! empty($option['value'])) { $sessionExpire = (int) $option['value']; } $expirationDate = (new Datetime()) ->add(new DateInterval('PT' . $sessionExpire . 'M')) ->getTimestamp(); $tokenStatement = $pearDB->prepare( 'UPDATE `security_token` SET `expiration_date` = :expirationDate WHERE `token` = :sessionId' ); $tokenStatement->bindValue(':expirationDate', $expirationDate, PDO::PARAM_INT); $tokenStatement->bindValue(':sessionId', $sessionId, PDO::PARAM_STR); $tokenStatement->execute(); $sessionUpdated = true; // return true if session is properly updated } catch (PDOException $e) { $sessionUpdated = false; // return false if session is not properly updated in database } } else { $sessionUpdated = false; // return false if session does not exist } return $sessionUpdated; } /** * @param string $sessionId * @param CentreonDB $pearDB * * @throws PDOException * @return int|string */ public static function getUser($sessionId, $pearDB) { $sessionId = str_replace(['_', '%'], ['', ''], $sessionId); $DBRESULT = $pearDB->query( "SELECT user_id FROM session WHERE `session_id` = '" . htmlentities(trim($sessionId), ENT_QUOTES, 'UTF-8') . "'" ); $row = $DBRESULT->fetchRow(); if (! $row) { return 0; } return $row['user_id']; } public static function resolveSessionCookie(): string { // Build session cookie name/value robustly to support subdomains (e.g., PHPSESSID_{SITE}) $sessionName = session_name(); if ($sessionName === '' || $sessionName === false) { $iniSessionName = ini_get('session.name'); $sessionName = is_string($iniSessionName) && $iniSessionName !== '' ? $iniSessionName : 'PHPSESSID'; } $sessionId = session_id(); if ($sessionId === '' || $sessionId === false) { // Fallback: try cookie matching the current session name if (isset($_COOKIE[$sessionName]) && is_string($_COOKIE[$sessionName])) { $sessionId = $_COOKIE[$sessionName]; } else { // Last resort: find any cookie starting with PHPSESSID (e.g., PHPSESSID_{SITE}) foreach ($_COOKIE as $cookieKey => $cookieVal) { if (is_string($cookieKey) && str_starts_with($cookieKey, 'PHPSESSID') && is_string($cookieVal)) { $sessionName = $cookieKey; $sessionId = $cookieVal; break; } } } } if (empty($sessionId)) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Unable to resolve session cookie: no valid session ID found' ); throw new RuntimeException('Unable to resolve session cookie: no valid session ID found'); } return $sessionName . '=' . $sessionId; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonUser.class.php
centreon/www/class/centreonUser.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/centreonACL.class.php'; require_once __DIR__ . '/centreonLog.class.php'; require_once __DIR__ . '/centreonAuth.class.php'; /** * Class * * @class CentreonUser */ class CentreonUser { /** @var int|string|null */ public $user_id; /** @var string|null */ public $name; /** @var string|null */ public $alias; /** @var string|null */ public $passwd; /** @var string|null */ public $email; /** @var string|null */ public $lang; /** @var string */ public $charset = 'UTF-8'; /** @var int */ public $version = 3; /** @var int|string|null */ public $admin; /** @var */ public $limit; /** @var */ public $num; /** @var mixed|null */ public $gmt; /** @var bool|null */ public $is_admin = null; /** @var */ public $groupList; /** @var */ public $groupListStr; /** @var CentreonACL */ public $access; /** @var CentreonUserLog */ public $log; /** @var int|mixed */ public $default_page; /** @var string|null */ public $theme; // User LCA // Array with elements ID for loop test /** @var array|null */ public $lcaTopo; // String with elements ID separated by commas for DB requests /** @var string|null */ public $lcaTStr; /** @var string */ public $authType; /** @var string|null */ protected $token; /** @var bool */ protected $restApi; /** @var bool */ protected $restApiRt; /** @var bool */ private $showDeprecatedPages; /** @var int */ private $currentPage; private bool $showDeprecatedCustomViews; /** * CentreonUser constructor * * @param array $user * * @throws PDOException */ public function __construct($user = []) { global $pearDB; $this->user_id = $user['contact_id'] ?? null; $this->name = isset($user['contact_name']) ? html_entity_decode($user['contact_name'], ENT_QUOTES, 'UTF-8') : null; $this->alias = isset($user['contact_alias']) ? html_entity_decode($user['contact_alias'], ENT_QUOTES, 'UTF-8') : null; $this->email = isset($user['contact_email']) ? html_entity_decode($user['contact_email'], ENT_QUOTES, 'UTF-8') : null; $this->lang = $user['contact_lang'] ?? null; $this->passwd = $user['contact_passwd'] ?? null; $this->token = $user['contact_autologin_key'] ?? null; $this->admin = $user['contact_admin'] ?? null; $this->default_page = $user['default_page'] ?? CentreonAuth::DEFAULT_PAGE; $this->gmt = $user['contact_location'] ?? null; $this->showDeprecatedPages = (bool) ($user['show_deprecated_pages'] ?? false); $this->showDeprecatedCustomViews = (bool) ($user['show_deprecated_custom_views'] ?? false); $this->theme = $user['contact_theme'] ?? 'light'; // Initiate ACL $this->access = new CentreonACL($this->user_id, $this->admin); $this->lcaTopo = $this->access->topology; $this->lcaTStr = $this->access->topologyStr; // Initiate Log Class $this->log = new CentreonUserLog($this->user_id, $pearDB); /** * Init rest api auth */ $this->restApi = isset($user['reach_api']) && $user['reach_api'] == 1; $this->restApiRt = isset($user['reach_api_rt']) && $user['reach_api_rt'] == 1; // Init authentication type, could by local, openid, web-sso, saml $this->authType = $user['auth_type'] ?? 'unknown'; } /** * @param $div_name * * @return int|mixed */ public function showDiv($div_name = null) { global $pearDB; if (! isset($div_name)) { return 0; } return $_SESSION['_Div_' . $div_name] ?? 1; } /** * @param CentreonDB $pearDB * * @throws PDOException * @return array */ public function getAllTopology($pearDB) { $DBRESULT = $pearDB->query('SELECT topology_page FROM topology WHERE topology_page IS NOT NULL'); while ($topo = $DBRESULT->fetch()) { if (isset($topo['topology_page'])) { $lcaTopo[$topo['topology_page']] = 1; } } unset($topo); $DBRESULT->closeCursor(); return $lcaTopo; } /** * Check if user is admin or had ACL * * @param string $sid * @param CentreonDB $pearDB * * @throws PDOException */ public function checkUserStatus($sid, $pearDB): void { $query1 = 'SELECT contact_admin, contact_id FROM session, contact ' . 'WHERE session.session_id = :session_id' . " AND contact.contact_id = session.user_id AND contact.contact_register = '1'"; $statement = $pearDB->prepare($query1); $statement->bindValue(':session_id', $sid); $statement->execute(); $admin = $statement->fetch(PDO::FETCH_ASSOC); $statement->closeCursor(); $query2 = 'SELECT count(*) FROM `acl_group_contacts_relations` ' . 'WHERE contact_contact_id = :contact_id'; $statement = $pearDB->prepare($query2); $statement->bindValue(':contact_id', (int) $admin['contact_id'], PDO::PARAM_INT); $statement->execute(); $admin2 = $statement->fetch(PDO::FETCH_ASSOC); $statement->closeCursor(); $this->is_admin = 0; if ($admin['contact_admin']) { unset($admin); $this->is_admin = 1; } elseif (! $admin2['count(*)']) { unset($admin2); $this->is_admin = 1; } } // Getters /** * @return int|mixed|string|null */ public function get_id() { return $this->user_id; } /** * @return string|null */ public function get_name() { return $this->name; } /** * @return string|null */ public function get_email() { return $this->email; } /** * @return string|null */ public function get_alias() { return $this->alias; } /** * @return int */ public function get_version() { return $this->version; } /** * @return string */ public function get_lang(): string { $lang = $this->lang; // Get locale from browser if ($lang === 'browser') { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $lang = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); } // check that the variable value end with .UTF-8 or add it $lang = (str_contains($lang, '.UTF-8')) ?: $lang . '.UTF-8'; } return $lang; } /** * @return mixed|string|null */ public function get_passwd() { return $this->passwd; } /** * @return int|string|null */ public function get_admin() { return $this->admin; } /** * @return bool|null */ public function is_admin() { return $this->is_admin; } /** * @return bool */ public function doesShowDeprecatedPages() { return $this->showDeprecatedPages; } public function doesShowDeprecatedCustomViews() { return $this->showDeprecatedCustomViews; } // Setters /** * @param $id * * @return void */ public function set_id($id): void { $this->user_id = $id; } /** * @param string $name * * @return void */ public function set_name($name): void { $this->name = $name; } /** * @param string $email * * @return void */ public function set_email($email): void { $this->email = $email; } /** * @param string $lang * * @return void */ public function set_lang($lang): void { $this->lang = $lang; } /** * @param string $alias * * @return void */ public function set_alias($alias): void { $this->alias = $alias; } /** * @param string $version * * @return void */ public function set_version($version): void { $this->version = $version; } public function setPasswd(string $passwd): void { $this->passwd = $passwd; } public function setShowDeprecatedPages(bool $showDeprecatedPages): void { $this->showDeprecatedPages = $showDeprecatedPages; } public function setShowDeprecatedCustomViews(bool $showDeprecatedCustomViews): void { $this->showDeprecatedCustomViews = $showDeprecatedCustomViews; } // Methods /** * @return mixed|null */ public function getMyGMT() { return $this->gmt; } /** * @param CentreonDB $db * * @throws PDOException * @return array|mixed */ public function getUserList($db) { static $userList; if (! isset($userList)) { $userList = []; $res = $db->query( "SELECT contact_id, contact_name FROM contact WHERE contact_register = '1' AND contact_activate = '1' ORDER BY contact_name" ); while ($row = $res->fetchRow()) { $userList[$row['contact_id']] = $row['contact_name']; } } return $userList; } /** * Get Contact Name * * @param CentreonDB $db * @param int $userId * * @throws PDOException * @return string */ public function getContactName($db, $userId) { static $userNames; if (! isset($userNames)) { $userNames = []; $res = $db->query('SELECT contact_name, contact_id FROM contact'); while ($row = $res->fetch()) { $userNames[$row['contact_id']] = $row['contact_name']; } } return $userNames[$userId] ?? null; } /** * Get Contact Parameters * * @param CentreonDB $db * @param array $parameters * * @throws PDOException * @return array */ public function getContactParameters($db, $parameters = []) { $values = []; $queryParameters = ''; if (is_array($parameters) && count($parameters)) { $queryParameters = 'AND cp_key IN ("'; $queryParameters .= implode('","', $parameters); $queryParameters .= '") '; } $query = 'SELECT cp_key, cp_value ' . 'FROM contact_param ' . 'WHERE cp_contact_id = ' . $this->user_id . ' ' . $queryParameters; $res = $db->query($query); while ($row = $res->fetch()) { $values[$row['cp_key']] = $row['cp_value']; } return $values; } /** * Set Contact Parameters * * @param CentreonDB $db * @param array $parameters * * @throws PDOException * @return null|void */ public function setContactParameters($db, $parameters = []) { if (! count($parameters)) { return null; } $queryValues = []; $keys = array_keys($parameters); $deleteQuery = 'DELETE FROM contact_param WHERE cp_contact_id = :cp_contact_id AND cp_key IN( '; $queryValues[':cp_contact_id'] = $this->user_id; $queryKey = ''; foreach ($keys as $key) { $queryKey .= ' :cp_key' . $key . ','; $queryValues[':cp_key' . $key] = $key; } $queryKey = rtrim($queryKey, ','); $deleteQuery .= $queryKey . ' )'; $stmt = $db->prepare($deleteQuery); $stmt->execute($queryValues); $insertQuery = 'INSERT INTO contact_param (cp_key, cp_value, cp_contact_id) VALUES ' . '(:cp_key, :cp_value, :cp_contact_id)'; $sth = $db->prepare($insertQuery); foreach ($parameters as $key => $value) { $sth->bindParam(':cp_key', $key, PDO::PARAM_STR); $sth->bindParam(':cp_value', $value, PDO::PARAM_STR); $sth->bindParam(':cp_contact_id', $this->user_id, PDO::PARAM_INT); $sth->execute(); } } /** * Get current Page * * @return int */ public function getCurrentPage() { return $this->currentPage; } /** * Set current page * * @param int $currentPage * @return void */ public function setCurrentPage($currentPage): void { $this->currentPage = $currentPage; } /** * Get theme * * @return string */ public function getTheme() { return $this->theme; } /** * Set theme * * @param string $theme * @return void */ public function setTheme($theme): void { $this->theme = $theme; } /** * Get token * * @return string */ public function getToken() { return $this->token; } /** * Set token * * @param string $token * @return void */ public function setToken($token): void { $this->token = $token; } /** * If the user has access to Rest API Configuration * * @return bool */ public function hasAccessRestApiConfiguration() { return $this->restApi; } /** * If the user has access to Rest API Realtime * * @return bool */ public function hasAccessRestApiRealtime() { return $this->restApiRt; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonFileManager.php
centreon/www/class/centreonFileManager.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Pimple\Container; /** * Class * * @class CentreonFileManager */ class CentreonFileManager implements iFileManager { /** @var mixed */ protected $rawFile; /** @var Container */ protected $dependencyInjector; /** @var string */ protected $comment; /** @var mixed */ protected $tmpFile; /** @var */ protected $mediaPath; /** @var string */ protected $destinationPath; /** @var mixed */ protected $destinationDir; /** @var mixed */ protected $originalFile; /** @var mixed */ protected $fileName; /** @var mixed */ protected $size; /** @var array|string */ protected $extension; /** @var string */ protected $newFile; /** @var string */ protected $completePath; /** @var array */ protected $legalExtensions = []; /** @var int */ protected $legalSize = 500000; /** * CentreonFileManager constructor * * @param Container $dependencyInjector * @param $rawFile * @param $mediaPath * @param $destinationDir * @param string $comment */ public function __construct( Container $dependencyInjector, $rawFile, $mediaPath, $destinationDir, $comment = '', ) { $this->dependencyInjector = $dependencyInjector; $this->mediaPath = $mediaPath; $this->comment = $comment; $this->rawFile = $rawFile['filename']; $this->destinationDir = $this->secureName($destinationDir); $this->destinationPath = $this->mediaPath . $this->destinationDir; $this->dirExist($this->destinationPath); $this->originalFile = $this->rawFile['name']; $this->tmpFile = $this->rawFile['tmp_name']; $this->size = $this->rawFile['size']; $this->extension = pathinfo($this->originalFile, PATHINFO_EXTENSION); $this->fileName = $this->secureName(basename($this->originalFile, '.' . $this->extension)); $this->newFile = $this->fileName . '.' . $this->extension; $this->completePath = $this->destinationPath . '/' . $this->newFile; } /** * @return array|bool|void */ public function upload() { if ($this->securityCheck()) { $this->moveFile(); return true; } return false; } /** * @return bool */ protected function securityCheck() { return ! ( ! $this->validFile() || ! $this->validSize() || ! $this->secureExtension() || $this->fileExist() ); } /** * @param $text * * @return array|string|string[]|null */ protected function secureName($text) { $utf8 = ['/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', '/[“”«»„"’‘‹›‚]/u' => '', '/ /' => '', '/\//' => '', '/\'/' => '']; return preg_replace(array_keys($utf8), array_values($utf8), $text); } /** * @return bool */ protected function secureExtension() { return (bool) (in_array(strtolower($this->extension), $this->legalExtensions)); } /** * @return bool */ protected function validFile() { return ! (empty($this->tmpFile) || $this->size == 0); } /** * @return bool */ protected function validSize() { return (bool) ($this->size < $this->legalSize); } /** * @return bool */ protected function fileExist() { return (bool) (file_exists($this->completePath)); } /** * @param mixed $dir * @return void */ protected function dirExist($dir) { if (! is_dir($dir)) { @mkdir($dir); } } /** * @return void */ protected function moveFile() { move_uploaded_file($this->tmpFile, $this->completePath); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonTimeperiodRenderer.class.php
centreon/www/class/centreonTimeperiodRenderer.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonTimeperiodRenderer * @description Used for rendering time periods in order to make them more human-readable */ class CentreonTimeperiodRenderer { /** @var CentreonDB|null */ protected $db; /** @var int */ protected $tpid; /** @var mixed */ protected $tpname; /** @var mixed */ protected $tpalias; /** @var array[] */ protected $timerange; /** @var array[] */ protected $timeline; /** @var array */ protected $includedTp = []; /** @var array */ protected $excludedTp = []; /** @var array */ protected $exceptionList = []; /** * CentreonTimeperiodRenderer constructor * * @param CentreonDB $db * @param int $tpid * @param string $inex * * @throws PDOException */ public function __construct($db, $tpid, $inex) { $dayTab = ['tp_sunday' => [], 'tp_monday' => [], 'tp_tuesday' => [], 'tp_wednesday' => [], 'tp_thursday' => [], 'tp_friday' => [], 'tp_saturday' => []]; $this->timerange = $dayTab; $this->timeline = $dayTab; $this->db = $db; $this->tpid = $tpid; $query = "SELECT tp_name, tp_alias, tp_monday, tp_tuesday, tp_wednesday, tp_thursday, tp_friday, tp_saturday, tp_sunday FROM timeperiod WHERE tp_id = '" . $tpid . "'"; $res = $this->db->query($query); if (! $res->rowCount()) { throw new Exception('Timeperiod not found'); } $row = $res->fetchRow(); $this->tpname = $row['tp_name']; $this->tpalias = $row['tp_alias']; foreach ($this->timerange as $key => $val) { if ($row[$key]) { $tmparr = explode(',', $row[$key]); foreach ($tmparr as $tr) { $tmptr = $this->getTimeRange($this->tpid, $this->tpname, $inex, $tr); $this->timerange[$key][] = $tmptr; } } } $this->updateInclusions(); $this->updateExclusions(); $this->orderTimeRanges(); $this->db = null; } /** * Set time bars * * @return void */ public function timeBars(): void { $coef = 4; foreach ($this->timerange as $day => $ranges) { $timeindex = 0; $timeline[0] = ['start' => 0, 'style' => 'unset', 'end' => 0, 'size' => 0, 'Text' => 'init', 'From' => '', 'Textual' => '']; if (isset($ranges[0])) { $last['in'] = ''; $last['nb'] = 0; for ($i = 0; $i <= 1440; $i++) { $actual['in'] = ''; $actual['nb'] = 0; foreach ($ranges as $k => $r) { if ($r['tstart'] <= $i && $i <= $r['tend']) { $actual['in'] .= $actual['in'] != '' ? ',' . $k : $k; $actual['nb']++; } } if ($actual['in'] != $last['in'] || $i == 1440) { if ($i == 0) { $last = $actual; } $timeline[$timeindex]['end'] = $i; $timeline[$timeindex]['size'] = round(($i - $timeline[$timeindex]['start']) / $coef); switch ($last['nb']) { case 0: $ts = $timeline[$timeindex]['start']; $timeline[$timeindex]['style'] = 'unset'; $timeline[$timeindex]['Textual'] = sprintf('%02d', intval($ts / 60)) . ':' . sprintf('%02d', $ts % 60) . '-' . sprintf('%02d', intval($i / 60)) . ':' . sprintf('%02d', $i % 60); $timeline[$timeindex]['From'] = 'No timeperiod covering ' . $timeline[$timeindex]['Textual']; break; default: $idlist = explode(',', $last['in']); foreach ($idlist as $v) { if ($ranges[$v]['inex'] == 0) { $timeline[$timeindex]['style'] = 'excluded'; } $txt = $ranges[$v]['textual']; $inex = $ranges[$v]['inex'] ? 'include' : 'exclude'; $from = $ranges[$v]['fromTpName'] . ' ' . $inex . ' ' . $txt; $timeline[$timeindex]['From'] .= $timeline[$timeindex]['From'] != '' ? ',' . $from : $from; $timeline[$timeindex]['Textual'] .= $timeline[$timeindex]['Textual'] != '' ? ',' . $txt : $txt; } } switch ($last['nb']) { case 0: break; case 1: $timeline[$timeindex]['style'] = ($ranges[$last['in']]['inex'] == 1) ? 'included' : 'excluded'; break; default: $timeline[$timeindex]['style'] = 'warning'; $timeline[$timeindex]['From'] = 'OVERLAPS: ' . $timeline[$timeindex]['From']; break; } if ($i < 1440) { $timeline[++$timeindex] = ['start' => $i, 'style' => 'unset', 'end' => 0, 'size' => 0, 'Text' => 'New in loop', 'From' => '', 'Textual' => '']; } } $last = $actual; } } $endtime = $timeline[$timeindex]['end']; if ($endtime < 1440) { $textual = sprintf('%02d', intval($endtime / 60)) . ':' . sprintf('%02d', $endtime % 60) . '-24:00'; $timeline[$timeindex] = ['start' => $endtime, 'style' => 'unset', 'end' => 1440, 'size' => (1440 - $endtime) / $coef, 'Text' => 'No Timeperiod covering ' . $textual, 'From' => 'No Timeperiod covering ' . $textual, 'Textual' => $textual]; } $this->timeline[$day] = $timeline; unset($timeline); } } /** * Get Time Period Name * * @return string */ public function getName() { return $this->tpname; } /** * Get Time Period Alias * * @return string */ public function getAlias() { return $this->tpalias; } /** * Get Timeline * * @return array */ public function getTimeline() { return $this->timeline; } /** * Get Exception List * * @return array */ public function getExceptionList() { return $this->exceptionList; } /** * @param string $field * * @return array */ public static function getDefaultValuesParameters($field) { $parameters = []; $parameters['currentObject']['table'] = 'timeperiod'; $parameters['currentObject']['id'] = 'tp_id'; $parameters['currentObject']['name'] = 'tp_name'; $parameters['currentObject']['comparator'] = 'tp_id'; switch ($field) { case 'tp_include': $parameters['type'] = 'relation'; $parameters['externalObject']['table'] = 'timeperiod'; $parameters['externalObject']['id'] = 'tp_id'; $parameters['externalObject']['name'] = 'tp_name'; $parameters['externalObject']['comparator'] = 'tp_id'; $parameters['relationObject']['table'] = 'timeperiod_include_relations'; $parameters['relationObject']['field'] = 'timeperiod_include_id'; $parameters['relationObject']['comparator'] = 'timeperiod_id'; break; case 'tp_exclude': $parameters['type'] = 'relation'; $parameters['externalObject']['table'] = 'timeperiod'; $parameters['externalObject']['id'] = 'tp_id'; $parameters['externalObject']['name'] = 'tp_name'; $parameters['externalObject']['comparator'] = 'tp_id'; $parameters['relationObject']['table'] = 'timeperiod_exclude_relations'; $parameters['relationObject']['field'] = 'timeperiod_exclude_id'; $parameters['relationObject']['comparator'] = 'timeperiod_id'; break; } return $parameters; } /** * Compare * * @param array $a * @param array $b * @return int */ protected function startCompare($a, $b) { if ($a['tstart'] == $b['tstart']) { return 0; } if ($a['tstart'] < $b['tstart']) { return -1; } return 1; } /** * Order Time Ranges * * @return void */ protected function orderTimeRanges() { foreach ($this->timerange as $key => $val) { usort($val, ['CentreonTimeperiodRenderer', 'startCompare']); $this->timerange[$key] = $val; } } /** * Update Time Range * * @param array $inexTr * @return void */ protected function updateTimeRange($inexTr) { foreach ($inexTr as $key => $val) { if (isset($val[0])) { foreach ($val as $tp) { $this->timerange[$key][] = $tp; } } } } /** * Update Inclusions * * @throws PDOException * @return void */ protected function updateInclusions() { $query = "SELECT timeperiod_include_id FROM timeperiod_include_relations WHERE timeperiod_id= '" . $this->tpid . "'"; $res = $this->db->query($query); while ($row = $res->fetchRow()) { $inctp = new CentreonTimeperiodRenderer($this->db, $row['timeperiod_include_id'], 1); $this->updateTimeRange($inctp->timerange); foreach ($inctp->exceptionList as $key => $val) { $this->exceptionList[] = $val; } } } /** * Update Exclusions * * @throws PDOException * @return void */ protected function updateExclusions() { $query = "SELECT * FROM timeperiod_exceptions WHERE timeperiod_id='" . $this->tpid . "'"; $DBRESULT = $this->db->query($query); while ($row = $DBRESULT->fetchRow()) { $excep = $this->getException($row['timeperiod_id'], $this->tpname, $row['days'], $row['timerange']); $this->exceptionList[] = $excep; } $query = "SELECT timeperiod_exclude_id FROM timeperiod_exclude_relations WHERE timeperiod_id='" . $this->tpid . "'"; $DBRESULT = $this->db->query($query); while ($row = $DBRESULT->fetchRow()) { $extp = new CentreonTimePeriodRenderer($this->db, $row['timeperiod_exclude_id'], 0); $this->updateTimeRange($extp->timerange); } } /** * Get time range array * * @param int $id * @param string $name * @param string $in * @param string $range * @return array */ protected function getTimeRange($id, $name, $in, $range) { $timeRange = []; $timeRange['fromTpId'] = $id; $timeRange['fromTpName'] = $name; $timeRange['inex'] = $in; $timeRange['textual'] = $range; if (! preg_match('/([0-9]+):([0-9]+)-([0-9]+)+:([0-9]+)/', $range, $trange)) { return null; } if ($id < 1) { return null; } $timeRange['tstart'] = ($trange[1] * 60) + $trange[2]; $timeRange['tend'] = ($trange[3] * 60) + $trange[4]; return $timeRange; } /** * Get Exception * * @param int $id * @param string $name * @param string $day * @param string $range * @return array */ protected function getException($id, $name, $day, $range) { return ['fromTpId' => $id, 'fromTpName' => $name, 'day' => $day, 'range' => $range]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/CentreonLDAPAdmin.class.php
centreon/www/class/CentreonLDAPAdmin.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonLdapAdmin */ class CentreonLdapAdmin { /** @var CentreonLog */ public $centreonLog; /** @var CentreonDB */ private $db; /** * CentreonLdapAdmin constructor * * @param CentreonDB $pearDB The database connection */ public function __construct($pearDB) { $this->db = $pearDB; $this->centreonLog = new CentreonLog(); } /** * Get ldap parameters * * @return array * @todo sanitize the inputs to avoid XSS */ public function getLdapParameters() { return [ 'ldap_store_password', 'ldap_auto_import', 'ldap_connection_timeout', 'ldap_search_limit', 'ldap_search_timeout', 'ldap_contact_tmpl', 'ldap_default_cg', 'ldap_srv_dns', 'ldap_dns_use_ssl', 'ldap_dns_use_tls', 'ldap_dns_use_domain', 'bind_dn', 'bind_pass', 'protocol_version', 'ldap_template', 'user_base_search', 'group_base_search', 'user_filter', 'alias', 'user_group', 'user_name', 'user_firstname', 'user_lastname', 'user_email', 'user_pager', 'group_filter', 'group_name', 'group_member', 'ldap_auto_sync', // is auto synchronization enabled 'ldap_sync_interval', ]; } /** * Set ldap options * * 'ldap_auth_enable', 'ldap_auto_import', 'ldap_srv_dns', 'ldap_search_limit', 'ldap_search_timeout' * and 'ldap_dns_use_ssl', 'ldap_dns_use_tls', 'ldap_dns_use_domain' if ldap_srv_dns = 1 * * @param array<string, mixed> $options The list of options * @param int $arId * * @throws PDOException * @return int resource auth id */ public function setGeneralOptions(array $options, $arId = 0): int { $isUpdate = ((int) $arId !== 0); $gopt = $this->getGeneralOptions($arId); if (isset($gopt['bind_pass']) && $gopt['bind_pass'] === CentreonAuth::PWS_OCCULTATION && $isUpdate === false) { unset($gopt['bind_pass']); } if ( ! count($gopt) && isset($options['ar_name'], $options['ar_description']) ) { if (! isset($options['ar_sync_base_date'])) { $options['ar_sync_base_date'] = time(); $this->centreonLog->insertLog( 3, "LDAP PARAM - Warning the reference date wasn\'t set for LDAP : " . $options['ar_name'] ); } $statement = $this->db->prepare( "INSERT INTO auth_ressource (ar_name, ar_description, ar_type, ar_enable, ar_sync_base_date) VALUES (:name, :description, 'ldap', :is_enabled, :sync_date)" ); $statement->bindValue(':name', $options['ar_name'], PDO::PARAM_STR); $statement->bindValue(':description', $options['ar_description'], PDO::PARAM_STR); $statement->bindValue(':is_enabled', $options['ldap_auth_enable']['ldap_auth_enable'], PDO::PARAM_STR); $statement->bindValue(':sync_date', $options['ar_sync_base_date'], PDO::PARAM_INT); $statement->execute(); $statement = $this->db->prepare( 'SELECT MAX(ar_id) as last_id FROM auth_ressource WHERE ar_name = :name' ); $statement->bindValue(':name', $options['ar_name'], PDO::PARAM_STR); $statement->execute(); $row = $statement->fetch(); $arId = $row['last_id']; unset($statement); } else { $statement = $this->db->prepare( 'UPDATE auth_ressource SET ar_name = :name, ar_description = :description, ar_enable = :is_enabled, ar_sync_base_date = :sync_date WHERE ar_id = :id' ); $statement->bindValue(':name', $options['ar_name'], PDO::PARAM_STR); $statement->bindValue(':description', $options['ar_description'], PDO::PARAM_STR); $statement->bindValue(':is_enabled', $options['ldap_auth_enable']['ldap_auth_enable'], PDO::PARAM_STR); $statement->bindValue(':sync_date', $options['ar_sync_base_date'], PDO::PARAM_INT); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); } $knownParameters = $this->getLdapParameters(); if ( isset($options['bind_pass']) && $options['bind_pass'] === CentreonAuth::PWS_OCCULTATION && $isUpdate === true ) { unset($options['bind_pass']); } foreach ($options as $key => $value) { if (! in_array($key, $knownParameters)) { continue; } if (is_array($value)) { // radio buttons $value = $value[$key]; } // Make all attributes lowercase since ldap_get_entries // converts them to lowercase. if ( in_array( $key, ['alias', 'user_name', 'user_email', 'user_pager', 'user_firstname', 'user_lastname', 'group_name', 'group_member'] ) ) { $value = strtolower($value); } if (isset($gopt[$key])) { $statement = $this->db->prepare( 'UPDATE `auth_ressource_info` SET `ari_value` = :value WHERE `ari_name` = :name AND `ar_id` = :id' ); } else { $statement = $this->db->prepare( 'INSERT INTO `auth_ressource_info` (`ar_id`, `ari_name`, `ari_value`) VALUES (:id, :name, :value)' ); } $statement->bindValue(':value', $value, PDO::PARAM_STR); $statement->bindValue(':name', $key, PDO::PARAM_STR); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); } $this->updateLdapServers($arId); // Remove contact passwords if store password option is disabled $this->manageContactPasswords($arId); return $arId; } /** * Get the general options * * @param int $arId * * @throws PDOException * @return array */ public function getGeneralOptions($arId) { $gopt = []; $statement = $this->db->prepare( "SELECT `ari_name`, `ari_value` FROM `auth_ressource_info` WHERE `ari_name` <> 'bind_pass' AND ar_id = :id" ); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch()) { $gopt[$row['ari_name']] = $row['ari_value']; } $gopt['bind_pass'] = CentreonAuth::PWS_OCCULTATION; return $gopt; } /** * Add a Ldap server * (Possibility of a dead code) * * @param int $arId * @param array<string, mixed> $params * * @throws PDOException * @return void */ public function addServer($arId, $params = []): void { $statement = $this->db->prepare( 'INSERT INTO auth_ressource_host (auth_ressource_id, host_address, host_port, use_ssl, use_tls, host_order) VALUES (:id, :address, :port, :ssl, :tls, :order)' ); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->bindValue(':address', $params['hostname'], PDO::PARAM_STR); $statement->bindValue(':port', $params['port'], PDO::PARAM_INT); $statement->bindValue(':ssl', isset($params['use_ssl']) ? 1 : 0, PDO::PARAM_INT); $statement->bindValue(':tls', isset($params['use_tls']) ? 1 : 0, PDO::PARAM_INT); $statement->bindValue(':order', $params['order'], PDO::PARAM_INT); $statement->execute(); } /** * Modify a Ldap server * * @param int $arId * @param array<string, mixed> $params * * @throws PDOException * @return void */ public function modifyServer($arId, $params = []): void { if (! isset($params['order']) || ! isset($params['id'])) { return; } $use_ssl = isset($params['use_ssl']) ? 1 : 0; $use_tls = isset($params['use_tls']) ? 1 : 0; $statement = $this->db->prepare( 'UPDATE auth_ressource_host SET host_address = :address, host_port = :port, host_order = :order, use_ssl = :ssl, use_tls = :tls WHERE ldap_host_id = :id AND auth_ressource_id = :resource_id' ); $statement->bindValue(':address', $params['hostname'], PDO::PARAM_STR); $statement->bindValue(':port', $params['port'], PDO::PARAM_INT); $statement->bindValue(':order', $params['order'], PDO::PARAM_INT); $statement->bindValue(':ssl', isset($params['use_ssl']) ? 1 : 0, PDO::PARAM_INT); $statement->bindValue(':tls', isset($params['use_tls']) ? 1 : 0, PDO::PARAM_INT); $statement->bindValue(':id', $params['id'], PDO::PARAM_INT); $statement->bindValue(':resource_id', $arId, PDO::PARAM_INT); $statement->execute(); } /** * Add a template * (Possibility of a dead code) * * @param array $options A hash table with options for connections and search in ldap * @return int|bool The id of connection, false on error */ public function addTemplate(array $options = []) { try { $this->db->query( "INSERT INTO auth_ressource (ar_type, ar_enable) VALUES ('ldap_tmpl', '0')" ); } catch (PDOException $e) { return false; } try { $dbResult = $this->db->query("SELECT MAX(ar_id) as id FROM auth_ressource WHERE ar_type = 'ldap_tmpl'"); $row = $dbResult->fetch(); } catch (PDOException $e) { return false; } $id = $row['id']; foreach ($options as $name => $value) { try { $statement = $this->db->prepare( 'INSERT INTO auth_ressource_info (ar_id, ari_name, ari_value) VALUES (:id, :name, :value)' ); $statement->bindValue(':id', $id, PDO::PARAM_INT); $statement->bindValue(':name', $name, PDO::PARAM_STR); $statement->bindValue(':value', $value, PDO::PARAM_STR); $statement->execute(); } catch (PDOException $e) { return false; } } return $id; } /** * Modify a template * (Possibility of a dead code) * * @param int $id The id of the template * @param array $options A hash table with options for connections and search in ldap * @return bool */ public function modifyTemplate($id, array $options = []): bool { // Load configuration $config = $this->getTemplate($id); foreach ($options as $key => $value) { try { if (isset($config[$key])) { $statement = $this->db->prepare( 'UPDATE auth_ressource_info SET ari_value = :value WHERE ar_id = :id AND ari_name = :name' ); } else { $statement = $this->db->prepare( 'INSERT INTO auth_ressource_info (ar_id, ari_name, ari_value) VALUES (:id, :name, :value)' ); } $statement->bindValue(':value', $value, PDO::PARAM_STR); $statement->bindValue(':name', $key, PDO::PARAM_STR); $statement->bindValue(':id', $id, PDO::PARAM_INT); $statement->execute(); } catch (PDOException $e) { return false; } } return true; } /** * Get the template information * * @param int $id The template id, if 0 get the template * * @throws PDOException * @return array<string, string> */ public function getTemplate($id = 0): array { if ($id == 0) { $res = $this->db->query( "SELECT ar_id FROM auth_ressource WHERE ar_type = 'ldap_tmpl'" ); if ($res->rowCount() == 0) { return []; } $row = $res->fetch(); $id = $row['ar_id']; } $statement = $this->db->prepare( 'SELECT ari_name, ari_value FROM auth_ressource_info WHERE ar_id = :id' ); $statement->bindValue(':id', $id, PDO::PARAM_INT); $statement->execute(); $list = []; while ($row = $statement->fetch()) { $list[$row['ari_name']] = $row['ari_value']; } return $list; } /** * Get the default template for Active Directory * * @return array */ public function getTemplateAd() { $infos = []; $infos['user_filter'] = '(&(samAccountName=%s)(objectClass=user)(samAccountType=805306368))'; $attr = []; $attr['alias'] = 'samaccountname'; $attr['email'] = 'mail'; $attr['name'] = 'name'; $attr['pager'] = 'mobile'; $attr['group'] = 'memberOf'; $attr['firstname'] = 'givenname'; $attr['lastname'] = 'sn'; $infos['user_attr'] = $attr; $infos['group_filter'] = '(&(samAccountName=%s)(objectClass=group)(samAccountType=268435456))'; $attr = []; $attr['group_name'] = 'samaccountname'; $attr['member'] = 'member'; $infos['group_attr'] = $attr; return $infos; } /** * Get the default template for ldap * * @return array */ public function getTemplateLdap() { $infos = []; $infos['user_filter'] = '(&(uid=%s)(objectClass=inetOrgPerson))'; $attr = []; $attr['alias'] = 'uid'; $attr['email'] = 'mail'; $attr['name'] = 'cn'; $attr['pager'] = 'mobile'; $attr['group'] = ''; $attr['firstname'] = 'givenname'; $attr['lastname'] = 'sn'; $infos['user_attr'] = $attr; $infos['group_filter'] = '(&(cn=%s)(objectClass=groupOfNames))'; $attr = []; $attr['group_name'] = 'cn'; $attr['member'] = 'member'; $infos['group_attr'] = $attr; return $infos; } /** * Get LDAP configuration list * * @param string $search * @param string|int|null $offset * @param string|int|null $limit * * @throws PDOException * @return array */ public function getLdapConfigurationList($search = '', $offset = null, $limit = null): array { $request = 'SELECT ar_id, ar_enable, ar_name, ar_description, ar_sync_base_date FROM auth_ressource '; $bindValues = []; if ($search !== '') { $request .= 'WHERE ar_name LIKE :search '; $bindValues[':search'] = [PDO::PARAM_STR => '%' . $search . '%']; } $request .= 'ORDER BY ar_name '; if (! is_null($offset) && ! is_null($limit)) { $request .= 'LIMIT :offset,:limit'; $bindValues[':offset'] = [PDO::PARAM_INT => $offset]; $bindValues[':limit'] = [PDO::PARAM_INT => $limit]; } $statement = $this->db->prepare($request); foreach ($bindValues as $bindKey => $bindValue) { $bindType = key($bindValue); $statement->bindValue($bindKey, $bindValue[$bindType], $bindType); } $statement->execute(); $configuration = []; while ($row = $statement->fetch()) { $configuration[] = $row; } return $configuration; } /** * Delete ldap configuration * * @param array $configList * * @throws PDOException * @return void */ public function deleteConfiguration(array $configList = []): void { if ($configList !== []) { $configIds = []; foreach ($configList as $configId) { if (is_numeric($configId)) { $configIds[] = (int) $configId; } } if ($configIds !== []) { $this->db->query( 'DELETE FROM auth_ressource WHERE ar_id IN (' . implode(',', $configIds) . ')' ); } } } /** * Enable/Disable ldap configuration * * @param int $status * @param array $configList * * @throws PDOException * @return void */ public function setStatus($status, $configList = []): void { if (count($configList)) { $configIds = []; foreach ($configList as $configId) { if (is_numeric($configId)) { $configIds[] = (int) $configId; } } if ($configIds !== []) { $statement = $this->db->prepare( 'UPDATE auth_ressource SET ar_enable = :is_enabled WHERE ar_id IN (' . implode(',', $configIds) . ')' ); $statement->bindValue(':is_enabled', $status, PDO::PARAM_STR); $statement->execute(); } } } /** * Get list of servers from resource id * * @param int $arId Auth resource id * * @throws PDOException * @return array<int, array<string, mixed>> */ public function getServersFromResId($arId): array { $statement = $this->db->prepare( 'SELECT host_address, host_port, use_ssl, use_tls FROM auth_ressource_host WHERE auth_ressource_id = :id ORDER BY host_order' ); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); $arr = []; $i = 0; while ($row = $statement->fetch()) { $arr[$i]['address_#index#'] = $row['host_address']; $arr[$i]['port_#index#'] = $row['host_port']; if ($row['use_ssl']) { $arr[$i]['ssl_#index#'] = $row['use_ssl']; } if ($row['use_tls']) { $arr[$i]['tls_#index#'] = $row['use_tls']; } $i++; } return $arr; } /** * Update Ldap servers * * @param int $arId auth resource id * * @throws PDOException */ protected function updateLdapServers($arId): void { $statement = $this->db->prepare( 'DELETE FROM auth_ressource_host WHERE auth_ressource_id = :id' ); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); if (isset($_REQUEST['address'])) { $subRequest = ''; $bindValues = []; $bindIndex = 0; foreach ($_REQUEST['address'] as $index => $address) { $bindValues[':address_' . $bindIndex] = [PDO::PARAM_STR => $address]; $bindValues[':port_' . $bindIndex] = [PDO::PARAM_INT => $_REQUEST['port'][$index]]; $bindValues[':tls_' . $bindIndex] = [PDO::PARAM_STR => isset($_REQUEST['tls'][$index]) ? '1' : '0']; $bindValues[':ssl_' . $bindIndex] = [PDO::PARAM_STR => isset($_REQUEST['ssl'][$index]) ? '1' : '0']; $bindValues[':order_' . $bindIndex] = [PDO::PARAM_INT => $bindIndex + 1]; if (! empty($subRequest)) { $subRequest .= ', '; } $subRequest .= '(:id, :address_' . $bindIndex . ', :port_' . $bindIndex . ', :ssl_' . $bindIndex . ', :tls_' . $bindIndex . ', :order_' . $bindIndex . ')'; $bindIndex++; } if (! empty($subRequest)) { $bindValues[':id'] = [PDO::PARAM_INT => (int) $arId]; $statement = $this->db->prepare( 'INSERT INTO auth_ressource_host (auth_ressource_id, host_address, host_port, use_ssl, use_tls, host_order) VALUES ' . $subRequest ); foreach ($bindValues as $bindKey => $bindValue) { $bindType = key($bindValue); $statement->bindValue($bindKey, $bindValue[$bindType], $bindType); } $statement->execute(); } } } /** * Remove contact passwords if password storage is disabled * * @param int $arId Auth resource id * * @throws PDOException * @return void */ private function manageContactPasswords($arId): void { $statement = $this->db->prepare( 'SELECT ari_value FROM auth_ressource_info WHERE ar_id = :id AND ari_name = "ldap_store_password"' ); $statement->bindValue(':id', $arId, PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch()) { if ($row['ari_value'] === '0') { $statement2 = $this->db->prepare('SELECT contact_id FROM contact WHERE ar_id = :arId'); $statement2->bindValue(':arId', $arId, PDO::PARAM_INT); $statement2->execute(); $ldapContactIdList = []; while ($row2 = $statement2->fetch()) { $ldapContactIdList[] = (int) $row2['contact_id']; } if ($ldapContactIdList !== []) { $contactIds = implode(', ', $ldapContactIdList); $this->db->query( "DELETE FROM contact_password WHERE contact_id IN ({$contactIds})" ); } } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDBInstance.class.php
centreon/www/class/centreonDBInstance.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ // file centreon.config.php may not exist in test environment $configFile = realpath(__DIR__ . '/../../config/centreon.config.php'); if ($configFile !== false) { include_once $configFile; } require_once realpath(__DIR__ . '/centreonDB.class.php'); /** * Class * * @class CentreonDBInstance */ class CentreonDBInstance { /** @var CentreonDBInstance */ private static $dbCentreonInstance; /** @var CentreonDBInstance */ private static $dbCentreonStorageInstance; /** @var CentreonDB */ private $instance; /** * CentreonDBInstance constructor. * * @param string $db * * @throws Exception */ private function __construct($db = 'centreon') { $this->instance = new CentreonDB($db); } /** * @return CentreonDB */ public function getInstance() { return $this->instance; } /** * @return CentreonDB */ public static function getDbCentreonInstance() { if (is_null(self::$dbCentreonInstance)) { self::$dbCentreonInstance = new CentreonDBInstance('centreon'); } return self::$dbCentreonInstance->getInstance(); } /** * @return CentreonDB */ public static function getDbCentreonStorageInstance() { if (is_null(self::$dbCentreonStorageInstance)) { self::$dbCentreonStorageInstance = new CentreonDBInstance('centstorage'); } return self::$dbCentreonStorageInstance->getInstance(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonAclLazy.class.php
centreon/www/class/centreonAclLazy.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Assert\AssertionFailedException; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Domain\Exception\RepositoryException; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection; use Core\Security\AccessGroup\Domain\Model\AccessGroup; class CentreonAclLazy { use SqlMultipleBindTrait; private AccessGroupCollection $accessGroups; private CentreonDB $database; /** * This class is specificaly dedicated to non admin users * * @param int $userId * @param CentreonDB $database */ public function __construct(private readonly int $userId) { $this->database = new CentreonDB(); $this->accessGroups = $this->findAccessGroups(); } /** * @return AccessGroupCollection */ public function getAccessGroups(): AccessGroupCollection { return $this->accessGroups; } /** * Find all access groups according to a contact. * * @param int $userId * * @throws RepositoryException * @return AccessGroupCollection */ private function findAccessGroups(): AccessGroupCollection { try { $accessGroups = new AccessGroupCollection(); /** * Retrieve all access group from contact * and contact groups linked to contact. */ $query = <<<'SQL' SELECT * FROM acl_groups WHERE acl_group_activate = '1' AND ( acl_group_id IN ( SELECT acl_group_id FROM acl_group_contacts_relations WHERE contact_contact_id = :userId ) OR acl_group_id IN ( SELECT acl_group_id FROM acl_group_contactgroups_relations agcr INNER JOIN contactgroup_contact_relation cgcr ON cgcr.contactgroup_cg_id = agcr.cg_cg_id WHERE cgcr.contact_contact_id = :userId ) ) SQL; $statement = $this->database->prepare($query); $statement->bindValue(':userId', $this->userId, PDO::PARAM_INT); if ($statement->execute()) { /** * @var array{ * acl_group_id: int|string, * acl_group_name: string, * acl_group_alias: string, * acl_group_activate: string, * acl_group_changed: int, * claim_value: string, * priority: int, * } $result */ while ($result = $statement->fetch(PDO::FETCH_ASSOC)) { $accessGroup = new AccessGroup((int) $result['acl_group_id'], $result['acl_group_name'], $result['acl_group_alias']); $accessGroup->setActivate($result['acl_group_activate'] === '1'); $accessGroup->setChanged($result['acl_group_changed'] === 1); $accessGroups->add($accessGroup->getId(), $accessGroup); } return $accessGroups; } return $accessGroups; } catch (PDOException|CollectionException|AssertionFailedException $e) { throw new RepositoryException( 'Error while getting access groups by contact id', ['contact_id' => $this->userId], $e ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonUtils.class.php
centreon/www/class/centreonUtils.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; /** * Class * * @class CentreonUtils */ class CentreonUtils { /** * Remove all <script> data */ public const ESCAPE_LEGACY_METHOD = 0; /** * Convert all html tags into HTML entities except links */ public const ESCAPE_ALL_EXCEPT_LINK = 1; /** * Convert all html tags into HTML entities */ public const ESCAPE_ALL = 2; /** * Remove all specific characters defined in the configuration > pollers > engine > admin, illegal characters field */ public const ESCAPE_ILLEGAL_CHARS = 4; /** * Defines all self-closing html tags allowed * * @var string[] */ public static $selfclosingHtmlTagsAllowed = ['br', 'hr']; /** * Converts Object into Array * * @param mixed $arrObjData * @param array $arrSkipIndices * * @return array|string */ public function objectIntoArray($arrObjData, $arrSkipIndices = []) { $arrData = []; if (is_object($arrObjData)) { $arrObjData = get_object_vars($arrObjData); } if (is_array($arrObjData)) { foreach ($arrObjData as $index => $value) { if (is_object($value) || is_array($value)) { $value = self::objectIntoArray($value, $arrSkipIndices); } if (in_array($index, $arrSkipIndices)) { continue; } $arrData[$index] = $value; } } if ($arrData === []) { $arrData = ''; } return $arrData; } /** * Condition Builder * Creates condition with WHERE or AND or OR * * @param string $query * @param string $condition * @param bool $or * @return string */ public static function conditionBuilder($query, $condition, $or = false) { if (preg_match('/ WHERE /', $query)) { if ($or === true) { $query .= ' OR '; } else { $query .= ' AND '; } } else { $query .= ' WHERE '; } $query .= $condition . ' '; return $query; } /** * Get datetime timestamp * * @param string $datetime * @throws Exception * @return int */ public static function getDateTimeTimestamp($datetime) { static $db; static $centreonGmt; $invalidString = 'Date format is not valid'; if (! isset($db)) { $db = new CentreonDB(); } if (! isset($centreonGmt)) { $centreonGmt = new CentreonGMT(); } $centreonGmt->getMyGMTFromSession(session_id(), $db); $datetime = trim($datetime); $res = explode(' ', $datetime); if (count($res) != 2) { throw new Exception($invalidString); } $res1 = explode('/', $res[0]); if (count($res1) != 3) { throw new Exception($invalidString); } $res2 = explode(':', $res[1]); if (count($res2) != 2) { throw new Exception($invalidString); } $timestamp = $centreonGmt->getUTCDateFromString($datetime); return $timestamp; } /** * Convert operand to Mysql format * * @param string $str * @return string */ public static function operandToMysqlFormat($str) { $result = ''; switch ($str) { case 'gt': $result = '>'; break; case 'lt': $result = '<'; break; case 'gte': $result = '>='; break; case 'lte': $result = '<='; break; case 'eq': $result = '='; break; case 'ne': $result = '!='; break; case 'like': $result = 'LIKE'; break; case 'notlike': $result = 'NOT LIKE'; break; case 'regex': $result = 'REGEXP'; break; case 'notregex': $result = 'NOT REGEXP'; break; default: $result = ''; break; } return $result; } /** * Merge with initial values * * @param HTML_QuickFormCustom $form * @param string $key * * @throws InvalidArgumentException * @return array */ public static function mergeWithInitialValues($form, $key) { $init = []; try { $initForm = $form->getElement('initialValues'); $initForm = HtmlAnalyzer::sanitizeAndRemoveTags($initForm->getValue()); $initialValues = unserialize($initForm, ['allowed_classes' => false]); if (! empty($initialValues) && isset($initialValues[$key])) { $init = $initialValues[$key]; } $result = array_merge((array) $form->getSubmitValue($key), $init); } catch (HTML_QuickForm_Error $e) { $result = (array) $form->getSubmitValue($key); } return $result; } /** * Transforms an array into a string with the following format * '1','2','3' or '' if the array is empty * * @param array $arr * @param bool $transformKey | string will be formed with keys when true, * otherwise values will be used * @return string */ public static function toStringWithQuotes($arr = [], $transformKey = true) { $string = ''; $first = true; foreach ($arr as $key => $value) { if ($first) { $first = false; } else { $string .= ', '; } $string .= $transformKey ? "'" . $key . "'" : "'" . $value . "'"; } if ($string == '') { $string = "''"; } return $string; } /** * @param string $currentVersion Original version * @param string $targetVersion Version to compare * @param string $delimiter Indicates the delimiter parameter for version * * @param int $depth Indicates the depth of comparison, if 0 it means "unlimited" */ public static function compareVersion($currentVersion, $targetVersion, $delimiter = '.', $depth = 0) { $currentVersionExplode = explode($delimiter, $currentVersion); $targetVersionExplode = explode($delimiter, $targetVersion); $isCurrentSuperior = false; $isCurrentEqual = false; $maxRecursion = $depth == 0 ? count($currentVersionExplode) : $depth; for ($i = 0; $i < $maxRecursion; $i++) { if ($currentVersionExplode[$i] > $targetVersionExplode[$i]) { $isCurrentSuperior = true; $isCurrentEqual = false; break; } if ($currentVersionExplode[$i] < $targetVersionExplode[$i]) { $isCurrentSuperior = false; $isCurrentEqual = false; break; } $isCurrentEqual = true; } if ($isCurrentSuperior) { return 1; } if (($isCurrentSuperior === false) && $isCurrentEqual) { return 2; } return 0; } /** * Converted a HTML string according to the selected method * * @param string $stringToEscape String to escape * @param int $escapeMethod Escape method (default: ESCAPE_LEGACY_METHOD) * * @return string|false Escaped string * @see CentreonUtils::ESCAPE_LEGACY_METHOD * @see CentreonUtils::ESCAPE_ALL_EXCEPT_LINK * @see CentreonUtils::ESCAPE_ALL * @see CentreonUtils::ESCAPE_ILLEGAL_CHARS */ public static function escapeSecure( $stringToEscape, $escapeMethod = self::ESCAPE_LEGACY_METHOD, ) { switch ($escapeMethod) { case self::ESCAPE_LEGACY_METHOD: // Remove script and input tags by default return preg_replace(["/<script.*?\/script>/si", "/<input[^>]+\>/si"], '', $stringToEscape ?? ''); case self::ESCAPE_ALL_EXCEPT_LINK: return self::escapeAllExceptLink($stringToEscape); case self::ESCAPE_ALL: return self::escapeAll($stringToEscape); case self::ESCAPE_ILLEGAL_CHARS: $chars = (string) $_SESSION['centreon']->Nagioscfg['illegal_object_name_chars']; return str_replace(str_split($chars), '', $stringToEscape); default: return false; } } /** * Convert all html tags into HTML entities * * @param string $stringToEscape String to escape * @return string Converted string */ public static function escapeAll($stringToEscape) { return htmlentities($stringToEscape ?? '', ENT_QUOTES, 'UTF-8'); } /** * Protect a string and return it with single quotes around. * * This is the same behaviour as {@see PDO::quote}. * * @see https://dev.mysql.com/doc/refman/5.7/en/mysql-real-escape-string.html * @see https://www.php.net/manual/fr/mysqli.real-escape-string.php * * @param null|int|float|bool|string|Stringable $value * * @return string */ public static function quote(null|int|float|bool|string|Stringable $value): string { $pairs = [ "\x00" => '\x00', // \0 (ASCII 0) "\n" => '\n', // \n "\r" => '\r', // \r '\\' => '\\\\', // \ "'" => "\'", // ' '"' => '\"', // " "\x1a" => '\x1a', // Control-Z ]; return "'" . strtr((string) $value, $pairs) . "'"; } /** * Convert all HTML tags into HTML entities except those defined in parameter * * @param string $stringToEscape String (HTML) to escape * @param string[] $tagsNotToEscape List of tags not to escape * * @return string HTML escaped */ public static function escapeAllExceptSelectedTags( $stringToEscape, $tagsNotToEscape = [], ) { if (! is_array($tagsNotToEscape)) { // Do nothing if the tag list is empty return $stringToEscape; } $tagOccurences = []; /* * Before to escape HTML, we will search and replace all HTML tags * allowed by specific tags to avoid they are processed */ $counter = count($tagsNotToEscape); for ($indexTag = 0; $indexTag < $counter; $indexTag++) { $linkToken = "{{__TAG{$indexTag}x__}}"; $currentTag = $tagsNotToEscape[$indexTag]; if (! in_array($currentTag, self::$selfclosingHtmlTagsAllowed)) { // The current tag is not self-closing tag allowed $index = 0; $tagsFound = []; // Specific process for not self-closing HTML tags while ($occurence = self::getHtmlTags($currentTag, $stringToEscape)) { $tagsFound[$index] = $occurence['tag']; $linkTag = str_replace('x', $index, $linkToken); $stringToEscape = substr_replace( $stringToEscape, $linkTag, $occurence['start'], $occurence['length'] ); $index++; } } else { $linkToken = '{{__' . strtoupper($currentTag) . '__}}'; // Specific process for self-closing tag $stringToEscape = preg_replace( '~< *(' . $currentTag . ')+ *\/?>~im', $linkToken, $stringToEscape ); $tagsFound = ["<{$currentTag}/>"]; } $tagOccurences[$linkToken] = $tagsFound; } $escapedString = htmlentities($stringToEscape, ENT_QUOTES, 'UTF-8'); /* * After we escaped all unauthorized HTML tags, we will search and * replace all previous specifics tags by their original tag */ foreach ($tagOccurences as $linkToken => $tagsFound) { $counter = count($tagsFound); for ($indexTag = 0; $indexTag < $counter; $indexTag++) { $linkTag = str_replace('x', $indexTag, $linkToken); $escapedString = str_replace($linkTag, $tagsFound[$indexTag], $escapedString); } } return $escapedString; } /** * Convert all html tags into HTML entities except links (<a>...</a>) * * @param string $stringToEscape String (HTML) to escape * @return string HTML escaped (except links) */ public static function escapeAllExceptLink($stringToEscape) { return self::escapeAllExceptSelectedTags($stringToEscape, ['a']); } /** * Return all occurences of a html tag found in html string * * @param string $tag HTML tag to find * @param string $html HTML to analyse * * @return array (('tag'=> html tag; 'start' => start position of tag, * 'length'=> length between start and end of tag), ...) */ public static function getHtmlTags($tag, $html) { $occurrences = false; $start = 0; if ( ($start = stripos($html, "<{$tag}", $start)) !== false && ($end = stripos($html, "</{$tag}>", strlen("</{$tag}>"))) ) { if (! is_array($occurrences[$tag])) { $occurrences[$tag] = []; } $occurrences = ['tag' => substr( $html, $start, $end + strlen("</{$tag}>") - $start ), 'start' => $start, 'length' => $end + strlen("</{$tag}>") - $start]; } return $occurrences; } /** * @param string $coords -90.0,180.0 * * @return bool */ public static function validateGeoCoords($coords): bool { return (bool) ( preg_match( '/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/', $coords ) ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonStatistics.class.php
centreon/www/class/centreonStatistics.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../../bootstrap.php'; require_once __DIR__ . '/centreonUUID.class.php'; require_once __DIR__ . '/centreonGMT.class.php'; require_once __DIR__ . '/centreonVersion.class.php'; require_once __DIR__ . '/centreonDB.class.php'; require_once __DIR__ . '/centreonStatsModules.class.php'; use App\Kernel; use Core\Common\Infrastructure\FeatureFlags; use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * Class * * @class CentreonStatistics */ class CentreonStatistics { /** @var LoggerInterface */ private LoggerInterface $logger; /** @var CentreonDB */ private CentreonDB $dbConfig; /** @var FeatureFlags|null */ private ?FeatureFlags $featureFlags; /** * CentreonStatistics constructor * * @param LoggerInterface $logger * * @throws LogicException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException */ public function __construct(LoggerInterface $logger) { $this->dbConfig = new CentreonDB(); $this->logger = $logger; $kernel = Kernel::createForWeb(); $this->featureFlags = $kernel->getContainer()->get(FeatureFlags::class); } /** * get Centreon UUID * * @return array */ public function getCentreonUUID() { $centreonUUID = new CentreonUUID($this->dbConfig); return [ 'CentreonUUID' => $centreonUUID->getUUID(), ]; } /** * get Centreon information * * @throws PDOException * @return array */ public function getPlatformInfo() { $query = <<<'SQL' SELECT COUNT(h.host_id) as nb_hosts, ( SELECT COUNT(hg.hg_id) FROM hostgroup hg WHERE hg.hg_activate = '1' ) as nb_hg, ( SELECT COUNT(s.service_id) FROM service s WHERE s.service_activate = '1' AND s.service_register = '1' ) as nb_services, ( SELECT COUNT(sg.sg_id) FROM servicegroup sg WHERE sg.sg_activate = '1' ) as nb_sg, @nb_remotes:=( SELECT COUNT(ns.id) FROM nagios_server ns, remote_servers rs WHERE ns.ns_activate = '1' AND rs.server_id = ns.id ) as nb_remotes, ( ( SELECT COUNT(ns2.id) FROM nagios_server ns2 WHERE ns2.ns_activate = '1' )-@nb_remotes-1 ) as nb_pollers, '1' as nb_central FROM host h WHERE h.host_activate = '1' AND h.host_register = '1' SQL; return $this->dbConfig->query($query)->fetch(); } /** * get version of Centreon Web * * @throws Exception * @return array */ public function getVersion() { $dbStorage = new CentreonDB('centstorage'); $centreonVersion = new CentreonVersion($this->dbConfig, $dbStorage); return [ 'core' => $centreonVersion->getCore(), 'modules' => $centreonVersion->getModules(), 'widgets' => $centreonVersion->getWidgets(), 'system' => $centreonVersion->getSystem(), ]; } /** * get Centreon timezone * * @return array */ public function getPlatformTimezone() { $oTimezone = new CentreonGMT(); $defaultTimezone = $oTimezone->getCentreonTimezone(); $timezoneById = $oTimezone->getList(); if (! empty($defaultTimezone) && ! empty($timezoneById[$defaultTimezone])) { $timezone = $timezoneById[$defaultTimezone]; } else { $timezone = date_default_timezone_get(); } return [ 'timezone' => $timezone, ]; } /** * get LDAP configured authentications options * * @throws PDOException * @return array */ public function getLDAPAuthenticationOptions() { $data = []; // Get the number of LDAP directories configured by LDAP configuration $query = <<<'SQL' SELECT ar.ar_id, COUNT(arh.auth_ressource_id) AS configured_ad FROM auth_ressource_host AS arh INNER JOIN auth_ressource AS ar ON (arh.auth_ressource_id = ar.ar_id) WHERE ar.ar_enable = '1' GROUP BY ar_id SQL; $result = $this->dbConfig->query($query); while ($row = $result->fetch()) { $data[$row['ar_id']] = [ 'nb_ar_servers' => $row['configured_ad'], ]; } // Get configured options by LDAP configuration $query = <<<'SQL' SELECT ar.ar_id, ari.ari_name, ari.ari_value FROM auth_ressource_host AS arh INNER JOIN auth_ressource AS ar ON (arh.auth_ressource_id = ar.ar_id) INNER JOIN auth_ressource_info AS ari ON (ari.ar_id = ar.ar_id) WHERE ari.ari_name IN ('ldap_template', 'ldap_auto_sync', 'ldap_sync_interval', 'ldap_auto_import', 'ldap_search_limit', 'ldap_search_timeout', 'ldap_srv_dns', 'ldap_store_password', 'protocol_version') SQL; $result = $this->dbConfig->query($query); while ($row = $result->fetch()) { $data[$row['ar_id']][$row['ari_name']] = $row['ari_value']; } return $data; } /** * get Local / SSO configured authentications options * * @throws PDOException * @return array */ public function getNewAuthenticationOptions() { $data = []; // Get authentication configuration $query = "SELECT * FROM provider_configuration WHERE is_active = '1'"; $result = $this->dbConfig->query($query); while ($row = $result->fetch()) { $customConfiguration = json_decode($row['custom_configuration'], true); switch ($row['type']) { case 'local': $data['local'] = $customConfiguration['password_security_policy']; break; case 'web-sso': $data['web-sso'] = [ 'is_forced' => (bool) $row['is_forced'], 'trusted_client_addresses' => count($customConfiguration['trusted_client_addresses'] ?? []), 'blacklist_client_addresses' => count($customConfiguration['blacklist_client_addresses'] ?? []), 'pattern_matching_login' => (bool) $customConfiguration['pattern_matching_login'], 'pattern_replace_login' => (bool) $customConfiguration['pattern_replace_login'], ]; break; case 'openid': $authenticationConditions = $customConfiguration['authentication_conditions']; $groupsMapping = $customConfiguration['groups_mapping']; $rolesMapping = $customConfiguration['roles_mapping']; $data['openid'] = [ 'is_forced' => (bool) $row['is_forced'], 'authenticationConditions' => [ 'is_enabled' => (bool) $authenticationConditions['is_enabled'], 'trusted_client_addresses' => count($authenticationConditions['trusted_client_addresses'] ?? []), 'blacklist_client_addresses' => count($authenticationConditions['blacklist_client_addresses'] ?? []), 'authorized_values' => count($authenticationConditions['authorized_values'] ?? []), ], 'groups_mapping' => [ 'is_enabled' => (bool) $groupsMapping['is_enabled'], 'relations' => $this->getContactGroupRelationsByProviderType('openid'), ], 'roles_mapping' => [ 'is_enabled' => (bool) $rolesMapping['is_enabled'], 'apply_only_first_role' => (bool) $rolesMapping['apply_only_first_role'], 'relations' => $this->getAclRelationsByProviderType('openid'), ], 'introspection_token_endpoint' => (bool) $customConfiguration['introspection_token_endpoint'], 'userinfo_endpoint' => (bool) $customConfiguration['userinfo_endpoint'], 'endsession_endpoint' => (bool) $customConfiguration['endsession_endpoint'], 'connection_scopes' => count($customConfiguration['connection_scopes'] ?? []), 'authentication_type' => $customConfiguration['authentication_type'], 'verify_peer' => (bool) $customConfiguration['verify_peer'], 'auto_import' => (bool) $customConfiguration['auto_import'], 'redirect_url' => $customConfiguration['redirect_url'] !== null, ]; break; case 'saml': $authenticationConditions = $customConfiguration['authentication_conditions']; $groupsMapping = $customConfiguration['groups_mapping']; $rolesMapping = $customConfiguration['roles_mapping']; $data['saml'] = [ 'is_forced' => (bool) $row['is_forced'], 'authenticationConditions' => [ 'is_enabled' => (bool) $authenticationConditions['is_enabled'], 'authorized_values' => count($authenticationConditions['authorized_values'] ?? []), ], 'groups_mapping' => [ 'is_enabled' => (bool) $groupsMapping['is_enabled'], 'relations' => $this->getContactGroupRelationsByProviderType('saml'), ], 'roles_mapping' => [ 'is_enabled' => (bool) $rolesMapping['is_enabled'], 'apply_only_first_role' => (bool) $rolesMapping['apply_only_first_role'], 'relations' => $this->getAclRelationsByProviderType('saml'), ], 'auto_import' => (bool) $customConfiguration['auto_import'], 'logout_from' => (bool) $customConfiguration['logout_from'] === true ? 'Only Centreon' : 'Centreon + Idp', ]; break; } } return $data; } /** * get configured authentications options * * @throws PDOException * @return array */ public function getAuthenticationOptions() { $data = $this->getNewAuthenticationOptions(); $data['LDAP'] = $this->getLDAPAuthenticationOptions(); return $data; } /** * get info about manually managed API tokens * * @throws PDOException * @return array */ public function getApiTokensInfo() { $statementManagerCount = $this->dbConfig->fetchOne( <<<'SQL' SELECT count(contact_id) FROM contact WHERE contact_id IN ( SELECT contact_id FROM contact WHERE contact_admin = '1' AND is_service_account = '0' ) OR contact_id IN ( SELECT contact_id FROM contact JOIN acl_group_contacts_relations acl_grp_contact_rel ON contact.contact_id = acl_grp_contact_rel.contact_contact_id JOIN acl_group_actions_relations acl_grp_action_rel ON acl_grp_contact_rel.acl_group_id = acl_grp_action_rel.acl_group_id JOIN acl_actions_rules acl_action ON acl_grp_action_rel.acl_action_id = acl_action.acl_action_rule_id AND acl_action.acl_action_name = 'manage_tokens' ) SQL ); $statementTokenInfos = $this->dbConfig->fetchAllAssociative( <<<'SQL' SELECT security_authentication_tokens.token_name as name, security_authentication_tokens.user_id, DATEDIFF( FROM_UNIXTIME(security_token.expiration_date), FROM_UNIXTIME(security_token.creation_date) ) as lifespan FROM security_authentication_tokens JOIN security_token ON security_token.token = security_authentication_tokens.token WHERE security_authentication_tokens.token_type ='manual' AND security_authentication_tokens.is_revoked = 0 SQL ); return [ 'managers' => $statementManagerCount ?: 0, 'tokens' => $statementTokenInfos, ]; } /** * Get Additional data * * @return array */ public function getAdditionalData() { $centreonVersion = new CentreonVersion($this->dbConfig); $data = [ 'extension' => [ 'widgets' => $centreonVersion->getWidgetsUsage(), ], ]; $oModulesStats = new CentreonStatsModules($this->logger); $modulesData = $oModulesStats->getModulesStatistics(); foreach ($modulesData as $moduleData) { $data['extension'] = array_merge($data['extension'], $moduleData); } if ($this->featureFlags?->isEnabled('notification')) { $data['notification'] = $this->getAdditionalNotificationInformation(); } $data['dashboards'] = $this->getAdditionalDashboardsInformation(); $data['playlists'] = $this->getAdditionalDashboardPlaylistsInformation(); $data['user_filter'] = $this->getAdditionalUserFiltersInformation(); return $data; } /** * Get additional connector configurations data. * * @return array */ public function getAccData(): array { $data = ['total' => 0]; $statement = $this->dbConfig->executeQuery( <<<'SQL' SELECT type, count(id) as value FROM additional_connector_configuration GROUP BY type UNION SELECT 'total' as type, count(id) as value FROM additional_connector_configuration SQL ); foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) { $data[$row['type']] = $row['value']; } return $data; } /** * Get poller/agent configuration data. * * @throws CentreonDbException * * @return array */ public function getAgentConfigurationData(): array { $data = []; $totalAC = $this->dbConfig->fetchOne( <<<'SQL' SELECT count(id) FROM agent_configuration ac SQL ); $data['total'] = $totalAC ?: 0; $configSums = $this->dbConfig->fetchAllAssociative( <<<'SQL' SELECT ac.type, count(DISTINCT ac.id) as nb_ac_per_type, count(rel.poller_id) as nb_poller_per_type FROM agent_configuration ac JOIN ac_poller_relation rel ON ac.id = rel.ac_id GROUP BY ac.type SQL ); foreach ($configSums as $configSum) { $data[$configSum['type']]['configuration'] = $configSum['nb_ac_per_type']; $data[$configSum['type']]['pollers'] = $configSum['nb_poller_per_type']; } $pearDBO = new CentreonDB(CentreonDB::LABEL_DB_REALTIME); $query = <<<'SQL' SELECT `poller_id`, `enabled`, `infos` FROM `agent_information` SQL; $statement = $pearDBO->executeQuery($query); while (is_array($row = $pearDBO->fetch($statement))) { /** @var array{poller_id:int,enabled:int,infos:string} $row */ $decodedInfos = json_decode($row['infos'], true); if (! is_array($decodedInfos)) { $this->logger->warning( "Invalid JSON format in agent_information table for poller_id {$row['poller_id']}", ['context' => $row] ); continue; } $data['agents'][] = [ 'id' => $row['poller_id'], 'enabled' => (bool) $row['enabled'], 'infos' => array_map(function ($info) { return [ 'agentMajor' => $info['agent_major'] ?? '', 'agentMinor' => $info['agent_minor'] ?? '', 'agentPatch' => $info['agent_patch'] ?? null, 'reverse' => $info['reverse'] ?? false, 'os' => $info['os'] ?? '', 'osVersion' => $info['os_version'] ?? '', 'nbAgent' => $info['nb_agent'] ?? null, ]; }, $decodedInfos), ]; } return $data; } /** * @throws PDOException * @return array{ * total: int, * avg_hg_notification?: float, * avg_sg_notification?: float, * avg_bv_notification?: float, * avg_contact_notification?: float, * avg_cg_notification?: float * } */ private function getAdditionalNotificationInformation(): array { $data = []; $avgGetValue = function (string $tableRelation): float|null { $sqlAverage = <<<SQL SELECT AVG(nb) FROM ( SELECT COUNT(id) as nb, n.id FROM {$tableRelation} rel INNER JOIN notification n ON n.id=rel.notification_id AND n.is_activated=1 GROUP BY n.id ) tmp SQL; $sqlTableExists = 'SHOW TABLES LIKE ' . $this->dbConfig->quote($tableRelation); $statement = $this->dbConfig->query($sqlTableExists); $tableExists = $statement && $statement->rowCount() > 0; return $tableExists ? round((float) $this->sqlFetchValue($sqlAverage), 1) : null; }; $data['total'] = (int) $this->sqlFetchValue('SELECT COUNT(id) FROM notification WHERE is_activated=1'); $data['avg_hg_notification'] = $avgGetValue('notification_hg_relation'); $data['avg_sg_notification'] = $avgGetValue('notification_sg_relation'); $data['avg_bv_notification'] = $avgGetValue('mod_bam_notification_bv_relation'); $data['avg_contact_notification'] = $avgGetValue('notification_user_relation'); $data['avg_cg_notification'] = $avgGetValue('notification_contactgroup_relation'); return array_filter($data, static fn (mixed $value): bool => $value !== null); } /** * @throws PDOException * @return array<string,array<string, array{widget_number: int, metric_number?: int}>> */ private function getAdditionalDashboardsInformation(): array { $data = []; $dashboardsInformations = $this->dbConfig->query( <<<'SQL' SELECT `dashboard_id`, `name` AS `widget_name`, `widget_settings` FROM `dashboard_panel` SQL ); $extractMetricInformationFromWidgetSettings = function (array $widgetSettings): int|null { return array_key_exists('metrics', $widgetSettings['data']) ? count($widgetSettings['data']['metrics']) : null; }; $dashboardId = ''; foreach ($dashboardsInformations as $dashboardsInformation) { $widgetName = (string) $dashboardsInformation['widget_name']; $widgetSettings = json_decode((string) $dashboardsInformation['widget_settings'], true); if ($dashboardId !== (string) $dashboardsInformation['dashboard_id']) { $dashboardId = (string) $dashboardsInformation['dashboard_id']; $data[$dashboardId] = []; } if (array_key_exists($widgetName, $data[$dashboardId])) { ++$data[$dashboardId][$widgetName]['widget_number']; if ($data[$dashboardId][$widgetName]['metric_number'] !== null) { $data[$dashboardId][$widgetName]['metric_number'] += $extractMetricInformationFromWidgetSettings($widgetSettings); } } else { $data[$dashboardId][$widgetName]['widget_number'] = 1; $data[$dashboardId][$widgetName]['metric_number'] = $extractMetricInformationFromWidgetSettings($widgetSettings); } } return $data; } /** * @throws PDOException * @return array<string,array{rotation_time: int, dashboards_count: int, shared_users_groups_count: int}> */ private function getAdditionalDashboardPlaylistsInformation(): array { $data = []; $statement = $this->dbConfig->query( <<<'SQL' SELECT dp.name, dp.rotation_time, COALESCE(viewer_contacts.viewer_count, 0) AS viewer_contacts, COALESCE(editor_contacts.editor_count, 0) AS editor_contacts, COALESCE(viewer_contactgroups.viewer_group_count, 0) AS viewer_contactgroups, COALESCE(editor_contactgroups.editor_group_count, 0) AS editor_contactgroups, COALESCE(dashboard_rels.dashboard_count, 0) AS dashboard_count FROM dashboard_playlist dp LEFT JOIN ( SELECT playlist_id, COUNT(*) AS viewer_count FROM dashboard_playlist_contact_relation WHERE role = 'viewer' GROUP BY playlist_id ) AS viewer_contacts ON dp.id = viewer_contacts.playlist_id LEFT JOIN ( SELECT playlist_id, COUNT(*) AS editor_count FROM dashboard_playlist_contact_relation WHERE role = 'editor' GROUP BY playlist_id ) AS editor_contacts ON dp.id = editor_contacts.playlist_id LEFT JOIN ( SELECT playlist_id, COUNT(*) AS viewer_group_count FROM dashboard_playlist_contactgroup_relation WHERE role = 'viewer' GROUP BY playlist_id ) AS viewer_contactgroups ON dp.id = viewer_contactgroups.playlist_id LEFT JOIN ( SELECT playlist_id, COUNT(*) AS editor_group_count FROM dashboard_playlist_contactgroup_relation WHERE role = 'editor' GROUP BY playlist_id ) AS editor_contactgroups ON dp.id = editor_contactgroups.playlist_id LEFT JOIN ( SELECT playlist_id, COUNT(*) AS dashboard_count FROM dashboard_playlist_relation GROUP BY playlist_id ) AS dashboard_rels ON dp.id = dashboard_rels.playlist_id SQL ); while (false !== ($record = $statement->fetch(PDO::FETCH_ASSOC))) { $data[$record['name']] = [ 'rotation_time' => $record['rotation_time'], 'dashboards_count' => $record['dashboard_count'], 'shared_viewer_contacts' => $record['viewer_contacts'], 'shared_editor_contacts' => $record['editor_contacts'], 'shared_viewer_contactgroups' => $record['viewer_contactgroups'], 'shared_editor_contactgroups' => $record['editor_contactgroups'], ]; } return $data; } /** * @throws PDOException * @return array{ * nb_users: int, * avg_filters_per_user: float, * max_filters_user: int * } */ private function getAdditionalUserFiltersInformation(): array { $data = []; $filtersPerUserRequest = <<<'SQL' SELECT COUNT(id) as count FROM user_filter GROUP BY user_id; SQL; $statement = $this->dbConfig->query($filtersPerUserRequest); $filtersPerUser = []; while (false !== ($record = $statement->fetch(PDO::FETCH_ASSOC))) { $filtersPerUser[] = $record['count']; } $data['nb_users'] = (int) $this->sqlFetchValue('SELECT COUNT(DISTINCT user_id) FROM user_filter'); $filters = (int) $this->sqlFetchValue('SELECT COUNT(id) FROM user_filter'); $data['avg_filters_per_user'] = ((int) $data['nb_users'] !== 0) ? (float) ($filters / $data['nb_users']) : 0; $data['max_filters_user'] = ($filtersPerUser !== []) ? (int) max(array_values($filtersPerUser)) : 0; return $data; } /** * @param string $providerType * * @return int */ private function getAclRelationsByProviderType(string $providerType): int { return (int) $this->sqlFetchValue( <<<'SQL' SELECT COUNT(*) AS acl_relation FROM security_provider_access_group_relation gr INNER JOIN provider_configuration pc on pc.id = gr.provider_configuration_id WHERE pc.type = :providerType SQL, [':providerType', $providerType, PDO::PARAM_STR] ); } /** * @param string $providerType * * @return int */ private function getContactGroupRelationsByProviderType(string $providerType): int { return (int) $this->sqlFetchValue( <<<'SQL' SELECT COUNT(*) AS cg_relation FROM security_provider_contact_group_relation cg INNER JOIN provider_configuration pc on pc.id = cg.provider_configuration_id WHERE pc.type = :providerType SQL, [':providerType', $providerType, PDO::PARAM_STR] ); } /** * Helper to retrieve the first value of a SQL query. * * @param string $sql * @param array{string, mixed, int} ...$binds List of [':field', $value, \PDO::PARAM_STR] * * @return string|float|int|null */ private function sqlFetchValue(string $sql, array ...$binds): string|float|int|null { try { $statement = $this->dbConfig->prepare($sql) ?: null; foreach ($binds as $args) { $statement?->bindValue(...$args); } $statement?->execute(); $row = $statement?->fetch(PDO::FETCH_NUM); $value = is_array($row) && isset($row[0]) ? $row[0] : null; return is_string($value) || is_int($value) || is_float($value) ? $value : null; } catch (PDOException $exception) { $this->logger->error($exception->getMessage(), ['context' => $exception]); return null; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMonitoring.class.php
centreon/www/class/centreonMonitoring.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; /** * Class * * @class CentreonMonitoring */ class CentreonMonitoring { use SqlMultipleBindTrait; public const SERVICE_STATUS_OK = 0; public const SERVICE_STATUS_WARNING = 1; public const SERVICE_STATUS_CRITICAL = 2; public const SERVICE_STATUS_UNKNOWN = 3; public const SERVICE_STATUS_PENDING = 4; /** @var string */ protected $poller; /** @var CentreonDB */ protected $DB; /** @var */ protected $objBroker; /** * CentreonMonitoring constructor * * @param CentreonDB $DB */ public function __construct($DB) { $this->DB = $DB; } /** * @param string $pollerId * * @return void */ public function setPoller($pollerId): void { $this->poller = $pollerId; } /** * @return string */ public function getPoller() { return $this->poller; } /** * @param $host_name * @param $objXMLBG * @param $o * @param $status * @param $obj * * Proxy function * * @param string $hostName * @param CentreonXMLBGRequest $centreonXMLBGRequest * @param string $o * @param int $serviceStatus * * @throws CentreonDbException * @return int */ public function getServiceStatusCount( string $hostName, CentreonXMLBGRequest $centreonXMLBGRequest, string $o, int $serviceStatus, ): int { $toBind = [':service_status' => $serviceStatus, ':host_name' => $hostName]; if ($centreonXMLBGRequest->is_admin) { $query = <<<'SQL' SELECT count(distinct s.service_id) as count, 1 AS REALTIME FROM services s INNER JOIN hosts h ON h.host_id = s.host_id WHERE s.state = :service_status AND s.host_id = h.host_id AND s.enabled = '1' AND h.enabled = '1' AND h.name = :host_name SQL; } else { $accessGroups = $centreonXMLBGRequest->access->getAccessGroups(); [$bindValues, $subRequest] = $this->createMultipleBindQuery(array_keys($accessGroups), ':grp_'); $query = <<<SQL SELECT count(distinct s.service_id) as count, 1 AS REALTIME FROM services s INNER JOIN hosts h ON h.host_id = s.host_id INNER JOIN centreon_acl acl ON acl.host_id = h.host_id AND acl.service_id = s.service_id WHERE s.state = :service_status AND s.host_id = h.host_id AND s.enabled = '1' AND h.enabled = '1' AND h.name = :host_name AND acl.group_id IN ({$subRequest}) SQL; $toBind = [...$toBind, ...$bindValues]; } // Acknowledgement filter if ($o === 'svcSum_ack_0') { $query .= ' AND s.acknowledged = 0 AND s.state != 0 '; } elseif ($o === 'svcSum_ack_1') { $query .= ' AND s.acknowledged = 1 AND s.state != 0 '; } $statement = $centreonXMLBGRequest->DBC->prepare($query); $centreonXMLBGRequest->DBC->executePreparedQuery($statement, $toBind); if (($count = $centreonXMLBGRequest->DBC->fetchColumn($statement)) !== false) { return (int) $count; } return 0; } /** * @param int[] $hostIds * @param CentreonXMLBGRequest $centreonXMLBGRequest * @param string $o * @param int $monitoringServerId * * @throws CentreonDbException * @return array<string, array<string, array{state: int, service_id: int}>> */ public function getServiceStatus( array $hostIds, CentreonXMLBGRequest $centreonXMLBGRequest, string $o, int $monitoringServerId, ): array { if ($hostIds === []) { return []; } [$hostIdsToBind, $hostNamesSubQuery] = $this->createMultipleBindQuery($hostIds, ':host_id_'); $toBind = $hostIdsToBind; $query = <<<'SQL' SELECT 1 AS REALTIME, h.name, s.description AS service_name, s.state, s.service_id, (CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri FROM hosts h INNER JOIN services s ON s.host_id = h.host_id SQL; if (! $centreonXMLBGRequest->is_admin) { $accessGroups = $centreonXMLBGRequest->access->getAccessGroups(); [$bindValues, $accessGroupsSubQuery] = $this->createMultipleBindQuery(array_keys($accessGroups), ':grp_'); $toBind = [...$toBind, ...$bindValues]; $query .= <<<SQL INNER JOIN centreon_acl ON centreon_acl.host_id = h.host_id AND centreon_acl.service_id = s.service_id AND centreon_acl.group_id IN ({$accessGroupsSubQuery}) SQL; } $query .= <<<SQL WHERE s.enabled = '1' AND h.enabled = '1' AND h.name NOT LIKE '\_Module\_%' SQL; if ($o === 'svcgrid_pb' || $o === 'svcOV_pb') { $query .= ' AND s.state != 0 '; } elseif ($o === 'svcgrid_ack_0' || $o === 'svcOV_ack_0') { $query .= ' AND s.acknowledged = 0 AND s.state != 0 '; } elseif ($o === 'svcgrid_ack_1' || $o === 'svcOV_ack_1') { $query .= ' AND s.acknowledged = 1 '; } $query .= " AND h.host_id IN ({$hostNamesSubQuery}) "; // Instance filter if ($monitoringServerId !== -1) { $query .= ' AND h.instance_id = :monitoring_server_id'; $toBind[':monitoring_server_id'] = $monitoringServerId; } $query .= ' ORDER BY tri ASC, service_name'; $serviceDetails = []; $statement = $centreonXMLBGRequest->DBC->prepare($query); $centreonXMLBGRequest->DBC->executePreparedQuery($statement, $toBind); while ($result = $centreonXMLBGRequest->DBC->fetch($statement)) { if (! isset($serviceDetails[$result['name']])) { $serviceDetails[$result['name']] = []; } $serviceDetails[$result['name']][$result['service_name']] = [ 'state' => $result['state'], 'service_id' => $result['service_id'], ]; } $centreonXMLBGRequest->DBC->closeQuery($statement); return $serviceDetails; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDB.class.php
centreon/www/class/centreonDB.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Adaptation\Database\Connection\Adapter\Pdo\Transformer\PdoParameterTypeTransformer; use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\ConnectionInterface; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\Model\ConnectionConfig; use Adaptation\Database\Connection\Trait\ConnectionTrait; use Adaptation\Database\Connection\ValueObject\QueryParameter; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Psr\Log\LogLevel; // file centreon.config.php may not exist in test environment $configFile = realpath(__DIR__ . '/../../config/centreon.config.php'); if ($configFile !== false) { require_once $configFile; } require_once __DIR__ . '/centreonDBStatement.class.php'; require_once __DIR__ . '/centreonLog.class.php'; /** * Class * * @class CentreonDB * @description used to manage DB connection */ class CentreonDB extends PDO implements ConnectionInterface { use ConnectionTrait; public const DRIVER_PDO_MYSQL = 'mysql'; public const LABEL_DB_CONFIGURATION = 'centreon'; public const LABEL_DB_REALTIME = 'centstorage'; /** @var int */ private const RETRY = 3; /** @var int */ protected $retry; /** @var array<int, array<int, mixed>|int|bool|string> */ protected $options; /** @var string */ protected $centreon_path; /** @var CentreonLog */ protected $logger; // Statistics /** @var int */ protected $requestExecuted; /** @var int */ protected $requestSuccessful; /** @var int */ protected $lineRead; /** @var array<string,CentreonDB> */ private static $instance = []; /** @var int */ private $queryNumber; /** @var int */ private $successQueryNumber; /** @var ConnectionConfig */ private ConnectionConfig $connectionConfig; /** * By default, the queries are buffered. * * @var bool */ private bool $isBufferedQueryActive = true; /** * CentreonDB constructor. * * @param string $dbLabel LABEL_DB_* constants * @param int $retry * @param ConnectionConfig|null $connectionConfig * * @throws Exception */ public function __construct( string $dbLabel = self::LABEL_DB_CONFIGURATION, int $retry = self::RETRY, ?ConnectionConfig $connectionConfig = null, ) { if (is_null($connectionConfig)) { $this->connectionConfig = new ConnectionConfig( host: $dbLabel === self::LABEL_DB_CONFIGURATION ? hostCentreon : hostCentstorage, user: user, password: password, databaseNameConfiguration: $dbLabel === self::LABEL_DB_CONFIGURATION ? db : dbcstg, databaseNameRealTime: dbcstg, port: port ?? 3306 ); } else { $this->connectionConfig = $connectionConfig; } $this->logger = CentreonLog::create(); $this->centreon_path = _CENTREON_PATH_; $this->retry = $retry; $this->options = [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_STATEMENT_CLASS => [ CentreonDBStatement::class, [$this->logger], ], PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$this->connectionConfig->getCharset()}", PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; // Init request statistics $this->requestExecuted = 0; $this->requestSuccessful = 0; $this->lineRead = 0; try { parent::__construct( $this->connectionConfig->getMysqlDsn(), $this->connectionConfig->getUser(), $this->connectionConfig->getPassword(), $this->options ); } catch (Exception $e) { $this->writeDbLog( message: "Unable to connect to database : {$e->getMessage()}", customContext: ['dsn_mysql' => $this->connectionConfig->getMysqlDsn()], previous: $e, ); if (PHP_SAPI !== 'cli') { $this->displayConnectionErrorPage( $e->getCode() === 2002 ? 'Unable to connect to database' : $e->getMessage() ); } else { throw new Exception($e->getMessage()); } } } /** * Factory * * @param ConnectionConfig $connectionConfig * * @throws ConnectionException * @return CentreonDB */ public static function connectToCentreonDb(ConnectionConfig $connectionConfig): CentreonDB { try { return new self(dbLabel: self::LABEL_DB_CONFIGURATION, connectionConfig: $connectionConfig); } catch (Exception $e) { throw ConnectionException::connectionFailed($e); } } /** * Factory * * @param ConnectionConfig $connectionConfig * * @throws ConnectionException * @return CentreonDB */ public static function connectToCentreonStorageDb(ConnectionConfig $connectionConfig): CentreonDB { try { return new self(dbLabel: self::LABEL_DB_REALTIME, connectionConfig: $connectionConfig); } catch (Exception $e) { throw ConnectionException::connectionFailed($e); } } /** * Factory * * @param ConnectionConfig $connectionConfig * * @throws ConnectionException * @return ConnectionInterface */ public static function createFromConfig(ConnectionConfig $connectionConfig): ConnectionInterface { try { return new static(connectionConfig: $connectionConfig); } catch (Exception $e) { throw ConnectionException::connectionFailed($e); } } /** * @return ConnectionConfig */ public function getConnectionConfig(): ConnectionConfig { return $this->connectionConfig; } /** * To get the used native connection by DBAL (PDO, mysqli, ...). * * @return PDO */ public function getNativeConnection(): PDO { return $this; } /*** * Returns the ID of the last inserted row. * If the underlying driver does not support identity columns, an exception is thrown. * * @throws ConnectionException * @return string */ public function getLastInsertId(): string { try { return (string) $this->lastInsertId(); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to get last insert id', previous: $exception, ); throw ConnectionException::getLastInsertFailed($exception); } } /** * Check if a connection with the database exist. * * @return bool */ public function isConnected(): bool { try { $this->executeSelectQuery('SELECT 1'); return true; } catch (ConnectionException $exception) { $this->writeDbLog( message: 'Unable to check if the connection is established', query: 'SELECT 1', previous: $exception, ); return false; } } /** * The usage of this method is discouraged. Use prepared statements. * * @param string $value * * @return string */ public function quoteString(string $value): string { return parent::quote($value); } // --------------------------------------- CUD METHODS ----------------------------------------- /** * To execute all queries except the queries getting results (SELECT). * * Executes an SQL statement with the given parameters and returns the number of affected rows. * * Could be used for: * - DML statements: INSERT, UPDATE, DELETE, etc. * - DDL statements: CREATE, DROP, ALTER, etc. * - DCL statements: GRANT, REVOKE, etc. * - Session control statements: ALTER SESSION, SET, DECLARE, etc. * - Other statements that don't yield a row set. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return int * * @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]); * $nbAffectedRows = $db->executeStatement('UPDATE table SET name = :name WHERE id = :id', $queryParameters); * // $nbAffectedRows = 1 */ public function executeStatement(string $query, ?QueryParameters $queryParameters = null): int { try { if (empty($query)) { throw ConnectionException::notEmptyQuery(); } if (str_starts_with($query, 'SELECT') || str_starts_with($query, 'select')) { throw ConnectionException::executeStatementBadFormat( 'Cannot use it with a SELECT query', $query ); } // here we don't want to use CentreonDbStatement, instead used PDOStatement $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class]); $pdoStatement = $this->prepare($query); if (! is_null($queryParameters) && ! $queryParameters->isEmpty()) { /** @var QueryParameter $queryParameter */ foreach ($queryParameters->getIterator() as $queryParameter) { $pdoStatement->bindValue( $queryParameter->getName(), $queryParameter->getValue(), ($queryParameter->getType() !== null) ? PdoParameterTypeTransformer::transformFromQueryParameterType( $queryParameter->getType() ) : PDO::PARAM_STR ); } } $pdoStatement->execute(); return $pdoStatement->rowCount(); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to execute statement', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::executeStatementFailed($exception, $query, $queryParameters); } finally { // here we restart CentreonDbStatement for the other requests $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [ CentreonDBStatement::class, [$this->logger], ]); } } // --------------------------------------- FETCH METHODS ----------------------------------------- /** * Prepares and executes an SQL query and returns the first row of the result * as a numerically indexed array. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return array<int, mixed>|false false is returned if no rows are found * * @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]); * $result = $db->fetchNumeric('SELECT * FROM table WHERE id = :id', $queryParameters); * // $result = [0 => 1, 1 => 'John', 2 => 'Doe'] */ public function fetchNumeric(string $query, ?QueryParameters $queryParameters = null): false|array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetch(PDO::FETCH_NUM); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch numeric query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchNumericQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the first row of the result as an associative array. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return array<string, mixed>|false false is returned if no rows are found * * @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]); * $result = $db->fetchAssociative('SELECT * FROM table WHERE id = :id', $queryParameters); * // $result = ['id' => 1, 'name' => 'John', 'surname' => 'Doe'] */ public function fetchAssociative(string $query, ?QueryParameters $queryParameters = null): false|array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetch(PDO::FETCH_ASSOC); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch associative query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchAssociativeQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the value of a single column * of the first row of the result. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return mixed|false false is returned if no rows are found * * @example $queryParameters = QueryParameters::create([QueryParameter::string('name', 'John')]); * $result = $db->fetchOne('SELECT name FROM table WHERE name = :name', $queryParameters); * // $result = 'John' */ public function fetchOne(string $query, ?QueryParameters $queryParameters = null): mixed { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetch(PDO::FETCH_COLUMN); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch one query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchOneQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an array of the first column values. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return list<mixed> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->fetchFirstColumn('SELECT name FROM table WHERE active = :active', $queryParameters); * // $result = ['John', 'Jean'] */ public function fetchFirstColumn(string $query, ?QueryParameters $queryParameters = null): array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetchAll(PDO::FETCH_COLUMN); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch by column query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchFirstColumnQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an array of numeric arrays. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return array<array<int,mixed>> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->fetchAllNumeric('SELECT * FROM table WHERE active = :active', $queryParameters); * // $result = [[0 => 1, 1 => 'John', 2 => 'Doe'], [0 => 2, 1 => 'Jean', 2 => 'Dupont']] */ public function fetchAllNumeric(string $query, ?QueryParameters $queryParameters = null): array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetchAll(PDO::FETCH_NUM); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch all numeric query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchAllNumericQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an array of associative arrays. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return array<array<string,mixed>> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->fetchAllAssociative('SELECT * FROM table WHERE active = :active', $queryParameters); * // $result = [['id' => 1, 'name' => 'John', 'surname' => 'Doe'], ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']] */ public function fetchAllAssociative(string $query, ?QueryParameters $queryParameters = null): array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetchAll(PDO::FETCH_ASSOC); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch all associative query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchAllAssociativeQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an associative array with the keys * mapped to the first column and the values mapped to the second column. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return array<int|string,mixed> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->fetchAllKeyValue('SELECT name, surname FROM table WHERE active = :active', $queryParameters); * // $result = ['John' => 'Doe', 'Jean' => 'Dupont'] */ public function fetchAllKeyValue(string $query, ?QueryParameters $queryParameters = null): array { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); return $pdoStatement->fetchAll(PDO::FETCH_KEY_PAIR); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to fetch all key value query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::fetchAllKeyValueQueryFailed($exception, $query, $queryParameters); } } // --------------------------------------- ITERATE METHODS ----------------------------------------- /** * Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return Traversable<int,list<mixed>> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->iterateNumeric('SELECT * FROM table WHERE active = :active', $queryParameters); * foreach ($result as $row) { * // $row = [0 => 1, 1 => 'John', 2 => 'Doe'] * // $row = [0 => 2, 1 => 'Jean', 2 => 'Dupont'] * } */ public function iterateNumeric(string $query, ?QueryParameters $queryParameters = null): Traversable { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); while (($row = $pdoStatement->fetch(PDO::FETCH_NUM)) !== false) { yield $row; } } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to iterate numeric query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::iterateNumericQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an iterator over rows represented * as associative arrays. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return Traversable<int,array<string,mixed>> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->iterateAssociative('SELECT * FROM table WHERE active = :active', $queryParameters); * foreach ($result as $row) { * // $row = ['id' => 1, 'name' => 'John', 'surname' => 'Doe'] * // $row = ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont'] * } */ public function iterateAssociative(string $query, ?QueryParameters $queryParameters = null): Traversable { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); while (($row = $pdoStatement->fetch(PDO::FETCH_ASSOC)) !== false) { yield $row; } } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to iterate associative query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::iterateAssociativeQueryFailed($exception, $query, $queryParameters); } } /** * Prepares and executes an SQL query and returns the result as an iterator over the column values. * * Could be only used with SELECT. * * @param string $query * @param QueryParameters|null $queryParameters * * @throws ConnectionException * @return Traversable<int,list<mixed>> * * @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]); * $result = $db->iterateColumn('SELECT name FROM table WHERE active = :active', $queryParameters); * foreach ($result as $value) { * // $value = 'John' * // $value = 'Jean' * } */ public function iterateColumn(string $query, ?QueryParameters $queryParameters = null): Traversable { try { $this->validateSelectQuery($query); $pdoStatement = $this->executeSelectQuery($query, $queryParameters); while (($row = $pdoStatement->fetch(PDO::FETCH_COLUMN)) !== false) { yield $row; } } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to iterate by column query', customContext: ['query_parameters' => $queryParameters], query: $query, previous: $exception, ); throw ConnectionException::iterateColumnQueryFailed($exception, $query, $queryParameters); } } // ----------------------------------------- TRANSACTIONS ----------------------------------------- /** * Checks whether a transaction is currently active. * * @return bool TRUE if a transaction is currently active, FALSE otherwise */ public function isTransactionActive(): bool { return parent::inTransaction(); } /** * Opens a new transaction. This must be closed by calling one of the following methods: * {@see commitTransaction} or {@see rollBackTransaction} * * @throws ConnectionException * @return void */ public function startTransaction(): void { try { $this->beginTransaction(); } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to start transaction', previous: $exception, ); throw ConnectionException::startTransactionFailed($exception); } } /** * To validate a transaction. * * @throws ConnectionException * @return bool */ public function commitTransaction(): bool { try { if (! parent::commit()) { throw ConnectionException::commitTransactionFailed(); } return true; } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to commit transaction', previous: $exception, ); throw ConnectionException::commitTransactionFailed($exception); } } /** * To cancel a transaction. * * @throws ConnectionException * @return bool */ public function rollBackTransaction(): bool { try { if (! parent::rollBack()) { throw ConnectionException::rollbackTransactionFailed(); } return true; } catch (Throwable $exception) { $this->writeDbLog( message: 'Unable to rollback transaction', previous: $exception, ); throw ConnectionException::rollbackTransactionFailed($exception); } } // ------------------------------------- UNBUFFERED QUERIES ----------------------------------------- /** * Checks that the connection instance allows the use of unbuffered queries. * * @throws ConnectionException */ public function allowUnbufferedQuery(): bool { $currentDriverName = "pdo_{$this->getAttribute(PDO::ATTR_DRIVER_NAME)}"; if (! in_array($currentDriverName, self::DRIVER_ALLOWED_UNBUFFERED_QUERY, true)) { $this->writeDbLog( message: 'Unbuffered queries are not allowed with this driver', customContext: ['driver_name' => $currentDriverName] ); throw ConnectionException::allowUnbufferedQueryFailed(parent::class, $currentDriverName); } return true; } /** * Prepares a statement to execute a query without buffering. Only works for SELECT queries. * * @throws ConnectionException * @return void */ public function startUnbufferedQuery(): void { $this->allowUnbufferedQuery(); if (! $this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)) { $this->writeDbLog(message: 'Error while starting an unbuffered query'); throw ConnectionException::startUnbufferedQueryFailed(); } $this->isBufferedQueryActive = false; } /** * Checks whether an unbuffered query is currently active. * * @return bool */ public function isUnbufferedQueryActive(): bool { return $this->isBufferedQueryActive === false; } /** * To close an unbuffered query. * * @throws ConnectionException * @return void */ public function stopUnbufferedQuery(): void { if (! $this->isUnbufferedQueryActive()) { $this->writeDbLog( message: 'Error while stopping an unbuffered query, no unbuffered query is currently active' ); throw ConnectionException::stopUnbufferedQueryFailed( 'Error while stopping an unbuffered query, no unbuffered query is currently active' ); } if (! $this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)) { $this->writeDbLog(message: 'Error while stopping an unbuffered query'); throw ConnectionException::stopUnbufferedQueryFailed('Error while stopping an unbuffered query'); } $this->isBufferedQueryActive = true; } // --------------------------------------- BASE METHODS ----------------------------------------- /** * @param PDOStatement $pdoStatement * * @throws ConnectionException * @return bool */ public function closeQuery(PDOStatement $pdoStatement): bool { try { return $pdoStatement->closeCursor(); } catch (Throwable $exception) { $this->writeDbLog( message: "Error while closing the \PDOStatement cursor: {$exception->getMessage()}", query: $pdoStatement->queryString, previous: $exception, ); throw ConnectionException::closeQueryFailed($exception, $pdoStatement->queryString); } } /** * return database Properties * * <code> * $dataCentreon = getProperties(); * </code> * * @return array<mixed> dbsize, numberOfRow, freeSize */ public function getProperties() { $unitMultiple = 1024 * 1024; $info = [ 'version' => null, 'engine' => null, 'dbsize' => 0, 'rows' => 0, 'datafree' => 0, 'indexsize' => 0, ]; // Get Version if ($res = $this->query('SELECT VERSION() AS mysql_version')) { $row = $res->fetch(); $versionInformation = explode('-', $row['mysql_version']); $info['version'] = $versionInformation[0]; $info['engine'] = $versionInformation[1] ?? 'MySQL'; if ($dbResult = $this->query( 'SHOW TABLE STATUS FROM `' . $this->connectionConfig->getDatabaseNameConfiguration() . '`' )) { while ($data = $dbResult->fetch()) { $info['dbsize'] += $data['Data_length'] + $data['Index_length']; $info['indexsize'] += $data['Index_length'];
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonACL.class.php
centreon/www/class/centreonACL.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum; use Adaptation\Database\Connection\Exception\ConnectionException; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Domain\Exception\RepositoryException; require_once realpath(__DIR__ . '/centreonDBInstance.class.php'); require_once _CENTREON_PATH_ . '/www/include/common/sqlCommonFunction.php'; /** * Class * * @class CentreonACL * @description Class for Access Control List management */ class CentreonACL { public const ACL_ACCESS_NONE = 0; public const ACL_ACCESS_READ_WRITE = 1; public const ACL_ACCESS_READ_ONLY = 2; /** @var bool|null */ public $admin; // Flag that tells us if the user is admin or not /** @var array */ public $hostGroups = []; // Hostgroups the user can see /** @var array */ public $topology = []; /** @var string */ public $topologyStr = ''; /** @var bool */ public $hasAccessToAllHostGroups = false; /** @var bool */ public $hasAccessToAllServiceGroups = false; /** @var bool */ public $hasAccessToAllImageFolders = true; /** @var array */ protected $pollers = []; // Pollers the user can see /** @var int */ private $userID; // ID of the user /** @var array|null */ private ?array $parentTemplates = null; /** @var array */ private $accessGroups = []; // Access groups the user belongs to /** @var array */ private $resourceGroups = []; // Resource groups the user belongs to /** @var array */ private $hostGroupsAlias = []; // Hostgroups by alias the user can see /** @var array */ private $serviceGroups = []; // Servicegroups the user can see /** @var array */ private $serviceGroupsAlias = []; // Servicegroups by alias the user can see /** @var array */ private $serviceCategories = []; // Service categories the user can see /** @var array */ private $hostCategories = []; /** @var array */ private $actions = []; // Actions the user can do /** @var array */ private $hostGroupsFilter = []; /** @var array */ private $serviceGroupsFilter = []; /** @var array */ private $serviceCategoriesFilter = []; /** @var array */ private $metaServices = []; /** @var string */ private $metaServiceStr = ''; /** @var array */ private $tempTableArray = []; /** * CentreonACL constructor * * @param int $userId * @param bool|null $isAdmin */ public function __construct($userId, $isAdmin = null) { $this->userID = $userId; if (! isset($isAdmin)) { $db = CentreonDBInstance::getDbCentreonInstance(); $query = 'SELECT contact_admin ' . 'FROM `contact` ' . "WHERE contact_id = '" . CentreonDB::escape($userId) . "' " . 'LIMIT 1 '; $result = $db->query($query); $row = $result->fetch(); $this->admin = $row['contact_admin']; } else { $this->admin = $isAdmin; } if (! $this->admin) { $this->setAccessGroups(); $this->setResourceGroups(); $this->hasAccessToAllHostGroups = $this->hasAccessToAllHostGroups(); $this->hasAccessToAllServiceGroups = $this->hasAccessToAllServiceGroups(); $this->hasAccessToAllImageFolders = $this->hasAccessToAllImageFolders(); $this->setHostGroups(); $this->setPollers(); $this->setServiceGroups(); $this->setServiceCategories(); $this->setHostCategories(); $this->setMetaServices(); $this->setActions(); } $this->setTopology(); $this->getACLStr(); } /** * Function that will update poller ACL * * @return void */ public function updatePollerACL(): void { $this->pollers = []; $this->setPollers(); } // Getter functions /** * Get ACL by string * * @return void */ public function getACLStr(): void { $this->topologyStr = $this->topology === [] ? "''" : implode(',', array_keys($this->topology)); } /** * Access groups Getter * * @return array */ public function getAccessGroups() { $this->setAccessGroups(); return $this->accessGroups; } /** * Access groups string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $escape * * @return string */ public function getAccessGroupsString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } // before returning access groups as string, make sure that those are up to date $this->setAccessGroups(); $accessGroups = ''; foreach ($this->accessGroups as $key => $value) { switch ($flag) { case 'NAME': if ($escape === true) { $accessGroups .= "'" . CentreonDB::escape($value) . "',"; } else { $accessGroups .= "'" . $value . "',"; } break; case 'ID': $accessGroups .= $key . ','; break; default: $accessGroups .= "'" . $key . "',"; break; } } $result = "'0'"; if (strlen($accessGroups)) { $result = trim($accessGroups, ','); } return $result; } /** * Resource groups Getter * * @return array */ public function getResourceGroups() { return $this->resourceGroups; } /** * Resource groups string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $escape * * @return string */ public function getResourceGroupsString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } $resourceGroups = ''; foreach ($this->resourceGroups as $key => $value) { switch ($flag) { case 'NAME': if ($escape === true) { $resourceGroups .= "'" . CentreonDB::escape($value) . "',"; } else { $resourceGroups .= "'" . $value . "',"; } break; case 'ID': $resourceGroups .= $key . ','; break; default: $resourceGroups .= "'" . $key . "',"; break; } } $result = "''"; if (strlen($resourceGroups)) { $result = trim($resourceGroups, ','); } return $result; } /** * Hostgroups Getter * * @param $flag * * @return array */ public function getHostGroups($flag = null) { $this->checkUpdateACL(); if ($flag !== null && strtoupper($flag) == 'ALIAS') { return $this->hostGroupsAlias; } return $this->hostGroups; } /** * Poller Getter * * @return array */ public function getPollers() { return $this->pollers; } /** * Hostgroups string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * * @return string */ public function getHostGroupsString($flag = null) { if ($flag !== null) { $flag = strtoupper($flag); } $hostgroups = ''; foreach ($this->hostGroups as $key => $value) { switch ($flag) { case 'NAME': $hostgroups .= "'" . $value . "',"; break; case 'ALIAS': $hostgroups .= "'" . addslashes($this->hostGroupsAlias[$key]) . "',"; break; case 'ID': $hostgroups .= $key . ','; break; default: $hostgroups .= "'" . $key . "',"; break; } } $result = "''"; if (strlen($hostgroups)) { $result = trim($hostgroups, ','); } return $result; } /** * Poller string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $escape * * @return string */ public function getPollerString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } $pollers = ''; $flagFirst = true; foreach ($this->pollers as $key => $value) { switch ($flag) { case 'NAME': if (! $flagFirst) { $pollers .= ','; } $flagFirst = false; if ($escape === true) { $pollers .= "'" . CentreonDB::escape($value) . "'"; } else { $pollers .= "'" . $value . "'"; } break; case 'ID': if (! $flagFirst) { $pollers .= ','; } $flagFirst = false; $pollers .= $key; break; default: if (! $flagFirst) { $pollers .= ','; } $flagFirst = false; $pollers .= "'" . $key . "'"; break; } } return $pollers; } /** * Service groups Getter * * @return array */ public function getServiceGroups() { return $this->serviceGroups; } /** * Service groups string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $escape * * @return string */ public function getServiceGroupsString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } $servicegroups = ''; foreach ($this->serviceGroups as $key => $value) { switch ($flag) { case 'NAME': if ($escape === true) { $servicegroups .= "'" . CentreonDB::escape($value) . "',"; } else { $servicegroups .= "'" . $value . "',"; } break; case 'ALIAS': $servicegroups .= "'" . $this->serviceGroupsAlias[$key] . "',"; break; case 'ID': $servicegroups .= $key . ','; break; default: $servicegroups .= "'" . $key . "',"; break; } } $result = "''"; if (strlen($servicegroups)) { $result = trim($servicegroups, ','); } return $result; } /** * Service categories Getter * * @return array */ public function getServiceCategories() { return $this->serviceCategories; } /** * Get HostCategories * * @return array */ public function getHostCategories() { return $this->hostCategories; } /** * Service categories string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $escape * * @return string */ public function getServiceCategoriesString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } $serviceCategories = ''; foreach ($this->serviceCategories as $key => $value) { switch ($flag) { case 'NAME': if ($escape === true) { $serviceCategories .= "'" . CentreonDB::escape($value) . "',"; } else { $serviceCategories .= "'" . $value . "',"; } break; case 'ID': $serviceCategories .= $key . ','; break; default: $serviceCategories .= "'" . $key . "',"; break; } } $result = "''"; if (strlen($serviceCategories)) { $result = trim($serviceCategories, ','); } return $result; } /** * Get HostCategories String * * @param mixed $flag * @param mixed $escape * * @return string */ public function getHostCategoriesString($flag = null, $escape = true) { if ($flag !== null) { $flag = strtoupper($flag); } $hostCategories = ''; foreach ($this->hostCategories as $key => $value) { switch ($flag) { case 'NAME': if ($escape === true) { $hostCategories .= "'" . CentreonDB::escape($value) . "',"; } else { $hostCategories .= "'" . $value . "',"; } break; case 'ID': $hostCategories .= $key . ','; break; default: $hostCategories .= "'" . $key . "',"; break; } } $result = "''"; if (strlen($hostCategories)) { $result = trim($hostCategories, ','); } return $result; } /** * @param $hostId * * @return bool */ public function checkHost($hostId) { $pearDBO = CentreonDBInstance::getDbCentreonStorageInstance(); $hostArray = $this->getHostsArray('ID', $pearDBO); return (bool) (in_array($hostId, $hostArray)); } /** * @param $serviceId * * @return bool */ public function checkService($serviceId) { $pearDBO = CentreonDBInstance::getDbCentreonStorageInstance(); $serviceArray = $this->getServicesArray('ID', $pearDBO); return (bool) (in_array($serviceId, $serviceArray)); } /** * Hosts array Getter / same as getHostsString function * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $pearDBndo * @param $escape * * @return array|string */ public function getHostsArray($flag = null, $pearDBndo = null, $escape = true) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } if ($flag !== null) { $flag = strtoupper($flag); } switch ($flag) { case 'NAME': $query = 'SELECT DISTINCT h.host_id, h.name ' . 'FROM centreon_acl ca, hosts h ' . 'WHERE ca.host_id = h.host_id ' . 'AND group_id IN (' . implode(',', $groupIds) . ') ' . 'GROUP BY h.name, h.host_id ' . 'ORDER BY h.name ASC '; $fieldName = 'name'; break; default: $query = 'SELECT DISTINCT host_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'host_id'; break; } $hosts = []; $DBRES = CentreonDBInstance::getDbCentreonStorageInstance()->query($query); while ($row = $DBRES->fetchRow()) { $hosts[] = $escape === true ? CentreonDB::escape($row[$fieldName]) : $row[$fieldName]; } return $hosts; } /** * @param $tmpTableName * @param $db * @param $rows * @param $originTable * @param $force * @param $fields * * @return mixed */ public function getACLTemporaryTable( $tmpTableName, $db, $rows, $originTable = 'centreon_acl', $force = false, $fields = [], ) { if (! empty($this->tempTableArray[$tmpTableName]) && ! $force) { return $this->tempTableArray[$tmpTableName]; } if ($force) { $this->destroyTemporaryTable($tmpTableName); } $this->createTemporaryTable($tmpTableName, $db, $rows, $originTable, $fields); return $this->tempTableArray[$tmpTableName]; } /** * @param $db * @param $name * * @return void */ public function destroyTemporaryTable($db, $name = false): void { if (! $name) { foreach ($this->tempTableArray as $tmpTable) { $query = 'DROP TEMPORARY TABLE IF EXISTS ' . $tmpTable; $db->query($query); } } else { $query = 'DROP TEMPORARY TABLE IF EXISTS ' . $this->tempTableArray[$name]; $db->query($query); } } /** * @param $db * @param $fieldToJoin * @param $force * * @return string */ public function getACLHostsTemporaryTableJoin($db, $fieldToJoin, $force = false) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } $query = 'SELECT DISTINCT host_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $DBRES = $db->query($query); $rows = []; while ($row = $DBRES->fetchRow()) { $rows[] = $row; } $tableName = $this->getACLTemporaryTable('hosts', $db, $rows, 'centreon_acl', $force); return ' INNER JOIN ' . $tableName . ' ON ' . $tableName . '.host_id = ' . $fieldToJoin . ' '; } /** * @param $db * @param $fieldToJoin * @param $force * * @return false|string */ public function getACLServicesTemporaryTableJoin($db, $fieldToJoin, $force = false) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return false; } $query = 'SELECT DISTINCT service_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $DBRES = $db->query($query); $rows = []; while ($row = $DBRES->fetchRow()) { $rows[] = $row; } $tableName = $this->getACLTemporaryTable('services', $db, $rows, 'centreon_acl', $force); return ' INNER JOIN ' . $tableName . ' ON ' . $tableName . '.service_id = ' . $fieldToJoin . ' '; } /** * @param $db * @param $fieldToJoin * @param $force * * @return string */ public function getACLHostsTableJoin($db, $fieldToJoin, $force = false) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return ''; } $tempTableName = 'centreon_acl_' . self::generateRandomString(5); return ' INNER JOIN centreon_acl ' . $tempTableName . ' ON ' . $tempTableName . '.host_id = ' . $fieldToJoin . ' AND ' . $tempTableName . '.group_id IN (' . implode(',', $groupIds) . ') '; } /** * @param $db * @param $fieldToJoin * @param $force * * @return string */ public function getACLServicesTableJoin($db, $fieldToJoin, $force = false) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return ''; } $tempTableName = 'centreon_acl_' . self::generateRandomString(5); return ' INNER JOIN centreon_acl ' . $tempTableName . ' ON ' . $tempTableName . '.service_id = ' . $fieldToJoin . ' AND ' . $tempTableName . '.group_id IN (' . implode(',', $groupIds) . ') '; } /** * Hosts string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $pearDBndo * @param $escape * * @return string */ public function getHostsString($flag = null, $pearDBndo = null, $escape = true) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } if ($flag !== null) { $flag = strtoupper($flag); } switch ($flag) { case 'NAME': $query = 'SELECT DISTINCT h.host_id, h.name ' . 'FROM centreon_acl ca, hosts h ' . 'WHERE ca.host_id = h.host_id ' . 'AND group_id IN (' . implode(',', $groupIds) . ') ' . 'GROUP BY h.name, h.host_id ' . 'ORDER BY h.name ASC '; $fieldName = 'name'; break; default: $query = 'SELECT DISTINCT host_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'host_id'; break; } $hosts = ''; $DBRES = $pearDBndo->query($query); while ($row = $DBRES->fetchRow()) { if ($escape === true) { $hosts .= "'" . CentreonDB::escape($row[$fieldName]) . "',"; } elseif ($flag == 'ID') { $hosts .= $row[$fieldName] . ','; } else { $hosts .= "'" . $row[$fieldName] . "',"; } } $result = "''"; if (strlen($hosts)) { $result = trim($hosts, ','); } return $result; } /** * Services array Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $pearDBndo * @param $escape * * @return array|string */ public function getServicesArray($flag = null, $pearDBndo = null, $escape = true) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } if ($flag !== null) { $flag = strtoupper($flag); } switch ($flag) { case 'NAME': $query = 'SELECT DISTINCT s.service_id, s.description ' . 'FROM centreon_acl ca, services s ' . 'WHERE ca.service_id = s.service_id ' . 'AND group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'description'; break; default: $query = 'SELECT DISTINCT service_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'service_id'; break; } $services = []; $DBRES = $pearDBndo->query($query); $items = []; while ($row = $DBRES->fetchRow()) { if (isset($items[$row[$fieldName]])) { continue; } $items[$row[$fieldName]] = true; $services[] = $escape === true ? CentreonDB::escape($row[$fieldName]) : $row[$fieldName]; } return $services; } /** * Services string Getter * * Possible flags : * - ID => will return the id's of the element * - NAME => will return the names of the element * * @param $flag * @param $pearDBndo * @param $escape * * @return string */ public function getServicesString($flag = null, $pearDBndo = null, $escape = true) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } if ($flag !== null) { $flag = strtoupper($flag); } switch ($flag) { case 'NAME': $query = 'SELECT DISTINCT s.service_id, s.description ' . 'FROM centreon_acl ca, services s ' . 'WHERE ca.service_id = s.service_id ' . 'AND group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'description'; break; default: $query = 'SELECT DISTINCT service_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $fieldName = 'service_id'; break; } $services = ''; $DBRES = $pearDBndo->query($query); $items = []; while ($row = $DBRES->fetchRow()) { if (isset($items[$row[$fieldName]])) { continue; } $items[$row[$fieldName]] = true; if ($escape === true) { $services .= "'" . CentreonDB::escape($row[$fieldName]) . "',"; } elseif ($flag == 'ID') { $services .= $row[$fieldName] . ','; } else { $services .= "'" . $row[$fieldName] . "',"; } } $result = "''"; if (strlen($services)) { $result = trim($services, ','); } return $result; } /** * Get authorized host service ids * * @param $db CentreonDB * * @return string return id combinations like '14_26' (hostId_serviceId) */ public function getHostServiceIds($db) { $this->checkUpdateACL(); $groupIds = array_keys($this->accessGroups); if ($groupIds === []) { return "''"; } $hostsServices = ''; $query = 'SELECT DISTINCT host_id, service_id ' . 'FROM centreon_acl ' . 'WHERE group_id IN (' . implode(',', $groupIds) . ') '; $res = $db->query($query); while ($row = $res->fetchRow()) { $hostsServices .= "'" . $row['host_id'] . '_' . $row['service_id'] . "',"; } $result = "''"; if (strlen($hostsServices)) { $result = trim($hostsServices, ','); } return $result; } // Actions Getter /** * @return array */ public function getActions() { $this->checkUpdateACL(); return $this->actions; } /** * @return array */ public function getTopology() { $this->checkUpdateACL(); return $this->topology; } /** * Update topologystr value */ public function updateTopologyStr(): void { $this->setTopology(); $this->topologyStr = $this->getTopologyString(); } /** * @return string */ public function getTopologyString() { $this->checkUpdateACL(); $topology = array_keys($this->topology); $result = "''"; if ($topology !== []) { $result = implode(', ', $topology); } return $result; } /** * This functions returns a string that forms a condition of a query * i.e : " WHERE host_id IN ('1', '2', '3') " * or : " AND host_id IN ('1', '2', '3') " * * @param $condition * @param $field * @param $stringlist * * @return string */ public function queryBuilder($condition, $field, $stringlist) { $str = ''; if ($this->admin) { return $str; } if ($stringlist == '') { $stringlist = "''"; } $str .= ' ' . $condition . ' ' . $field . ' IN (' . $stringlist . ') '; return $str; } /** * Function that returns * * @param mixed $p * @param bool $checkAction * * @return int | 1 : if user is allowed to access the page * 0 : if user is NOT allowed to access the page */ public function page(mixed $p, bool $checkAction = false): int { $this->checkUpdateACL(); if ($this->admin) { return self::ACL_ACCESS_READ_WRITE; } if (isset($this->topology[$p])) { if ( $checkAction && $this->topology[$p] == self::ACL_ACCESS_READ_ONLY && isset($_REQUEST['o']) && $_REQUEST['o'] == 'a' ) { return self::ACL_ACCESS_NONE; } return (int) $this->topology[$p]; } return self::ACL_ACCESS_NONE; } /** * Function that checks if the user can execute the action * * 1 : user can execute it * 0 : user CANNOT execute it * * @param $action * * @return int */ public function checkAction($action) { $this->checkUpdateACL(); if ($this->admin || isset($this->actions[$action])) { return 1; } return 0; } /** * Function that returns the pair host/service by ID if $host_id is NULL * Otherwise, it returns all the services of a specific host * * @param CentreonDB $pearDBMonitoring access to centreon_storage database * @param bool $withServiceDescription to retrieve description of services * * @return array */ public function getHostsServices($pearDBMonitoring, $withServiceDescription = false) { $tab = []; if ($this->admin) { $req = $withServiceDescription ? ', s.service_description ' : ''; $query = 'SELECT h.host_id, s.service_id ' . $req . 'FROM host h ' . 'LEFT JOIN host_service_relation hsr on hsr.host_host_id = h.host_id ' . 'LEFT JOIN service s on hsr.service_service_id = s.service_id ' . "WHERE h.host_register = '1' "; $result = CentreonDBInstance::getDbCentreonInstance()->query($query); while ($row = $result->fetchRow()) { $tab[$row['host_id']][$row['service_id']] = $withServiceDescription ? $row['service_description'] : 1; } $result->closeCursor(); // Used By EventLogs page Only if ($withServiceDescription) { // Get Services attached to hostgroups $query = 'SELECT hgr.host_host_id, s.service_id, s.service_description ' . 'FROM hostgroup_relation hgr, service s, host_service_relation hsr ' . 'WHERE hsr.hostgroup_hg_id = hgr.hostgroup_hg_id ' . 'AND s.service_id = hsr.service_service_id ';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonHostcategories.class.php
centreon/www/class/centreonHostcategories.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonHostcategories */ class CentreonHostcategories { /** @var CentreonDB */ protected $db; /** * CentreonHostcategories constructor * * @param CentreonDB $pearDB */ public function __construct($pearDB) { $this->db = $pearDB; } /** * @param int $field * @return array */ public static function getDefaultValuesParameters($field) { $parameters = []; $parameters['currentObject']['table'] = 'hostcategories'; $parameters['currentObject']['id'] = 'hc_id'; $parameters['currentObject']['name'] = 'hc_name'; $parameters['currentObject']['comparator'] = 'hc_id'; switch ($field) { case 'hc_hosts': $parameters['type'] = 'relation'; $parameters['externalObject']['object'] = 'centreonHost'; $parameters['relationObject']['table'] = 'hostcategories_relation'; $parameters['relationObject']['field'] = 'host_host_id'; $parameters['relationObject']['comparator'] = 'hostcategories_hc_id'; break; case 'hc_hostsTemplate': $parameters['type'] = 'relation'; $parameters['externalObject']['object'] = 'centreonHosttemplates'; $parameters['relationObject']['table'] = 'hostcategories_relation'; $parameters['relationObject']['field'] = 'host_host_id'; $parameters['relationObject']['comparator'] = 'hostcategories_hc_id'; break; } return $parameters; } /** * @param array $values * @param array $options * * @throws PDOException * @return array */ public function getObjectForSelect2($values = [], $options = []) { global $centreon; $items = []; // get list of authorized host categories if (! $centreon->user->access->admin) { $hcAcl = $centreon->user->access->getHostCategories(); } $listValues = ''; $queryValues = []; if (! empty($values)) { foreach ($values as $v) { // As it happens that $v could be like "X,Y" when two hostgroups are selected, we added a second foreach $multiValues = explode(',', $v); foreach ($multiValues as $item) { $listValues .= ':sc' . $item . ', '; $queryValues['sc' . $item] = (int) $item; } } $listValues = rtrim($listValues, ', '); } else { $listValues .= '""'; } // get list of selected host categories $query = 'SELECT hc_id, hc_name FROM hostcategories ' . 'WHERE hc_id IN (' . $listValues . ') ORDER BY hc_name '; $stmt = $this->db->prepare($query); if ($queryValues !== []) { foreach ($queryValues as $key => $id) { $stmt->bindValue(':' . $key, $id, PDO::PARAM_INT); } } $stmt->execute(); while ($row = $stmt->fetch()) { // hide unauthorized host categories $hide = false; if (! $centreon->user->access->admin && count($hcAcl) && ! in_array($row['hc_id'], array_keys($hcAcl))) { $hide = true; } $items[] = ['id' => $row['hc_id'], 'text' => $row['hc_name'], 'hide' => $hide]; } return $items; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonManufacturer.class.php
centreon/www/class/centreonManufacturer.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonManufacturer */ class CentreonManufacturer { /** @var CentreonDB */ protected $db; /** * CentreonManufacturer constructor * * @param CentreonDB $db */ public function __construct($db) { $this->db = $db; } /** * @param array $values * @param array $options * * @throws PDOException * @return array */ public function getObjectForSelect2($values = [], $options = []) { $items = []; $listValues = ''; $queryValues = []; if (! empty($values)) { foreach ($values as $k => $v) { $listValues .= ':traps' . $v . ','; $queryValues['traps' . $v] = (int) $v; } $listValues = rtrim($listValues, ','); } else { $listValues .= '""'; } // get list of selected timeperiods $query = 'SELECT id, name FROM traps_vendor ' . 'WHERE id IN (' . $listValues . ') ORDER BY name '; $stmt = $this->db->prepare($query); if ($queryValues !== []) { foreach ($queryValues as $key => $id) { $stmt->bindValue(':' . $key, $id, PDO::PARAM_INT); } } $stmt->execute(); while ($row = $stmt->fetch()) { $items[] = ['id' => $row['id'], 'text' => $row['name']]; } return $items; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDBStatement.class.php
centreon/www/class/centreonDBStatement.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ // file centreon.config.php may not exist in test environment $configFile = realpath(__DIR__ . '/../../config/centreon.config.php'); if ($configFile !== false) { include_once $configFile; } require_once realpath(__DIR__ . '/centreonDB.class.php'); /** * Class * * @class CentreonDBStatement */ class CentreonDBStatement extends PDOStatement { /** * When data is retrieved from `numRows()` method, it is stored in `allFetched` * in order to be usable later without requesting one more time the database. * * @var array|null */ public $allFetched = null; /** @var CentreonLog */ private $log; /** * CentreonDBStatement constructor * * @param CentreonLog|null $log */ protected function __construct(?CentreonLog $log = null) { $this->log = $log; } /** * This method overloads PDO `fetch` in order to use the possible already * loaded data available in `allFetched`. * * @param int $mode * @param int $cursorOrientation * @param int $cursorOffset * * @return mixed */ public function fetch( int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0, ): mixed { if (is_null($this->allFetched)) { return parent::fetch($mode, $cursorOrientation, $cursorOffset); } if (count($this->allFetched) <= 0) { return false; } return array_shift($this->allFetched); } /** * This method wraps the Fetch method for legacy code compatibility * @return mixed */ public function fetchRow() { return $this->fetch(); } /** * Free resources. * * @return void */ public function free(): void { $this->closeCursor(); } /** * Counts the number of rows returned by the query.\ * This method fetches data if needed and store it in `allFetched` * in order to be usable later without requesting database again. * * @return int */ public function numRows() { if (is_null($this->allFetched)) { $this->allFetched = $this->fetchAll(); } return count($this->allFetched); } /** * This method wraps the PDO `execute` method and manages failures logging * * @param $parameters * * @throws PDOException * @return bool */ public function execute($parameters = null): bool { $this->allFetched = null; try { $result = parent::execute($parameters); } catch (PDOException $e) { $string = str_replace('`', '', $this->queryString); $string = str_replace('*', "\*", $string); $this->log->insertLog(2, $e->getMessage() . ' QUERY : ' . $string . ', ' . json_encode($parameters)); throw $e; } return $result; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonData.class.php
centreon/www/class/centreonData.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonData * @description Object used for storing and accessing specific data * @version 2.5.0 * @since 2.5.0 * @author Sylvestre Ho <sho@centreon.com> */ class CentreonData { /** * Instance of Centreon Template * * @var CentreonData */ private static $instance = null; /** * List of javascript data * * @var array */ private $jsData = []; /** * Pass data to javascript * * @param string $key * @param string $value * @throws Exception * @return void */ public function addJsData($key, $value): void { if (isset($this->jsData[$key])) { throw new Exception( sprintf('Key %s in Javascript Data already used', $key) ); } $this->jsData[$key] = $value; } /** * Get javascript data * * @return array */ public function getJsData() { return $this->jsData; } /** * Get a instance of Centreon_Template * * @return CentreonData */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new CentreonData(); } return self::$instance; } } // vim: set ai softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonResources.class.php
centreon/www/class/centreonResources.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonResources */ class CentreonResources { /** @var CentreonDB */ protected $db; /** * CentreonResources constructor * * @param CentreonDB $pearDB */ public function __construct($pearDB) { $this->db = $pearDB; } /** * @param int $field * * @return array */ public static function getDefaultValuesParameters($field) { $parameters = []; $parameters['currentObject']['table'] = 'cfg_resource'; $parameters['currentObject']['id'] = 'resource_id'; $parameters['currentObject']['name'] = 'resource_name'; $parameters['currentObject']['comparator'] = 'resource_id'; switch ($field) { case 'instance_id': $parameters['type'] = 'relation'; $parameters['externalObject']['object'] = 'centreonInstance'; $parameters['relationObject']['table'] = 'cfg_resource_instance_relations'; $parameters['relationObject']['field'] = 'instance_id'; $parameters['relationObject']['comparator'] = 'resource_id'; break; } return $parameters; } /** * @param CentreonDB $db * @param string $name * * @throws Exception * @return array */ public static function getResourceByName($db, $name) { $queryResources = "SELECT * FROM cfg_resource WHERE resource_name = '{$name}'"; $resultQueryResources = $db->query($queryResources); $finalResource = []; while ($resultResources = $resultQueryResources->fetchRow()) { $finalResource = $resultResources; } if (count($finalResource) === 0) { throw new Exception('No central broker found', 500); } return $finalResource; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphVirtualMetric.class.php
centreon/www/class/centreonGraphVirtualMetric.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonGraphVirtualMetric */ class CentreonGraphVirtualMetric { /** @var CentreonDB */ protected $db; /** * CentreonGraphVirtualMetric constructor * * @param CentreonDB $pearDB */ public function __construct($pearDB) { $this->db = $pearDB; } /** * @param int $field * @return array */ public static function getDefaultValuesParameters($field) { $parameters = []; $parameters['currentObject']['table'] = 'virtual_metrics'; $parameters['currentObject']['id'] = 'vmetric_id'; $parameters['currentObject']['name'] = 'vmetric_name'; $parameters['currentObject']['comparator'] = 'vmetric_id'; switch ($field) { case 'host_id': $parameters['type'] = 'simple'; $parameters['currentObject']['additionalField'] = 'service_id'; $parameters['externalObject']['object'] = 'centreonService'; break; } return $parameters; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonInstance.class.php
centreon/www/class/centreonInstance.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class CentreonInstance * @description Class for handling Instances */ class CentreonInstance { /** @var array */ public $paramsByName; /** @var CentreonDB */ protected $db; /** @var CentreonDB */ protected $dbo; /** @var array */ protected $params; /** @var array */ protected $instances; /** @var CentreonInstance|null */ private static ?CentreonInstance $staticInstance = null; /** * CentreonInstance constructor * * @param CentreonDB $db * @param CentreonDB|null $dbo * * @throws PDOException */ public function __construct($db, $dbo = null) { $this->db = $db; if (! empty($dbo)) { $this->dbo = $dbo; } $this->instances = []; $this->initParams(); } /** * @param CentreonDB $db * @param CentreonDB|null $dbo * * @throws PDOException * @return CentreonInstance */ public static function getInstance(CentreonDB $db, ?CentreonDB $dbo = null): CentreonInstance { return self::$staticInstance ??= new self($db, $dbo); } /** * Get instance_id and name from instances ids * * @param int[] $pollerIds * * @throws PDOException * @return array $pollers [['instance_id => integer, 'name' => string],...] */ public function getInstancesMonitoring($pollerIds = []) { $pollers = []; if (! empty($pollerIds)) { /* checking here that the array provided as parameter * is exclusively made of integers (servicegroup ids) */ $filteredPollerIds = $this->filteredArrayId($pollerIds); $pollerParams = []; if ($filteredPollerIds !== []) { /* * Building the pollerParams hash table in order to correctly * bind ids as ints for the request. */ foreach ($filteredPollerIds as $index => $filteredPollerId) { $pollerParams[':pollerId' . $index] = $filteredPollerId; } $stmt = $this->db->prepare( 'SELECT i.instance_id, i.name FROM instances i ' . 'WHERE i.instance_id IN ( ' . implode(',', array_keys($pollerParams)) . ' )' ); foreach ($pollerParams as $index => $value) { $stmt->bindValue($index, $value, PDO::PARAM_INT); } $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $pollers[] = [ 'id' => $row['instance_id'], 'name' => $row['name'], ]; } } } return $pollers; } /** * Get Parameter * * @param mixed $instance * @param string $paramName * @return string */ public function getParam($instance, $paramName) { if (is_numeric($instance)) { if (isset($this->params[$instance], $this->params[$instance][$paramName])) { return $this->params[$instance][$paramName]; } } elseif (isset($this->paramsByName[$instance], $this->paramsByName[$instance][$paramName])) { return $this->paramsByName[$instance][$paramName]; } return null; } /** * Get Instances * * @return array */ public function getInstances() { return $this->instances; } /** * Get command data from poller id * * @param int $pollerId * * @throws PDOException * @return array */ public function getCommandData($pollerId) { $sql = 'SELECT c.command_id, c.command_name, c.command_line FROM command c, poller_command_relations pcr WHERE pcr.poller_id = ? AND pcr.command_id = c.command_id ORDER BY pcr.command_order'; $res = $this->db->prepare($sql); $res->execute([$pollerId]); $arr = []; while ($row = $res->fetchRow()) { $arr[] = $row; } return $arr; } /** * Return list of commands used by poller * * @param int|null $pollerId * * @throws PDOException * @return array */ public function getCommandsFromPollerId($pollerId = null) { $arr = []; $i = 0; if (! isset($_REQUEST['pollercmd']) && $pollerId) { $sql = 'SELECT command_id FROM poller_command_relations WHERE poller_id = ? ORDER BY command_order'; $res = $this->db->prepare($sql); $res->execute([$pollerId]); while ($row = $res->fetchRow()) { $arr[$i]['pollercmd_#index#'] = $row['command_id']; $i++; } } elseif (isset($_REQUEST['pollercmd'])) { foreach ($_REQUEST['pollercmd'] as $val) { $arr[$i]['pollercmd_#index#'] = $val; $i++; } } return $arr; } /** * Set post-restart commands * * @param int $pollerId * @param array $commands * * @throws PDOException * @return void */ public function setCommands($pollerId, $commands): void { $this->db->query('DELETE FROM poller_command_relations WHERE poller_id = ' . $this->db->escape($pollerId)); $stored = []; $i = 1; foreach ($commands as $value) { if ($value != '' && ! isset($stored[$value]) ) { $this->db->query('INSERT INTO poller_command_relations (`poller_id`, `command_id`, `command_order`) VALUES (' . $this->db->escape($pollerId) . ', ' . $this->db->escape($value) . ', ' . $i . ')'); $stored[$value] = true; $i++; } } } /** * @param array $values * @param array $options * * @throws PDOException * @return array */ public function getObjectForSelect2($values = [], $options = []) { global $centreon; $selectedInstances = ''; $items = []; if (empty($values)) { return $items; } // get list of authorized pollers if (! $centreon->user->access->admin) { $pollerAcl = $centreon->user->access->getPollers(); } $listValues = ''; $queryValues = []; foreach ($values as $k => $v) { $multipleValues = explode(',', $v); foreach ($multipleValues as $item) { $listValues .= ':pId_' . $item . ', '; $queryValues['pId_' . $item] = (int) $item; } } $listValues = rtrim($listValues, ', '); $selectedInstances .= " AND rel.instance_id IN ({$listValues}) "; $query = 'SELECT DISTINCT p.name as name, p.id as id FROM cfg_resource r, nagios_server p, ' . 'cfg_resource_instance_relations rel ' . ' WHERE r.resource_id = rel.resource_id' . ' AND p.id = rel.instance_id ' . ' AND p.id IN (' . $listValues . ')' . $selectedInstances . ' ORDER BY p.name'; $stmt = $this->db->prepare($query); foreach ($queryValues as $key => $id) { $stmt->bindValue(':' . $key, $id, PDO::PARAM_INT); } $stmt->execute(); while ($data = $stmt->fetch()) { $hide = false; if ( ! $centreon->user->access->admin && count($pollerAcl) && ! in_array($data['id'], array_keys($pollerAcl)) ) { $hide = true; } $items[] = [ 'id' => $data['id'], 'text' => HtmlSanitizer::createFromString($data['name'])->sanitize()->getString(), 'hide' => $hide, ]; } return $items; } /** * @param string $instanceName * * @throws PDOException * @return array */ public function getHostsByInstance($instanceName) { $instanceList = []; $query = 'SELECT host_name, name ' . ' FROM host h, nagios_server ns, ns_host_relation nshr ' . " WHERE ns.name = '" . $this->db->escape($instanceName) . "'" . ' AND nshr.host_host_id = h.host_id ' . " AND h.host_activate = '1' " . ' ORDER BY h.host_name'; $result = $this->db->query($query); while ($elem = $result->fetchrow()) { $instanceList[] = ['host' => $elem['host_name'], 'name' => $instanceName]; } return $instanceList; } /** * @param string $instanceName * * @throws PDOException * @return mixed */ public function getInstanceId($instanceName) { $query = 'SELECT ns.id ' . ' FROM nagios_server ns ' . " WHERE ns.name = '" . $this->db->escape($instanceName) . "'"; $result = $this->db->query($query); return $result->fetchrow(); } /** * Initialize Parameters * * @throws PDOException * @return void */ protected function initParams() { $this->params = []; $this->paramsByName = []; $query = 'SELECT id, name, localhost, last_restart, ns_ip_address FROM nagios_server'; $res = $this->db->query($query); while ($row = $res->fetchRow()) { $instanceId = $row['id']; $instanceName = $row['name']; $this->instances[$instanceId] = $instanceName; $this->params[$instanceId] = []; $this->paramsByName[$instanceName] = []; foreach ($row as $key => $value) { $this->params[$instanceId][$key] = $value; $this->paramsByName[$instanceName][$key] = $value; } } } /** * Returns a filtered array with only integer ids * * @param int[] $ids * @return int[] filtered */ private function filteredArrayId(array $ids): array { return array_filter($ids, function ($id) { return is_numeric($id); }); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params.class.php
centreon/www/class/centreonWidget/Params.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/Params/Interface.class.php'; /** * Class * * @class CentreonWidgetParamsException */ class CentreonWidgetParamsException extends Exception { } /** * Class * * @class CentreonWidgetParams */ abstract class CentreonWidgetParams implements CentreonWidgetParamsInterface { /** @var int */ public $userId; /** @var mixed */ public $element; /** @var */ protected static $instances; /** @var CentreonDB */ protected $db; /** @var HTML_Quickform */ protected $quickform; /** @var mixed */ protected $params; /** @var array */ protected $userGroups = []; /** @var false */ protected $trigger = false; /** @var CentreonACL */ protected $acl; /** @var CentreonDB */ protected $monitoringDb; /** @var string[] */ protected $multiType = ['serviceMulti']; /** * Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { $this->db = $db; $this->quickform = $quickform; $this->userId = $userId; $query = 'SELECT contactgroup_cg_id FROM contactgroup_contact_relation WHERE contact_contact_id = ' . $this->db->escape($this->userId); $res = $this->db->query($query); while ($row = $res->fetchRow()) { $this->userGroups[$row['contactgroup_cg_id']] = $row['contactgroup_cg_id']; } $this->acl = new CentreonACL($userId); $this->monitoringDb = new CentreonDB('centstorage'); } /** * Factory * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param $className * @param int $userId * * @return mixed */ public static function factory($db, $quickform, $className, $userId) { if (! isset(self::$instances[$className])) { self::$instances[$className] = new $className($db, $quickform, $userId); } return self::$instances[$className]; } /** * Init * * @param array $params * @return void */ public function init($params): void { $this->params = $params; } /** * Set Value * * @param array $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); if (in_array($params['ft_typename'], $this->multiType)) { if (is_string($userPref) && strpos($userPref, ',') > -1) { $userPref = explode(',', $userPref); } } if (isset($userPref)) { $this->quickform->setDefaults(['param_' . $params['parameter_id'] => $userPref]); } elseif (isset($params['default_value']) && $params['default_value'] != '') { $this->quickform->setDefaults(['param_' . $params['parameter_id'] => $params['default_value']]); } } /** * Get Element * * @return HTML_Quickform */ public function getElement() { return $this->element; } /** * Get List Values * * @param int $paramId * * @throws PDOException * @return array */ public function getListValues($paramId) { $query = 'SELECT option_name, option_value FROM widget_parameters_multiple_options WHERE parameter_id = ' . $this->db->escape($paramId); $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['option_value']] = $row['option_name']; } return $tab; } /** * @return false */ public function getTrigger() { return $this->trigger; } /** * Get User Preferences * * @param array $params * * @throws PDOException * @return mixed */ protected function getUserPreferences($params) { $query = 'SELECT preference_value FROM widget_preferences wp, widget_views wv, custom_view_user_relation cvur WHERE wp.parameter_id = ' . $this->db->escape($params['parameter_id']) . ' AND wp.widget_view_id = wv.widget_view_id AND wv.widget_id = ' . $this->db->escape($params['widget_id']) . ' AND wv.custom_view_id = cvur.custom_view_id AND wp.user_id = ' . $this->db->escape($this->userId) . ' AND (cvur.user_id = wp.user_id'; if (count($this->userGroups)) { $cglist = implode(',', $this->userGroups); $query .= " OR cvur.usergroup_id IN ({$cglist}) "; } $query .= ') AND cvur.custom_view_id = ' . $this->db->escape($params['custom_view_id']) . ' LIMIT 1'; $res = $this->db->query($query); if ($res->rowCount()) { $row = $res->fetchRow(); return $row['preference_value']; } return null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Range.class.php
centreon/www/class/centreonWidget/Params/Range.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsRange */ class CentreonWidgetParamsRange extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsRange Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $query = 'SELECT min_range, max_range, step ' . 'FROM widget_parameters_range ' . 'WHERE parameter_id = ' . $this->db->escape($params['parameter_id']); $res = $this->db->query($query); $row = $res->fetchRow(); $min = $row['min_range']; $max = $row['max_range']; $step = $row['step']; $tab = []; for ($i = $min; $i <= $max; $i += $step) { $tab[$i] = $i; } $this->element = $this->quickform->addElement( 'select', 'param_' . $params['parameter_id'], $params['parameter_name'], $tab ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Compare.class.php
centreon/www/class/centreonWidget/Params/Compare.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsCompare */ class CentreonWidgetParamsCompare extends CentreonWidgetParams { /** @var HTML_QuickForm_element */ public $element; /** * CentreonWidgetParamsCompare Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $elems = []; $operands = [null => null, 'gt' => '>', 'lt' => '<', 'gte' => '>=', 'lte' => '<=', 'eq' => '=', 'ne' => '!=', 'like' => 'LIKE', 'notlike' => 'NOT LIKE', 'regex' => 'REGEXP', 'notregex' => 'NOT REGEXP']; $elems[] = $this->quickform->addElement('select', 'op_' . $params['parameter_id'], '', $operands); $elems[] = $this->quickform->addElement( 'text', 'cmp_' . $params['parameter_id'], $params['parameter_name'], ['size' => 30] ); $this->element = $this->quickform->addGroup( $elems, 'param_' . $params['parameter_id'], $params['parameter_name'], '&nbsp;' ); } } /** * @param $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); if (isset($userPref)) { $target = $userPref; } elseif (isset($params['default_value']) && $params['default_value'] != '') { $target = $params['default_value']; } if (isset($target)) { if (preg_match('/(gt |lt |gte |lte |eq |ne |like |notlike |regex |notregex )(.+)/', $target, $matches)) { $op = trim($matches[1]); $val = trim($matches[2]); } if (isset($op, $val)) { $this->quickform->setDefaults(['op_' . $params['parameter_id'] => $op, 'cmp_' . $params['parameter_id'] => $val]); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Select2.class.php
centreon/www/class/centreonWidget/Params/Select2.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsSelect2 */ class CentreonWidgetParamsSelect2 extends CentreonWidgetParams { /** @var HTML_QuickForm_element */ public $element; /** * CentreonWidgetParamsSelect2 Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $this->element = $this->quickform->addElement( 'select2', 'param_' . $params['parameter_id'], $params['parameter_name'], [], $this->getParameters() ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Sort.class.php
centreon/www/class/centreonWidget/Params/Sort.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsSort */ class CentreonWidgetParamsSort extends CentreonWidgetParams { /** @var HTML_QuickForm_element */ public $element; /** * CentreonWidgetParamsSort Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $elems = []; $operands = [null => null, 'ASC' => 'ASC', 'DESC' => 'DESC']; $columnList = $this->getListValues($params['parameter_id']); $elems[] = $this->quickform->addElement('select', 'column_' . $params['parameter_id'], '', $columnList); $elems[] = $this->quickform->addElement('select', 'order_' . $params['parameter_id'], '', $operands); $this->element = $this->quickform->addGroup( $elems, 'param_' . $params['parameter_id'], $params['parameter_name'], '&nbsp;' ); } } /** * @param $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); if (isset($userPref)) { $target = $userPref; } elseif (isset($params['default_value']) && $params['default_value'] != '') { $target = $params['default_value']; } if (isset($target)) { if (preg_match("/([a-zA-Z\._]+) (ASC|DESC)/", $target, $matches)) { $column = trim($matches[1]); $order = trim($matches[2]); } if (isset($order, $column)) { $this->quickform->setDefaults(['order_' . $params['parameter_id'] => $order, 'column_' . $params['parameter_id'] => $column]); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Boolean.class.php
centreon/www/class/centreonWidget/Params/Boolean.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsBoolean */ class CentreonWidgetParamsBoolean extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsBoolean Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param array $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $this->element = $this->quickform->addElement( 'checkbox', 'param_' . $params['parameter_id'], $params['parameter_name'] ); } } /** * @param array $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); $cbVal = false; if (isset($userPref)) { $cbVal = $userPref; } elseif (isset($params['default_value']) && $params['default_value'] != '') { if ($params['default_value'] == 1) { $cbVal = true; } } $cb = $this->quickform->getElement('param_' . $params['parameter_id']); $cb->setChecked($cbVal); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Password.class.php
centreon/www/class/centreonWidget/Params/Password.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsPassword */ class CentreonWidgetParamsPassword extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsPassword Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $this->element = $this->quickform->addElement( 'password', 'param_' . $params['parameter_id'], $params['parameter_name'], ['size' => 30] ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Interface.class.php
centreon/www/class/centreonWidget/Params/Interface.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Interface * * @class CentreonWidgetParamsInterface */ interface CentreonWidgetParamsInterface { /** * @param CentreonDB $db * @param HTML_QuickForm $quickform * @param string $className * @param int $userId * * @return mixed */ public static function factory($db, $quickform, $className, $userId); /** * @param array $params * * @return mixed */ public function init($params); /** * @param array $params * * @return mixed */ public function setValue($params); /** * @return mixed */ public function getElement(); /** * @param mixed $paramId * * @return mixed */ public function getListValues($paramId); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/List.class.php
centreon/www/class/centreonWidget/Params/List.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsList */ class CentreonWidgetParamsList extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsList Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error|PDOException * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $tab = $this->getListValues($params['parameter_id']); $this->element = $this->quickform->addElement( 'select', 'param_' . $params['parameter_id'], $params['parameter_name'], $tab ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Hidden.class.php
centreon/www/class/centreonWidget/Params/Hidden.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsHidden */ class CentreonWidgetParamsHidden extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsHidden Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $this->element = $this->quickform->addElement( 'hidden', 'param_' . $params['parameter_id'] ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Text.class.php
centreon/www/class/centreonWidget/Params/Text.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsText */ class CentreonWidgetParamsText extends CentreonWidgetParams { /** @var HTML_QuickForm_element */ public $element; /** * CentreonWidgetParamsText Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param array $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $this->element = $this->quickform->addElement( 'text', 'param_' . $params['parameter_id'], $params['parameter_name'], ['size' => 30] ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Date.class.php
centreon/www/class/centreonWidget/Params/Date.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Params.class.php'; /** * Class * * @class CentreonWidgetParamsDate */ class CentreonWidgetParamsDate extends CentreonWidgetParams { /** @var HTML_QuickForm_Element */ public $element; /** * CentreonWidgetParamsDate Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $params * * @throws HTML_QuickForm_Error * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $elems = []; $elems[] = $this->quickform->addElement( 'text', 'from_' . $params['parameter_id'], _('From'), ['size' => 10, 'class' => 'datepicker'] ); $elems[] = $this->quickform->addElement( 'text', 'to_' . $params['parameter_id'], _('To'), ['size' => 10, 'class' => 'datepicker'] ); $this->element = $this->quickform->addGroup( $elems, 'param_' . $params['parameter_id'], $params['parameter_name'], '&nbsp;to&nbsp;' ); } } /** * @param $params * * @throws CentreonWidgetParamsException * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); if (isset($userPref)) { $target = $userPref; } elseif (isset($params['default_value']) && $params['default_value'] != '') { $target = $params['default_value']; } if (isset($target)) { $tab = explode(',', $target); if (! isset($tab[0]) || ! isset($tab[1])) { throw new CentreonWidgetParamsException('Incorrect date format found in database'); } $this->quickform->setDefaults(['from_' . $params['parameter_id'] => $tab[0], 'to_' . $params['parameter_id'] => $tab[1]]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostCategories.class.php
centreon/www/class/centreonWidget/Params/Connector/HostCategories.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostCategories */ class CentreonWidgetParamsConnectorHostCategories extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorHostCategories constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = "SELECT hc_id, hc_name FROM hostcategories WHERE hc_activate = '1' "; $query .= ' ORDER BY hc_name '; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['hc_id']] = $row['hc_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Host.class.php
centreon/www/class/centreonWidget/Params/Connector/Host.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHost */ class CentreonWidgetParamsConnectorHost extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorHost constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = 'SELECT host_id, host_name ' . 'FROM host ' . "WHERE host_activate = '1' " . "AND host_register = '1' "; $query .= $this->acl->queryBuilder( 'AND', 'host_id', $this->acl->getHostsString('ID', $this->monitoringDb) ); $query .= ' ORDER BY host_name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['host_id']] = $row['host_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceTemplate.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceTemplate.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServiceTemplate */ class CentreonWidgetParamsConnectorServiceTemplate extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorServiceTemplate constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = 'SELECT service_id, service_description FROM service ' . "WHERE service_activate = '1' " . "AND service_register = '0' " . 'ORDER BY service_description'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['service_id']] = $row['service_description']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceCategories.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceCategories.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServiceCategories */ class CentreonWidgetParamsConnectorServiceCategories extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorServiceCategories constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = "SELECT sc_id, sc_name FROM service_categories WHERE sc_activate = '1' "; $query .= ' ORDER BY sc_name '; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['sc_id']] = $row['sc_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/PollerMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/PollerMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorPollerMulti */ class CentreonWidgetParamsConnectorPollerMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorPollerMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array|mixed */ public function getParameters() { static $tab; if (! isset($tab)) { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_poller&action=list'; $attrPollers = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonInstance']; $tab = $attrPollers; } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostSeverityMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/HostSeverityMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Creation of a new connector for the host severity that use the centreonHostcategories object * with configuration from centreon_configuration_host_severity file */ /** * Class * * @class CentreonWidgetParamsConnectorHostSeverityMulti */ class CentreonWidgetParamsConnectorHostSeverityMulti extends CentreonWidgetParamsSelect2 { /** * @return array */ public function getParameters() { $path = './api/internal.php?object=centreon_configuration_hostcategory&action=list&t=s'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonHostcategories']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceCategory.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceCategory.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServiceCategory */ class CentreonWidgetParamsConnectorServiceCategory extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorServiceCategory constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = "SELECT sc_id AS id, sc_name AS name FROM service_categories WHERE sc_activate = '1'"; $query .= ' ORDER BY name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['id']] = $row['name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Hostgroup.class.php
centreon/www/class/centreonWidget/Params/Connector/Hostgroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostgroup */ class CentreonWidgetParamsConnectorHostgroup extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorHostgroup constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = "SELECT hg_id, hg_name FROM hostgroup WHERE hg_activate = '1' "; $query .= $this->acl->queryBuilder('AND', 'hg_id', $this->acl->getHostGroupsString()); $query .= ' ORDER BY hg_name '; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['hg_id']] = $row['hg_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostTemplate.class.php
centreon/www/class/centreonWidget/Params/Connector/HostTemplate.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostTemplate */ class CentreonWidgetParamsConnectorHostTemplate extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorHostTemplate constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = 'SELECT host_id, host_name ' . 'FROM host ' . "WHERE host_activate = '1' " . "AND host_register = '0' " . 'ORDER BY host_name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['host_id']] = $row['host_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Metric.class.php
centreon/www/class/centreonWidget/Params/Connector/Metric.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorMetric */ class CentreonWidgetParamsConnectorMetric extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorMetric constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = 'SELECT metric_id, metric_name FROM metrics WHERE to_delete = 0 '; $query .= ' ORDER BY metric_name '; $res = $this->monitoringDb->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['metric_id']] = $row['metric_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostCategory.class.php
centreon/www/class/centreonWidget/Params/Connector/HostCategory.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostCategory */ class CentreonWidgetParamsConnectorHostCategory extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorHostCategory constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = 'SELECT hc_id AS id, hc_name AS name ' . 'FROM hostcategories ' . "WHERE hc_activate = '1' " . 'ORDER BY name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['id']] = $row['name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Poller.class.php
centreon/www/class/centreonWidget/Params/Connector/Poller.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorPoller */ class CentreonWidgetParamsConnectorPoller extends CentreonWidgetParamsList { /** @var int */ public $userId; /** * CentreonWidgetParamsConnectorPoller constructor * * @param $db * @param $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $tab = [null => null]; $userACL = new CentreonACL($this->userId); $isContactAdmin = $userACL->admin; $request = 'SELECT SQL_CALC_FOUND_ROWS id, name FROM nagios_server ns'; if (! $isContactAdmin) { $request .= ' INNER JOIN acl_resources_poller_relations arpr ON ns.id = arpr.poller_id INNER JOIN acl_resources res ON arpr.acl_res_id = res.acl_res_id INNER JOIN acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN acl_groups ag ON argr.acl_group_id = ag.acl_group_id LEFT JOIN acl_group_contacts_relations agcr ON ag.acl_group_id = agcr.acl_group_id LEFT JOIN acl_group_contactgroups_relations agcgr ON ag.acl_group_id = agcgr.acl_group_id LEFT JOIN contactgroup_contact_relation cgcr ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id WHERE (agcr.contact_contact_id = :userId OR cgcr.contact_contact_id = :userId)'; } $request .= ! $isContactAdmin ? ' AND' : ' WHERE'; $request .= " ns_activate = '1' ORDER BY name"; $statement = $this->db->prepare($request); if (! $isContactAdmin) { $statement->bindValue(':userId', $this->userId, PDO::PARAM_INT); } $statement->execute(); $entriesCount = $this->db->query('SELECT FOUND_ROWS()'); if ($entriesCount !== false && ($total = $entriesCount->fetchColumn()) !== false) { // it means here that there is poller relations with this user if ((int) $total === 0) { // if no relations found for this user it means that he can see all poller available $statement = $this->db->query( "SELECT id, name FROM nagios_server WHERE ns_activate = '1'" ); } while (($record = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { $tab[$record['id']] = $record['name']; } } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/MetricMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/MetricMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorMetricMulti */ class CentreonWidgetParamsConnectorMetricMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorMetricMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './api/internal.php?object=centreon_metric&action=listByService'; return [ 'datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonMetrics', ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostGroupMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/HostGroupMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostGroupMulti */ class CentreonWidgetParamsConnectorHostGroupMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorHostGroupMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonHostgroups']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostCategoriesMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/HostCategoriesMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostCategoriesMulti */ class CentreonWidgetParamsConnectorHostCategoriesMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorHostCategoriesMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostcategory&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonHostcategories']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServiceMulti */ class CentreonWidgetParamsConnectorServiceMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorServiceMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonService']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/HostMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/HostMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorHostMulti */ class CentreonWidgetParamsConnectorHostMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorHostMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonHost']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Servicegroup.class.php
centreon/www/class/centreonWidget/Params/Connector/Servicegroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServicegroup */ class CentreonWidgetParamsConnectorServicegroup extends CentreonWidgetParamsList { /** * CentreonWidgetParamsConnectorServicegroup constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $query = "SELECT sg_id, sg_name FROM servicegroup WHERE sg_activate = '1' "; $query .= $this->acl->queryBuilder('AND', 'sg_id', $this->acl->getServiceGroupsString()); $query .= ' ORDER BY sg_name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['sg_id']] = $row['sg_name']; } } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/Service.class.php
centreon/www/class/centreonWidget/Params/Connector/Service.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../List.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorService */ class CentreonWidgetParamsConnectorService extends CentreonWidgetParamsList { /** @var HTML_QuickForm_element */ public $element; /** * CentreonWidgetParamsConnectorService constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); $this->trigger = true; } /** * @param $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function init($params): void { parent::init($params); if (isset($this->quickform)) { $tab = $this->getListValues($params['parameter_id']); $triggerSource = './include/home/customViews/triggers/loadServiceFromHost.php'; $this->element = $this->quickform->addElement( 'select', 'param_trigger_' . $params['parameter_id'], 'Host', $tab, ['onchange' => 'javascript:loadFromTrigger("' . $triggerSource . '", ' . $params['parameter_id'] . ', this.value);'] ); $userPref = $this->getUserPreferences($params); $svcTab = []; if (isset($userPref)) { [$hostId, $serviceId] = explode('-', $userPref); $svcTab = $this->getServiceIds($hostId); } $this->quickform->addElement( 'select', 'param_' . $params['parameter_id'], $params['parameter_name'], $svcTab ); } } /** * @param $paramId * * @throws PDOException * @return mixed|null[] */ public function getListValues($paramId) { static $tab; if (! isset($tab)) { $aclString = $this->acl->queryBuilder( 'AND', 'host_id', $this->acl->getHostsString( 'ID', $this->monitoringDb ) ); $query = "SELECT host_id, host_name FROM host WHERE host_activate = '1' AND host_register = '1' "; $query .= $aclString; // Add virtual host 'Meta' in the list if it exists and if ACL allows it $query .= "UNION SELECT host_id, 'Meta' FROM host WHERE host_register = '2' AND host_name = '_Module_Meta' "; $query .= $aclString; $query .= ' ORDER BY host_name'; $res = $this->db->query($query); $tab = [null => null]; while ($row = $res->fetchRow()) { $tab[$row['host_id']] = $row['host_name']; } } return $tab; } /** * Set Value * * @param array $params * * @throws HTML_QuickForm_Error * @throws PDOException * @return void */ public function setValue($params): void { $userPref = $this->getUserPreferences($params); if (isset($userPref)) { [$hostId, $serviceId] = explode('-', $userPref); $this->quickform->setDefaults(['param_trigger_' . $params['parameter_id'] => $hostId]); $this->quickform->setDefaults(['param_' . $params['parameter_id'] => $userPref]); } } /** * Get service id from host id * * @param int $hostId * * @throws PDOException * @return array */ protected function getServiceIds($hostId) { $aclString = $this->acl->queryBuilder( 'AND', 's.service_id', $this->acl->getServicesString('ID', $this->monitoringDb) ); $sql = 'SELECT service_id, service_description, display_name FROM service s, host_service_relation hsr WHERE hsr.host_host_id = ' . $this->db->escape($hostId) . ' AND hsr.service_service_id = s.service_id '; $sql .= $aclString; $sql .= ' UNION '; $sql .= ' SELECT service_id, service_description, display_name FROM service s, host_service_relation hsr, hostgroup_relation hgr WHERE hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND hgr.host_host_id = ' . $this->db->escape($hostId) . ' AND hsr.service_service_id = s.service_id '; $sql .= $aclString; $sql .= ' ORDER BY service_description '; $res = $this->db->query($sql); $tab = []; while ($row = $res->fetchRow()) { // For meta services, use display_name column instead of service_description $serviceDescription = (preg_match('/meta_/', $row['service_description'])) ? $row['display_name'] : $row['service_description']; $tab[$hostId . '-' . $row['service_id']] = $serviceDescription; } return $tab; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceGroupMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceGroupMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Class * * @class CentreonWidgetParamsConnectorServiceGroupMulti */ class CentreonWidgetParamsConnectorServiceGroupMulti extends CentreonWidgetParamsSelect2 { /** * CentreonWidgetParamsConnectorServiceGroupMulti constructor * * @param $db * @param $quickform * @param $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonServicegroups']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget/Params/Connector/ServiceSeverityMulti.class.php
centreon/www/class/centreonWidget/Params/Connector/ServiceSeverityMulti.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require_once __DIR__ . '/../Select2.class.php'; /** * Creation of a new connector for the host severity that use the centreonHostcategories object * with configuration from centreon_configuration_host_severity file */ /** * Class * * @class CentreonWidgetParamsConnectorServiceSeverityMulti */ class CentreonWidgetParamsConnectorServiceSeverityMulti extends CentreonWidgetParamsSelect2 { /** * Constructor * * @param CentreonDB $db * @param HTML_Quickform $quickform * @param int $userId * * @throws PDOException */ public function __construct($db, $quickform, $userId) { parent::__construct($db, $quickform, $userId); } /** * @return array */ public function getParameters() { $path = './api/internal.php?object=centreon_configuration_service_severity&action=list'; return ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $path, 'multiple' => true, 'linkedObject' => 'centreonServicecategories']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonContact.class.php
centreon/www/class/centreon-clapi/centreonContact.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_Contact; use Centreon_Object_Relation_Contact_Command_Host; use Centreon_Object_Relation_Contact_Command_Service; use Centreon_Object_Timezone; use CentreonAuth; use Exception; use PDOException; use Pimple\Container; use Throwable; require_once __DIR__ . '/../../../bootstrap.php'; require_once 'centreonObject.class.php'; require_once 'centreonUtils.class.php'; require_once 'centreonTimePeriod.class.php'; require_once 'Centreon/Object/Contact/Contact.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Timezone/Timezone.php'; require_once 'Centreon/Object/Relation/Contact/Command/Host.php'; require_once 'Centreon/Object/Relation/Contact/Command/Service.php'; /** * Class * * @class CentreonContact * @package CentreonClapi * @description Class for managing Contact configuration */ class CentreonContact extends CentreonObject { public const ORDER_UNIQUENAME = 1; public const ORDER_NAME = 0; public const ORDER_MAIL = 2; public const ORDER_PASS = 3; public const ORDER_ADMIN = 4; public const ORDER_ACCESS = 5; public const ORDER_LANG = 6; public const ORDER_AUTHTYPE = 7; public const ORDER_DEFAULT_PAGE = 8; public const HOST_NOTIF_TP = 'hostnotifperiod'; public const SVC_NOTIF_TP = 'svcnotifperiod'; public const HOST_NOTIF_CMD = 'hostnotifcmd'; public const SVC_NOTIF_CMD = 'svcnotifcmd'; public const UNKNOWN_LOCALE = 'Invalid locale'; public const UNKNOWN_TIMEZONE = 'Invalid timezone'; public const CONTACT_LOCATION = 'timezone'; public const UNKNOWN_NOTIFICATION_OPTIONS = 'Invalid notifications options'; /** @var string[] */ public static $aDepends = ['CONTACTTPL', 'CMD', 'TP']; /** * @var array * Contains : list of authorized notifications_options for each objects */ public static $aAuthorizedNotificationsOptions = ['host' => ['d' => 'Down', 'u' => 'Unreachable', 'r' => 'Recovery', 'f' => 'Flapping', 's' => 'Downtime Scheduled', 'n' => 'None'], 'service' => ['w' => 'Warning', 'u' => 'Unreachable', 'c' => 'Critical', 'r' => 'Recovery', 'f' => 'Flapping', 's' => 'Downtime Scheduled', 'n' => 'None']]; /** @var int */ protected $register = 1; /** @var CentreonTimePeriod */ protected $tpObject; /** @var Centreon_Object_Timezone */ protected $timezoneObject; /** @var array<string,mixed> */ protected $addParams = []; /** * CentreonContact constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->dependencyInjector = $dependencyInjector; $this->tpObject = new CentreonTimePeriod($dependencyInjector); $this->object = new Centreon_Object_Contact($dependencyInjector); $this->timezoneObject = new Centreon_Object_Timezone($dependencyInjector); $this->params = ['contact_host_notification_options' => 'n', 'contact_service_notification_options' => 'n', 'contact_location' => '0', 'contact_enable_notifications' => '0', 'contact_type_msg' => 'txt', 'contact_activate' => '1', 'contact_register' => '1']; $this->insertParams = [ 'contact_name', 'contact_alias', 'contact_email', 'contact_passwd', 'contact_admin', 'contact_oreon', 'contact_lang', 'contact_auth_type', ]; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'contact_register', 'ar_id'] ); $this->action = 'CONTACT'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'contact_activate'; } /** * Get contact ID * * @param null $contact_name * @throws CentreonClapiException * @return mixed */ public function getContactID($contact_name = null) { $cIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$contact_name]); if (! count($cIds)) { throw new CentreonClapiException('Unknown contact: ' . $contact_name); } return $cIds[0]; } /** * Delete action * * @param $objectName * * @throws CentreonClapiException */ public function del($objectName): void { if (isset($objectName)) { $parameters = str_replace(' ', '_', $objectName); } parent::del($objectName); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = ['contact_register' => $this->register]; if (isset($parameters)) { $parameters = str_replace(' ', '_', $parameters); $filters[$this->object->getUniqueLabelField()] = '%' . $parameters . '%'; } $params = ['contact_id', 'contact_name', 'contact_alias', 'contact_email', 'contact_pager', 'contact_oreon', 'contact_admin', 'contact_activate']; $paramString = str_replace('contact_', '', implode($this->delim, $params)); $paramString = str_replace('oreon', 'gui access', $paramString); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters, 'AND' ); foreach ($elements as $tab) { unset($tab['contact_passwd']); echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $this->addParams = []; $this->initUniqueField($params); $this->initUserInformation($params); if ($params[7] === 'local') { $this->initPassword($params); } $this->initUserAccess($params); $this->initLang($params); $this->initAuthenticationType($params); $this->initDefaultPage($params); $this->params = array_merge($this->params, $this->addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_NAME]); $params[self::ORDER_NAME] = str_replace(' ', '_', $params[self::ORDER_NAME]); if ($objectId != 0) { $regularParam = true; if ($params[1] == self::HOST_NOTIF_TP) { $params[1] = 'timeperiod_tp_id'; $params[2] = $this->tpObject->getTimeperiodId($params[2]); } elseif ($params[1] == self::SVC_NOTIF_TP) { $params[1] = 'timeperiod_tp_id2'; $params[2] = $this->tpObject->getTimeperiodId($params[2]); } elseif ($params[1] == self::HOST_NOTIF_CMD || $params[1] == self::SVC_NOTIF_CMD) { $this->setNotificationCmd($params[1], $objectId, $params[2]); $regularParam = false; } elseif ($params[1] == self::CONTACT_LOCATION) { $iIdTimezone = $this->timezoneObject->getIdByParameter( $this->timezoneObject->getUniqueLabelField(), $params[2] ); if (count($iIdTimezone)) { $iIdTimezone = $iIdTimezone[0]; } else { throw new CentreonClapiException(self::UNKNOWN_TIMEZONE); } $params[1] = 'contact_location'; $params[2] = $iIdTimezone; } elseif (! preg_match('/^contact_/', $params[1])) { if ($params[1] == 'access') { $params[1] = 'oreon'; } elseif ($params[1] == 'template') { $params[1] = 'template_id'; $contactId = $this->getContactID($params[2]); if (! isset($contactId) || ! $contactId) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $params[2] = $contactId; } elseif ($params[1] == 'authtype') { $params[1] = 'auth_type'; } elseif ($params[1] == 'lang' || $params[1] == 'language' || $params[1] == 'locale') { if ( empty($params[2]) || strtoupper(substr($params[2], -6)) === '.UTF-8' || strtolower($params[2]) === 'browser' ) { $completeLanguage = $params[2]; } else { $completeLanguage = $params[2] . '.UTF-8'; } if ($this->checkLang($completeLanguage) == false) { throw new CentreonClapiException(self::UNKNOWN_LOCALE); } $params[1] = 'lang'; $params[2] = $completeLanguage; } elseif ($params[1] === 'password') { $params[1] = 'passwd'; if (password_needs_rehash($params[2], CentreonAuth::PASSWORD_HASH_ALGORITHM)) { $contact = new \CentreonContact($this->db); try { $contact->respectPasswordPolicyOrFail($params[2], $objectId); } catch (Throwable $e) { throw new CentreonClapiException($e->getMessage(), $e->getCode(), $e); } $params[2] = password_hash($params[2], CentreonAuth::PASSWORD_HASH_ALGORITHM); } } elseif ($params[1] == 'hostnotifopt') { $params[1] = 'host_notification_options'; $aNotifs = explode(',', $params[2]); foreach ($aNotifs as $notif) { if (! array_key_exists($notif, self::$aAuthorizedNotificationsOptions['host'])) { throw new CentreonClapiException(self::UNKNOWN_NOTIFICATION_OPTIONS); } } } elseif ($params[1] == 'servicenotifopt') { $params[1] = 'service_notification_options'; $aNotifs = explode(',', $params[2]); foreach ($aNotifs as $notif) { if (! array_key_exists($notif, self::$aAuthorizedNotificationsOptions['service'])) { throw new CentreonClapiException(self::UNKNOWN_NOTIFICATION_OPTIONS); } } } if ( ! in_array( $params[1], [ 'reach_api', 'reach_api_rt', 'default_page', 'show_deprecated_pages', ] ) ) { $params[1] = 'contact_' . $params[1]; } } if ($regularParam == true) { $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } return []; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * Export data * * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = ['contact_register' => $this->register]; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $addStr .= $this->delim . $element[$param]; } $addStr .= "\n"; echo $addStr; foreach ($element as $parameter => $value) { if (! is_null($value) && $value != '' && ! in_array($parameter, $this->exportExcludedParams)) { if ($parameter == 'timeperiod_tp_id') { $parameter = self::HOST_NOTIF_TP; $value = $this->tpObject->getObjectName($value); CentreonTimePeriod::getInstance()->export($value); } elseif ($parameter == 'timeperiod_tp_id2') { $parameter = self::SVC_NOTIF_TP; $value = $this->tpObject->getObjectName($value); CentreonTimePeriod::getInstance()->export($value); } elseif ($parameter == 'contact_lang') { $parameter = 'locale'; } elseif ($parameter == 'contact_host_notification_options') { $parameter = 'hostnotifopt'; } elseif ($parameter == 'contact_service_notification_options') { $parameter = 'servicenotifopt'; } elseif ($parameter == 'contact_template_id') { $parameter = 'template'; $result = $this->object->getParameters($value, $this->object->getUniqueLabelField()); $value = $result[$this->object->getUniqueLabelField()]; CentreonContactTemplate::getInstance()->export($value); } elseif ($parameter == 'contact_location') { $parameter = self::CONTACT_LOCATION; $result = $this->timezoneObject->getParameters( $value, $this->timezoneObject->getUniqueLabelField() ); if ($result !== false) { $value = $result[$this->timezoneObject->getUniqueLabelField()]; } } $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } $objId = $element[$this->object->getPrimaryKey()]; $this->exportNotifCommands(self::HOST_NOTIF_CMD, $objId, $element[$this->object->getUniqueLabelField()]); $this->exportNotifCommands(self::SVC_NOTIF_CMD, $objId, $element[$this->object->getUniqueLabelField()]); } } /** * Checks if language exists * * @param string $locale * @return bool */ protected function checkLang($locale) { if (! $locale || $locale == '') { return true; } if (strtolower($locale) === 'en_us.utf-8' || strtolower($locale) === 'browser') { return true; } $centreonDir = realpath(__DIR__ . '/../../../'); $dir = $centreonDir . "/www/locale/{$locale}"; return (bool) (is_dir($dir)); } /** * Initialize Unique Field * * @param array<int,mixed> $params */ protected function initUniqueField(array $params): void { $this->addParams[$this->object->getUniqueLabelField()] = str_replace( ' ', '_', $params[static::ORDER_UNIQUENAME] ); } /** * Initialize user information * * @param array<int,mixed> $params * * @throws PDOException */ protected function initUserInformation(array $params): void { $this->addParams['contact_name'] = $this->checkIllegalChar($params[static::ORDER_NAME]); $this->addParams['contact_email'] = $params[static::ORDER_MAIL]; } /** * Initialize password * * @param array<int,mixed> $params * * @throws CentreonClapiException */ protected function initPassword(array $params): void { if (password_needs_rehash($params[static::ORDER_PASS], CentreonAuth::PASSWORD_HASH_ALGORITHM)) { $contact = new \CentreonContact($this->db); try { $contact->respectPasswordPolicyOrFail($params[static::ORDER_PASS], null); } catch (Throwable $e) { throw new CentreonClapiException($e->getMessage(), $e->getCode(), $e); } $this->addParams['contact_passwd'] = password_hash( $params[static::ORDER_PASS], CentreonAuth::PASSWORD_HASH_ALGORITHM ); } else { $this->addParams['contact_passwd'] = $params[static::ORDER_PASS]; } } /** * Initialize user access * * @param array<int,mixed> $params */ protected function initUserAccess(array $params): void { $this->addParams['contact_admin'] = $params[static::ORDER_ADMIN]; if ($this->addParams['contact_admin'] == '') { $this->addParams['contact_admin'] = '0'; } $this->addParams['contact_oreon'] = $params[static::ORDER_ACCESS]; if ($this->addParams['contact_oreon'] == '') { $this->addParams['contact_oreon'] = '1'; } } /** * Initialize user language * * @param array<int,mixed> $params * * @throws CentreonClapiException */ protected function initLang(array $params): void { if ( empty($params[static::ORDER_LANG]) || strtolower($params[static::ORDER_LANG]) === 'browser' || strtoupper(substr($params[static::ORDER_LANG], -6)) === '.UTF-8' ) { $completeLanguage = $params[static::ORDER_LANG]; } else { $completeLanguage = $params[static::ORDER_LANG] . '.UTF-8'; } if ($this->checkLang($completeLanguage) == false) { throw new CentreonClapiException(static::UNKNOWN_LOCALE); } $this->addParams['contact_lang'] = $completeLanguage; } /** * Initialize authentication type * * @param array<int, mixed> $params */ protected function initAuthenticationType(array $params): void { $this->addParams['contact_auth_type'] = $params[static::ORDER_AUTHTYPE]; } /** * Initialize default page * * @param array<int,mixed> $params */ protected function initDefaultPage(array $params): void { if (isset($params[static::ORDER_DEFAULT_PAGE])) { $this->addParams['default_page'] = $params[static::ORDER_DEFAULT_PAGE]; } } /** * Set Notification Commands * * @param string $type * @param int $contactId * @param string $commands * @throws CentreonClapiException */ protected function setNotificationCmd($type, $contactId, $commands) { $cmds = explode('|', $commands); $cmdIds = []; $cmdObject = new Centreon_Object_Command($this->dependencyInjector); foreach ($cmds as $commandName) { $tmp = $cmdObject->getIdByParameter($cmdObject->getUniqueLabelField(), $commandName); if (count($tmp)) { $cmdIds[] = $tmp[0]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $commandName); } } if ($type == self::HOST_NOTIF_CMD) { $relObj = new Centreon_Object_Relation_Contact_Command_Host($this->dependencyInjector); } else { $relObj = new Centreon_Object_Relation_Contact_Command_Service($this->dependencyInjector); } $relObj->delete($contactId); foreach ($cmdIds as $cmdId) { $relObj->insert($contactId, $cmdId); } } /** * Export notification commands * * @param string $objType * @param int $contactId * @param string $contactName * * @throws Exception * @return void */ private function exportNotifCommands($objType, $contactId, $contactName): void { $commandObj = new Centreon_Object_Command($this->dependencyInjector); if ($objType == self::HOST_NOTIF_CMD) { $obj = new Centreon_Object_Relation_Contact_Command_Host($this->dependencyInjector); } else { $obj = new Centreon_Object_Relation_Contact_Command_Service($this->dependencyInjector); } $cmds = $obj->getMergedParameters( [], [$commandObj->getUniqueLabelField()], -1, 0, null, null, [$this->object->getPrimaryKey() => $contactId], 'AND' ); $str = ''; foreach ($cmds as $element) { if ($str != '') { $str .= '|'; } $str .= $element[$commandObj->getUniqueLabelField()]; } if ($str) { echo $this->action . $this->delim . 'setparam' . $this->delim . $contactName . $this->delim . $objType . $this->delim . $str . "\n"; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonDowntime.class.php
centreon/www/class/centreon-clapi/centreonDowntime.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Downtime; use Centreon_Object_Host; use Centreon_Object_Host_Group; use Centreon_Object_Service_Group; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonHost.class.php'; require_once 'centreonService.class.php'; require_once 'Centreon/Object/Downtime/Downtime.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Relation/Downtime/Host.php'; require_once 'Centreon/Object/Relation/Downtime/Hostgroup.php'; require_once 'Centreon/Object/Relation/Downtime/Servicegroup.php'; /** * Class * * @class CentreonDowntime * @package CentreonClapi * @description Class for managing recurring downtime objects */ class CentreonDowntime extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; /** @var string[] */ public static $aDepends = ['SERVICE', 'HOST']; /** @var int[] */ protected $weekDays = ['monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6, 'sunday' => 7]; /** @var CentreonService */ protected $serviceObj; /** @var string[] */ protected $availableCycles = ['first', 'second', 'third', 'fourth', 'last']; /** * CentreonDowntime constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->serviceObj = new CentreonService($dependencyInjector); $this->object = new Centreon_Object_Downtime($dependencyInjector); $this->action = 'DOWNTIME'; $this->insertParams = ['dt_name', 'dt_description']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey()] ); $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'dt_activate'; } /** * @param null $parameters * @param array $filters * * @throws CentreonClapiException * @throws PDOException */ public function show($parameters = null, $filters = []): void { $filters = []; $filter = []; if (isset($parameters) && $parameters !== '') { $filter = explode(';', $parameters); $filters = [$this->object->getUniqueLabelField() => '%' . $filter[0] . '%']; } $params = ['dt_id', 'dt_name', 'dt_description', 'dt_activate']; $paramString = str_replace('dt_', '', implode($this->delim, $params)); $elements = $this->object->getList($params, -1, 0, null, null, $filters); if (empty($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND); } if ($filter === []) { echo $paramString . "\n"; $filterList = ''; foreach ($elements as $element) { echo implode($this->delim, $element) . "\n"; } } else { if (isset($filter[1])) { switch (strtolower($filter[1])) { case 'host': $paramString .= ";hosts\n"; break; case 'hg': $paramString .= ";host groups\n"; break; case 'service': $paramString .= ";services\n"; break; case 'sg': $paramString .= ";service groups\n"; break; default: throw new CentreonClapiException(self::UNKNOWNPARAMETER); } } else { $paramString .= ";hosts;host groups;services;service groups\n"; } echo $paramString; foreach ($elements as $element) { if (isset($filter[1])) { switch (strtolower($filter[1])) { case 'host': $filterList = $this->listHosts($element['dt_id']); break; case 'hg': $filterList = $this->listHostGroups($element['dt_id']); break; case 'service': $filterList = $this->listServices($element['dt_id']); break; case 'sg': $filterList = $this->listServiceGroups($element['dt_id']); break; default: throw new CentreonClapiException(self::UNKNOWNPARAMETER); } } else { $filterList = $this->listResources($element['dt_id']); } if (! empty($filterList)) { echo implode($this->delim, $element) . ';' . $filterList . "\n"; } } } } /** * @param null $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['dt_description'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param null $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^dt_/', $params[1])) { $params[1] = 'dt_' . $params[1]; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * List periods * * @param string $parameters | downtime name * * @throws CentreonClapiException * @throws PDOException */ public function listperiods($parameters): void { $dtId = $this->getObjectId($parameters); $rows = $this->getPeriods($dtId); echo implode( $this->delim, ['position', 'start time', 'end time', 'fixed', 'duration', 'day of week', 'day of month', 'month cycle'] ) . "\n"; $pos = 1; foreach ($rows as $row) { unset($row['dt_id']); echo $pos . $this->delim; echo implode($this->delim, $row) . "\n"; $pos++; } } /** * Add weekly period * * @param string $parameters | downtime_name;start;end;fixed;duration;monday...sunday * * @throws CentreonClapiException * @throws PDOException */ public function addweeklyperiod($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 6) { throw new CentreonClapiException('Incorrect number of parameters'); } if (! is_numeric($tmp[3])) { throw new CentreonClapiException('Incorrect fixed parameters'); } if ($tmp[3] == 0 && ! is_numeric($tmp[4])) { throw new CentreonClapiException('Incorrect duration parameters: mandatory for flexible downtimes'); } $p = []; $p[':dt_id'] = $this->getObjectId($tmp[0]); $p[':start_time'] = $tmp[1]; $p[':end_time'] = $tmp[2]; $p[':fixed'] = $tmp[3]; $p[':duration'] = $tmp[3] == 0 ? $tmp[4] : null; $daysOfWeek = explode(',', strtolower($tmp[5])); $days = []; foreach ($daysOfWeek as $dayOfWeek) { if (! isset($this->weekDays[$dayOfWeek]) && ! in_array($dayOfWeek, $this->weekDays)) { throw new CentreonClapiException(sprintf('Invalid period format %s', $dayOfWeek)); } $days[] = is_numeric($dayOfWeek) ? $dayOfWeek : $this->weekDays[$dayOfWeek]; } $p[':day_of_week'] = implode(',', $days); $p[':day_of_month'] = null; $p[':month_cycle'] = 'all'; $this->insertPeriod($p); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addmonthlyperiod($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 6) { throw new CentreonClapiException('Incorrect number of parameters'); } if (! is_numeric($tmp[3])) { throw new CentreonClapiException('Incorrect fixed parameters'); } if (! is_numeric($tmp[4])) { throw new CentreonClapiException('Incorrect duration parameters'); } $p = []; $p[':dt_id'] = $this->getObjectId($tmp[0]); $p[':start_time'] = $tmp[1]; $p[':end_time'] = $tmp[2]; $p[':fixed'] = $tmp[3]; $p[':duration'] = $tmp[4]; $p[':day_of_month'] = $tmp[5]; $p[':day_of_week'] = null; $p[':month_cycle'] = 'none'; $this->insertPeriod($p); } /** * Add specific period * * @param string $parameters | downtime_name;start;end;fixed;duration;monday...sunday;first,last * * @throws CentreonClapiException * @throws PDOException */ public function addspecificperiod($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 7) { throw new CentreonClapiException('Incorrect number of parameters'); } if (! is_numeric($tmp[3])) { throw new CentreonClapiException('Incorrect fixed parameters'); } if (! is_numeric($tmp[4])) { throw new CentreonClapiException('Incorrect duration parameters'); } $p = []; $p[':dt_id'] = $this->getObjectId($tmp[0]); $p[':start_time'] = $tmp[1]; $p[':end_time'] = $tmp[2]; $p[':fixed'] = $tmp[3]; $p[':duration'] = $tmp[4]; $dayOfWeek = strtolower($tmp[5]); if (! isset($this->weekDays[$dayOfWeek]) && ! in_array($dayOfWeek, $this->weekDays)) { throw new CentreonClapiException(sprintf('Invalid period format %s', $dayOfWeek)); } $p[':day_of_week'] = is_numeric($dayOfWeek) ? $dayOfWeek : $this->weekDays[$dayOfWeek]; $p[':day_of_month'] = null; $cycle = strtolower($tmp[6]); if (! in_array($cycle, $this->availableCycles)) { throw new CentreonClapiException( sprintf('Invalid cycle format %s. Must be "first", "second, "third", "fourth" or "last"', $cycle) ); } $p[':month_cycle'] = $cycle; $this->insertPeriod($p); } /** * Delete period from downtime * * @param string $parameters | downtime_name;position to delete * * @throws CentreonClapiException * @throws PDOException */ public function delperiod($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Incorrect number of parameters'); } $sql = 'DELETE FROM downtime_period WHERE dt_id = ? AND dtp_start_time = ? AND dtp_end_time = ? AND dtp_fixed = ? AND dtp_duration = ? AND dtp_day_of_week = ? AND dtp_day_of_month = ? AND dtp_month_cycle = ?'; $period = $this->getPeriods($this->getObjectId($tmp[0]), $tmp[1]); $periodParams = []; foreach ($period as $k => $v) { if ($v == '') { $sql = str_replace("{$k} = ?", "{$k} IS NULL", $sql); } else { $periodParams[] = $v; } } $this->db->query($sql, $periodParams); } /** * @param $downtimeId * * @throws PDOException * @return string */ public function listHosts($downtimeId) { // hosts $sql = 'SELECT host_name FROM downtime_host_relation dhr, host h WHERE h.host_id = dhr.host_host_id AND dhr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $hosts = []; foreach ($rows as $row) { $hosts[] = $row['host_name']; } return implode('|', $hosts); } /** * @param $downtimeId * * @throws PDOException * @return string */ public function listHostGroups($downtimeId) { // host groups $sql = 'SELECT hg_name FROM downtime_hostgroup_relation dhr, hostgroup hg WHERE hg.hg_id = dhr.hg_hg_id AND dhr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $hostgroups = []; foreach ($rows as $row) { $hostgroups[] = $row['hg_name']; } return implode('|', $hostgroups); } /** * @param $downtimeId * * @throws PDOException * @return string */ public function listServices($downtimeId) { // services $sql = 'SELECT host_name, service_description FROM downtime_service_relation dsr, host h, service s WHERE h.host_id = dsr.host_host_id AND dsr.service_service_id = s.service_id AND dsr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $services = []; foreach ($rows as $row) { $services[] = $row['host_name'] . ',' . $row['service_description']; } return implode('|', $services); } /** * @param $downtimeId * * @throws PDOException * @return string */ public function listServiceGroups($downtimeId) { // service groups $sql = 'SELECT sg_name FROM downtime_servicegroup_relation dsr, servicegroup sg WHERE sg.sg_id = dsr.sg_sg_id AND dsr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $servicegroups = []; foreach ($rows as $row) { $servicegroups[] = $row['sg_name']; } return implode('|', $servicegroups); } /** * @param $downtimeId * * @throws PDOException * @return string */ public function listResources($downtimeId) { // hosts $sql = 'SELECT host_name FROM downtime_host_relation dhr, host h WHERE h.host_id = dhr.host_host_id AND dhr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $hosts = []; foreach ($rows as $row) { $hosts[] = $row['host_name']; } // host groups $sql = 'SELECT hg_name FROM downtime_hostgroup_relation dhr, hostgroup hg WHERE hg.hg_id = dhr.hg_hg_id AND dhr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $hostgroups = []; foreach ($rows as $row) { $hostgroups[] = $row['hg_name']; } // services $sql = 'SELECT host_name, service_description FROM downtime_service_relation dsr, host h, service s WHERE h.host_id = dsr.host_host_id AND dsr.service_service_id = s.service_id AND dsr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $services = []; foreach ($rows as $row) { $services[] = $row['host_name'] . ',' . $row['service_description']; } // service groups $sql = 'SELECT sg_name FROM downtime_servicegroup_relation dsr, servicegroup sg WHERE sg.sg_id = dsr.sg_sg_id AND dsr.dt_id = ?'; $stmt = $this->db->query($sql, [$downtimeId]); $rows = $stmt->fetchAll(); $servicegroups = []; foreach ($rows as $row) { $servicegroups[] = $row['sg_name']; } return implode('|', $hosts) . $this->delim . implode('|', $hostgroups) . $this->delim . implode('|', $services) . $this->delim . implode('|', $servicegroups); } /** * Add host to downtime * * @param string $parameters | downtime name; host names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function addhost($parameters): void { $object = new Centreon_Object_Host($this->dependencyInjector); $this->addGenericRelation($parameters, $object, 'downtime_host_relation', 'host_host_id'); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function sethost($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // delete all host relationships $downtimeId = $this->getObjectId($tmp[0]); $this->db->query('DELETE FROM downtime_host_relation WHERE dt_id = ?', [$downtimeId]); $this->addhost($parameters); } /** * Delete host from downtime * * @param string $parameters | downtime name; host names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function delhost($parameters): void { $object = new Centreon_Object_Host($this->dependencyInjector); $this->delGenericRelation($parameters, $object, 'downtime_host_relation', 'host_host_id'); } /** * Add host group to downtime * * @param string $parameters | downtime name; host group names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function addhostgroup($parameters): void { $object = new Centreon_Object_Host_Group($this->dependencyInjector); $this->addGenericRelation($parameters, $object, 'downtime_hostgroup_relation', 'hg_hg_id'); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function sethostgroup($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // delete all host group relationships $downtimeId = $this->getObjectId($tmp[0]); $this->db->query('DELETE FROM downtime_hostgroup_relation WHERE dt_id = ?', [$downtimeId]); $this->addhostgroup($parameters); } /** * Delete host groups * * @param string $parameters | downtime name; host group names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function delhostgroup($parameters): void { $object = new Centreon_Object_Host_Group($this->dependencyInjector); $this->delGenericRelation($parameters, $object, 'downtime_hostgroup_relation', 'hg_hg_id'); } /** * Add service to downtime * * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addservice($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // init var $downtimeId = $this->getObjectId($tmp[0]); if ($downtimeId == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $tmp[0]); } $resources = explode('|', $tmp[1]); // retrieve object ids $objectIds = []; foreach ($resources as $resource) { $tmp = explode(',', $resource); if (count($tmp) != 2) { throw new CentreonClapiException(sprintf('Wrong format for service %s', $resource)); } $host = $tmp[0]; $service = $tmp[1]; $ids = $this->serviceObj->getHostAndServiceId($host, $service); // object does not exist if (! count($ids)) { throw new CentreonClapiException(sprintf('Could not find service %s on host %s', $service, $host)); } // checks whether or not relationship already exists $sql = 'SELECT * FROM downtime_service_relation WHERE dt_id = ? AND host_host_id = ? AND service_service_id = ?'; $stmt = $this->db->query($sql, [$downtimeId, $ids[0], $ids[1]]); if ($stmt->rowCount()) { throw new CentreonClapiException( sprintf( 'Relationship with %s / %s already exists', $host, $service ) ); } $objectIds[] = $ids; } // insert relationship $sql = 'INSERT INTO downtime_service_relation (dt_id, host_host_id, service_service_id) VALUES (?, ?, ?)'; foreach ($objectIds as $id) { $this->db->query($sql, [$downtimeId, $id[0], $id[1]]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setservice($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // delete all service relationships $downtimeId = $this->getObjectId($tmp[0]); $this->db->query('DELETE FROM downtime_service_relation WHERE dt_id = ?', [$downtimeId]); $this->addservice($parameters); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function delservice($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // init var $downtimeId = $this->getObjectId($tmp[0]); $resources = explode('|', $tmp[1]); // retrieve object ids $objectIds = []; foreach ($resources as $resource) { $tmp = explode(',', $resource); if (count($tmp) != 2) { throw new CentreonClapiException(sprintf('Wrong format for service %s', $resource)); } $host = $tmp[0]; $service = $tmp[1]; $ids = $this->serviceObj->getHostAndServiceId($host, $service); // object does not exist if (! count($ids)) { throw new CentreonClapiException(sprintf('Could not find service %s on host %s', $service, $host)); } // checks whether or not relationship already exists $sql = 'SELECT * FROM downtime_service_relation WHERE dt_id = ? AND host_host_id = ? AND service_service_id = ?'; $stmt = $this->db->query($sql, [$downtimeId, $ids[0], $ids[1]]); if (! $stmt->rowCount()) { throw new CentreonClapiException( sprintf( 'Relationship with %s / %s does not exist', $host, $service ) ); } $objectIds[] = $ids; } // delete relationship $sql = 'DELETE FROM downtime_service_relation WHERE dt_id = ? AND host_host_id = ? AND service_service_id = ?'; foreach ($objectIds as $id) { $this->db->query($sql, [$downtimeId, $id[0], $id[1]]); } } /** * Add service group to downtime * * @param string $parameters | downtime name; service group names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function addservicegroup($parameters): void { $object = new Centreon_Object_Service_Group($this->dependencyInjector); $this->addGenericRelation($parameters, $object, 'downtime_servicegroup_relation', 'sg_sg_id'); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setservicegroup($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) != 2) { throw new CentreonClapiException('Missing parameters'); } // delete all service group relationships $downtimeId = $this->getObjectId($tmp[0]); $this->db->query('DELETE FROM downtime_servicegroup_relation WHERE dt_id = ?', [$downtimeId]); $this->addservicegroup($parameters); } /** * Delete service group from downtime * * @param string $parameters | downtime name; service group names separated by "|" character * * @throws CentreonClapiException * @throws PDOException */ public function delservicegroup($parameters): void { $object = new Centreon_Object_Service_Group($this->dependencyInjector); $this->delGenericRelation($parameters, $object, 'downtime_servicegroup_relation', 'sg_sg_id'); } /** * Export * * @param null $filterName * * @throws PDOException * @return false|void */ public function export($filterName = null) { // generic add & setparam if (! parent::export($filterName)) { return false; } // handle host relationships $this->exportHostRel(); // handle hostgroup relationships $this->exportHostgroupRel(); // handle service relationships $this->exportServiceRel(); // handle servicegroup relationships $this->exportServicegroupRel(); // handle periods $this->exportPeriods(); } /** * @throws PDOException * @return void */ protected function exportPeriods() { $sql = 'SELECT dt_name, dtp_start_time, dtp_end_time, dtp_fixed, dtp_duration, dtp_day_of_week, dtp_day_of_month, dtp_month_cycle FROM downtime d, downtime_period p WHERE d.dt_id = p.dt_id'; $stmt = $this->db->query($sql); $rows = $stmt->fetchAll(); foreach ($rows as $row) { $periodType = null; $extraData = []; $row['dtp_start_time'] = preg_replace('/:00$/', '', $row['dtp_start_time']); $row['dtp_end_time'] = preg_replace('/:00$/', '', $row['dtp_end_time']); if (! $row['dtp_day_of_month'] && $row['dtp_month_cycle'] == 'all') { // weekly $periodType = 'ADDWEEKLYPERIOD'; $extraData[] = $row['dtp_day_of_week']; } elseif (! $row['dtp_day_of_week'] && $row['dtp_month_cycle'] == 'none') { // monthly $periodType = 'ADDMONTHLYPERIOD'; $extraData[] = $row['dtp_day_of_month']; } elseif ($row['dtp_month_cycle'] == 'last' || $row['dtp_month_cycle'] == 'first') { // specific $periodType = 'ADDSPECIFICPERIOD'; $extraData[] = $row['dtp_day_of_week']; $extraData[] = $row['dtp_month_cycle']; } if (! is_null($periodType)) { echo implode( $this->delim, array_merge( [$this->action, $periodType, $row['dt_name'], $row['dtp_start_time'], $row['dtp_end_time'], $row['dtp_fixed'], $row['dtp_duration']], $extraData ) ) . "\n"; } } } /** * @throws PDOException * @return void */ protected function exportHostRel() { $sql = 'SELECT dt_name, host_name as object_name FROM downtime d, host o, downtime_host_relation rel WHERE d.dt_id = rel.dt_id AND rel.host_host_id = o.host_id'; $this->exportGenericRel('ADDHOST', $sql); } /** * @throws PDOException * @return void */ protected function exportHostgroupRel() { $sql = 'SELECT dt_name, hg_name as object_name FROM downtime d, hostgroup o, downtime_hostgroup_relation rel WHERE d.dt_id = rel.dt_id AND rel.hg_hg_id = o.hg_id'; $this->exportGenericRel('ADDHOSTGROUP', $sql); } /** * @throws PDOException * @return void */ protected function exportServiceRel() { $sql = "SELECT dt_name, CONCAT_WS(',', host_name, service_description) as object_name FROM downtime d, host h, service s, downtime_service_relation rel WHERE d.dt_id = rel.dt_id AND rel.host_host_id = h.host_id AND rel.service_service_id = s.service_id"; $this->exportGenericRel('ADDSERVICE', $sql); } /** * @throws PDOException * @return void */ protected function exportServicegroupRel() { $sql = 'SELECT dt_name, sg_name as object_name FROM downtime d, servicegroup o, downtime_servicegroup_relation rel WHERE d.dt_id = rel.dt_id AND rel.sg_sg_id = o.sg_id'; $this->exportGenericRel('ADDSERVICEGROUP', $sql); } /** * @param string $actionType | addhost, addhostgroup, addservice or addservicegroup * @param string $sql | query * * @throws PDOException */ protected function exportGenericRel($actionType, $sql) { $stmt = $this->db->query($sql); $rows = $stmt->fetchAll(); foreach ($rows as $row) { echo implode( $this->delim, [$this->action, $actionType, $row['dt_name'], $row['object_name']] ) . "\n"; } } /** * Add period * * @param $p * * @throws CentreonClapiException * @throws PDOException */ protected function insertPeriod($p) { // check time periods $p[':start_time'] .= ':00'; $p[':end_time'] .= ':00'; if (! preg_match('/^(\d+):(\d+):00$/', $p[':start_time'])) { throw new CentreonClapiException(sprintf('Invalid start time %s', $p[':start_time'])); } if (! preg_match('/^(\d+):(\d+):00$/', $p[':end_time'])) { throw new CentreonClapiException(sprintf('Invalid end time %s', $p[':end_time'])); } // handle fixed / duration if ($p[':fixed']) {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACLGroup.class.php
centreon/www/class/centreon-clapi/centreonACLGroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; require_once 'centreonObject.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Group.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Action.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Menu.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Resource.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Contact.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Group.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Resource.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Menu.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Action.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Contact/Contact.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Contact/Group.php'; require_once __DIR__ . '/Repository/AclGroupRepository.php'; require_once __DIR__ . '/Repository/SessionRepository.php'; use App\Kernel; use Centreon_Object_Acl_Group; use CentreonClapi\Repository\AclGroupRepository; use CentreonClapi\Repository\SessionRepository; use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface; use Exception; use InvalidArgumentException; use LogicException; use PDOException; use Pimple\Container; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Throwable; /** * Class * * @class CentreonACLGroup * @package CentreonClapi * @description Class for managing ACL groups */ class CentreonACLGroup extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; /** @var string[] */ public $aDepends = ['CONTACT', 'CG', 'ACLMENU', 'ACLACTION', 'ACLRESOURCE']; /** @var AclGroupRepository */ private AclGroupRepository $aclGroupRepository; /** @var SessionRepository */ private SessionRepository $sessionRepository; /** * CentreonACLGroup constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Acl_Group($dependencyInjector); $db = $dependencyInjector['configuration_db']; $this->aclGroupRepository = new AclGroupRepository($db); $this->sessionRepository = new SessionRepository($db); $this->params = ['acl_group_changed' => '1', 'acl_group_activate' => '1']; $this->nbOfCompulsoryParams = 2; $this->activateField = 'acl_group_activate'; $this->action = 'ACLGROUP'; } /** * Magic method * * @param string $name * @param array $arg * * @throws CentreonClapiException * @throws InvalidArgumentException * @throws Throwable * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { $relclass = 'Centreon_Object_Relation_Acl_Group_' . ucwords($matches[2]); if (class_exists('Centreon_Object_Acl_' . ucwords($matches[2]))) { $class = 'Centreon_Object_Acl_' . ucwords($matches[2]); } elseif ($matches[2] == 'contactgroup') { $class = 'Centreon_Object_Contact_Group'; $relclass = 'Centreon_Object_Relation_Acl_Group_Contact_Group'; } else { $class = 'Centreon_Object_' . ucwords($matches[2]); } if (class_exists($relclass) && class_exists($class)) { $uniqueLabel = $this->object->getUniqueLabelField(); // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $groupIds = $this->object->getIdByParameter($uniqueLabel, [$args[0]]); if (! count($groupIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $groupId = $groupIds[0]; $relobj = new $relclass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $groupIds); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } if ($matches[1] == 'set') { $relobj->delete($groupId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getSecondKey(), $relobj->getFirstKey(), [$groupId] ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($groupId, $relationId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($groupId, $relationId); } } } if ($matches[2] === 'action') { $this->flagUpdatedAclForAuthentifiedUsers($groupIds); } $updateParams = ['acl_group_changed' => '1']; if ( isset($updateParams[$uniqueLabel]) && $this->objectExists($updateParams[$uniqueLabel], $groupId) == true ) { throw new CentreonClapiException(self::NAMEALREADYINUSE); } $this->object->update($groupId, $updateParams); $p = $this->object->getParameters($groupId, $uniqueLabel); if (isset($p[$uniqueLabel])) { $this->addAuditLog( 'c', $groupId, $p[$uniqueLabel], $updateParams ); } } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['acl_group_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $params[1] = 'acl_group_' . $params[1]; $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['acl_group_id', 'acl_group_name', 'acl_group_alias', 'acl_group_activate']; $paramString = str_replace('acl_group_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $aclGroupList = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); $exportLine = ''; foreach ($aclGroupList as $aclGroup) { $exportLine .= $this->action . $this->delim . 'ADD' . $this->delim . $aclGroup['acl_group_name'] . $this->delim . $aclGroup['acl_group_alias'] . $this->delim . "\n"; $exportLine .= $this->action . $this->delim . 'SETPARAM' . $this->delim . $aclGroup['acl_group_name'] . $this->delim . 'activate' . $this->delim . $aclGroup['acl_group_activate'] . $this->delim . "\n"; $exportLine .= $this->exportLinkedObjects($aclGroup['acl_group_id'], $aclGroup['acl_group_name']); echo $exportLine; $exportLine = ''; } } /** * @param $aclGroupId * @param $aclGroupName * * @throws CentreonClapiException * @return string */ private function exportLinkedObjects($aclGroupId, $aclGroupName) { $objectList = [['object' => 'MENU', 'relClass' => 'Centreon_Object_Relation_Acl_Group_Menu', 'objectFieldName' => 'acl_topo_name'], ['object' => 'ACTION', 'relClass' => 'Centreon_Object_Relation_Acl_Group_Action', 'objectFieldName' => 'acl_action_name'], ['object' => 'RESOURCE', 'relClass' => 'Centreon_Object_Relation_Acl_Group_Resource', 'objectFieldName' => 'acl_res_name'], ['object' => 'CONTACT', 'relClass' => 'Centreon_Object_Relation_Acl_Group_Contact', 'objectFieldName' => 'contact_alias'], ['object' => 'CONTACTGROUP', 'relClass' => 'Centreon_Object_Relation_Acl_Group_Contact_Group', 'objectFieldName' => 'cg_name']]; $linkedObjectsSetter = $this->action . $this->delim . 'SET%s' . $this->delim . $aclGroupName . $this->delim . '%s' . $this->delim . "\n"; $linkedObjectsStr = ''; foreach ($objectList as $currentObject) { $linkedObjects = $this->getLinkedObject( $aclGroupId, $currentObject['relClass'], $currentObject['objectFieldName'] ); if (! empty($linkedObjects)) { $linkedObjectsStr .= sprintf($linkedObjectsSetter, $currentObject['object'], $linkedObjects); } } return $linkedObjectsStr; } /** * @param $aclGroupId * @param $relClass * @param $objectFieldName * @throws CentreonClapiException * @return string */ private function getLinkedObject($aclGroupId, $relClass, $objectFieldName) { if (! class_exists($relClass)) { throw new CentreonClapiException('Unsupported relation object : ' . $relClass); } $relObj = new $relClass($this->dependencyInjector); $comparisonKey1 = $this->object->getTableName() . '.' . $this->object->getPrimaryKey(); $links = $relObj->getMergedParameters( [], [$objectFieldName], -1, 0, $objectFieldName, 'ASC', [$comparisonKey1 => $aclGroupId], 'AND' ); $linkedObjects = ''; foreach ($links as $link) { $linkedObjects .= $link[$objectFieldName] . '|'; } return trim($linkedObjects, '|'); } /** * This method flags updated ACL for authentified users. * * @param int[] $aclGroupIds * * @throws InvalidArgumentException * @throws Throwable */ private function flagUpdatedAclForAuthentifiedUsers(array $aclGroupIds): void { $userIds = $this->aclGroupRepository->getUsersIdsByAclGroupIds($aclGroupIds); $readSessionRepository = $this->getReadSessionRepository(); foreach ($userIds as $userId) { $sessionIds = $readSessionRepository->findSessionIdsByUserId($userId); $this->sessionRepository->flagUpdateAclBySessionIds($sessionIds); } } /** * This method gets SessionRepository from Service container * * @throws LogicException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return ReadSessionRepositoryInterface */ private function getReadSessionRepository(): ReadSessionRepositoryInterface { $kernel = Kernel::createForWeb(); return $kernel->getContainer()->get( ReadSessionRepositoryInterface::class ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonSeverityAbstract.class.php
centreon/www/class/centreon-clapi/centreonSeverityAbstract.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; require_once 'centreonObject.class.php'; /** * Class * * @class CentreonSeverityAbstract * @package CentreonClapi */ abstract class CentreonSeverityAbstract extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; /** * Set severity * * @param string $parameters * @throws CentreonClapiException */ public function setseverity($parameters): void { $params = explode($this->delim, $parameters); $uniqueLabel = $params[self::ORDER_UNIQUENAME]; if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($uniqueLabel); if ($objectId != 0) { if (! is_numeric($params[1])) { throw new CentreonClapiException('Incorrect severity level parameters'); } $level = (int) $params[1]; $iconId = CentreonUtils::getImageId($params[2], $this->db); if (is_null($iconId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $updateParams = ['level' => $level, 'icon_id' => $iconId]; $this->object->update($objectId, $updateParams); $this->addAuditLog( 'c', $objectId, $uniqueLabel, $updateParams ); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * Unset severity * * @param string $parameters * @throws CentreonClapiException */ public function unsetseverity($parameters): void { $params = explode($this->delim, $parameters); $uniqueLabel = $params[self::ORDER_UNIQUENAME]; if (count($params) < 1) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($uniqueLabel); if ($objectId != 0) { $updateParams = ['level' => null, 'icon_id' => null]; $this->object->update($objectId, $updateParams); $this->addAuditLog( 'c', $objectId, $uniqueLabel, $updateParams ); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonHostGroupService.class.php
centreon/www/class/centreon-clapi/centreonHostGroupService.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_Graph_Template; use Centreon_Object_Host_Group; use Centreon_Object_Relation_Contact_Group_Service; use Centreon_Object_Relation_Contact_Service; use Centreon_Object_Relation_Host_Group_Service; use Centreon_Object_Relation_Service_Category_Service; use Centreon_Object_Service; use Centreon_Object_Service_Category; use Centreon_Object_Service_Extended; use Centreon_Object_Service_Macro_Custom; use Centreon_Object_Timeperiod; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonUtils.class.php'; require_once 'centreonTimePeriod.class.php'; require_once 'centreonACL.class.php'; require_once 'centreonCommand.class.php'; require_once 'Centreon/Object/Instance/Instance.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Timeperiod/Timeperiod.php'; require_once 'Centreon/Object/Graph/Template/Template.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Extended.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Macro/Custom.php'; require_once 'Centreon/Object/Service/Service.php'; require_once 'Centreon/Object/Service/Macro/Custom.php'; require_once 'Centreon/Object/Service/Extended.php'; require_once 'Centreon/Object/Contact/Contact.php'; require_once 'Centreon/Object/Contact/Group.php'; require_once 'Centreon/Object/Relation/Host/Template/Host.php'; require_once 'Centreon/Object/Relation/Contact/Service.php'; require_once 'Centreon/Object/Relation/Contact/Group/Service.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Relation/Host/Group/Service/Service.php'; require_once 'Centreon/Object/Relation/Service/Category/Service.php'; /** * Class * * @class CentreonHostGroupService * @package CentreonClapi */ class CentreonHostGroupService extends CentreonObject { public const ORDER_HOSTNAME = 0; public const ORDER_SVCDESC = 1; public const ORDER_SVCTPL = 2; public const NB_UPDATE_PARAMS = 4; /** @var string[] */ public static $aDepends = ['HOST', 'SERVICE']; /** @var int */ public $register = 1; /** @var */ protected $hgId; /** * CentreonHostGroupService constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Service($dependencyInjector); $this->params = ['service_is_volatile' => '2', 'service_active_checks_enabled' => '2', 'service_passive_checks_enabled' => '2', 'service_parallelize_check' => '2', 'service_obsess_over_service' => '2', 'service_check_freshness' => '2', 'service_event_handler_enabled' => '2', 'service_flap_detection_enabled' => '2', 'service_process_perf_data' => '2', 'service_retain_status_information' => '2', 'service_retain_nonstatus_information' => '2', 'service_notifications_enabled' => '2', 'service_register' => '1', 'service_activate' => '1']; $this->insertParams = ['hg_name', 'service_description', 'service_template_model_stm_id']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'HGSERVICE'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'service_activate'; } /** * Magic method * * @param string $name * @param array $arg * * @throws CentreonClapiException * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { switch ($matches[2]) { case 'hostgroup': $class = 'Centreon_Object_Host_Group'; $relclass = 'Centreon_Object_Relation_Host_Group_Service'; break; case 'contact': $class = 'Centreon_Object_Contact'; $relclass = 'Centreon_Object_Relation_Contact_Service'; break; case 'contactgroup': $class = 'Centreon_Object_Contact_Group'; $relclass = 'Centreon_Object_Relation_Contact_Group_Service'; break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); break; } if (class_exists($relclass) && class_exists($class)) { // Parse arguments if (! isset($arg[0]) || ! $arg[0]) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $args[0], 'service_description' => $args[1]], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0] . '/' . $args[1]); } $serviceId = $elements[0]['service_id']; $relobj = new $relclass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $serviceId ); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { if ($value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } } else { if (! isset($args[1]) || ! isset($args[2])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($matches[2] == 'contact') { $args[2] = str_replace(' ', '_', $args[2]); } $relation = $args[2]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { if ($matches[1] != 'del' && $matches[2] == 'hostgroup' && $this->serviceExists($rel, $args[1]) ) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $serviceId ); if ($matches[1] == 'set') { $relobj->delete(null, $serviceId); } foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($relationId, $serviceId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($relationId, $serviceId); } } } } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * Returns type of host service relation * * @param int $serviceId * * @throws PDOException * @return int */ public function hostTypeLink($serviceId) { $sql = 'SELECT host_host_id, hostgroup_hg_id FROM host_service_relation WHERE service_service_id = ?'; $res = $this->db->query($sql, [$serviceId]); $rows = $res->fetch(); if (count($rows)) { if (isset($rows['host_host_id']) && $rows['host_host_id']) { return 1; } if (isset($rows['hostgroup_hg_id']) && $rows['hostgroup_hg_id']) { return 2; } } return 0; } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = ['service_register' => $this->register]; if (isset($parameters)) { $filters['service_description'] = '%' . $parameters . '%'; } $commandObject = new Centreon_Object_Command($this->dependencyInjector); $paramsHost = ['hg_id', 'hg_name']; $paramsSvc = ['service_id', 'service_description', 'command_command_id', 'command_command_id_arg', 'service_normal_check_interval', 'service_retry_check_interval', 'service_max_check_attempts', 'service_active_checks_enabled', 'service_passive_checks_enabled']; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( $paramsHost, $paramsSvc, -1, 0, 'hg_name,service_description', 'ASC', $filters, 'AND' ); $paramHostString = str_replace('_', ' ', implode($this->delim, $paramsHost)); echo $paramHostString . $this->delim; $paramSvcString = str_replace('service_', '', implode($this->delim, $paramsSvc)); $paramSvcString = str_replace('command_command_id', 'check command', $paramSvcString); $paramSvcString = str_replace('command_command_id_arg', 'check command arguments', $paramSvcString); $paramSvcString = str_replace('_', ' ', $paramSvcString); echo $paramSvcString . "\n"; foreach ($elements as $tab) { if (isset($tab['command_command_id']) && $tab['command_command_id']) { $tmp = $commandObject->getParameters( $tab['command_command_id'], [$commandObject->getUniqueLabelField()] ); if (isset($tmp[$commandObject->getUniqueLabelField()])) { $tab['command_command_id'] = $tmp[$commandObject->getUniqueLabelField()]; } } echo implode($this->delim, $tab) . "\n"; } } /** * Delete service * * @param string $objectName * * @throws CentreonClapiException * @return void */ public function del($objectName): void { $params = explode($this->delim, $objectName); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDesc = $params[1]; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDesc], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hgName . '/' . $serviceDesc); } $this->object->delete($elements[0]['service_id']); } /** * @param $parameters * * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($this->serviceExists($params[self::ORDER_HOSTNAME], $params[self::ORDER_SVCDESC]) == true) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $hgObject = new Centreon_Object_Host_Group($this->dependencyInjector); $tmp = $hgObject->getIdByParameter($hgObject->getUniqueLabelField(), $params[self::ORDER_HOSTNAME]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_HOSTNAME]); } $this->hgId = $tmp[0]; $addParams = []; $addParams['service_description'] = $params[self::ORDER_SVCDESC]; $template = $params[self::ORDER_SVCTPL]; $tmp = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, ['service_description' => $template, 'service_register' => '0'], 'AND' ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $template); } $addParams['service_template_model_stm_id'] = $tmp[0][$this->object->getPrimaryKey()]; $this->params = array_merge($this->params, $addParams); } /** * @param $serviceId */ public function insertRelations($serviceId): void { $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $relObject->insert($this->hgId, $serviceId); $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $extended->insert([$extended->getUniqueLabelField() => $serviceId]); } /** * Set parameters * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDesc = $params[1]; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDesc], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hgName . '/' . $serviceDesc); } $objectId = $elements[0]['service_id']; $extended = false; $commandObject = new CentreonCommand($this->dependencyInjector); switch ($params[2]) { case 'contact_additive_inheritance': case 'cg_additive_inheritance': break; case 'check_command': $params[2] = 'command_command_id'; $params[3] = $commandObject->getId($params[3]); break; case 'check_command_arguments': $params[2] = 'command_command_id_arg'; break; case 'event_handler': $params[2] = 'command_command_id2'; $params[3] = $commandObject->getId($params[3]); break; case 'event_handler_arguments': $params[2] = 'command_command_id_arg2'; break; case 'check_period': $params[2] = 'timeperiod_tp_id'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[3] = $tpObj->getTimeperiodId($params[3]); break; case 'notification_period': $params[2] = 'timeperiod_tp_id2'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[3] = $tpObj->getTimeperiodId($params[3]); break; case 'flap_detection_options': break; case 'template': $params[2] = 'service_template_model_stm_id'; $tmp = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, ['service_description' => $params[3], 'service_register' => '0'], 'AND' ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[3]); } $params[3] = $tmp[0][$this->object->getPrimaryKey()]; break; case 'graphtemplate': $extended = true; $graphObj = new Centreon_Object_Graph_Template($this->dependencyInjector); $tmp = $graphObj->getIdByParameter($graphObj->getUniqueLabelField(), $params[3]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[3]); } $params[2] = 'graph_id'; $params[3] = $tmp[0]; break; case 'notes': case 'notes_url': case 'action_url': case 'icon_image': case 'icon_image_alt': $extended = true; break; default: if (! preg_match('/^service_/', $params[2])) { $params[2] = 'service_' . $params[2]; } break; } if ($extended == false) { $updateParams = [$params[2] => $params[3]]; $updateParams['objectId'] = $objectId; return $updateParams; } if ($params[2] != 'graph_id') { $params[2] = 'esi_' . $params[2]; if ($params[2] == 'esi_icon_image') { if ($params[3]) { $id = CentreonUtils::getImageId($params[3], $this->db); if (is_null($id)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[3]); } $params[3] = $id; } else { $params[3] = null; } } } $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $extended->update($objectId, [$params[2] => $params[3]]); return []; } /** * Get macro list of a service * * @param string $parameters * * @throws CentreonClapiException * @return void */ public function getmacro($parameters): void { $tmp = explode($this->delim, $parameters); if (count($tmp) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $tmp[0]; $serviceDescription = $tmp[1]; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDescription], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hgName . '/' . $serviceDescription); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( ['svc_macro_name', 'svc_macro_value'], -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id']] ); echo "macro name;macro value\n"; foreach ($macroList as $macro) { echo $this->csvEscape($macro['svc_macro_name']) . $this->delim . $this->csvEscape($macro['svc_macro_value']) . "\n"; } } /** * Inserts/updates custom macro * * @param string $parameters * * @throws CentreonClapiException * @return void */ public function setmacro($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 4) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDescription = $params[1]; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDescription], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hgName . '/' . $serviceDescription); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( $macroObj->getPrimaryKey(), -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($params[2])], 'AND' ); if (count($macroList)) { $macroObj->update($macroList[0][$macroObj->getPrimaryKey()], ['svc_macro_value' => $params[3]]); } else { $macroObj->insert(['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($params[2]), 'svc_macro_value' => $params[3]]); } } /** * Delete custom macro * * @param string $parameters * * @throws CentreonClapiException * @return void */ public function delmacro($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDescription = $params[1]; $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDescription], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hgName . '/' . $serviceDescription); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( $macroObj->getPrimaryKey(), -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($params[2])], 'AND' ); if (count($macroList)) { $macroObj->delete($macroList[0][$macroObj->getPrimaryKey()]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setseverity($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDescription = $params[1]; $rel = new Centreon_Object_Relation_Service_Category_Service($this->dependencyInjector); $relObject = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDescription], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0] . '/' . $params[1]); } $serviceId = $elements[0]['service_id']; $severityObj = new Centreon_Object_Service_Category($this->dependencyInjector); $severity = $severityObj->getIdByParameter( $severityObj->getUniqueLabelField(), $params[2] ); if (! isset($severity[0])) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $severityId = $severity[0]; $severity = $severityObj->getParameters( $severityId, ['level'] ); if ($severity['level']) { // can't delete with generic method $this->db->query( 'DELETE FROM service_categories_relation WHERE service_service_id = ? AND sc_id IN (SELECT sc_id FROM service_categories WHERE level > 0)', $serviceId ); $rel->insert($severityId, $serviceId); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function unsetseverity($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hgName = $params[0]; $serviceDescription = $params[1]; $hostServiceRel = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $hostServiceRel->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $hgName, 'service_description' => $serviceDescription], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0] . '/' . $params[1]); } $serviceId = $elements[0]['service_id']; // can't delete with generic method $this->db->query( 'DELETE FROM service_categories_relation WHERE service_service_id = ? AND sc_id IN (SELECT sc_id FROM service_categories WHERE level > 0)', $serviceId ); } /** * Get Object Name * * @param int $id * * @return string */ public function getObjectName($id) { $tmp = $this->object->getParameters($id, ['service_description']); return $tmp['service_description'] ?? ''; } /** * Export * * @param null $filterName * * @throws Exception * @return int|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return 0; } $labelField = $this->object->getUniqueLabelField(); $filters = ['service_register' => $this->register]; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $hostRel = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $elements = $hostRel->getMergedParameters( ['hg_name'], ['*'], -1, 0, null, null, $filters, 'AND' ); $extendedObj = new Centreon_Object_Service_Extended($this->dependencyInjector); $commandObj = new Centreon_Object_Command($this->dependencyInjector); $tpObj = new Centreon_Object_Timeperiod($this->dependencyInjector); $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $addStr .= $this->delim; if ($param == 'service_template_model_stm_id') { $tmp = $this->object->getParameters($element[$param], 'service_description'); if (isset($tmp, $tmp['service_description']) && $tmp['service_description']) { $element[$param] = $tmp['service_description']; CentreonServiceTemplate::getInstance()->export($tmp['service_description']); } if (! $element[$param]) { $element[$param] = ''; } } $addStr .= $element[$param]; } $addStr .= "\n"; echo $addStr; foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams) && ! is_null($value) && $value != '') { $action_tmp = null; if ($parameter == 'timeperiod_tp_id' || $parameter == 'timeperiod_tp_id2') { $action_tmp = 'TP'; $tmpObj = CentreonTimePeriod::getInstance(); } elseif ($parameter == 'command_command_id' || $parameter == 'command_command_id2') { $action_tmp = 'CMD'; $tmpObj = CentreonCommand::getInstance(); } if (isset($tmpObj)) { $tmpLabelField = $tmpObj->getObject()->getUniqueLabelField(); $tmp = $tmpObj->getObject()->getParameters($value, $tmpLabelField); if (isset($tmp, $tmp[$tmpLabelField])) { $tmp_id = $value; $value = $tmp[$tmpLabelField]; if (! is_null($action_tmp)) { $tmpObj::getInstance()->export($value); } } unset($tmpObj); } echo $this->action . $this->delim . 'setparam' . $this->delim . $element['hg_name'] . $this->delim . $element['service_description'] . $this->delim . $this->getClapiActionName($parameter) . $this->delim . $value . "\n"; } } $params = $extendedObj->getParameters( $element[$this->object->getPrimaryKey()], ['esi_notes', 'esi_notes_url', 'esi_action_url', 'esi_icon_image', 'esi_icon_image_alt'] ); if (isset($params) && is_array($params)) {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonHostTemplate.class.php
centreon/www/class/centreon-clapi/centreonHostTemplate.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Host_Extended; use Centreon_Object_Host_Macro_Custom; use Centreon_Object_Relation_Contact_Group_Host; use Centreon_Object_Relation_Contact_Host; use Centreon_Object_Relation_Host_Group_Host; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Host_Template_Host; use Exception; use PDOException; use Pimple\Container; require_once 'centreonHost.class.php'; /** * Class * * @class CentreonHostTemplate * @package CentreonClapi */ class CentreonHostTemplate extends CentreonHost { /** @var string[] */ public static $aDepends = ['CMD', 'TP', 'TRAP', 'INSTANCE']; /** * CentreonHostTemplate constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->params['host_register'] = '0'; $this->register = 0; $this->action = 'HTPL'; } /** * Will throw an exception if set instance is called * * @param null|mixed $parameters * @throws CentreonClapiException */ public function setinstance($parameters = null): void { throw new CentreonClapiException(self::UNKNOWN_METHOD); } /** * Export * * @param mixed|null $filterName * * @throws Exception * @return void */ public function export(mixed $filterName = null): void { if (! $this->canBeExported($filterName)) { return; } $labelField = $this->object->getUniqueLabelField(); $filters = ['host_register' => $this->register]; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); $extendedObj = new Centreon_Object_Host_Extended($this->dependencyInjector); $macroObj = new Centreon_Object_Host_Macro_Custom($this->dependencyInjector); foreach ($elements as $element) { // add host template $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $addStr .= $this->delim; if (isset($element[$param]) && $param != 'hostgroup' && $param != 'template') { $addStr .= $element[$param]; } } $addStr .= "\n"; echo $addStr; CentreonExported::getInstance()->setExported($this->action, $element['host_id']); // host template params foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams) && ! is_null($value) && $value != '') { $action_tmp = null; if ($parameter == 'timeperiod_tp_id' || $parameter == 'timeperiod_tp_id2') { $action_tmp = 'TP'; $tmpObj = CentreonTimePeriod::getInstance(); } elseif ($parameter == 'command_command_id' || $parameter == 'command_command_id2') { $action_tmp = 'CMD'; $tmpObj = CentreonCommand::getInstance(); } elseif ($parameter == 'host_location') { $tmpObj = CentreonTimezone::getInstance(); } if (isset($tmpObj)) { $tmpLabelField = $tmpObj->getObject()->getUniqueLabelField(); $tmp = $tmpObj->getObject()->getParameters($value, $tmpLabelField); if (isset($tmp, $tmp[$tmpLabelField])) { $value = $tmp[$tmpLabelField]; if (! is_null($action_tmp)) { $tmpObj::getInstance()->export($value); } } unset($tmpObj); } $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $this->getClapiActionName($parameter) . $this->delim . $value . "\n"; } } $params = $extendedObj->getParameters( $element[$this->object->getPrimaryKey()], ['ehi_notes', 'ehi_notes_url', 'ehi_action_url', 'ehi_icon_image', 'ehi_icon_image_alt', 'ehi_vrml_image', 'ehi_statusmap_image', 'ehi_2d_coords', 'ehi_3d_coords'] ); if (isset($params) && is_array($params)) { foreach ($params as $k => $v) { if (! is_null($v) && $v != '') { $v = CentreonUtils::convertLineBreak($v); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $this->getClapiActionName($k) . $this->delim . $v . "\n"; } } } // macros linked $macros = $macroObj->getList( '*', -1, 0, null, null, ['host_host_id' => $element[$this->object->getPrimaryKey()]], 'AND' ); foreach ($macros as $macro) { $description = $macro['description']; if ( strlen($description) > 0 && ! str_starts_with($description, "'") && ! str_ends_with($description, "'") ) { $description = "'" . $description . "'"; } echo $this->action . $this->delim . 'setmacro' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $this->stripMacro($macro['host_macro_name']) . $this->delim . $macro['host_macro_value'] . $this->delim . ((strlen($macro['is_password']) === 0) ? 0 : (int) $macro['is_password']) . $this->delim . $description . "\n"; } } // contact groups linked $cgRel = new Centreon_Object_Relation_Contact_Group_Host($this->dependencyInjector); $filters_cgRel = ['host_register' => $this->register]; if (! is_null($filterName)) { $filters_cgRel['host_name'] = $filterName; } $cgElements = $cgRel->getMergedParameters( ['cg_name', 'cg_id'], [$this->object->getUniqueLabelField()], -1, 0, null, null, $filters_cgRel, 'AND' ); foreach ($cgElements as $cgElement) { CentreonContactGroup::getInstance()->export($cgElement['cg_name']); echo $this->action . $this->delim . 'addcontactgroup' . $this->delim . $cgElement[$this->object->getUniqueLabelField()] . $this->delim . $cgElement['cg_name'] . "\n"; } // contacts linked $contactRel = new Centreon_Object_Relation_Contact_Host($this->dependencyInjector); $filters_contactRel = ['host_register' => $this->register]; if (! is_null($filterName)) { $filters_contactRel['host_name'] = $filterName; } $contactElements = $contactRel->getMergedParameters( ['contact_alias', 'contact_id'], [$this->object->getUniqueLabelField()], -1, 0, null, null, $filters_contactRel, 'AND' ); foreach ($contactElements as $contactElement) { CentreonContact::getInstance()->export($contactElement['contact_alias']); echo $this->action . $this->delim . 'addcontact' . $this->delim . $contactElement[$this->object->getUniqueLabelField()] . $this->delim . $contactElement['contact_alias'] . "\n"; } // host templates linked $htplRel = new Centreon_Object_Relation_Host_Template_Host($this->dependencyInjector); $filters_htplRel = ['h.host_register' => $this->register]; if (! is_null($filterName)) { $filters_htplRel['h.host_name'] = $filterName; } $tplElements = $htplRel->getMergedParameters( ['host_name as host'], ['host_name as template', 'host_id as tpl_id'], -1, 0, 'host,`order`', 'ASC', $filters_htplRel, 'AND' ); foreach ($tplElements as $tplElement) { CentreonHostTemplate::getInstance()->export($tplElement['template']); echo $this->action . $this->delim . 'addtemplate' . $this->delim . $tplElement['host'] . $this->delim . $tplElement['template'] . "\n"; } // Filter only if (! is_null($filterName)) { // service templates linked $hostRel = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $helements = $hostRel->getMergedParameters( ['host_name'], ['service_description', 'service_id'], -1, 0, null, null, ['service_register' => 0, 'host_name' => $filterName], 'AND' ); foreach ($helements as $helement) { CentreonServiceTemplate::getInstance()->export($helement['service_description']); } // services linked $hostRel = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $helements = $hostRel->getMergedParameters( ['host_name'], ['service_description', 'service_id'], -1, 0, null, null, ['service_register' => 1, 'host_name' => $filterName], 'AND' ); foreach ($helements as $helement) { CentreonService::getInstance()->export($filterName . ';' . $helement['service_description']); } // service hg linked and hostgroups $hostRel = new Centreon_Object_Relation_Host_Group_Host($this->dependencyInjector); $helements = $hostRel->getMergedParameters( ['hg_name', 'hg_id'], ['*'], -1, 0, null, null, ['host_name' => $filterName], 'AND' ); foreach ($helements as $helement) { CentreonHostGroup::getInstance()->export($helement['hg_name']); CentreonHostGroupService::getInstance()->export($helement['hg_name']); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonDependency.class.php
centreon/www/class/centreon-clapi/centreonDependency.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object; use Centreon_Object_Dependency; use Centreon_Object_Host; use Centreon_Object_Host_Group; use Centreon_Object_Meta_Service; use Centreon_Object_Relation; use Centreon_Object_Relation_Dependency_Parent_Host; use Centreon_Object_Relation_Dependency_Parent_Hostgroup; use Centreon_Object_Relation_Dependency_Parent_Metaservice; use Centreon_Object_Relation_Dependency_Parent_Servicegroup; use Centreon_Object_Service_Group; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonHost.class.php'; require_once 'centreonService.class.php'; require_once 'Centreon/Object/Dependency/Dependency.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Meta/Service.php'; require_once 'Centreon/Object/Relation/Dependency/Parent/Host.php'; require_once 'Centreon/Object/Relation/Dependency/Parent/Hostgroup.php'; require_once 'Centreon/Object/Relation/Dependency/Parent/Servicegroup.php'; require_once 'Centreon/Object/Relation/Dependency/Parent/Metaservice.php'; /** * Class * * @class CentreonDependency * @package CentreonClapi * @description Class for managing dependency objects */ class CentreonDependency extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const ORDER_DEP_TYPE = 2; public const ORDER_PARENTS = 3; public const DEP_TYPE_HOST = 'HOST'; public const DEP_TYPE_HOSTGROUP = 'HG'; public const DEP_TYPE_SERVICE = 'SERVICE'; public const DEP_TYPE_SERVICEGROUP = 'SG'; public const DEP_TYPE_META = 'META'; /** @var CentreonService */ protected $serviceObj; /** * CentreonDependency constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->serviceObj = new CentreonService($dependencyInjector); $this->object = new Centreon_Object_Dependency($dependencyInjector); $this->action = 'DEP'; $this->insertParams = ['dep_name', 'dep_description', 'type', 'parents']; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['dep_id', 'dep_name', 'dep_description', 'inherits_parent', 'execution_failure_criteria', 'notification_failure_criteria']; $paramString = str_replace('dep_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * Add action * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function add($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['dep_description'] = $params[self::ORDER_ALIAS]; $addParams['parents'] = $params[self::ORDER_PARENTS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); switch (strtoupper($params[self::ORDER_DEP_TYPE])) { case self::DEP_TYPE_HOST: $this->addHostDependency($addParams); break; case self::DEP_TYPE_HOSTGROUP: $this->addHostGroupDependency($addParams); break; case self::DEP_TYPE_SERVICE: $this->addServiceDependency($addParams); break; case self::DEP_TYPE_SERVICEGROUP: $this->addServiceGroupDependency($addParams); break; case self::DEP_TYPE_META: $this->addMetaDependency($addParams); break; default: throw new CentreonClapiException( sprintf( 'Unknown type %s. Please choose one of the following host|hg|service|sg|meta', $params[self::ORDER_DEP_TYPE] ) ); break; } } /** * @param null $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (in_array($params[1], ['comment', 'name', 'description']) && ! preg_match('/^dep_/', $params[1])) { $params[1] = 'dep_' . $params[1]; } $params[2] = str_replace('<br/>', "\n", $params[2]); $updateParams = [$params[1] => htmlentities($params[2], ENT_QUOTES, 'UTF-8')]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * List dependencies * * @param string $parameters | dependency name * * @throws CentreonClapiException * @throws PDOException */ public function listdep($parameters): void { $type = $this->getDependencyType($parameters); if ($type == '') { throw new CentreonClapiException('Could not define type of dependency'); } $depId = $this->getObjectId($parameters); // header echo implode($this->delim, ['parents', 'children']) . "\n"; switch ($type) { case self::DEP_TYPE_HOST: $this->listhostdep($depId); break; case self::DEP_TYPE_HOSTGROUP: $this->listhostgroupdep($depId); break; case self::DEP_TYPE_SERVICE: $this->listservicedep($depId); break; case self::DEP_TYPE_SERVICEGROUP: $this->listservicegroupdep($depId); break; case self::DEP_TYPE_META: $this->listmetadep($depId); break; default: break; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function delparent($parameters): void { $this->deleteRelations($parameters, 'parent'); } /** * Delete child * * @param string $parameters | dep_name;children_to_delete * * @throws CentreonClapiException * @throws PDOException */ public function delchild($parameters): void { $this->deleteRelations($parameters, 'child'); } /** * Add parent * * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addparent($parameters): void { $this->addRelations($parameters, 'parent'); } /** * Add child * * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function addchild($parameters): void { $this->addRelations($parameters, 'child'); } /** * Export * * @param $filterName * * @return void */ public function export($filterName = null): void { $this->exportHostDep(); $this->exportServiceDep(); $this->exportHostgroupDep(); $this->exportServicegroupDep(); $this->exportMetaDep(); } /** * Return the type of dependency * * @param string $dependencyName * * @throws PDOException * @return string */ protected function getDependencyType($dependencyName) { $sql = "SELECT '" . self::DEP_TYPE_HOST . "' as type FROM dependency d, dependency_hostParent_relation rel WHERE rel.dependency_dep_id = d.dep_id AND d.dep_name = :name UNION SELECT '" . self::DEP_TYPE_SERVICE . "' FROM dependency d, dependency_serviceParent_relation rel WHERE rel.dependency_dep_id = d.dep_id AND d.dep_name = :name UNION SELECT '" . self::DEP_TYPE_HOSTGROUP . "' FROM dependency d, dependency_hostgroupParent_relation rel WHERE rel.dependency_dep_id = d.dep_id AND d.dep_name = :name UNION SELECT '" . self::DEP_TYPE_SERVICEGROUP . "' FROM dependency d, dependency_servicegroupParent_relation rel WHERE rel.dependency_dep_id = d.dep_id AND d.dep_name = :name UNION SELECT '" . self::DEP_TYPE_META . "' FROM dependency d, dependency_metaserviceParent_relation rel WHERE rel.dependency_dep_id = d.dep_id AND d.dep_name = :name"; $res = $this->db->query($sql, [':name' => $dependencyName]); $row = $res->fetch(); return $row['type'] ?? ''; } /** * @param int $dependencyId * * @throws PDOException * @return string */ protected function getDependencyName(int $dependencyId): string { $sql = 'SELECT `dep_name` FROM `dependency` WHERE `dep_id` = :depId'; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $dependencyId, PDO::PARAM_INT); $stmt->execute(); $row = $stmt->fetch(); return $row['dep_name'] ?? ''; } /** * Insert new dependency * * @param string $name * @param string $description * @param Centreon_Object $parentObj * @param string $parentString * @param Centreon_Object_Relation $relationObj * * @throws CentreonClapiException * @return void */ protected function insertDependency($name, $description, $parentObj, $parentString, $relationObj) { $parents = explode('|', $parentString); $parentIds = []; foreach ($parents as $parent) { $idTab = $parentObj->getIdByParameter( $parentObj->getUniqueLabelField(), [$parent] ); // make sure that all parents exist if (! count($idTab)) { throw new CentreonClapiException(sprintf('Could not find %s', $parent)); } $parentIds[] = $idTab[0]; } // insert dependency $depId = $this->object->insert( ['dep_name' => $name, 'dep_description' => $description] ); if (is_null($depId)) { throw new CentreonClapiException(sprintf('Could not insert dependency %s', $name)); } // insert relations foreach ($parentIds as $parentId) { $relationObj->insert($depId, $parentId); } } /** * Add host type dependency * * @param array $params * * @throws CentreonClapiException */ protected function addHostDependency($params) { $obj = new Centreon_Object_Host($this->dependencyInjector); $relObj = new Centreon_Object_Relation_Dependency_Parent_Host($this->dependencyInjector); $this->insertDependency( $params['dep_name'], $params['dep_description'], $obj, $params['parents'], $relObj ); } /** * Add hostgroup type dependency * * @param array $params * * @throws CentreonClapiException */ protected function addHostGroupDependency($params) { $obj = new Centreon_Object_Host_Group($this->dependencyInjector); $relObj = new Centreon_Object_Relation_Dependency_Parent_Hostgroup($this->dependencyInjector); $this->insertDependency( $params['dep_name'], $params['dep_description'], $obj, $params['parents'], $relObj ); } /** * @param $params * * @throws CentreonClapiException * @throws PDOException */ protected function addServiceDependency($params) { $parents = explode('|', $params['parents']); $parentIds = []; foreach ($parents as $parent) { $tmp = explode(',', $parent); if (count($tmp) != 2) { throw new CentreonClapiException('Incorrect service definition'); } // make sure that all parents exist $host = $tmp[0]; $service = $tmp[1]; $idTab = $this->serviceObj->getHostAndServiceId($host, $service); if (! count($idTab)) { throw new CentreonClapiException(sprintf('Could not find service %s on host %s', $service, $host)); } $parentIds[] = $idTab; } // insert dependency $depId = $this->object->insert( ['dep_name' => $params['dep_name'], 'dep_description' => $params['dep_description']] ); if (is_null($depId)) { throw new CentreonClapiException(sprintf('Could not insert dependency %s', $name)); } // insert relations $sql = 'INSERT INTO dependency_serviceParent_relation (dependency_dep_id, host_host_id, service_service_id) VALUES (?, ?, ?)'; foreach ($parentIds as $parentId) { $this->db->query($sql, [$depId, $parentId[0], $parentId[1]]); } } /** * Add servicegroup type dependency * * @param array $params * * @throws CentreonClapiException */ protected function addServiceGroupDependency($params) { $obj = new Centreon_Object_Service_Group($this->dependencyInjector); $relObj = new Centreon_Object_Relation_Dependency_Parent_Servicegroup($this->dependencyInjector); $this->insertDependency( $params['dep_name'], $params['dep_description'], $obj, $params['parents'], $relObj ); } /** * Add meta type dependency * * @param array $params * * @throws CentreonClapiException */ protected function addMetaDependency($params) { $obj = new Centreon_Object_Meta_Service($this->dependencyInjector); $relObj = new Centreon_Object_Relation_Dependency_Parent_Metaservice($this->dependencyInjector); $this->insertDependency( $params['dep_name'], $params['dep_description'], $obj, $params['parents'], $relObj ); } /** * List host group dependency * * @param int $depId * * @throws PDOException */ protected function listhostgroupdep($depId) { // Parents $sql = 'SELECT hg_name FROM hostgroup hg, dependency_hostgroupParent_relation rel WHERE hg.hg_id = rel.hostgroup_hg_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $parents = []; foreach ($rows as $row) { $parents[] = $row['hg_name']; } // Children $sql = 'SELECT hg_name FROM hostgroup hg, dependency_hostgroupChild_relation rel WHERE hg.hg_id = rel.hostgroup_hg_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $children = []; foreach ($rows as $row) { $children[] = $row['hg_name']; } $str = implode('|', $parents) . $this->delim; $str .= implode('|', $children); echo str_replace('||', '|', $str) . "\n"; } /** * List service dependency * * @param int $depId * * @throws PDOException */ protected function listservicedep($depId) { // Parents $sql = 'SELECT host_name, service_description FROM host h, service s, dependency_serviceParent_relation rel WHERE h.host_id = rel.host_host_id AND rel.service_service_id = s.service_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $parents = []; foreach ($rows as $row) { $parents[] = $row['host_name'] . ',' . $row['service_description']; } // Host children $sql = 'SELECT host_name FROM host h, dependency_hostChild_relation rel WHERE h.host_id = rel.host_host_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $hostChildren = []; foreach ($rows as $row) { $hostChildren[] = $row['host_name']; } // Service children $sql = 'SELECT host_name, service_description FROM host h, service s, dependency_serviceChild_relation rel WHERE h.host_id = rel.host_host_id AND rel.service_service_id = s.service_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $serviceChildren = []; foreach ($rows as $row) { $serviceChildren[] = $row['host_name'] . ',' . $row['service_description']; } $strParents = implode('|', $parents) . $this->delim; $strChildren = implode('|', $hostChildren) . '|'; $strChildren .= implode('|', $serviceChildren); echo str_replace('||', '|', $strParents . trim($strChildren, '|')) . "\n"; } /** * List service group dependency * * @param int $depId * * @throws PDOException */ protected function listservicegroupdep($depId) { // Parents $sql = 'SELECT sg_name FROM servicegroup sg, dependency_servicegroupParent_relation rel WHERE sg.sg_id = rel.servicegroup_sg_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $parents = []; foreach ($rows as $row) { $parents[] = $row['sg_name']; } // Children $sql = 'SELECT sg_name FROM servicegroup sg, dependency_servicegroupChild_relation rel WHERE sg.sg_id = rel.servicegroup_sg_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $children = []; foreach ($rows as $row) { $children[] = $row['sg_name']; } $str = implode('|', $parents) . $this->delim; $str .= implode('|', $children); echo str_replace('||', '|', trim($str, '|')) . "\n"; } /** * List meta service dependency * * @param int $depId * * @throws PDOException */ protected function listmetadep($depId) { // Parents $sql = 'SELECT meta_name FROM meta_service m, dependency_metaserviceParent_relation rel WHERE m.meta_id = rel.meta_service_meta_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $parents = []; foreach ($rows as $row) { $parents[] = $row['meta_name']; } // Children $sql = 'SELECT meta_name FROM meta_service m, dependency_metaserviceChild_relation rel WHERE m.meta_id = rel.meta_service_meta_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $children = []; foreach ($rows as $row) { $children[] = $row['meta_name']; } $str = implode('|', $parents) . $this->delim; $str .= implode('|', $children); echo str_replace('||', '|', trim($str, '|')) . "\n"; } /** * List host dependency * * @param int $depId * * @throws PDOException */ protected function listhostdep($depId) { // Parents $sql = 'SELECT host_name FROM host h, dependency_hostParent_relation rel WHERE h.host_id = rel.host_host_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $parents = []; foreach ($rows as $row) { $parents[] = $row['host_name']; } // Host children $sql = 'SELECT host_name FROM host h, dependency_hostChild_relation rel WHERE h.host_id = rel.host_host_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $hostChildren = []; foreach ($rows as $row) { $hostChildren[] = $row['host_name']; } // Service children $sql = 'SELECT host_name, service_description FROM host h, service s, dependency_serviceChild_relation rel WHERE h.host_id = rel.host_host_id AND rel.service_service_id = s.service_id AND rel.dependency_dep_id = ?'; $res = $this->db->query($sql, [$depId]); $rows = $res->fetchAll(); $serviceChildren = []; foreach ($rows as $row) { $serviceChildren[] = $row['host_name'] . ',' . $row['service_description']; } $strParents = implode('|', $parents) . $this->delim; $strChildren = implode('|', $hostChildren) . '|'; $strChildren .= implode('|', $serviceChildren); echo str_replace('||', '|', $strParents . trim($strChildren, '|')) . "\n"; } /** * Add relations * * @param $parameters * @param string $relType * * @throws CentreonClapiException * @throws PDOException */ protected function addRelations($parameters, $relType = 'parent') { $param = explode($this->delim, $parameters); if (count($param) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } // get dependency id $depId = $this->getObjectId($param[0]); if (! $depId) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND); } // get dependency type $depType = $this->getDependencyType($param[0]); $objectToDelete = $param[1]; switch ($depType) { case self::DEP_TYPE_HOSTGROUP: $this->addHostgroupRelations($depId, $objectToDelete, $relType); break; case self::DEP_TYPE_SERVICEGROUP: $this->addServicegroupRelations($depId, $objectToDelete, $relType); break; case self::DEP_TYPE_META: $this->addMetaRelations($depId, $objectToDelete, $relType); break; case self::DEP_TYPE_HOST: $this->addHostRelations($depId, $objectToDelete, $relType); break; case self::DEP_TYPE_SERVICE: $this->addServiceRelations($depId, $objectToDelete, $relType); break; default: break; } } /** * @param $depId * @param $objectToInsert * @param $relType * * @throws CentreonClapiException * @throws PDOException */ protected function addHostgroupRelations($depId, $objectToInsert, $relType) { $table = 'dependency_hostgroup' . ucfirst($relType) . '_relation'; $obj = new Centreon_Object_Host_Group($this->dependencyInjector); $ids = $obj->getIdByParameter($obj->getUniqueLabelField(), [$objectToInsert]); if (! count($ids)) { throw new CentreonClapiException(sprintf('Could not find host group %s', $objectToInsert)); } $dataField = ['dependency_dep_id' => $depId, 'hostgroup_hg_id' => $ids[0]]; if ($this->isExistingDependency($table, $dataField)) { throw new CentreonClapiException( sprintf( 'Hostgroup %s is already linked to the dependency %s', $objectToInsert, $this->getDependencyName($depId) ) ); } $sql = "INSERT INTO {$table} (dependency_dep_id, hostgroup_hg_id) VALUES (:depId, :hgId)"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $depId, PDO::PARAM_INT); $stmt->bindParam(':hgId', $ids[0], PDO::PARAM_INT); $stmt->execute(); } /** * @param $depId * @param $objectToInsert * @param $relType * * @throws CentreonClapiException * @throws PDOException */ protected function addServicegroupRelations($depId, $objectToInsert, $relType) { $table = 'dependency_servicegroup' . ucfirst($relType) . '_relation'; $obj = new Centreon_Object_Service_Group($this->dependencyInjector); $ids = $obj->getIdByParameter($obj->getUniqueLabelField(), [$objectToInsert]); if (! count($ids)) { throw new CentreonClapiException(sprintf('Could not find service group %s', $objectToInsert)); } $dataField = ['dependency_dep_id' => $depId, 'servicegroup_sg_id' => $ids[0]]; if ($this->isExistingDependency($table, $dataField)) { throw new CentreonClapiException( sprintf( 'Servicegroup %s is already linked to the dependency %s', $objectToInsert, $this->getDependencyName($depId) ) ); } $sql = "INSERT INTO {$table} (dependency_dep_id, servicegroup_sg_id) VALUES (:depId, :sgId)"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $depId, PDO::PARAM_INT); $stmt->bindParam(':sgId', $ids[0], PDO::PARAM_INT); $stmt->execute(); } /** * @param $depId * @param $objectToInsert * @param $relType * * @throws CentreonClapiException * @throws PDOException */ protected function addMetaRelations($depId, $objectToInsert, $relType) { $table = 'dependency_metaservice' . ucfirst($relType) . '_relation'; $obj = new Centreon_Object_Meta_Service($this->dependencyInjector); $ids = $obj->getIdByParameter($obj->getUniqueLabelField(), [$objectToInsert]); if (! count($ids)) { throw new CentreonClapiException(sprintf('Could not find meta service %s', $objectToInsert)); } $dataField = ['dependency_dep_id' => $depId, 'meta_service_meta_id' => $ids[0]]; if ($this->isExistingDependency($table, $dataField)) { throw new CentreonClapiException( sprintf( 'Meta %s already is already linked to the dependency %s', $objectToInsert, $this->getDependencyName($depId) ) ); } $sql = "INSERT INTO {$table} (dependency_dep_id, meta_service_meta_id) VALUES (:depId, :metaId)"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $depId, PDO::PARAM_INT); $stmt->bindParam(':metaId', $ids[0], PDO::PARAM_INT); $stmt->execute(); } /** * @param $depId * @param $objectToInsert * @param $relType * * @throws CentreonClapiException * @throws PDOException */ protected function addHostRelations($depId, $objectToInsert, $relType) { if ($relType == 'parent') { $hostObj = new Centreon_Object_Host($this->dependencyInjector); $hostIds = $hostObj->getIdByParameter($hostObj->getUniqueLabelField(), [$objectToInsert]); if (! count($hostIds)) { throw new CentreonClapiException(sprintf('Could not find host %s', $objectToInsert)); } $dataField = ['dependency_dep_id' => $depId, 'host_host_id' => $hostIds[0]]; if ($this->isExistingDependency('dependency_hostParent_relation', $dataField)) { throw new CentreonClapiException( sprintf( 'Host %s is already linked to the dependency %s', $objectToInsert, $this->getDependencyName($depId) ) ); } $sql = 'INSERT INTO dependency_hostParent_relation (dependency_dep_id, host_host_id) VALUES (:depId, :hostId)'; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $depId, PDO::PARAM_INT); $stmt->bindParam(':hostId', $hostIds[0], PDO::PARAM_INT); $stmt->execute(); } elseif ($relType == 'child' && strstr($objectToInsert, ',')) { // service child [$host, $service] = explode(',', $objectToInsert); $idTab = $this->serviceObj->getHostAndServiceId($host, $service); if (! count($idTab)) { throw new CentreonClapiException(sprintf('Could not find service %s on host %s', $service, $host)); } $dataField = [ 'dependency_dep_id' => $depId, 'host_host_id' => $idTab[0], 'service_service_id' => $idTab[1], ]; if ($this->isExistingDependency('dependency_serviceChild_relation', $dataField)) { throw new CentreonClapiException( sprintf( 'Dependency between service %s and host %s already exists on %s', $service, $host, $this->getDependencyName($depId) ) ); } $sql = 'INSERT INTO dependency_serviceChild_relation (dependency_dep_id, host_host_id, service_service_id) VALUES (:depId, :hostId, :svcId)'; $stmt = $this->db->prepare($sql); $stmt->bindParam(':depId', $depId, PDO::PARAM_INT); $stmt->bindParam(':hostId', $idTab[0], PDO::PARAM_INT); $stmt->bindParam(':svcId', $idTab[1], PDO::PARAM_INT); $stmt->execute(); } elseif ($relType == 'child') { // host child $hostObj = new Centreon_Object_Host($this->dependencyInjector); $hostIds = $hostObj->getIdByParameter($hostObj->getUniqueLabelField(), [$objectToInsert]); if (! count($hostIds)) { throw new CentreonClapiException(sprintf('Could not find host %s', $objectToInsert)); } $dataField = ['dependency_dep_id' => $depId, 'host_host_id' => $hostIds[0]]; if ($this->isExistingDependency('dependency_hostChild_relation', $dataField)) { throw new CentreonClapiException( sprintf( 'Host %s is already linked to the dependency %s',
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonTrap.class.php
centreon/www/class/centreon-clapi/centreonTrap.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Trap; use Centreon_Object_Trap_Matching; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonManufacturer.class.php'; require_once 'centreonHost.class.php'; require_once 'centreonService.class.php'; require_once 'Centreon/Object/Trap/Trap.php'; require_once 'Centreon/Object/Trap/Matching.php'; require_once 'Centreon/Object/Relation/Trap/Service.php'; /** * Class * * @class CentreonTrap * @package CentreonClapi */ class CentreonTrap extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_OID = 1; public const UNKNOWN_STATUS = 'Unknown status'; public const INCORRECT_PARAMETER = 'Incorrect parameter'; /** @var string[] */ public static $aDepends = ['VENDOR']; /** @var CentreonManufacturer */ public $manufacturerObj; /** * CentreonTrap constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Trap($dependencyInjector); $this->manufacturerObj = new CentreonManufacturer($dependencyInjector); $this->params = []; $this->insertParams = ['traps_name', 'traps_oid']; $this->action = 'TRAP'; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param string|null $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['traps_oid'] = $params[self::ORDER_OID]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * Get monitoring status * * @param string $val * @throws CentreonClapiException * @return int */ public function getStatusInt($val) { $val = strtolower($val); if (! is_numeric($val)) { $statusTab = ['ok' => 0, 'warning' => 1, 'critical' => 2, 'unknown' => 3]; if (isset($statusTab[$val])) { return $statusTab[$val]; } throw new CentreonClapiException(self::UNKNOWN_STATUS . ':' . $val); } elseif ($val > 3) { throw new CentreonClapiException(self::UNKNOWN_STATUS . ':' . $val); } return $val; } /** * @param string|null $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters = null) { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if ($params[1] == 'manufacturer' || $params[1] == 'vendor') { $params[1] = 'manufacturer_id'; $params[2] = $this->manufacturerObj->getId($params[2]); } elseif ($params[1] == 'status') { $params[1] = 'traps_status'; $params[2] = $this->getStatusInt($params[2]); } elseif ($params[1] == 'output') { $params[1] = 'traps_args'; } elseif ($params[1] == 'matching_mode') { $params[1] = 'traps_advanced_treatment'; } elseif (! preg_match('/^traps_/', $params[1])) { $params[1] = 'traps_' . $params[1]; } $params[2] = str_replace('<br/>', "\n", $params[2]); $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param string|null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['traps_id', 'traps_name', 'traps_oid', 'manufacturer_id']; $paramString = str_replace('_', ' ', implode($this->delim, $params)); $paramString = str_replace('traps ', '', $paramString); $paramString = str_replace('manufacturer id', 'manufacturer', $paramString); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { if ($key == 'manufacturer_id') { $value = $this->manufacturerObj->getName($value); } $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * Get matching rules * * @param string|null $parameters * @throws CentreonClapiException * @return void */ public function getmatching($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $trapId = $this->getObjectId($parameters); if (! $trapId) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $parameters); } $matchObj = new Centreon_Object_Trap_Matching($this->dependencyInjector); $params = ['tmo_id', 'tmo_string', 'tmo_regexp', 'tmo_status', 'tmo_order']; $elements = $matchObj->getList( $params, -1, 0, 'tmo_order', 'ASC', ['trap_id' => $trapId] ); $status = [0 => 'OK', 1 => 'WARNING', 2 => 'CRITICAL', 3 => 'UNKNOWN']; echo 'id' . $this->delim . 'string' . $this->delim . 'regexp' . $this->delim . 'status' . $this->delim . "order\n"; foreach ($elements as $element) { echo $element['tmo_id'] . $this->delim . $element['tmo_string'] . $this->delim . $element['tmo_regexp'] . $this->delim . $status[$element['tmo_status']] . $this->delim . $element['tmo_order'] . "\n"; } } /** * @param string|null $parameters * @throws CentreonClapiException */ public function addmatching($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < 4) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $trapId = $this->getObjectId($params[0]); if (! $trapId) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } $string = $params[1]; $regexp = $params[2]; $status = $this->getStatusInt($params[3]); $matchObj = new Centreon_Object_Trap_Matching($this->dependencyInjector); $elements = $matchObj->getList( '*', -1, 0, null, null, ['trap_id' => $trapId, 'tmo_regexp' => $regexp, 'tmo_string' => $string, 'tmo_status' => $status], 'AND' ); if (! count($elements)) { $elements = $matchObj->getList('*', -1, 0, null, null, ['trap_id' => $trapId]); $order = count($elements) + 1; $matchObj->insert(['trap_id' => $trapId, 'tmo_regexp' => $regexp, 'tmo_string' => $string, 'tmo_status' => $status, 'tmo_order' => $order]); } } /** * @param mixed $parameters * @throws CentreonClapiException */ public function delmatching($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (! is_numeric($parameters)) { throw new CentreonClapiException('Incorrect id parameters'); } $matchObj = new Centreon_Object_Trap_Matching($this->dependencyInjector); $matchObj->delete($parameters); } /** * @param string|null $parameters * @throws CentreonClapiException */ public function updatematching($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $matchingId = $params[0]; if (! is_numeric($matchingId)) { throw new CentreonClapiException('Incorrect id parameters'); } $key = $params[1]; $value = $params[2]; if ($key == 'trap_id') { throw new CentreonClapiException(self::INCORRECT_PARAMETER); } if (! preg_match('/tmo_/', $key)) { $key = 'tmo_' . $key; } if ($key == 'tmo_status') { $value = $this->getStatusInt($value); } $matchObj = new Centreon_Object_Trap_Matching($this->dependencyInjector); $matchObj->update($matchingId, [$key => $value]); } /** * Export * * @param string|null $filterName * * @throws Exception * @return false|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $addStr .= $this->delim . $element[$param]; } $addStr .= "\n"; echo $addStr; foreach ($element as $parameter => $value) { if ($parameter != 'traps_id') { if (! is_null($value) && $value != '') { $value = str_replace("\n", '<br/>', $value); if ($parameter == 'manufacturer_id') { $parameter = 'vendor'; $value = $this->manufacturerObj->getName($value); } $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } } $matchingObj = new Centreon_Object_Trap_Matching($this->dependencyInjector); $matchingProps = $matchingObj->getList( '*', -1, 0, null, 'ASC', ['trap_id' => $element['traps_id']] ); foreach ($matchingProps as $prop) { echo $this->action . $this->delim . 'addmatching' . $this->delim . $element['traps_name'] . $this->delim . $prop['tmo_string'] . $this->delim . $prop['tmo_regexp'] . $this->delim . $prop['tmo_status'] . "\n"; } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/CentreonLDAPContactRelation.class.php
centreon/www/class/centreon-clapi/CentreonLDAPContactRelation.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Contact; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonUtils.class.php'; require_once 'centreonTimePeriod.class.php'; require_once 'Centreon/Object/Contact/Contact.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Relation/Contact/Command/Host.php'; require_once 'Centreon/Object/Relation/Contact/Command/Service.php'; require_once 'centreonLDAP.class.php'; /** * Class * * @class CentreonLDAPContactRelation * @package CentreonClapi * @description Class representating relation between a contact and his LDAP configuration */ class CentreonLDAPContactRelation extends CentreonObject { private const ORDER_NAME = 0; private const LDAP_PARAMETER_NAME = 'ar_name'; /** @var string[] */ public static $aDepends = [ 'CONTACT', 'LDAP', ]; /** @var CentreonLdap */ public $ldap; /** @var Centreon_Object_Contact */ public $contact; /** @var int */ protected $register = 1; /** * CentreonLDAPContactRelation constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->ldap = new CentreonLdap($dependencyInjector); $this->contact = new Centreon_Object_Contact($dependencyInjector); $this->action = 'LDAPCONTACT'; $this->activateField = 'contact_activate'; } /** * @param string $parameters * @throws CentreonClapiException */ public function initUpdateParameters(string $parameters): void { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params[self::ORDER_NAME] = str_replace(' ', '_', $params[self::ORDER_NAME]); } /** * Export data * * @param null $filterName * * @throws Exception * @return bool */ public function export($filterName = null): bool { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->contact->getUniqueLabelField(); $filters = ['contact_register' => $this->register]; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $contacts = $this->contact->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($contacts as $contact) { foreach ($contact as $parameter => $value) { if (! empty($value) && ! in_array($parameter, $this->exportExcludedParams) && $parameter === 'ar_id') { $value = $this->ldap->getObjectName($value); $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $contact[$this->contact->getUniqueLabelField()] . $this->delim . self::LDAP_PARAMETER_NAME . $this->delim . $value . "\n"; } } } return true; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonRtAcknowledgement.class.php
centreon/www/class/centreon-clapi/centreonRtAcknowledgement.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_RtAcknowledgement; use CentreonClapi\Validator\RtValidator; use CentreonExternalCommand; use CentreonGMT; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonHost.class.php'; require_once 'centreonService.class.php'; require_once 'Centreon/Object/Acknowledgement/RtAcknowledgement.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Service/Service.php'; require_once dirname(__FILE__, 2) . '/centreonExternalCommand.class.php'; require_once dirname(__FILE__, 2) . '/centreonDB.class.php'; require_once dirname(__FILE__, 2) . '/centreonUser.class.php'; require_once dirname(__FILE__, 2) . '/centreonGMT.class.php'; require_once __DIR__ . '/Validator/RtValidator.php'; /** * Class * * @class CentreonRtAcknowledgement * @package CentreonClapi * @description Manage Acknowledgement with clapi */ class CentreonRtAcknowledgement extends CentreonObject { /** @var array */ protected $acknowledgementType = ['HOST', 'SVC']; /** @var array */ protected $aHosts; /** @var array */ protected $aServices; /** @var CentreonHost */ protected $hostObject; /** @var CentreonService */ protected $serviceObject; /** @var CentreonGMT */ protected $GMTObject; /** @var CentreonExternalCommand */ protected $externalCmdObj; /** @var string */ protected $author; /** @var RtValidator */ protected $rtValidator; /** * CentreonRtAcknowledgement constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_RtAcknowledgement($dependencyInjector); $this->hostObject = new CentreonHost($dependencyInjector); $this->serviceObject = new CentreonService($dependencyInjector); $this->GMTObject = new CentreonGMT(); $this->externalCmdObj = new CentreonExternalCommand(); $this->action = 'RTACKNOWLEDGEMENT'; $this->author = CentreonUtils::getUserName(); $this->rtValidator = new RtValidator($this->hostObject, $this->serviceObject); $this->externalCmdObj->setUserAlias($this->author); $this->externalCmdObj->setUserId(CentreonUtils::getUserId()); } /** * show acknowledgement without option * * @param null $parameters * @param array $filter * @throws CentreonClapiException */ public function show($parameters = null, $filter = []): void { if ($parameters !== '') { $parsedParameters = $this->parseShowparameters($parameters); if (strtoupper($parsedParameters['type']) !== 'HOST' && strtoupper($parsedParameters['type']) !== 'SVC') { throw new CentreonClapiException(self::UNKNOWNPARAMETER . ' : ' . $parsedParameters['type']); } $method = 'show' . ucfirst($parsedParameters['type']); $this->{$method}($parsedParameters['resource']); } else { $this->aHosts = $this->object->getLastHostAcknowledgement(); $this->aServices = $this->object->getLastSvcAcknowledgement(); $list = ''; // all host if (count($this->aHosts) !== 0) { foreach ($this->aHosts as $host) { $list .= $host['name'] . ";\n"; } } // all service if (count($this->aServices) !== 0) { foreach ($this->aServices as $service) { $list .= $service['name'] . ';' . $service['description'] . " \n"; } } echo "hosts;services\n"; echo $list; } } /** * @param $hostList * @throws CentreonClapiException */ public function showHost($hostList): void { $fields = ['id', 'host_name', 'entry_time', 'author', 'comment_data', 'sticky', 'notify_contacts', 'persistent_comment']; if (! empty($hostList)) { $hostList = array_filter(explode('|', $hostList)); $db = $this->db; $hostList = array_map( function ($element) use ($db) { return $db->escape($element); }, $hostList ); // check if host exist $unknownHost = []; $existingHostIds = []; foreach ($hostList as $host) { if (($hostId = $this->hostObject->getHostID($host)) == 0) { $unknownHost[] = $host; } else { $existingHostIds[] = $hostId; } } if ($unknownHost !== []) { echo "\n"; throw new CentreonClapiException( self::OBJECT_NOT_FOUND . ' : Host : ' . implode('|', $unknownHost) . "\n" ); } // Result of the research in the base $hostAcknowledgementList = $this->object->getLastHostAcknowledgement($existingHostIds); } else { $hostAcknowledgementList = $this->object->getLastHostAcknowledgement(); } // Init user timezone $this->GMTObject->getMyGTMFromUser(CentreonUtils::getuserId()); echo implode($this->delim, $fields) . "\n"; // Separates hosts if (count($hostAcknowledgementList)) { foreach ($hostAcknowledgementList as $hostAcknowledgement) { $hostAcknowledgement['entry_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $hostAcknowledgement['entry_time'], $this->GMTObject->getMyGMT() ); if ($hostAcknowledgement['sticky'] !== 0) { $hostAcknowledgement['sticky'] = 2; } echo implode($this->delim, array_values($hostAcknowledgement)) . "\n"; } } } /** * @param $svcList * @throws CentreonClapiException */ public function showSvc($svcList): void { $serviceAcknowledgementList = []; $unknownService = []; $existingService = []; $fields = ['id', 'host_name', 'service_name', 'entry_time', 'author', 'comment_data', 'sticky', 'notify_contacts', 'persistent_comment']; if (! empty($svcList)) { $svcList = array_filter(explode('|', $svcList)); $db = $this->db; $svcList = array_map( function ($arrayElem) use ($db) { return $db->escape($arrayElem); }, $svcList ); // check if service exist foreach ($svcList as $service) { $serviceData = explode(',', $service); if ($this->serviceObject->serviceExists($serviceData[0], $serviceData[1])) { $existingService[] = $serviceData; } else { $unknownService[] = $service; } } // Result of the research in the base if ($existingService !== []) { foreach ($existingService as $svc) { $tmpAcknowledgement = $this->object->getLastSvcAcknowledgement($svc); if (! empty($tmpAcknowledgement)) { $serviceAcknowledgementList[] = array_pop($tmpAcknowledgement); } } } } else { $serviceAcknowledgementList = $this->object->getLastSvcAcknowledgement(); } // Init user timezone $this->GMTObject->getMyGTMFromUser(CentreonUtils::getuserId()); // Separates hosts and services echo implode($this->delim, $fields) . "\n"; if (count($serviceAcknowledgementList)) { foreach ($serviceAcknowledgementList as $serviceAcknowledgement) { $serviceAcknowledgement['entry_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $serviceAcknowledgement['entry_time'], $this->GMTObject->getMyGMT() ); if ($serviceAcknowledgement['sticky'] !== 0) { $serviceAcknowledgement['sticky'] = 2; } echo implode($this->delim, array_values($serviceAcknowledgement)) . "\n"; } } if ($unknownService !== []) { echo "\n"; throw new CentreonClapiException( self::OBJECT_NOT_FOUND . ' : Service : ' . implode('|', $unknownService) . "\n" ); } } /** * redirect on SVC or HOST * * @param null $parameters * @throws CentreonClapiException * @return void */ public function add($parameters = null): void { $parsedParameters = $this->parseParameters($parameters); // to choose the best add (addHostAcknowledgement, addSvcAcknowledgement.) $method = 'add' . ucfirst($parsedParameters['type']) . 'Acknowledgement'; $this->{$method}( $parsedParameters['resource'], $parsedParameters['comment'], $parsedParameters['sticky'], $parsedParameters['notify'], $parsedParameters['persistent'] ); } /** * @param mixed $parameters * * @throws CentreonClapiException * @throws PDOException */ public function cancel($parameters = null): void { if (empty($parameters) || is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $listAcknowledgement = explode('|', $parameters); $unknownAcknowledgement = []; foreach ($listAcknowledgement as $acknowledgement) { [$hostName, $serviceName] = explode(',', $acknowledgement); if ($serviceName) { $serviceId = $this->serviceObject->getObjectId($hostName . ';' . $serviceName); if ( $this->rtValidator->isServiceNameValid($hostName, $serviceName) && $this->object->svcIsAcknowledged($serviceId) ) { $this->externalCmdObj->deleteAcknowledgement( 'SVC', [$hostName . ';' . $serviceName => 'on'] ); } else { $unknownAcknowledgement[] = $acknowledgement; } } else { $hostId = $this->hostObject->getHostID($hostName); if ($this->object->hostIsAcknowledged($hostId)) { $this->externalCmdObj->deleteAcknowledgement( 'HOST', [$hostName => 'on'] ); } else { $unknownAcknowledgement[] = $acknowledgement; } } } if (count($unknownAcknowledgement)) { throw new CentreonClapiException( self::OBJECT_NOT_FOUND . ' OR not acknowledged : ' . implode('|', $unknownAcknowledgement) ); } } /** * @param $parameters * @throws CentreonClapiException * @return array */ private function parseParameters($parameters) { // Make safe the inputs [$type, $resource, $comment, $sticky, $notify, $persistent] = explode(';', $parameters); // Check if object type is supported if (! in_array(strtoupper($type), $this->acknowledgementType)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } // Check if sticky is 0 or 2 if (! preg_match('/^(0|1|2)$/', $sticky)) { throw new CentreonClapiException('Bad sticky parameter (0 or 1/2)'); } // Check if notify is 0 or 1 if (! preg_match('/^(0|1)$/', $notify)) { throw new CentreonClapiException('Bad notify parameter (0 or 1)'); } // Check if fixed is 0 or 1 if (! preg_match('/^(0|1)$/', $persistent)) { throw new CentreonClapiException('Bad persistent parameter (0 or 1)'); } // Make safe the comment $comment = escapeshellarg($comment); return ['type' => $type, 'resource' => $resource, 'comment' => $comment, 'sticky' => $sticky, 'notify' => $notify, 'persistent' => $persistent]; } /** * @param $parameters * * @throws CentreonClapiException * @return array */ private function parseShowParameters($parameters) { $parameters = explode(';', $parameters); if (count($parameters) === 1) { $resource = ''; } elseif (count($parameters) === 2) { $resource = $parameters[1]; } else { throw new CentreonClapiException('Bad parameters'); } $type = $parameters[0]; return [ 'type' => $type, 'resource' => $resource, ]; } /** * @param $resource * @param $comment * @param $sticky * @param $notify * @param $persistent * * @throws CentreonClapiException * @throws PDOException */ private function addHostAcknowledgement( $resource, $comment, $sticky, $notify, $persistent, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $unknownHost = []; $listHost = explode('|', $resource); foreach ($listHost as $host) { if ($this->rtValidator->isHostNameValid($host)) { $this->externalCmdObj->acknowledgeHost( $host, $sticky, $notify, $persistent, $this->author, $comment ); } else { $unknownHost[] = $host; } } if ($unknownHost !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' HOST : ' . implode('|', $unknownHost)); } } /** * @param $resource * @param $comment * @param $sticky * @param $notify * @param $persistent * * @throws CentreonClapiException * @throws PDOException */ private function addSvcAcknowledgement( $resource, $comment, $sticky, $notify, $persistent, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $unknownService = []; $existingService = []; $listService = explode('|', $resource); // check if service exist foreach ($listService as $service) { $serviceData = explode(',', $service); if ($this->rtValidator->isServiceNameValid($serviceData[0], $serviceData[1])) { $existingService[] = $serviceData; } else { $unknownService[] = $service; } } // Result of the research in the base if ($existingService !== []) { foreach ($existingService as $service) { $this->externalCmdObj->acknowledgeService( $service[0], $service[1], $sticky, $notify, $persistent, $this->author, $comment ); } } if ($unknownService !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' SERVICE : ' . implode('|', $unknownService)); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonHostGroup.class.php
centreon/www/class/centreon-clapi/centreonHostGroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_DependencyHostgroupParent; use Centreon_Object_Host; use Centreon_Object_Host_Group; use Centreon_Object_Relation_Host_Group_Host; use Centreon_Object_Relation_Host_Group_Service_Group; use Centreon_Object_Service_Group; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonConfigurationChange.class.php'; require_once 'centreonACL.class.php'; require_once 'centreonHost.class.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Service/Service.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Relation/Host/Group/Host.php'; require_once 'Centreon/Object/Relation/Host/Group/Service/Service.php'; require_once 'Centreon/Object/Relation/Host/Group/Service/Group.php'; require_once 'Centreon/Object/Dependency/DependencyHostgroupParent.php'; /** * Class * * @class CentreonHostGroup * @package CentreonClapi * @description Class for managing host groups */ class CentreonHostGroup extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const INVALID_GEO_COORDS = 'Invalid geo coords'; public const NAME_IS_EMPTY = 'Host group name is mandatory and cannot be left empty'; /** @var string[] */ public static $aDepends = ['HOST']; /** * CentreonHostGroup constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Host_Group($dependencyInjector); $this->params = ['hg_activate' => '1']; $this->insertParams = ['hg_name', 'hg_alias']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'HG'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'hg_activate'; } /** * Magic method * * @param $name * @param $arg * @throws CentreonClapiException */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)(member|host|servicegroup)$/', $name, $matches)) { // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $hgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($hgIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $groupId = $hgIds[0]; if ($matches[2] == 'host' || $matches[2] == 'member') { $relobj = new Centreon_Object_Relation_Host_Group_Host($this->dependencyInjector); $obj = new Centreon_Object_Host($this->dependencyInjector); } elseif ($matches[2] == 'servicegroup') { $relobj = new Centreon_Object_Relation_Host_Group_Service_Group($this->dependencyInjector); $obj = new Centreon_Object_Service_Group($this->dependencyInjector); } if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $hgIds); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromHostGroupIds([$groupId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (isset($tab[0]) && $tab[0] != '') { $relationTable[] = $tab[0]; } elseif ($rel != '') { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } } if ($matches[1] == 'set') { $relobj->delete($groupId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getSecondKey(), $relobj->getFirstKey(), [$groupId] ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($groupId, $relationId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($groupId, $relationId); } } } $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $groupId, $previousPollerIds ); $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['hg_id', 'hg_name', 'hg_alias']; $paramString = str_replace('hg_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]); if ($addParams[$this->object->getUniqueLabelField()] === '') { throw new CentreonClapiException(self::NAME_IS_EMPTY); } $addParams['hg_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * * @throws Exception * @return void */ public function add($parameters): void { parent::add($parameters); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostgroupId = $this->getObjectId($this->params[$this->object->getUniqueLabelField()]); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $hostgroupId); } /** * Del Action * Must delete services as well * * @param string $objectName * * @throws CentreonClapiException * @throws PDOException * @return void */ public function del($objectName): void { $hostgroupId = $this->getObjectId($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromHostGroupIds([$hostgroupId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $parentDependency = new Centreon_Object_DependencyHostgroupParent($this->dependencyInjector); $parentDependency->removeRelationLastHostgroupDependency($hostgroupId); parent::del($objectName); $this->db->query( "DELETE FROM service WHERE service_register = '1' " . 'AND service_id NOT IN (SELECT service_service_id FROM host_service_relation)' ); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $hostgroupId, $previousPollerIds ); } /** * @param array $parameters * @throws CentreonClapiException */ public function setParam($parameters = []): void { $params = method_exists($this, 'initUpdateParameters') ? $this->initUpdateParameters($parameters) : $parameters; if (! empty($params)) { $hostgroupId = $params['objectId']; $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromHostGroupIds([$hostgroupId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); parent::setparam($parameters); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $hostgroupId, $previousPollerIds ); } } /** * Enable object * * @param string $objectName * * @throws Exception * @return void */ public function enable($objectName): void { parent::enable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostgroupId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $hostgroupId); } /** * Disable object * * @param string $objectName * * @throws Exception * @return void */ public function disable($objectName): void { parent::disable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostgroupId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOSTGROUP, $hostgroupId, [], false ); } /** * Get a parameter * * @param null $parameters * @throws CentreonClapiException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['alias', 'comment', 'name', 'activate', 'icon_image', 'geo_coords']; $unknownParam = []; if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ''; $paramString = ''; foreach ($listParam as $paramSearch) { $paramString = ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { switch ($paramSearch) { case 'geo_coords': break; default: if (! preg_match('/^hg_/', $paramSearch)) { $field = 'hg_' . $paramSearch; } break; } $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (($params[1] == 'icon_image' || $params[1] == 'map_icon_image')) { $params[2] = $this->getIdIcon($params[2]); } if (! preg_match('/^hg_/', $params[1]) && $params[1] != 'geo_coords') { $params[1] = 'hg_' . $params[1]; } elseif ($params[1] === 'geo_coords') { if (! CentreonUtils::validateGeoCoords($params[2])) { throw new CentreonClapiException(self::INVALID_GEO_COORDS); } } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param $path * * @throws PDOException * @return mixed */ public function getIdIcon($path) { $iconData = explode('/', $path); $dirStatement = $this->db->prepare('SELECT dir_id FROM view_img_dir WHERE dir_name = :IconData'); $dirStatement->bindValue(':IconData', $iconData[0], PDO::PARAM_STR); $dirStatement->execute(); $row = $dirStatement->fetch(); $dirId = $row['dir_id']; $imgStatement = $this->db->prepare('SELECT img_id FROM view_img WHERE img_path = :iconData'); $imgStatement->bindValue(':iconData', $iconData[1], PDO::PARAM_STR); $imgStatement->execute(); $row = $imgStatement->fetch(); $iconId = $row['img_id']; $vidrStatement = $this->db->prepare('SELECT vidr_id FROM view_img_dir_relation ' . 'WHERE dir_dir_parent_id = :dirId AND img_img_id = :iconId'); $vidrStatement->bindValue(':dirId', (int) $dirId, PDO::PARAM_INT); $vidrStatement->bindValue(':iconId', (int) $iconId, PDO::PARAM_INT); $vidrStatement->execute(); $row = $vidrStatement->fetch(); return $row['vidr_id']; } /** * Export * * @param null $filterName * * @throws Exception * @return false|void */ public function export($filterName = null) { if (! parent::export($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $relObj = new Centreon_Object_Relation_Host_Group_Host($this->dependencyInjector); $hostObj = new Centreon_Object_Host($this->dependencyInjector); $hFieldName = $hostObj->getUniqueLabelField(); $elements = $relObj->getMergedParameters( [$labelField], [$hFieldName, 'host_id'], -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { echo $this->action . $this->delim . 'addhost' . $this->delim . $element[$labelField] . $this->delim . $element[$hFieldName] . "\n"; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonTimePeriod.class.php
centreon/www/class/centreon-clapi/centreonTimePeriod.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Relation_Timeperiod_Exclude; use Centreon_Object_Relation_Timeperiod_Include; use Centreon_Object_Timeperiod; use Centreon_Object_Timeperiod_Exception; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Timeperiod/Timeperiod.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Timeperiod/Exception.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Timeperiod/Exclude.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Timeperiod/Include.php'; /** * Class * * @class CentreonTimePeriod * @package CentreonClapi */ class CentreonTimePeriod extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const TP_INCLUDE = 'include'; public const TP_EXCLUDE = 'exclude'; public const TP_EXCEPTION = 'exception'; /** @var Centreon_Object_Timeperiod */ protected $exclude; /** @var Container */ protected $dependencyInjector; /** @var Centreon_Object_Timeperiod */ protected $include; /** * CentreonTimePeriod constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->dependencyInjector = $dependencyInjector; $this->object = new Centreon_Object_Timeperiod($dependencyInjector); $this->params = ['tp_sunday' => '', 'tp_monday' => '', 'tp_tuesday' => '', 'tp_wednesday' => '', 'tp_thursday' => '', 'tp_friday' => '', 'tp_saturday' => '']; $this->insertParams = ['tp_name', 'tp_alias']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'TP'; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['tp_id', 'tp_name', 'tp_alias', 'tp_sunday', 'tp_monday', 'tp_tuesday', 'tp_wednesday', 'tp_thursday', 'tp_friday', 'tp_saturday']; $paramString = str_replace('tp_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { $tab = array_map('html_entity_decode', $tab); $tab = array_map(function ($s) { return mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1'); }, $tab); echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]); $addParams['tp_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if ($params[1] == self::TP_INCLUDE || $params[1] == self::TP_EXCLUDE) { $this->setRelations($params[1], $objectId, $params[2]); } elseif (! preg_match('/^tp_/', $params[1])) { $params[1] = 'tp_' . $params[1]; } if ($params[1] != self::TP_INCLUDE && $params[1] != self::TP_EXCLUDE) { $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * Set Exception * * @param string $parameters * @throws CentreonClapiException * @return void */ public function setexception($parameters): void { $params = explode($this->delim, $parameters); if (($tpId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $excObj = new Centreon_Object_Timeperiod_Exception($this->dependencyInjector); $escList = $excObj->getList( $excObj->getPrimaryKey(), -1, 0, null, null, ['timeperiod_id' => $tpId, 'days' => $params[1]], 'AND' ); if (count($escList)) { $excObj->update($escList[0][$excObj->getPrimaryKey()], ['timerange' => $params[2]]); } else { $excObj->insert(['timeperiod_id' => $tpId, 'days' => $params[1], 'timerange' => $params[2]]); } } /** * Delete exception * * @param string $parameters * @throws CentreonClapiException * @return void */ public function delexception($parameters): void { $params = explode($this->delim, $parameters); if (($tpId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $excObj = new Centreon_Object_Timeperiod_Exception($this->dependencyInjector); $escList = $excObj->getList( $excObj->getPrimaryKey(), -1, 0, null, null, ['timeperiod_id' => $tpId, 'days' => $params[1]], 'AND' ); if (count($escList)) { $excObj->delete($escList[0][$excObj->getPrimaryKey()]); } } /** * Get exception * * @param string $parameters * @throws CentreonClapiException * @return void */ public function getexception($parameters): void { if (($tpId = $this->getObjectId($parameters)) == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $parameters); } $excObj = new Centreon_Object_Timeperiod_Exception($this->dependencyInjector); $escList = $excObj->getList(['days', 'timerange'], -1, 0, null, null, ['timeperiod_id' => $tpId]); echo "days;timerange\n"; foreach ($escList as $exc) { echo $exc['days'] . $this->delim . $exc['timerange'] . "\n"; } } /** * Get Timeperiod Id * * @param string $name * @throws CentreonClapiException * @return int */ public function getTimeperiodId($name) { $tpIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$name]); if (! count($tpIds)) { throw new CentreonClapiException('Unknown timeperiod: ' . $name); } return $tpIds[0]; } /** * Get timeperiod name * * @param int $timeperiodId * @return string */ public function getTimeperiodName($timeperiodId) { $tpName = $this->object->getParameters($timeperiodId, [$this->object->getUniqueLabelField()]); return $tpName[$this->object->getUniqueLabelField()]; } /** * Set Include / Exclude relations * * @param int $relationType * @param int $sourceId * @param string $relationName * * @throws CentreonClapiException * @return void */ protected function setRelations($relationType, $sourceId, $relationName) { $relationIds = []; $relationNames = explode('|', $relationName); foreach ($relationNames as $name) { $name = trim($name); $relationIds[] = $this->getTimePeriodId($name); } if ($relationType == self::TP_INCLUDE) { $relObj = new Centreon_Object_Relation_Timeperiod_Include($this->dependencyInjector); } else { $relObj = new Centreon_Object_Relation_Timeperiod_Exclude($this->dependencyInjector); } $relObj->delete($sourceId); foreach ($relationIds as $relId) { $relObj->insert($sourceId, $relId); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonRtDowntime.class.php
centreon/www/class/centreon-clapi/centreonRtDowntime.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_RtDowntime; use CentreonClapi\Validator\RtValidator; use CentreonExternalCommand; use CentreonGMT; use CentreonHostgroups; use CentreonServicegroups; use DateTime; use PDOException; use Pimple\Container; use Throwable; require_once 'centreonObject.class.php'; require_once 'centreonHost.class.php'; require_once 'centreonService.class.php'; require_once 'Centreon/Object/Downtime/RtDowntime.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Relation/Downtime/Host.php'; require_once 'Centreon/Object/Relation/Downtime/Hostgroup.php'; require_once 'Centreon/Object/Relation/Downtime/Servicegroup.php'; require_once dirname(__FILE__, 2) . '/centreonExternalCommand.class.php'; require_once dirname(__FILE__, 2) . '/centreonDB.class.php'; require_once dirname(__FILE__, 2) . '/centreonUser.class.php'; require_once dirname(__FILE__, 2) . '/centreonGMT.class.php'; require_once dirname(__FILE__, 2) . '/centreonHostgroups.class.php'; require_once dirname(__FILE__, 2) . '/centreonServicegroups.class.php'; require_once dirname(__FILE__, 2) . '/centreonInstance.class.php'; require_once __DIR__ . '/Validator/RtValidator.php'; /** * Class * * @class CentreonRtDowntime * @package CentreonClapi */ class CentreonRtDowntime extends CentreonObject { /** @var CentreonHostgroups */ public $hgObject; /** @var CentreonServicegroups */ public $sgObject; /** @var \CentreonInstance */ public $instanceObject; /** @var CentreonGMT */ public $GMTObject; /** @var CentreonExternalCommand */ public $externalCmdObj; /** @var string[] */ protected $downtimeType = ['HOST', 'SVC', 'HG', 'SG', 'INSTANCE']; /** @var array */ protected $dHosts; /** @var array */ protected $dServices; /** @var CentreonHost */ protected $hostObject; /** @var CentreonService */ protected $serviceObject; /** @var RtValidator */ protected $rtValidator; /** * CentreonRtDowntime constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_RtDowntime($dependencyInjector); $this->hgObject = new CentreonHostgroups($this->db); $this->hostObject = new CentreonHost($dependencyInjector); $this->serviceObject = new CentreonService($dependencyInjector); $this->sgObject = new CentreonServicegroups($this->db); $this->instanceObject = new \CentreonInstance($this->db); $this->GMTObject = new CentreonGMT(); $this->externalCmdObj = new CentreonExternalCommand(); $this->action = 'RTDOWNTIME'; $this->externalCmdObj->setUserAlias(CentreonUtils::getUserName()); $this->externalCmdObj->setUserId(CentreonUtils::getUserId()); $this->rtValidator = new RtValidator($this->hostObject, $this->serviceObject); } /** * @param null $parameters * @param array $filter * @throws CentreonClapiException */ public function show($parameters = null, $filter = []): void { if ($parameters !== '') { $parsedParameters = $this->parseShowparameters($parameters); if (strtoupper($parsedParameters['type']) !== 'HOST' && strtoupper($parsedParameters['type']) !== 'SVC') { throw new CentreonClapiException(self::UNKNOWNPARAMETER . ' : ' . $parsedParameters['type']); } $method = 'show' . ucfirst(strtolower($parsedParameters['type'])); $this->{$method}($parsedParameters['resource']); } else { $this->dHosts = $this->object->getHostDowntimes(); $this->dServices = $this->object->getSvcDowntimes(); // all host $hostsToReturn = []; foreach ($this->dHosts as $host) { $hostsToReturn[] = $host['name']; } // all service $servicesToReturn = []; foreach ($this->dServices as $service) { $servicesToReturn[] = $service['name'] . ',' . $service['description']; } echo "hosts;services\n"; if ($hostsToReturn !== [] || $servicesToReturn !== []) { echo implode('|', $hostsToReturn) . ';' . implode('|', $servicesToReturn) . "\n"; } } } /** * @param $hostList * @throws CentreonClapiException */ public function showHost($hostList): void { $unknownHost = []; $fields = ['id', 'host_name', 'author', 'actual_start_time', 'actual_end_time', 'start_time', 'end_time', 'comment_data', 'duration', 'fixed', 'url']; if (! empty($hostList)) { $hostList = array_filter(explode('|', $hostList)); $db = $this->db; $hostList = array_map( function ($element) use ($db) { return $db->escape($element); }, $hostList ); // check if host exist $existingHost = []; foreach ($hostList as $host) { if ($this->hostObject->getHostID($host) == 0) { $unknownHost[] = $host; } else { $existingHost[] = $host; } } // Result of the research in the base $hostDowntimesList = $this->object->getHostDowntimes($existingHost); } else { $hostDowntimesList = $this->object->getHostDowntimes(); } // Init user timezone $this->GMTObject->getMyGTMFromUser(CentreonUtils::getuserId()); echo implode($this->delim, $fields) . "\n"; // Separates hosts if (count($hostDowntimesList)) { foreach ($hostDowntimesList as $hostDowntime) { $url = ''; if (isset($_SERVER['HTTP_HOST'])) { $url = $this->getBaseUrl() . '/' . 'main.php?p=210&search_host=' . $hostDowntime['name']; } $hostDowntime['actual_start_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $hostDowntime['actual_start_time'], $this->GMTObject->getMyGMT() ); $hostDowntime['actual_end_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $hostDowntime['actual_end_time'], $this->GMTObject->getMyGMT() ); $hostDowntime['start_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $hostDowntime['start_time'], $this->GMTObject->getMyGMT() ); $hostDowntime['end_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $hostDowntime['end_time'], $this->GMTObject->getMyGMT() ); echo implode($this->delim, array_values($hostDowntime)) . ';' . $url . "\n"; } } if ($unknownHost !== []) { echo "\n"; throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' : Host : ' . implode('|', $unknownHost) . "\n"); } } /** * @param $svcList * @throws CentreonClapiException */ public function showSvc($svcList): void { $serviceDowntimesList = []; $unknownService = []; $existingService = []; $fields = ['id', 'host_name', 'service_name', 'author', 'actual_start_time', 'actual_end_time', 'start_time', 'end_time', 'comment_data', 'duration', 'fixed', 'url']; if (! empty($svcList)) { $svcList = array_filter(explode('|', $svcList)); $db = $this->db; $svcList = array_map( function ($arrayElem) use ($db) { return $db->escape($arrayElem); }, $svcList ); // check if service exist foreach ($svcList as $service) { $serviceData = explode(',', $service); if ($this->serviceObject->serviceExists($serviceData[0], $serviceData[1])) { $existingService[] = $serviceData; } else { $unknownService[] = $service; } } // Result of the research in the base if ($existingService !== []) { foreach ($existingService as $svc) { $tmpDowntime = $this->object->getSvcDowntimes($svc); if (! empty($tmpDowntime)) { $serviceDowntimesList = $tmpDowntime; } } } } else { $serviceDowntimesList = $this->object->getSvcDowntimes(); } // Init user timezone $this->GMTObject->getMyGTMFromUser(CentreonUtils::getuserId()); // Separates hosts and services echo implode($this->delim, $fields) . "\n"; if (count($serviceDowntimesList)) { foreach ($serviceDowntimesList as $serviceDowntime) { $url = ''; if (isset($_SERVER['HTTP_HOST'])) { $url = $this->getBaseUrl() . '/' . 'main.php?p=210&search_host=' . $serviceDowntime['name'] . '&search_service=' . $serviceDowntime['description']; } $serviceDowntime['actual_start_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $serviceDowntime['actual_start_time'], $this->GMTObject->getMyGMT() ); $serviceDowntime['actual_end_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $serviceDowntime['actual_end_time'], $this->GMTObject->getMyGMT() ); $serviceDowntime['start_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $serviceDowntime['start_time'], $this->GMTObject->getMyGMT() ); $serviceDowntime['end_time'] = $this->GMTObject->getDate( 'Y/m/d H:i', $serviceDowntime['end_time'], $this->GMTObject->getMyGMT() ); echo implode($this->delim, array_values($serviceDowntime)) . ';' . $url . "\n"; } } if ($unknownService !== []) { echo "\n"; throw new CentreonClapiException( self::OBJECT_NOT_FOUND . ' : Service : ' . implode('|', $unknownService) . "\n" ); } } /** * @param null $parameters * * @throws CentreonClapiException */ public function add($parameters = null): void { $parsedParameters = $this->parseParameters($parameters); // to choose the best add (addHostDowntime, addSvcDowntime etc.) $method = 'add' . ucfirst(strtolower($parsedParameters['type'])) . 'Downtime'; if ((strtolower($parsedParameters['type']) === 'host') || (strtolower($parsedParameters['type']) === 'hg')) { $this->{$method}( $parsedParameters['resource'], $parsedParameters['start'], $parsedParameters['end'], $parsedParameters['fixed'], $parsedParameters['duration'], $parsedParameters['comment'], $parsedParameters['withServices'] ); } else { $this->{$method}( $parsedParameters['resource'], $parsedParameters['start'], $parsedParameters['end'], $parsedParameters['fixed'], $parsedParameters['duration'], $parsedParameters['comment'] ); } } /** * @param null $parameters * @throws CentreonClapiException */ public function cancel($parameters = null): void { if (empty($parameters) || is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $listDowntime = explode('|', $parameters); $unknownDowntime = []; foreach ($listDowntime as $downtime) { if (! is_numeric($downtime)) { $unknownDowntime[] = $downtime; } else { $infoDowntime = $this->object->getCurrentDowntime($downtime); if ($infoDowntime) { $hostName = $this->hostObject->getHostName($infoDowntime['host_id']); if ($infoDowntime['type'] == 2) { $this->externalCmdObj->deleteDowntime( 'HOST', [$hostName . ';' . $infoDowntime['internal_id'] => 'on'] ); } else { $this->externalCmdObj->deleteDowntime( 'SVC', [$hostName . ';' . $infoDowntime['internal_id'] => 'on'] ); } } else { $unknownDowntime[] = $downtime; } } } if (count($unknownDowntime)) { throw new CentreonClapiException( self::OBJECT_NOT_FOUND . ' DOWNTIME ID : ' . implode('|', $unknownDowntime) ); } } /** * @param $date * @param string $format * @return bool */ private function validateDate($date, $format = 'Y/m/d H:i') { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; } /** * @param $parameters * @throws CentreonClapiException * @return array */ private function parseParameters($parameters) { // Make safe the inputs [$type, $resource, $start, $end, $fixed, $duration, $comment, $withServices] = explode(';', $parameters); // Check if object type is supported if (! in_array(strtoupper($type), $this->downtimeType)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } // Check date format $checkStart = $this->validateDate($start); $checkEnd = $this->validateDate($end); if (! $checkStart || ! $checkEnd) { throw new CentreonClapiException('Wrong date format, expected : YYYY/MM/DD HH:mm'); } // Check if fixed is 0 or 1 if (! preg_match('/^(0|1)$/', $fixed)) { throw new CentreonClapiException('Bad fixed parameter (0 or 1)'); } // Check duration parameters if ( ($fixed == 0 && (! preg_match('/^\d+$/', $duration) || $duration <= 0)) || ($fixed == 1 && ! preg_match('/(^$)||(^\d+$)/', $duration)) ) { throw new CentreonClapiException('Bad duration parameter'); } // Check if host with services if (strtoupper($type) === 'HOST') { if (! preg_match('/^(0|1)$/', $withServices)) { throw new CentreonClapiException('Bad "apply to services" parameter (0 or 1)'); } } $withServices = ($withServices == 1) ? true : false; // Make safe the comment $comment = escapeshellarg($comment); return ['type' => $type, 'resource' => $resource, 'start' => $start, 'end' => $end, 'fixed' => $fixed, 'duration' => $duration, 'withServices' => $withServices, 'comment' => $comment]; } /** * @param $parameters * * @throws CentreonClapiException * @return array */ private function parseShowParameters($parameters) { $parameters = explode(';', $parameters); if (count($parameters) === 1) { $resource = ''; } elseif (count($parameters) === 2) { $resource = $parameters[1]; } else { throw new CentreonClapiException('Bad parameters'); } $type = $parameters[0]; return ['type' => $type, 'resource' => $resource]; } /** * @param $resource * @param $start * @param $end * @param $fixed * @param $duration * @param $withServices * @param $comment * @throws CentreonClapiException */ private function addHostDowntime( $resource, $start, $end, $fixed, $duration, $comment, $withServices = true, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $unknownHost = []; $listHost = explode('|', $resource); foreach ($listHost as $host) { if ($this->rtValidator->isHostNameValid($host)) { $this->externalCmdObj->addHostDowntime( $host, $comment, $start, $end, $fixed, $duration, $withServices ); } else { $unknownHost[] = $host; } } if ($unknownHost !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' HOST : ' . implode('|', $unknownHost)); } } /** * @param $resource * @param $start * @param $end * @param $fixed * @param $duration * @param $comment * @throws CentreonClapiException */ private function addSvcDowntime( $resource, $start, $end, $fixed, $duration, $comment, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $unknownService = []; $listService = explode('|', $resource); $existingService = []; // check if service exist foreach ($listService as $service) { $serviceData = explode(',', $service); if ($this->rtValidator->isServiceNameValid($serviceData[0], $serviceData[1])) { $existingService[] = $serviceData; } else { $unknownService[] = $service; } } // Result of the research in the base if ($existingService !== []) { foreach ($existingService as $service) { $this->externalCmdObj->addSvcDowntime( $service[0], $service[1], $comment, $start, $end, $fixed, $duration ); } } if ($unknownService !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' SERVICE : ' . implode('|', $unknownService)); } } /** * @param $resource * @param $start * @param $end * @param $fixed * @param $duration * @param $comment * @param int $withServices * @throws CentreonClapiException */ private function addHgDowntime( $resource, $start, $end, $fixed, $duration, $comment, $withServices = true, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $existingHg = []; $unknownHg = []; $listHg = explode('|', $resource); // check if service exist foreach ($listHg as $hg) { if ($this->hgObject->getHostgroupId($hg)) { $existingHg[] = $hg; } else { $unknownHg[] = $hg; } } if ($existingHg !== []) { foreach ($existingHg as $hg) { $hostList = $this->hgObject->getHostsByHostgroupName($hg); // check add services with host foreach ($hostList as $host) { $this->externalCmdObj->addHostDowntime( $host['host'], $comment, $start, $end, $fixed, $duration, $withServices ); } } } if ($unknownHg !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' HG : ' . implode('|', $unknownHg)); } } /** * @param string $resource * @param string $start * @param string $end * @param int $fixed * @param ?int $duration * @param string $comment * * @throws CentreonClapiException * @throws Throwable */ private function addSgDowntime( string $resource, string $start, string $end, int $fixed, ?int $duration, string $comment, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $existingSg = []; $unknownSg = []; $listSg = explode('|', $resource); // check if service exist foreach ($listSg as $sg) { if ($this->sgObject->getServicesGroupId($sg)) { $existingSg[] = $sg; } else { $unknownSg[] = $sg; } } if ($existingSg !== []) { foreach ($existingSg as $sg) { $serviceList = [ ...$this->sgObject->getServicesByServicegroupName($sg), ...$this->sgObject->getServicesThroughtServiceTemplatesByServicegroupName($sg), ]; foreach ($serviceList as $service) { $this->externalCmdObj->addSvcDowntime( $service['host'], $service['service'], $comment, $start, $end, $fixed, $duration ); } } } if ($unknownSg !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' SG : ' . implode('|', $unknownSg)); } } /** * @param $resource * @param $start * @param $end * @param $fixed * @param $duration * @param $comment * * @throws CentreonClapiException * @throws PDOException */ private function addInstanceDowntime( $resource, $start, $end, $fixed, $duration, $comment, ): void { if ($resource === '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $existingPoller = []; $unknownPoller = []; $listPoller = explode('|', $resource); foreach ($listPoller as $poller) { if ($this->instanceObject->getInstanceId($poller)) { $existingPoller[] = $poller; } else { $unknownPoller[] = $poller; } } if ($existingPoller !== []) { foreach ($existingPoller as $poller) { $hostList = $this->instanceObject->getHostsByInstance($poller); // check add services with host with true in last param foreach ($hostList as $host) { $this->externalCmdObj->addHostDowntime( $host['host'], $comment, $start, $end, $fixed, $duration, true ); } } } if ($unknownPoller !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' INSTANCE : ' . implode('|', $unknownPoller)); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonHostCategory.class.php
centreon/www/class/centreon-clapi/centreonHostCategory.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Host; use Centreon_Object_Host_Category; use Centreon_Object_Relation_Host_Category_Host; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonSeverityAbstract.class.php'; require_once 'centreonACL.class.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Category.php'; require_once 'Centreon/Object/Relation/Host/Category/Host.php'; /** * Class * * @class CentreonHostCategory * @package CentreonClapi * @description Class for managing host categories */ class CentreonHostCategory extends CentreonSeverityAbstract { /** @var string[] */ public static $aDepends = ['HOST']; /** * CentreonHostCategory constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Host_Category($dependencyInjector); $this->params = ['hc_activate' => '1']; $this->insertParams = ['hc_name', 'hc_alias']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'level', 'icon_id'] ); $this->action = 'HC'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'hc_activate'; } /** * @param $name * @param $arg * @throws CentreonClapiException */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)member$/', $name, $matches)) { $relobj = new Centreon_Object_Relation_Host_Category_Host($this->dependencyInjector); $obj = new Centreon_Object_Host($this->dependencyInjector); // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $hcIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($hcIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $categoryId = $hcIds[0]; if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $hcIds); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } if ($matches[1] == 'set') { $relobj->delete($categoryId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getSecondKey(), $relobj->getFirstKey(), [$categoryId] ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($categoryId, $relationId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($categoryId, $relationId); } } } $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['hc_id', 'hc_name', 'hc_alias', 'level']; $paramString = str_replace('hc_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { if (! $tab['level']) { $tab['level'] = 'none'; } echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['hc_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^hc_/', $params[1])) { $params[1] = 'hc_' . $params[1]; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * Set severity * * @param string $parameters * @throws CentreonClapiException */ public function setseverity($parameters): void { parent::setseverity($parameters); } /** * Unset severity * * @param string $parameters * @throws CentreonClapiException */ public function unsetseverity($parameters): void { parent::unsetseverity($parameters); } /** * Export * * @param null $filterName * * @throws PDOException * @return void */ public function export($filterName = null): void { if (! parent::export($filterName)) { return; } $hostCategories = $this->findHostCategories(); foreach ($hostCategories as $category) { if ($category['host_name'] !== null) { printf( "%s%saddmember%s%s%s%s\n", $this->action, $this->delim, $this->delim, $category['name'], $this->delim, $category['host_name'] ); } if ($category['level'] !== null) { printf( "%s%ssetseverity%s%s%s%s%s%s\n", $this->action, $this->delim, $this->delim, $category['name'], $this->delim, $category['level'], $this->delim, $category['img_path'], ); } } } /** * @throws PDOException * @return array<array{name: string, host_name: string, level: int|null, img_path: string|null}> */ private function findHostCategories(): array { $statement = $this->db->query( <<<'SQL' SELECT hc.hc_name, hc.level, host.host_name, CONCAT(dir.dir_name, '/' ,img.img_path) AS img_path FROM hostcategories hc LEFT JOIN hostcategories_relation rel ON rel.hostcategories_hc_id = hc.hc_id LEFT JOIN host ON host.host_id = rel.host_host_id LEFT JOIN view_img_dir_relation rel2 ON rel2.img_img_id = hc.icon_id LEFT JOIN view_img img ON img.img_id = rel2.img_img_id LEFT JOIN view_img_dir dir ON dir.dir_id = rel2.dir_dir_parent_id ORDER BY hc.hc_name SQL ); $hostCategories = []; while (($result = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { $hostCategories[] = [ 'name' => $result['hc_name'], 'host_name' => $result['host_name'], 'level' => $result['level'], 'img_path' => $result['img_path'], ]; } return $hostCategories; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACLResource.class.php
centreon/www/class/centreon-clapi/centreonACLResource.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Acl_Group; use Centreon_Object_Acl_Resource; use Centreon_Object_Host; use Centreon_Object_Host_Category; use Centreon_Object_Host_Group; use Centreon_Object_Instance; use Centreon_Object_Meta_Service; use Centreon_Object_Relation_Acl_Group_Resource; use Centreon_Object_Relation_Acl_Resource_Host; use Centreon_Object_Relation_Acl_Resource_Host_Category; use Centreon_Object_Relation_Acl_Resource_Host_Exclude; use Centreon_Object_Relation_Acl_Resource_Host_Group; use Centreon_Object_Relation_Acl_Resource_Instance; use Centreon_Object_Relation_Acl_Resource_Meta_Service; use Centreon_Object_Relation_Acl_Resource_Service_Category; use Centreon_Object_Relation_Acl_Resource_Service_Group; use Centreon_Object_Service_Category; use Centreon_Object_Service_Group; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'Centreon/Object/Acl/Group.php'; require_once 'Centreon/Object/Acl/Resource.php'; require_once 'Centreon/Object/Relation/Acl/Group/Resource.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Host/Category.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Service/Category.php'; require_once 'Centreon/Object/Meta/Service.php'; require_once 'Centreon/Object/Instance/Instance.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Host/Host.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Host/Group.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Host/Category.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Host/Exclude.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Service/Group.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Service/Category.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Meta/Service.php'; require_once 'Centreon/Object/Relation/Acl/Resource/Instance.php'; /** * Class * * @class CentreonACLResource * @package CentreonClapi * @description Class for managing ACL groups */ class CentreonACLResource extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const UNSUPPORTED_WILDCARD = "Action does not support the '*' wildcard"; /** @var string[] */ public $aDepends = ['HOST', 'SERVICE', 'HG', 'SG', 'INSTANCE', 'HC', 'SC']; /** @var Centreon_Object_Acl_Group */ protected $aclGroupObj; /** @var Centreon_Object_Relation_Acl_Group_Resource */ protected $relObject; /** * Depends * * @var object */ protected $resourceTypeObject; /** * Depends * * @var object */ protected $resourceTypeObjectRelation; /** * CentreonACLResource constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Acl_Resource($dependencyInjector); $this->aclGroupObj = new Centreon_Object_Acl_Group($dependencyInjector); $this->relObject = new Centreon_Object_Relation_Acl_Group_Resource($dependencyInjector); $this->params = ['all_hosts' => '0', 'all_hostgroups' => '0', 'all_servicegroups' => '0', 'acl_res_activate' => '1', 'changed' => '1']; $this->nbOfCompulsoryParams = 2; $this->activateField = 'acl_res_activate'; $this->action = 'ACLRESOURCE'; } /** * Magic method * * @param string $name * @param array $arg * @throws CentreonClapiException * @return void */ public function __call($name, $arg) { $name = strtolower($name); if (preg_match('/^(grant|revoke|addfilter|delfilter)_([a-zA-Z_]+)/', $name, $matches)) { if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $action = $matches[1]; $this->{$action}($matches[2], $arg[0]); } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['acl_res_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $params[1] = 'acl_res_' . $params[1]; $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['acl_res_id', 'acl_res_name', 'acl_res_alias', 'acl_res_comment', 'acl_res_activate']; $paramString = str_replace('acl_res_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * Get Acl Group * * @param $aclResName * @throws CentreonClapiException */ public function getaclgroup($aclResName): void { if (! isset($aclResName) || ! $aclResName) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclResId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$aclResName]); if (! count($aclResId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $aclResName); } $groupIds = $this->relObject->getacl_group_idFromacl_res_id($aclResId[0]); echo 'id;name' . "\n"; if (count($groupIds)) { foreach ($groupIds as $groupId) { $result = $this->aclGroupObj->getParameters($groupId, $this->aclGroupObj->getUniqueLabelField()); echo $groupId . $this->delim . $result[$this->aclGroupObj->getUniqueLabelField()] . "\n"; } } } /** * Add host exclusion * * @param string $parameters * * @throws CentreonClapiException * @return void */ public function addhostexclusion($parameters): void { $this->grant('excludehost', $parameters); } /** * Delete host exclusion * * @param string $parameters * * @throws CentreonClapiException * @return void */ public function delhostexclusion($parameters): void { $this->revoke('excludehost', $parameters); } /** * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $aclResourceList = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); $exportLine = ''; foreach ($aclResourceList as $aclResource) { $exportLine .= $this->action . $this->delim . 'ADD' . $this->delim . $aclResource['acl_res_name'] . $this->delim . $aclResource['acl_res_alias'] . $this->delim . "\n"; $exportLine .= $this->action . $this->delim . 'SETPARAM' . $this->delim . $aclResource['acl_res_name'] . $this->delim; if (! empty($aclResource['acl_res_comment'])) { $exportLine .= 'comment' . $this->delim . $aclResource['acl_res_comment'] . $this->delim; } $exportLine .= 'activate' . $this->delim . $aclResource['acl_res_activate'] . $this->delim . "\n"; $exportLine .= $this->exportGrantResources($aclResource); echo $exportLine; $exportLine = ''; } } /** * Slit parameters * * @param string $type * @param string $parameters * @throws CentreonClapiException * @return array */ protected function splitParams($type, $parameters) { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclResId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]); if (! count($aclResId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } $resources = explode('|', $params[1]); $resourceIds = []; switch ($type) { case 'host': $this->resourceTypeObject = new Centreon_Object_Host($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Host($this->dependencyInjector); break; case 'hostgroup': $this->resourceTypeObject = new Centreon_Object_Host_Group($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Host_Group($this->dependencyInjector); break; case 'hostcategory': $this->resourceTypeObject = new Centreon_Object_Host_Category($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Host_Category($this->dependencyInjector); break; case 'servicegroup': $this->resourceTypeObject = new Centreon_Object_Service_Group($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Service_Group($this->dependencyInjector); break; case 'servicecategory': $this->resourceTypeObject = new Centreon_Object_Service_Category($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Service_Category($this->dependencyInjector); break; case 'metaservice': $this->resourceTypeObject = new Centreon_Object_Meta_Service($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Meta_Service($this->dependencyInjector); break; case 'instance': $this->resourceTypeObject = new Centreon_Object_Instance($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Instance($this->dependencyInjector); break; case 'excludehost': $this->resourceTypeObject = new Centreon_Object_Host($this->dependencyInjector); $this->resourceTypeObjectRelation = new Centreon_Object_Relation_Acl_Resource_Host_Exclude($this->dependencyInjector); break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); break; } foreach ($resources as $resource) { if ($resource != '*') { $ids = $this->resourceTypeObject->getIdByParameter( $this->resourceTypeObject->getUniqueLabelField(), [$resource] ); if (! count($ids)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $resource); } $resourceIds[] = $ids[0]; } else { $resourceIds[] = $resource; } } return [$aclResId[0], $resourceIds]; } /** * @param $type * @param $arg * @throws CentreonClapiException */ protected function grant($type, $arg) { [$aclResourceId, $resourceIds] = $this->splitParams($type, $arg); if (isset($this->resourceTypeObjectRelation)) { $results = $this->resourceTypeObjectRelation->getTargetIdFromSourceId( $this->resourceTypeObjectRelation->getSecondKey(), $this->resourceTypeObjectRelation->getFirstKey(), $aclResourceId ); foreach ($resourceIds as $resourceId) { if ($resourceId != '*' && ! in_array($resourceId, $results)) { $this->resourceTypeObjectRelation->insert($aclResourceId, $resourceId); } elseif ($resourceId == '*') { if ($type != 'host' && $type != 'hostgroup' && $type != 'servicegroup') { throw new CentreonClapiException(self::UNSUPPORTED_WILDCARD); } $field = 'all_' . $type . 's'; $this->object->update($aclResourceId, [$field => '1', 'changed' => '1']); } } } } /** * Revoke * * @param string $type * @param string $arg * * @throws CentreonClapiException * @return void */ protected function revoke($type, $arg) { [$aclResourceId, $resourceIds] = $this->splitParams($type, $arg); if (isset($this->resourceTypeObjectRelation)) { foreach ($resourceIds as $resourceId) { if ($resourceId != '*') { $this->resourceTypeObjectRelation->delete($aclResourceId, $resourceId); } elseif ($resourceId == '*') { $this->resourceTypeObjectRelation->delete($aclResourceId); } } if ($type == 'host' || $type == 'hostgroup' || $type == 'servicegroup') { $field = 'all_' . $type . 's'; $this->object->update($aclResourceId, [$field => '0', 'changed' => '1']); } } } /** * Add filter * * @param string $type * @param string $arg * * @throws CentreonClapiException * @return void */ protected function addfilter($type, $arg) { $this->grant($type, $arg); } /** * Delete filter * * @param string $type * @param string $arg * * @throws CentreonClapiException * @return void */ protected function delfilter($type, $arg) { $this->revoke($type, $arg); } /** * @param $aclResourceParams * @return string */ private function exportGrantResources($aclResourceParams) { $grantResources = ''; $grantResources .= $this->exportGrantHostResources( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'], $aclResourceParams['all_hosts'] ); $grantResources .= $this->exportGrantHostgroupResources( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'], $aclResourceParams['all_hostgroups'] ); $grantResources .= $this->exportGrantServicegroupResources( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'], $aclResourceParams['all_servicegroups'] ); $grantResources .= $this->exportGrantMetaserviceResources( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'] ); $grantResources .= $this->exportFilterInstance( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'] ); $grantResources .= $this->exportFilterHostCategory( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'] ); $grantResources .= $this->exportFilterServiceCategory( $aclResourceParams['acl_res_id'], $aclResourceParams['acl_res_name'] ); return $grantResources; } /** * @param int $aclResId * @param string $aclResName * @param int $allHosts * @param bool $withExclusion * * @throws PDOException * @return string */ private function exportGrantHostResources($aclResId, $aclResName, $allHosts = 1, $withExclusion = true) { $grantHostResources = ''; if ($allHosts == 1) { $grantHostResources .= $this->exportGrantObject('*', 'GRANT_HOST', $aclResName); } else { $queryHostGranted = 'SELECT h.host_name AS "object_name" ' . 'FROM host h, acl_resources_host_relations arhr ' . 'WHERE arhr.host_host_id = h.host_id ' . 'AND arhr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryHostGranted); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $grantedHostList = $stmt->fetchAll(); $grantHostResources .= $this->exportGrantObject($grantedHostList, 'GRANT_HOST', $aclResName); } if ($withExclusion) { $queryHostExcluded = 'SELECT h.host_name AS "object_name" ' . 'FROM host h, acl_resources_hostex_relations arher ' . 'WHERE arher.host_host_id = h.host_id ' . 'AND arher.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryHostExcluded); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $excludedHostList = $stmt->fetchAll(); $grantHostResources .= $this->exportGrantObject( $excludedHostList, 'ADDHOSTEXCLUSION', $aclResName ); } return $grantHostResources; } /** * @param $aclResId * @param $aclResName * @param int $allHostgroups * * @throws PDOException * @return string */ private function exportGrantHostgroupResources($aclResId, $aclResName, $allHostgroups = 1) { $grantHostgroupResources = ''; if ($allHostgroups == 1) { $grantHostgroupResources .= $this->exportGrantObject('*', 'GRANT_HOSTGROUP', $aclResName); } else { $queryHostgroupGranted = 'SELECT hg.hg_name AS "object_name" ' . 'FROM hostgroup hg, acl_resources_hg_relations arhgr ' . 'WHERE arhgr.hg_hg_id = hg.hg_id ' . 'AND arhgr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryHostgroupGranted); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $grantedHostgroupList = $stmt->fetchAll(); $grantHostgroupResources .= $this->exportGrantObject( $grantedHostgroupList, 'GRANT_HOSTGROUP', $aclResName ); } return $grantHostgroupResources; } /** * @param $aclResId * @param $aclResName * @param int $allServicegroups * * @throws PDOException * @return string */ private function exportGrantServicegroupResources($aclResId, $aclResName, $allServicegroups = 1) { $grantServicegroupResources = ''; if ($allServicegroups == 1) { $grantServicegroupResources .= $this->exportGrantObject('*', 'GRANT_SERVICEGROUP', $aclResName); } else { $queryServicegroupGranted = 'SELECT sg.sg_name AS "object_name" ' . 'FROM servicegroup sg, acl_resources_sg_relations arsgr ' . 'WHERE arsgr.sg_id = sg.sg_id ' . 'AND arsgr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryServicegroupGranted); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $grantedServicegroupList = $stmt->fetchAll(); $grantServicegroupResources .= $this->exportGrantObject( $grantedServicegroupList, 'GRANT_SERVICEGROUP', $aclResName ); } return $grantServicegroupResources; } /** * @param $aclResId * @param $aclResName * * @throws PDOException * @return string */ private function exportGrantMetaserviceResources($aclResId, $aclResName) { $grantMetaserviceResources = ''; $queryMetaserviceGranted = 'SELECT m.meta_name AS "object_name" ' . 'FROM meta_service m, acl_resources_meta_relations armr ' . 'WHERE armr.meta_id = m.meta_id ' . 'AND armr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryMetaserviceGranted); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $grantedMetaserviceList = $stmt->fetchAll(); $grantMetaserviceResources .= $this->exportGrantObject( $grantedMetaserviceList, 'GRANT_METASERVICE', $aclResName ); return $grantMetaserviceResources; } /** * @param $aclResId * @param $aclResName * * @throws PDOException * @return string */ private function exportFilterInstance($aclResId, $aclResName) { $filterInstances = ''; $queryFilteredInstances = 'SELECT n.name AS "object_name" ' . 'FROM nagios_server n, acl_resources_poller_relations arpr ' . 'WHERE arpr.poller_id = n.id ' . 'AND arpr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryFilteredInstances); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $filteredInstanceList = $stmt->fetchAll(); $filterInstances .= $this->exportGrantObject($filteredInstanceList, 'ADDFILTER_INSTANCE', $aclResName); return $filterInstances; } /** * @param $aclResId * @param $aclResName * * @throws PDOException * @return string */ private function exportFilterHostCategory($aclResId, $aclResName) { $filterHostCategories = ''; $queryFilteredHostCategories = 'SELECT hc.hc_name AS "object_name" ' . 'FROM hostcategories hc, acl_resources_hc_relations arhcr ' . 'WHERE arhcr.hc_id = hc.hc_id ' . 'AND arhcr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryFilteredHostCategories); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $filteredHostCategoryList = $stmt->fetchAll(); $filterHostCategories .= $this->exportGrantObject( $filteredHostCategoryList, 'ADDFILTER_HOSTCATEGORY', $aclResName ); return $filterHostCategories; } /** * @param $aclResId * @param $aclResName * * @throws PDOException * @return string */ private function exportFilterServiceCategory($aclResId, $aclResName) { $filterServiceCategories = ''; $queryFilteredServiceCategories = 'SELECT sc.sc_name AS "object_name" ' . 'FROM service_categories sc, acl_resources_sc_relations arscr ' . 'WHERE arscr.sc_id = sc.sc_id ' . 'AND arscr.acl_res_id = :aclId'; $stmt = $this->db->prepare($queryFilteredServiceCategories); $stmt->bindParam(':aclId', $aclResId); $stmt->execute(); $filteredServiceCategoryList = $stmt->fetchAll(); $filterServiceCategories .= $this->exportGrantObject( $filteredServiceCategoryList, 'ADDFILTER_SERVICECATEGORY', $aclResName ); return $filterServiceCategories; } /** * @param $grantedResourceItems * @param $grantCommand * @param $aclResName * @return string */ private function exportGrantObject($grantedResourceItems, $grantCommand, $aclResName) { $grantObject = ''; // Template for object export command $grantedCommandTpl = $this->action . $this->delim . $grantCommand . $this->delim . $aclResName . $this->delim . '%s' . $this->delim . "\n"; $grantedObjectList = ''; if (is_array($grantedResourceItems)) { // Non wildcard mode foreach ($grantedResourceItems as $grantedObject) { $grantedObjectList .= $grantedObject['object_name'] . '|'; } } elseif (is_string($grantedResourceItems)) { // Wildcard mode ('*') $grantedObjectList .= $grantedResourceItems; } else { // Unknown mode throw new \CentreonClapiException('Unsupported resource'); } if (! empty($grantedObjectList)) { // Check if list is useful $grantObject .= sprintf($grantedCommandTpl, trim($grantedObjectList, '|')); } return $grantObject; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonContactGroup.class.php
centreon/www/class/centreon-clapi/centreonContactGroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Contact; use Centreon_Object_Contact_Group; use Centreon_Object_Relation_Contact_Group_Contact; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonACL.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Contact.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Group.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Contact/Group/Contact.php'; /** * Class * * @class CentreonContactGroup * @package CentreonClapi * @description Class for managing contact groups */ class CentreonContactGroup extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; /** @var string[] */ public static $aDepends = ['CMD', 'TP', 'CONTACT']; /** * CentreonContactGroup constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Contact_Group($dependencyInjector); $this->params = ['cg_activate' => '1']; $this->insertParams = ['cg_name', 'cg_alias']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'CG'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'cg_activate'; } /** * Magic method for get/set/add/del relations * * @param string $name * @param array $arg * @throws CentreonClapiException */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)contact$/', $name, $matches)) { $relobj = new Centreon_Object_Relation_Contact_Group_Contact($this->dependencyInjector); $obj = new Centreon_Object_Contact($this->dependencyInjector); // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $cgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($cgIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $cgId = $cgIds[0]; if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $cgIds); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } if ($matches[1] == 'set') { $relobj->delete($cgId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getSecondKey(), $relobj->getFirstKey(), [$cgId] ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($cgId, $relationId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($cgId, $relationId); } } } $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * Get contact group ID * * @param string|null $contactGroupName * @throws CentreonClapiException * @return int */ public function getContactGroupID($contactGroupName = null) { $cgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$contactGroupName]); if (count($cgIds) !== 1) { throw new CentreonClapiException('Unknown contact group: ' . $contactGroupName); } return (int) $cgIds[0]; } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['cg_id', 'cg_name', 'cg_alias']; $paramString = str_replace('cg_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]); $addParams['cg_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^cg_/', $params[1]) && $params[1] !== 'ar_id') { $params[1] = 'cg_' . $params[1]; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * Export * * @param null $filterName * * @throws Exception * @return false|void */ public function export($filterName = null) { if (! parent::export($filterName)) { return false; } $relObj = new Centreon_Object_Relation_Contact_Group_Contact($this->dependencyInjector); $contactObj = new Centreon_Object_Contact($this->dependencyInjector); $cgFieldName = $this->object->getUniqueLabelField(); $cFieldName = $contactObj->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$cgFieldName] = $filterName; } $elements = $relObj->getMergedParameters( [$cgFieldName], [$cFieldName, 'contact_id'], -1, 0, $cgFieldName . ', contact_alias', 'ASC', $filters, 'AND' ); foreach ($elements as $element) { CentreonContact::getInstance()->export($element[$cFieldName]); echo $this->action . $this->delim . 'addcontact' . $this->delim . $element[$cgFieldName] . $this->delim . $element[$cFieldName] . $this->delim . $element['contact_alias'] . "\n"; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonServiceTemplate.class.php
centreon/www/class/centreon-clapi/centreonServiceTemplate.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_Contact; use Centreon_Object_Contact_Group; use Centreon_Object_Graph_Template; use Centreon_Object_Host; use Centreon_Object_Host_Template; use Centreon_Object_Relation_Contact_Group_Service; use Centreon_Object_Relation_Contact_Service; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Service_Category_Service; use Centreon_Object_Relation_Service_Template_Host; use Centreon_Object_Relation_Trap_Service; use Centreon_Object_Service; use Centreon_Object_Service_Category; use Centreon_Object_Service_Extended; use Centreon_Object_Service_Macro_Custom; use Centreon_Object_Trap; use Exception; use PDOException; use Pimple\Container; require_once 'centreonService.class.php'; require_once 'centreonCommand.class.php'; require_once 'Centreon/Object/Relation/Service/Template/Host.php'; require_once 'Centreon/Object/Host/Template.php'; require_once 'Centreon/Object/Service/Template.php'; /** * Class * * @class CentreonServiceTemplate * @package CentreonClapi * @description Class for managing service templates */ class CentreonServiceTemplate extends CentreonObject { public const ORDER_SVCDESC = 0; public const ORDER_SVCALIAS = 1; public const ORDER_SVCTPL = 2; public const NB_UPDATE_PARAMS = 3; public const UNKNOWN_NOTIFICATION_OPTIONS = 'Invalid notifications options'; /** @var string[] */ public static $aDepends = ['CMD', 'TP', 'TRAP', 'HTPL']; /** * @var array * Contains : list of authorized notifications_options for this objects */ public static $aAuthorizedNotificationsOptions = ['w' => 'Warning', 'u' => 'Unreachable', 'c' => 'Critical', 'r' => 'Recovery', 'f' => 'Flapping', 's' => 'Downtime Scheduled']; /** @var int */ public $register = 0; /** * CentreonServiceTemplate constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Service($dependencyInjector); $this->params = ['service_is_volatile' => '2', 'service_active_checks_enabled' => '2', 'service_passive_checks_enabled' => '2', 'service_parallelize_check' => '2', 'service_obsess_over_service' => '2', 'service_check_freshness' => '2', 'service_event_handler_enabled' => '2', 'service_flap_detection_enabled' => '2', 'service_process_perf_data' => '2', 'service_retain_status_information' => '2', 'service_retain_nonstatus_information' => '2', 'service_notifications_enabled' => '2', 'service_register' => '0', 'service_activate' => '1']; $this->insertParams = ['service_description', 'service_alias', 'service_template_model_stm_id']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'children'] ); $this->action = 'STPL'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'service_activate'; } /** * Magic method. * * @param string $name * @param array $arg * * @throws CentreonClapiException */ public function __call($name, $arg): void { // Get the method name $name = mb_strtolower($name); // Get the action and the object if (! preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { throw new CentreonClapiException(self::UNKNOWN_METHOD . 'PHP >> ' . __LINE__); } [, $action, $entity] = $matches; switch ($entity) { case 'host': $class = Centreon_Object_Host::class; $relClass = Centreon_Object_Relation_Host_Service::class; break; case 'contact': $class = Centreon_Object_Contact::class; $relClass = Centreon_Object_Relation_Contact_Service::class; break; case 'contactgroup': $class = Centreon_Object_Contact_Group::class; $relClass = Centreon_Object_Relation_Contact_Group_Service::class; break; case 'trap': $class = Centreon_Object_Trap::class; $relClass = Centreon_Object_Relation_Trap_Service::class; break; case 'hosttemplate': $class = Centreon_Object_Host_Template::class; $relClass = Centreon_Object_Relation_Service_Template_Host::class; break; case 'category': $class = Centreon_Object_Service_Category::class; $relClass = Centreon_Object_Relation_Service_Category_Service::class; break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); } if (! class_exists($relClass) || ! class_exists($class)) { throw new CentreonClapiException(self::UNKNOWN_METHOD . 'PHP >> ' . __LINE__); } // First argument mandatory for all if (empty($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $elements = $this->object->getList( 'service_id', -1, 0, null, null, [ 'service_description' => $args[0], 'service_register' => 0, ], 'AND' ); if (empty($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $serviceId = $elements[0]['service_id']; $relObj = new $relClass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($action === 'get') { $tab = $entity === 'hosttemplate' ? $relObj->getTargetIdFromSourceId($relObj->getSecondKey(), $relObj->getFirstKey(), $serviceId) : $relObj->getTargetIdFromSourceId($relObj->getFirstKey(), $relObj->getSecondKey(), $serviceId); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } return; } // Second argument mandatory for all but 'get' if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { $tab = $entity === 'contact' ? $obj->getIdByParameter('contact_alias', [$rel]) : $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (empty($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } if ($action === 'del') { foreach ($relationTable as $relationId) { $relObj->delete($relationId, $serviceId); } return; } if ($action === 'set') { $relObj->delete(null, $serviceId); } $existingRelationIds = $entity === 'hosttemplate' && $action === 'add' ? $relObj->getTargetIdFromSourceId($relObj->getSecondKey(), $relObj->getFirstKey(), $serviceId) : $relObj->getTargetIdFromSourceId($relObj->getFirstKey(), $relObj->getSecondKey(), $serviceId); if ($action === 'set' || $action === 'add') { foreach ($relationTable as $relationId) { if (in_array($relationId, $existingRelationIds, true)) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $relObj->insert($relationId, $serviceId); } } } /** * Display all service templates * * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = ['service_register' => $this->register]; if (isset($parameters)) { $filters['service_description'] = '%' . $parameters . '%'; } $commandObject = new Centreon_Object_Command($this->dependencyInjector); $paramsSvc = ['service_id', 'service_description', 'service_alias', 'command_command_id', 'command_command_id_arg', 'service_normal_check_interval', 'service_retry_check_interval', 'service_max_check_attempts', 'service_active_checks_enabled', 'service_passive_checks_enabled']; $elements = $this->object->getList( $paramsSvc, -1, 0, null, null, $filters, 'AND' ); $paramSvcString = str_replace('service_', '', implode($this->delim, $paramsSvc)); $paramSvcString = str_replace('command_command_id', 'check command', $paramSvcString); $paramSvcString = str_replace('command_command_id_arg', 'check command arguments', $paramSvcString); $paramSvcString = str_replace('_', ' ', $paramSvcString); echo $paramSvcString . "\n"; foreach ($elements as $tab) { if (isset($tab['command_command_id']) && $tab['command_command_id']) { $tmp = $commandObject->getParameters( $tab['command_command_id'], [$commandObject->getUniqueLabelField()] ); if (isset($tmp[$commandObject->getUniqueLabelField()])) { $tab['command_command_id'] = $tmp[$commandObject->getUniqueLabelField()]; } } echo implode($this->delim, $tab) . "\n"; } } /** * Get a parameter * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['activate', 'description', 'alias', 'template', 'is_volatile', 'check_period', 'check_command', 'check_command_arguments', 'max_check_attempts', 'normal_check_interval', 'retry_check_interval', 'active_checks_enabled', 'passive_checks_enabled', 'notifications_enabled', 'contact_additive_inheritance', 'cg_additive_inheritance', 'notification_interval', 'notification_period', 'notification_options', 'first_notification_delay', 'obsess_over_service', 'check_freshness', 'freshness_threshold', 'event_handler_enabled', 'flap_detection_enabled', 'retain_status_information', 'retain_nonstatus_information', 'event_handler', 'event_handler_arguments', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_image_alt', 'comment']; $unknownParam = []; if (($objectId = $this->getObjectId($params[self::ORDER_SVCDESC])) != 0) { $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ''; foreach ($listParam as $paramSearch) { $paramString = ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { $extended = false; switch ($paramSearch) { case 'check_command': $field = 'command_command_id'; break; case 'check_command_arguments': $field = 'command_command_id_arg'; break; case 'event_handler': $field = 'command_command_id2'; break; case 'event_handler_arguments': $field = 'command_command_id_arg2'; break; case 'check_period': $field = 'timeperiod_tp_id'; break; case 'notification_period': $field = 'timeperiod_tp_id2'; break; case 'template': $field = 'service_template_model_stm_id'; break; case 'contact_additive_inheritance': case 'cg_additive_inheritance': case 'geo_coords': break; case 'notes': $extended = true; break; case 'notes_url': $extended = true; break; case 'action_url': $extended = true; break; case 'icon_image': $extended = true; break; case 'icon_image_alt': $extended = true; break; default: if (! preg_match('/^service_/', $paramSearch)) { $field = 'service_' . $paramSearch; } break; } if (! $extended) { $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; } else { $field = 'esi_' . $field; $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $ret = $extended->getParameters($objectId, $field); $ret = $ret[$field]; } switch ($paramSearch) { case 'check_command': case 'event_handler': $commandObject = new CentreonCommand($this->dependencyInjector); $field = $commandObject->object->getUniqueLabelField(); $ret = $commandObject->object->getParameters($ret, $field); $ret = $ret[$field]; break; case 'check_period': case 'notification_period': $tpObj = new CentreonTimePeriod($this->dependencyInjector); $field = $tpObj->object->getUniqueLabelField(); $ret = $tpObj->object->getParameters($ret, $field); $ret = $ret[$field]; break; case 'template': $tplObj = new CentreonServiceTemplate($this->dependencyInjector); $field = $tplObj->object->getUniqueLabelField(); $ret = $tplObj->object->getParameters($ret, $field); $ret = $ret[$field]; break; } if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($this->serviceExists($params[self::ORDER_SVCDESC]) == true) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $addParams = []; $addParams['service_description'] = $this->checkIllegalChar($params[self::ORDER_SVCDESC]); $addParams['service_alias'] = $params[self::ORDER_SVCALIAS]; $template = $params[self::ORDER_SVCTPL]; if ($template) { $tmp = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, ['service_description' => $template, 'service_register' => '0'], 'AND' ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $template); } $addParams['service_template_model_stm_id'] = $tmp[0][$this->object->getPrimaryKey()]; } $this->params = array_merge($this->params, $addParams); } /** * @param $serviceId */ public function insertRelations($serviceId): void { $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $extended->insert([$extended->getUniqueLabelField() => $serviceId]); } /** * Delete service template * * @param string $objectName * @throws CentreonClapiException * @return void */ public function del($objectName): void { $serviceDesc = $objectName; $elements = $this->object->getList( 'service_id', -1, 0, null, null, ['service_description' => $serviceDesc, 'service_register' => 0], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $serviceDesc); } $this->object->delete($elements[0]['service_id']); } /** * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $serviceDesc = $params[0]; $elements = $this->object->getList( 'service_id', -1, 0, null, null, ['service_description' => $serviceDesc, 'service_register' => 0], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $serviceDesc); } $objectId = $elements[0]['service_id']; $extended = false; $commandObject = new CentreonCommand($this->dependencyInjector); switch ($params[1]) { case 'check_command': $params[1] = 'command_command_id'; $params[2] = $commandObject->getId($params[2]); break; case 'check_command_arguments': $params[1] = 'command_command_id_arg'; break; case 'event_handler': $params[1] = 'command_command_id2'; $params[2] = $commandObject->getId($params[2]); break; case 'event_handler_arguments': $params[1] = 'command_command_id_arg2'; break; case 'check_period': $params[1] = 'timeperiod_tp_id'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[2] = $tpObj->getTimeperiodId($params[2]); break; case 'notification_period': $params[1] = 'timeperiod_tp_id2'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[2] = $tpObj->getTimeperiodId($params[2]); break; case 'flap_detection_options': break; case 'template': $params[1] = 'service_template_model_stm_id'; $tmp = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, ['service_description' => $params[2], 'service_register' => '0'], 'AND' ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $params[2] = $tmp[0][$this->object->getPrimaryKey()]; break; case 'graphtemplate': $extended = true; $graphObj = new Centreon_Object_Graph_Template($this->dependencyInjector); $tmp = $graphObj->getIdByParameter($graphObj->getUniqueLabelField(), $params[2]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $params[1] = 'graph_id'; $params[2] = $tmp[0]; break; case 'contact_additive_inheritance': case 'cg_additive_inheritance': break; case 'notes': case 'notes_url': case 'action_url': case 'icon_image': case 'icon_image_alt': $extended = true; break; case 'service_notification_options': $aNotifs = explode(',', $params[2]); foreach ($aNotifs as $notif) { if (! array_key_exists($notif, self::$aAuthorizedNotificationsOptions)) { throw new CentreonClapiException(self::UNKNOWN_NOTIFICATION_OPTIONS); } } break; default: if (! preg_match('/^service_/', $params[1])) { $params[1] = 'service_' . $params[1]; } break; } if ($extended == false) { $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } if ($params[1] != 'graph_id') { $params[1] = 'esi_' . $params[1]; if ($params[1] == 'esi_icon_image') { if ($params[2]) { $id = CentreonUtils::getImageId($params[2], $this->db); if (is_null($id)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $params[2] = $id; } else { $params[2] = null; } } } $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $extended->update($objectId, [$params[1] => $params[2]]); return []; } /** * Get macro list of a service template * * @param string $parameters * @throws CentreonClapiException * @return void */ public function getmacro($parameters): void { $serviceDesc = $parameters; $elements = $this->object->getList( 'service_id', -1, 0, null, null, ['service_description' => $serviceDesc, 'service_register' => 0], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $serviceDesc); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( ['svc_macro_name', 'svc_macro_value', 'description', 'is_password'], -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id']] ); echo "macro name;macro value;description;is_password\n"; foreach ($macroList as $macro) { $password = ! empty($macro['is_password']) ? (int) $macro['is_password'] : 0; echo $this->csvEscape($this->extractMacroName($macro['svc_macro_name'])) . $this->delim . $this->csvEscape($macro['svc_macro_value']) . $this->delim . $this->csvEscape($macro['description']) . $this->delim . $password . "\n"; } } /** * Inserts/updates custom macro * * @param string $parameters * @throws CentreonClapiException * @return void */ public function setmacro($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $serviceDescription = $params[0]; $macroName = $params[1]; $macroValue = $params[2]; $macroDescription = $params[3] ?? ''; $macroPassword = ! empty($params[4]) ? (int) $params[4] : 0; $elements = $this->object->getList( 'service_id', -1, 0, null, null, ['service_description' => $serviceDescription, 'service_register' => 0], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $serviceDescription); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( $macroObj->getPrimaryKey(), -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($macroName)], 'AND' ); if (count($macroList)) { $macroObj->update( $macroList[0][$macroObj->getPrimaryKey()], ['svc_macro_value' => $macroValue, 'is_password' => $macroPassword, 'description' => $macroDescription] ); } else { $macroObj->insert( ['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($macroName), 'is_password' => $macroPassword, 'svc_macro_value' => $macroValue, 'description' => $macroDescription] ); } } /** * Delete custom macro * * @param string $parameters * @throws CentreonClapiException * @return void */ public function delmacro($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $elements = $this->object->getList( 'service_id', -1, 0, null, null, ['service_description' => $params[0], 'service_register' => 0], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } $macroObj = new Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( $macroObj->getPrimaryKey(), -1, 0, null, null, ['svc_svc_id' => $elements[0]['service_id'], 'svc_macro_name' => $this->wrapMacro($params[1])], 'AND' ); if (count($macroList)) { $macroObj->delete($macroList[0][$macroObj->getPrimaryKey()]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setseverity($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (($serviceId = $this->getObjectId($params[self::ORDER_SVCDESC])) == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_SVCDESC]); } $severityObj = new Centreon_Object_Service_Category($this->dependencyInjector); $severity = $severityObj->getIdByParameter( $severityObj->getUniqueLabelField(), $params[1] ); if (! isset($severity[0])) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[1]); } $severityId = $severity[0]; $severity = $severityObj->getParameters( $severityId, ['level'] ); if ($severity['level']) { // can't delete with generic method $this->db->query( 'DELETE FROM service_categories_relation WHERE service_service_id = ? AND sc_id IN (SELECT sc_id FROM service_categories WHERE level > 0)', $serviceId ); $rel = new Centreon_Object_Relation_Service_Category_Service($this->dependencyInjector); $rel->insert($severityId, $serviceId); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[1]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function unsetseverity($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 1) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (($serviceId = $this->getObjectId($params[self::ORDER_SVCDESC])) == 0) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_SVCDESC]); } // can't delete with generic method $this->db->query( 'DELETE FROM service_categories_relation WHERE service_service_id = ? AND sc_id IN (SELECT sc_id FROM service_categories WHERE level > 0)', $serviceId ); } /** * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $filterId = null; if (! is_null($filterName)) { $filterId = $this->getObjectId($filterName); } $labelField = $this->object->getUniqueLabelField(); $filters = ['service_register' => $this->register]; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); // No need to sort all service templates. We only export the current if (is_null($filterId)) { $templateTree = $this->sortTemplates($elements); $this->parseTemplateTree($templateTree);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonCentbrokerCfg.class.php
centreon/www/class/centreon-clapi/centreonCentbrokerCfg.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Broker; use CentreonConfigCentreonBroker; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonInstance.class.php'; require_once 'Centreon/Object/Broker/Broker.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonConfigCentreonBroker.php'; /** * Class * * @class CentreonCentbrokerCfg * @package CentreonClapi */ class CentreonCentbrokerCfg extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_INSTANCE = 1; public const UNKNOWNCOMBO = 'Unknown combination'; public const INVALIDFIELD = 'Invalid field'; public const NOENTRYFOUND = 'No entry found'; /** @var string[] */ public static $aDepends = ['INSTANCE']; /** @var CentreonInstance */ protected $instanceObj; /** @var CentreonConfigCentreonBroker */ protected $brokerObj; /** * CentreonCentbrokerCfg constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->instanceObj = new CentreonInstance($dependencyInjector); $this->brokerObj = new CentreonConfigCentreonBroker($dependencyInjector['configuration_db']); $this->object = new Centreon_Object_Broker($dependencyInjector); $this->params = ['config_filename' => 'central-broker.json', 'config_activate' => '1']; $this->insertParams = ['name', 'ns_nagios_server']; $this->action = 'CENTBROKERCFG'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'config_activate'; } /** * Magic method * * @param $name * @param $arg * @throws CentreonClapiException */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(list|get|set|add|del)(input|output)/', $name, $matches)) { $tagName = $matches[2]; // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $configIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($configIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $configId = $configIds[0]; switch ($matches[1]) { case 'list': $this->listFlow($configId, $tagName, $args); break; case 'get': $this->getFlow($configId, $tagName, $args); break; case 'set': $this->setFlow($configId, $tagName, $args); break; case 'add': $this->addFlow($configId, $tagName, $args); break; case 'del': $this->delFlow($configId, $tagName, $args); break; } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['ns_nagios_server'] = $this->instanceObj->getInstanceId($params[self::ORDER_INSTANCE]); $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if ($params[1] == 'instance' || $params[1] == 'ns_nagios_server') { $params[1] = 'ns_nagios_server'; $params[2] = $this->instanceObj->getInstanceId($params[2]); } elseif (! preg_match('/^config_/', $params[1])) { $parametersWithoutPrefix = [ 'event_queue_max_size', 'event_queues_total_size', 'cache_directory', 'stats_activate', 'daemon', 'pool_size', 'command_file', 'log_directory', 'log_filename', ]; if (! in_array($params[1], $parametersWithoutPrefix)) { $params[1] = 'config_' . $params[1]; } } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['config_id', 'config_name', 'ns_nagios_server']; $paramString = str_replace('_', ' ', implode($this->delim, $params)); $paramString = str_replace('ns nagios server', 'instance', $paramString); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { if ($key == 'ns_nagios_server') { $value = $this->instanceObj->getInstanceName($value); } $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * Get list from tag * * @param string $tagName * * @throws CentreonClapiException * @throws PDOException */ public function getTypeList($tagName = ''): void { if ($tagName == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $sql = 'SELECT ct.cb_type_id, ct.type_shortname, ct.type_name FROM cb_tag_type_relation cttr, cb_type ct, cb_tag ca WHERE ct.cb_type_id = cttr.cb_type_id AND cttr.cb_tag_id = ca.cb_tag_id AND ca.tagname = ? ORDER BY ct.type_name'; $res = $this->db->query($sql, [$tagName]); $rows = $res->fetchAll(); if (! count($rows)) { throw new CentreonClapiException(self::NOENTRYFOUND . ' for ' . $tagName); } echo 'type id' . $this->delim . 'short name' . $this->delim . "name\n"; foreach ($rows as $row) { echo $row['cb_type_id'] . $this->delim . $row['type_shortname'] . $this->delim . $row['type_name'] . "\n"; } } /** * User help method * Get Field list from Type * * @param $typeName * * @throws CentreonClapiException * @throws PDOException */ public function getFieldList($typeName): void { if ($typeName == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $sql = 'SELECT f.cb_field_id, f.fieldname, f.displayname, f.fieldtype FROM cb_type_field_relation tfr, cb_field f, cb_type ct WHERE ct.cb_type_id = tfr.cb_type_id AND tfr.cb_field_id = f.cb_field_id AND ct.type_shortname = ? ORDER BY f.fieldname'; $res = $this->db->query($sql, [$typeName]); $rows = $res->fetchAll(); if (! count($rows)) { throw new CentreonClapiException(self::NOENTRYFOUND . ' for ' . $typeName); } echo 'field id' . $this->delim . 'short name' . $this->delim . "name\n"; foreach ($rows as $row) { echo $row['cb_field_id'] . $this->delim . $row['fieldname']; if ($row['fieldtype'] == 'select' || $row['fieldtype'] == 'multiselect') { echo '*'; } echo $this->delim . $row['displayname'] . $this->delim . $row['fieldtype'] . "\n"; } } /** * User help method * Get Value list from Selectbox name * * @param $selectName * * @throws CentreonClapiException * @throws PDOException */ public function getValueList($selectName): void { if ($selectName == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $sql = 'SELECT value_value FROM cb_list_values lv, cb_list l, cb_field f WHERE lv.cb_list_id = l.cb_list_id AND l.cb_field_id = f.cb_field_id AND f.fieldname = ? ORDER BY lv.value_value'; $res = $this->db->query($sql, [$selectName]); $rows = $res->fetchAll(); if (! count($rows)) { throw new CentreonClapiException(self::NOENTRYFOUND . ' for ' . $selectName); } echo "possible values\n"; foreach ($rows as $row) { echo $row['value_value'] . "\n"; } } /** * @param null $filterName * * @throws PDOException * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD' . $this->delim . $element['config_name'] . $this->delim . $this->instanceObj->getInstanceName($element['ns_nagios_server']); echo $addStr . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'filename' . $this->delim . $element['config_filename'] . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'cache_directory' . $this->delim . $element['cache_directory'] . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'stats_activate' . $this->delim . $element['stats_activate'] . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'daemon' . $this->delim . $element['daemon'] . "\n"; $poolSize = empty($element['pool_size']) ? '' : $element['pool_size']; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'pool_size' . $this->delim . $poolSize . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $element['config_name'] . $this->delim . 'event_queues_total_size' . $this->delim . ($element['event_queues_total_size'] ?? '') . "\n"; $sql = 'SELECT config_key, config_value, config_group, config_group_id FROM cfg_centreonbroker_info WHERE config_id = ? ORDER BY config_group_id'; $res = $this->db->query($sql, [$element['config_id']]); $blockId = []; $categories = []; $addParamStr = []; $setParamStr = []; $resultSet = $res->fetchAll(); unset($res); foreach ($resultSet as $row) { if ( $row['config_key'] != 'name' && $row['config_key'] != 'blockId' && $row['config_key'] != 'filters' && $row['config_key'] != 'category' ) { if (! isset($setParamStr[$row['config_group'] . '_' . $row['config_group_id']])) { $setParamStr[$row['config_group'] . '_' . $row['config_group_id']] = ''; } $row['config_value'] = CentreonUtils::convertLineBreak($row['config_value']); if ($row['config_value'] != '') { $setParamStr[$row['config_group'] . '_' . $row['config_group_id']] .= $this->action . $this->delim . 'SET' . strtoupper($row['config_group']) . $this->delim . $element['config_name'] . $this->delim . $row['config_group_id'] . $this->delim . $row['config_key'] . $this->delim . $row['config_value'] . "\n"; } } elseif ($row['config_key'] == 'name') { $addParamStr[$row['config_group'] . '_' . $row['config_group_id']] = $this->action . $this->delim . 'ADD' . strtoupper($row['config_group']) . $this->delim . $element['config_name'] . $this->delim . $row['config_value']; } elseif ($row['config_key'] == 'blockId') { $blockId[$row['config_group'] . '_' . $row['config_group_id']] = $row['config_value']; } elseif ($row['config_key'] == 'category') { $categories[$row['config_group'] . '_' . $row['config_group_id']][] = $row['config_value']; } } foreach ($addParamStr as $id => $add) { if (isset($blockId[$id], $setParamStr[$id])) { [$tag, $type] = explode('_', $blockId[$id]); $resType = $this->db->query( 'SELECT type_shortname FROM cb_type WHERE cb_type_id = ?', [$type] ); $rowType = $resType->fetch(); if (isset($rowType['type_shortname'])) { echo $add . $this->delim . $rowType['type_shortname'] . "\n"; echo $setParamStr[$id]; } unset($resType); } if (isset($categories[$id])) { [$configGroup, $configGroupId] = explode('_', $id); echo $this->action . $this->delim . 'SET' . strtoupper($configGroup) . $this->delim . $element['config_name'] . $this->delim . $configGroupId . $this->delim . 'category' . $this->delim . implode(',', $categories[$id]) . "\n"; } } } } /** * get list of multi select fields * * @throws PDOException * @return array */ protected function getMultiselect() { $sql = "SELECT f.cb_fieldgroup_id, fieldname, groupname FROM cb_field f, cb_fieldgroup fg WHERE f.cb_fieldgroup_id = fg.cb_fieldgroup_id AND f.fieldtype = 'multiselect'"; $res = $this->db->query($sql); $arr = []; while ($row = $res->fetch()) { $arr[$row['fieldname']]['groupid'] = $row['cb_fieldgroup_id']; $arr[$row['fieldname']]['groupname'] = $row['groupname']; } return $arr; } /** * Get block id * * @param string $tagName * @param string $typeName * * @throws CentreonClapiException * @throws PDOException * @return string */ protected function getBlockId($tagName, $typeName) { $sql = 'SELECT cttr.cb_tag_id, cttr.cb_type_id FROM cb_tag, cb_type, cb_tag_type_relation cttr WHERE cb_tag.cb_tag_id = cttr.cb_tag_id AND cttr.cb_type_id = cb_type.cb_type_id AND cb_tag.tagname = ? AND cb_type.type_shortname = ?'; $res = $this->db->query($sql, [$tagName, $typeName]); $row = $res->fetch(); if (! isset($row['cb_type_id']) || ! isset($row['cb_tag_id'])) { throw new CentreonClapiException(self::UNKNOWNCOMBO . ': ' . $tagName . '/' . $typeName); } return $row['cb_tag_id'] . '_' . $row['cb_type_id']; } /** * Checks if field is valid * * @param int $configId * @param string $tagName * @param array $args | index 1 => config group id, 2 => config_key, 3 => config_value * * @throws PDOException * @return bool */ protected function fieldIsValid($configId, $tagName, $args) { $sql = "SELECT config_value FROM cfg_centreonbroker_info WHERE config_key = 'blockId' AND config_id = ? AND config_group_id = ? AND config_group = ?"; $res = $this->db->query($sql, [$configId, $args[1], $tagName]); $row = $res->fetch(); unset($res); if (! isset($row['config_value'])) { return false; } [$tagId, $typeId] = explode('_', $row['config_value']); $sql = 'SELECT fieldtype, cf.cb_field_id, ct.cb_module_id FROM cb_type_field_relation ctfr, cb_field cf, cb_type ct WHERE ctfr.cb_field_id = cf.cb_field_id AND ctfr.cb_type_id = ct.cb_type_id AND cf.fieldname = ? AND ctfr.cb_type_id = ?'; $res = $this->db->query($sql, [$args[2], $typeId]); $row = $res->fetch(); unset($res); if (! isset($row['fieldtype'])) { $sql = 'SELECT fieldtype, cf.cb_field_id, ct.cb_module_id FROM cb_type_field_relation ctfr, cb_field cf, cb_type ct WHERE ctfr.cb_field_id = cf.cb_field_id AND ctfr.cb_type_id = ct.cb_type_id AND ctfr.cb_type_id = ?'; $res = $this->db->query($sql, [$typeId]); $rows = $res->fetchAll(); unset($res); $found = false; foreach ($rows as $row) { $sql = 'SELECT fieldtype, cf.cb_field_id FROM cb_module_relation cmr, cb_type ct, cb_type_field_relation ctfr, cb_field cf WHERE cmr.cb_module_id = ? AND cf.fieldname = ? AND cmr.inherit_config = 1 AND cmr.module_depend_id = ct.cb_module_id AND ct.cb_type_id = ctfr.cb_type_id AND ctfr.cb_field_id = cf.cb_field_id ORDER BY fieldname'; $res = $this->db->query($sql, [$row['cb_module_id'], $args[2]]); $row = $res->fetch(); if (isset($row['fieldtype'])) { $found = true; break; } unset($res); } if ($found == false) { return false; } } if ($row['fieldtype'] != 'select' && $row['fieldtype'] != 'multiselect') { return true; } if ($row['fieldtype'] == 'select') { $sql = 'SELECT value_value FROM cb_list cl, cb_list_values clv, cb_field cf WHERE cl.cb_list_id = clv.cb_list_id AND cl.cb_field_id = cf.cb_field_id AND cf.cb_field_id = ? AND cf.fieldname = ? AND clv.value_value = ?'; $res = $this->db->query($sql, [$row['cb_field_id'], $args[2], $args[3]]); $row = $res->fetch(); if (! isset($row['value_value'])) { return false; } } else { $vals = explode(',', $args[3]); $sql = 'SELECT value_value FROM cb_list cl, cb_list_values clv, cb_field cf WHERE cl.cb_list_id = clv.cb_list_id AND cl.cb_field_id = cf.cb_field_id AND cf.cb_field_id = ? AND cf.fieldname = ?'; $res = $this->db->query($sql, [$row['cb_field_id'], $args[2]]); $allowedValues = []; while ($row = $res->fetch()) { $allowedValues[] = $row['value_value']; } foreach ($vals as $v) { if (! in_array($v, $allowedValues)) { return false; } } } return true; } /** * List flows * * @param $configId * @param $tagName * @param $args * * @throws PDOException */ private function listFlow($configId, $tagName, $args): void { $query = 'SELECT config_group_id as id, config_value as name ' . 'FROM cfg_centreonbroker_info ' . 'WHERE config_id = ? ' . 'AND config_group = ? ' . "AND config_key = 'name' " . 'ORDER BY config_group_id '; $res = $this->db->query($query, [$configId, $tagName]); echo "id;name\n"; while ($row = $res->fetch()) { echo $row['id'] . $this->delim . $row['name'] . "\n"; } } /** * Get flow parameters * * @param $configId * @param $tagName * @param $args * * @throws CentreonClapiException * @throws PDOException */ private function getFlow($configId, $tagName, $args): void { if (! isset($args[1]) || $args[1] == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $query = 'SELECT config_key, config_value ' . 'FROM cfg_centreonbroker_info ' . 'WHERE config_id = ? ' . 'AND config_group_id = ? ' . 'AND config_group = ? ' . 'ORDER BY config_key '; $res = $this->db->query($query, [$configId, $args[1], $tagName]); echo "parameter key;parameter value\n"; while ($row = $res->fetch()) { if ($row['config_key'] != 'blockId') { echo $row['config_key'] . $this->delim . $row['config_value'] . "\n"; } } } /** * Set flow parameter * * @param $configId * @param $tagName * @param $args * * @throws CentreonClapiException * @throws PDOException */ private function setFlow($configId, $tagName, $args): void { if (! isset($args[3])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($this->fieldIsValid($configId, $tagName, $args) == false) { throw new CentreonClapiException(self::INVALIDFIELD); } $multiselect = $this->getMultiselect(); $query = 'DELETE FROM cfg_centreonbroker_info ' . 'WHERE config_id = :config_id ' . 'AND config_group_id = :config_group_id ' . 'AND config_key = :config_key ' . 'AND config_group = :config_group '; $this->db->query( $query, [':config_id' => $configId, ':config_group_id' => $args[1], ':config_key' => $args[2], ':config_group' => $tagName] ); $sql = 'INSERT INTO cfg_centreonbroker_info ' . '(config_id, config_group_id, config_key, ' . 'config_value, config_group, grp_level, ' . 'parent_grp_id, subgrp_id) ' . 'VALUES (?,?,?,?,?,?,?,?)'; $grplvl = 0; $parentgrpid = null; if (isset($multiselect[$args[2]])) { $this->db->query( $sql, [$configId, $args[1], $multiselect[$args[2]]['groupname'], '', $tagName, 0, null, 1] ); $grplvl = 1; $parentgrpid = $multiselect[$args[2]]['groupid']; } $values = explode(',', $args[3]); foreach ($values as $value) { $this->db->query( $sql, [$configId, $args[1], $args[2], $value, $tagName, $grplvl, $parentgrpid, null] ); } } /** * Add flow * * @param $configId * @param $tagName * @param $args * * @throws CentreonClapiException * @throws PDOException */ private function addFlow($configId, $tagName, $args): void { if (! isset($args[2])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $cbTypeId = $this->brokerObj->getTypeId($args[2]); if (is_null($cbTypeId)) { throw new CentreonClapiException(self::UNKNOWNPARAMETER); } $fields = $this->brokerObj->getBlockInfos($cbTypeId); $defaultValues = []; foreach ($fields as $field) { if ($field['required'] === 0) { continue; } if (is_null($field['value'])) { $field['value'] = $this->brokerObj->getDefaults($field['id']); } if (is_null($field['value'])) { $field['value'] = ''; } if ($field['group_name'] !== null) { $field['fieldname'] = $field['group_name'] . '__' . $field['fieldname']; } $defaultValues[$field['fieldname']] = $field['value']; } $sql = 'SELECT config_value ' . 'FROM cfg_centreonbroker_info ' . 'WHERE config_id = ? ' . "AND config_key = 'name' " . 'AND config_group = ? '; $res = $this->db->query($sql, [$configId, $tagName]); $listName = []; while ($list = $res->fetch()) { $listName[] = $list['config_value']; } if (in_array($args[1], $listName)) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $blockId = $this->getBlockId($tagName, $args[2]); $sql = 'SELECT MAX(config_group_id) as max_id ' . 'FROM cfg_centreonbroker_info ' . 'WHERE config_id = ? ' . 'AND config_group = ? '; $res = $this->db->query($sql, [$configId, $tagName]); $row = $res->fetch(); $i = isset($row['max_id']) ? $row['max_id'] + 1 : 0; unset($res); $sql = 'INSERT INTO cfg_centreonbroker_info ' . '(config_id, config_key, config_value, ' . 'config_group, config_group_id) ' . 'VALUES (:config_id, :config_key, :config_value, ' . ':config_group, :config_group_id)'; $sqlParams = [':config_id' => $configId, ':config_key' => 'blockId', ':config_value' => $blockId, ':config_group' => $tagName, ':config_group_id' => $i]; $this->db->query($sql, $sqlParams); $values = explode(',', $args[1]); foreach ($values as $value) { $sqlParams[':config_key'] = 'type'; $sqlParams[':config_value'] = $args[2]; $this->db->query($sql, $sqlParams); $sqlParams[':config_key'] = 'name'; $sqlParams[':config_value'] = $value; $this->db->query($sql, $sqlParams); } unset($defaultValues['name']); foreach ($defaultValues as $key => $value) { $sqlParams[':config_key'] = $key; $sqlParams[':config_value'] = $value; $this->db->query($sql, $sqlParams); } } /** * Remove flow * * @param $configId * @param $tagName * @param $args * * @throws CentreonClapiException * @throws PDOException */ private function delFlow($configId, $tagName, $args): void { if (! isset($args[1]) || $args[1] == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } $sql = 'DELETE FROM cfg_centreonbroker_info ' . 'WHERE config_id = ? ' . 'AND config_group_id = ? ' . 'AND config_group = ? '; $this->db->query($sql, [$configId, $args[1], $tagName]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonResourceCfg.class.php
centreon/www/class/centreon-clapi/centreonResourceCfg.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Relation_Instance_Resource; use Centreon_Object_Resource; use Exception; use LogicException; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonInstance.class.php'; require_once 'Centreon/Object/Resource/Resource.php'; require_once 'Centreon/Object/Relation/Instance/Resource.php'; /** * Class * * @class CentreonResourceCfg * @package CentreonClapi */ class CentreonResourceCfg extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_VALUE = 1; public const ORDER_INSTANCE = 2; public const ORDER_COMMENT = 3; public const MACRO_ALREADY_IN_USE = 'Resource is already tied to instance'; /** @var string[] */ public static $aDepends = ['INSTANCE']; /** @var CentreonInstance */ protected $instanceObj; /** @var Centreon_Object_Relation_Instance_Resource */ protected $relObj; /** @var */ protected $instanceIds; /** * CentreonResourceCfg constructor * * @param Container $dependencyInjector * * @throws PDOException * @throws LogicException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->instanceObj = new CentreonInstance($dependencyInjector); $this->relObj = new Centreon_Object_Relation_Instance_Resource($dependencyInjector); $this->object = new Centreon_Object_Resource($dependencyInjector); $this->params = ['resource_line' => '', 'resource_comment' => '', 'resource_activate' => '1']; $this->insertParams = [$this->object->getUniqueLabelField(), 'resource_line', 'instance_id', 'resource_comment']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->nbOfCompulsoryParams = 4; $this->activateField = 'resource_activate'; $this->action = 'RESOURCECFG'; } /** * Magic method * * @param string $name * @param array $arg * @throws CentreonClapiException * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { switch ($matches[2]) { case 'instance': $class = 'Centreon_Object_Instance'; $relclass = 'Centreon_Object_Relation_Instance_Resource'; break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); break; } if (class_exists($relclass) && class_exists($class)) { // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (isset($object[0][$this->object->getPrimaryKey()])) { $objectId = $object[0][$this->object->getPrimaryKey()]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $relobj = new $relclass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $objectId ); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relations = explode('|', $args[1]); $relationTable = []; foreach ($relations as $rel) { $sRel = $rel; if (is_string($rel)) { $rel = htmlentities($rel, ENT_QUOTES, 'UTF-8'); } $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $sRel); } $relationTable[] = $tab[0]; } if ($matches[1] == 'set') { $relobj->delete(null, $objectId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $objectId ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($relationId, $objectId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($relationId, $objectId); } } } } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (! preg_match('/^\$\S+\$$/', $params[self::ORDER_UNIQUENAME])) { $params[self::ORDER_UNIQUENAME] = '$' . $params[self::ORDER_UNIQUENAME] . '$'; } $addParams = []; $instanceNames = explode('|', $params[self::ORDER_INSTANCE]); $this->instanceIds = []; foreach ($instanceNames as $instanceName) { $this->instanceIds[] = $this->instanceObj->getInstanceId($instanceName); } foreach ($this->instanceIds as $instanceId) { if ($this->isUnique($params[self::ORDER_UNIQUENAME], $instanceId) == false) { throw new CentreonClapiException(self::MACRO_ALREADY_IN_USE); } } $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['resource_line'] = $params[self::ORDER_VALUE]; $addParams['resource_comment'] = $params[self::ORDER_COMMENT]; $this->params = array_merge($this->params, $addParams); } /** * @param $resourceId */ public function insertRelations($resourceId): void { $this->setRelations($resourceId, $this->instanceIds); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (is_numeric($params[0])) { $objectId = $params[0]; } else { $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]); if (isset($object[0][$this->object->getPrimaryKey()])) { $objectId = $object[0][$this->object->getPrimaryKey()]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } } if ($params[1] == 'instance') { $instanceNames = explode('|', $params[2]); $instanceIds = []; foreach ($instanceNames as $instanceName) { $instanceIds[] = $this->instanceObj->getInstanceId($instanceName); } $this->setRelations($objectId, $instanceIds); } else { $params[1] = str_replace('value', 'line ', $params[1]); if ($params[1] == 'name') { if (! preg_match('/^\$\S+\$$/', $params[2])) { $params[2] = '$' . $params[2] . '$'; } } $params[1] = 'resource_' . $params[1]; $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } return []; } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addPoller($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (is_numeric($params[0])) { $objectId = $params[0]; } else { $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]); if (isset($object[0][$this->object->getPrimaryKey()])) { $objectId = $object[0][$this->object->getPrimaryKey()]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } } if ($params[1] == 'instance') { $instanceNames = explode('|', $params[2]); $instanceIds = []; foreach ($instanceNames as $instanceName) { $instanceId = $this->instanceObj->getInstanceId($instanceName); $stmt = $this->db->query('SELECT instance_id FROM cfg_resource_instance_relations WHERE instance_id = ? AND resource_id = ?', [$instanceId, $objectId]); $results = $stmt->fetchAll(); $oldInstanceIds = []; foreach ($results as $result) { $oldInstanceIds[] = $result['instance_id']; } if (! in_array($instanceId, $oldInstanceIds)) { $instanceIds[] = $instanceId; } } $this->addRelations($objectId, $instanceIds); } } /** * @param string $objectName * @throws CentreonClapiException */ public function del($objectName): void { if (is_numeric($objectName)) { $objectId = $objectName; } else { if (! preg_match('/^\$\S+\$$/', $objectName)) { $objectName = '$' . $objectName . '$'; } $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$objectName]); if (isset($object[0][$this->object->getPrimaryKey()])) { $objectId = $object[0][$this->object->getPrimaryKey()]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objectName); } } $this->object->delete($objectId); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['resource_id', 'resource_name', 'resource_line', 'resource_comment', 'resource_activate']; $paramString = str_replace('_', ' ', implode($this->delim, $params)); $paramString = str_replace('resource ', '', $paramString); $paramString = str_replace('line', 'value', $paramString); echo $paramString . $this->delim . 'instance' . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { $str .= $value . $this->delim; } $instanceIds = $this->relObj->getinstance_idFromresource_id(trim($tab['resource_id'])); $strInstance = ''; foreach ($instanceIds as $instanceId) { if ($strInstance != '') { $strInstance .= '|'; } $strInstance .= $this->instanceObj->getInstanceName($instanceId); } $str .= $strInstance; $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * @param null $filterName * * @throws Exception * @return int|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return 0; } $labelField = $this->object->getUniqueLabelField(); $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC' ); if (! is_null($filterName) && ! empty($filterName)) { $nbElements = count($elements); for ($i = 0; $i < $nbElements; $i++) { if ($elements[$i][$labelField] != $filterName) { unset($elements[$i]); } } } foreach ($elements as $element) { $instanceIds = $this->relObj->getinstance_idFromresource_id( trim($element[$this->object->getPrimaryKey()]) ); // ADD action $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { if ($param == 'instance_id') { $instances = []; foreach ($instanceIds as $instanceId) { $instances[] = $this->instanceObj->getInstanceName($instanceId); } $element[$param] = implode('|', $instances); } $addStr .= $this->delim . $element[$param]; } $addStr .= "\n"; echo $addStr; // SETPARAM action foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams) && ! is_null($value) && $value != '') { $parameter = str_replace('resource_', '', $parameter); $value = str_replace("\n", '<br/>', $value); $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getPrimaryKey()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } } } /** * Checks if macro is unique on a given poller * * @param $macro * @param int $pollerId * * @throws CentreonClapiException * @throws PDOException * @return bool */ protected function isUnique($macro, $pollerId) { if (is_numeric($macro)) { $stmt = $this->db->query('SELECT resource_name FROM cfg_resource WHERE resource_id = ?', [$macro]); $res = $stmt->fetchAll(); if (count($res)) { $macroName = $res[0]['resource_name']; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND); } unset($res, $stmt); } else { $macroName = $macro; } $stmt = $this->db->query('SELECT r.resource_id FROM cfg_resource r, cfg_resource_instance_relations rir WHERE r.resource_id = rir.resource_id AND rir.instance_id = ? AND r.resource_name = ?', [$pollerId, $macroName]); $res = $stmt->fetchAll(); return ! (count($res)); } /** * Set Instance relations * * @param int $resourceId * @param array $instances * @return void */ protected function setRelations($resourceId, $instances) { $this->relObj->delete_resource_id($resourceId); foreach ($instances as $instanceId) { $this->relObj->insert($instanceId, $resourceId); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonCommand.class.php
centreon/www/class/centreon-clapi/centreonCommand.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_Graph_Template; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonUtils.class.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Graph/Template/Template.php'; /** * Class * * @class CentreonCommand * @package CentreonClapi * @author jmathis */ class CentreonCommand extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_TYPE = 1; public const ORDER_COMMAND = 2; public const UNKNOWN_CMD_TYPE = 'Unknown command type'; /** @var array[] */ public $aTypeCommand = ['host' => ['key' => '$_HOST', 'preg' => '/\$_HOST(\w+)\$/'], 'service' => ['key' => '$_SERVICE', 'preg' => '/\$_SERVICE(\w+)\$/']]; /** @var int[] */ protected $typeConversion = ['notif' => 1, 'check' => 2, 'misc' => 3, 'discovery' => 4, 1 => 'notif', 2 => 'check', 3 => 'misc', 4 => 'discovery']; /** * CentreonCommand constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Command($dependencyInjector); $this->params = []; $this->insertParams = ['command_name', 'command_type', 'command_line']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'graph_id', 'cmd_cat_id'] ); $this->action = 'CMD'; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['command_id', 'command_name', 'command_type', 'command_line']; $paramString = str_replace('command_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $tab['command_line'] = CentreonUtils::convertSpecialPattern(html_entity_decode($tab['command_line'])); $tab['command_line'] = CentreonUtils::convertLineBreak($tab['command_line']); $tab['command_type'] = $this->typeConversion[$tab['command_type']]; echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]); if (! isset($this->typeConversion[$params[self::ORDER_TYPE]])) { throw new CentreonClapiException(self::UNKNOWN_CMD_TYPE . ':' . $params[self::ORDER_TYPE]); } $addParams['command_type'] = is_numeric($params[self::ORDER_TYPE]) ? $params[self::ORDER_TYPE] : $this->typeConversion[$params[self::ORDER_TYPE]]; $addParams['command_line'] = $params[self::ORDER_COMMAND]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^command_/', $params[1])) { if (! in_array($params[1], ['graph', 'enable_shell', 'connector_id'])) { $params[1] = 'command_' . $params[1]; } elseif ($params[1] == 'graph') { $params[1] = 'graph_id'; } } if ($params[1] == 'command_type') { if (! isset($this->typeConversion[$params[2]])) { throw new CentreonClapiException(self::UNKNOWN_CMD_TYPE . ':' . $params[2]); } if (! is_numeric($params[2])) { $params[2] = $this->typeConversion[$params[2]]; } } elseif ($params[1] == 'graph_id') { $graphObject = new Centreon_Object_Graph_Template($this->dependencyInjector); $tmp = $graphObject->getIdByParameter($graphObject->getUniqueLabelField(), $params[2]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } $params[2] = $tmp[0]; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * Get a parameter * * @param null $parameters * @throws CentreonClapiException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['name', 'line', 'type', 'graph', 'example', 'comment', 'activate', 'enable_shell']; $unknownParam = []; if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ''; foreach ($listParam as $paramSearch) { $paramString = ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { switch ($paramSearch) { case 'graph': $field = 'graph_id'; break; case 'enable_shell': break; default: if (! preg_match('/^command_/', $paramSearch)) { $field = 'command_' . $paramSearch; } break; } $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; switch ($paramSearch) { case 'graph': $graphObj = new Centreon_Object_Graph_Template($this->dependencyInjector); $field = $graphObj->getUniqueLabelField(); $ret = $graphObj->getParameters($ret, $field); $ret = $ret[$field]; break; } if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * Get command arguments descriptions * * @param string $objUniqueName * * @throws CentreonClapiException * @throws PDOException */ public function getargumentdesc($objUniqueName): void { if ($objUniqueName != '' && ($objectId = $this->getObjectId($objUniqueName)) != 0) { $sql = 'SELECT macro_name, macro_description FROM command_arg_description WHERE cmd_id = ?'; $res = $this->db->query($sql, [$objectId]); echo 'name' . $this->delim . 'description' . "\n"; foreach ($res as $param) { echo $param['macro_name'] . $this->delim . $param['macro_description'] . "\n"; } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objUniqueName); } } /** * Set command arguments descriptions * * @param string $descriptions * * @throws CentreonClapiException * @throws PDOException */ public function setargumentdescr($descriptions): void { $data = explode($this->delim, trim($descriptions, $this->delim)); if (count($data) < 1) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objUniqueName = array_shift($data); if (($objectId = $this->getObjectId($objUniqueName)) != 0) { $sql = 'DELETE FROM command_arg_description WHERE cmd_id = ?'; $this->db->query($sql, [$objectId]); foreach ($data as $description) { [$arg, $desc] = explode(':', $description, 2); $sql = 'INSERT INTO command_arg_description (cmd_id, macro_name, macro_description) VALUES (?,?,?)'; $this->db->query($sql, [$objectId, $arg, $desc]); } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objUniqueName); } } /** * Returns command id * * @param string $commandName * @throws CentreonClapiException * @return int */ public function getId($commandName) { $obj = new Centreon_Object_Command($this->dependencyInjector); $tmp = $obj->getIdByParameter($obj->getUniqueLabelField(), $commandName); if (count($tmp)) { $id = $tmp[0]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $commandName); } return $id; } /** * @param null $filterName * @throws CentreonClapiException * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $addStr .= $this->delim; if ($param === 'command_line') { $decodedHtmlParam = CentreonUtils::convertSpecialPattern(html_entity_decode($element[$param])); $decodedHtmlParam = CentreonUtils::convertLineBreak($decodedHtmlParam); $addStr .= $decodedHtmlParam; } else { $addStr .= $element[$param]; } } $addStr .= "\n"; echo $addStr; foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams)) { if (! is_null($value) && $value != '') { $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } if ($parameter == 'graph_id' && ! empty($value)) { $graphObject = new Centreon_Object_Graph_Template($this->dependencyInjector); $tmp = $graphObject->getParameters($value, [$graphObject->getUniqueLabelField()]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $value); } $v = $tmp[$graphObject->getUniqueLabelField()]; $v = CentreonUtils::convertLineBreak($v); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $this->getClapiActionName($parameter) . $this->delim . $v . "\n"; } } $argDescriptions = $this->getArgsDescriptions($element['command_id']); if (sizeof($argDescriptions) > 0) { echo $this->action . $this->delim . 'setargumentdescr' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . implode(';', $argDescriptions) . "\n"; } } } /** * This method gat the list of command containt a specific macro * * @param int $iIdCommand * @param string $sType * @param int $iWithFormatData * * @throws PDOException * @return array */ public function getMacroByIdAndType($iIdCommand, $sType, $iWithFormatData = 1) { $inputName = $sType; if ($sType == 'service') { $inputName = 'svc'; } $macroToFilter = ['SNMPVERSION', 'SNMPCOMMUNITY']; if (empty($iIdCommand) || ! array_key_exists($sType, $this->aTypeCommand)) { return []; } $aDescription = $this->getMacroDescription($iIdCommand); $sql = "SELECT command_id, command_name, command_line FROM command WHERE command_type = 2 AND command_id = ? AND command_line like '%" . $this->aTypeCommand[$sType]['key'] . "%' ORDER BY command_name"; $res = $this->db->query($sql, [$iIdCommand]); $arr = []; $i = 0; if ($iWithFormatData == 1) { while ($row = $res->fetch()) { preg_match_all($this->aTypeCommand[$sType]['preg'], $row['command_line'], $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (! in_array($match[1], $macroToFilter)) { $sName = $match[1]; $sDesc = $aDescription[$sName]['description'] ?? ''; $arr[$i][$inputName . '_macro_name'] = $sName; $arr[$i][$inputName . '_macro_value'] = ''; $arr[$i]['is_password'] = null; $arr[$i]['macroDescription'] = $sDesc; $i++; } } } } else { while ($row = $res->fetch()) { $arr[$row['command_id']] = $row['command_name']; } } return $arr; } /** * @param $iIdCmd * * @throws PDOException * @return array */ public function getMacroDescription($iIdCmd) { $aReturn = []; $sSql = 'SELECT * FROM `on_demand_macro_command` WHERE `command_command_id` = ' . (int) $iIdCmd; $DBRESULT = $this->db->query($sSql); while ($row = $DBRESULT->fetch()) { $arr['id'] = $row['command_macro_id']; $arr['name'] = $row['command_macro_name']; $arr['description'] = $row['command_macro_desciption']; $arr['type'] = $row['command_macro_type']; $aReturn[$row['command_macro_name']] = $arr; } return $aReturn; } /** * Get clapi action name from db column name * * @param string $columnName * @return string */ protected function getClapiActionName($columnName) { static $table; if (! isset($table)) { $table = ['graph_id' => 'graph']; } return $table[$columnName] ?? $columnName; } /** * Export command_arg_description * * @param int $command_id * * @throws PDOException * @return array */ protected function getArgsDescriptions($command_id) { $sql = 'SELECT macro_name, macro_description FROM command_arg_description WHERE cmd_id = ? ORDER BY macro_name'; $res = $this->db->query($sql, [$command_id]); $args_desc = []; while ($row = $res->fetch()) { $args_desc[] = $row['macro_name'] . ':' . trim($row['macro_description']); } unset($res); return $args_desc; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonEngineCfg.class.php
centreon/www/class/centreon-clapi/centreonEngineCfg.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_Engine; use Centreon_Object_Engine_Broker_Module; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonInstance.class.php'; require_once 'Centreon/Object/Engine/Engine.php'; require_once 'Centreon/Object/Engine/Engine_Broker_Module.php'; require_once 'Centreon/Object/Command/Command.php'; /** * Class * * @class CentreonEngineCfg * @package CentreonClapi */ class CentreonEngineCfg extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_INSTANCE = 1; public const ORDER_COMMENT = 2; /** @var string[] */ public static $aDepends = ['INSTANCE']; /** @var Centreon_Object_Command */ public $commandObj; /** @var Centreon_Object_Engine_Broker_Module */ public $brokerModuleObj; /** @var CentreonInstance */ protected $instanceObj; /** * CentreonEngineCfg constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->instanceObj = new CentreonInstance($dependencyInjector); $this->commandObj = new Centreon_Object_Command($dependencyInjector); $this->object = new Centreon_Object_Engine($dependencyInjector); $this->brokerModuleObj = new Centreon_Object_Engine_Broker_Module($dependencyInjector); $this->params = [ 'log_file' => '/var/log/centreon-engine/centengine.log', 'cfg_dir' => '/etc/centreon-engine/', 'enable_notifications' => '0', 'execute_service_checks' => '1', 'accept_passive_service_checks' => '1', 'execute_host_checks' => '2', 'accept_passive_host_checks' => '2', 'enable_event_handlers' => '1', 'check_external_commands' => '1', 'command_check_interval' => '1s', 'command_file' => '/var/log/centreon-engine/rw/nagios.cmd', 'retain_state_information' => '1', 'state_retention_file' => '/var/log/centreon-engine/status.sav', 'retention_update_interval' => '60', 'use_retained_program_state' => '1', 'use_retained_scheduling_info' => '1', 'use_syslog' => '0', 'log_notifications' => '1', 'log_service_retries' => '1', 'log_host_retries' => '1', 'log_event_handlers' => '1', 'log_external_commands' => '1', 'log_passive_checks' => '2', 'sleep_time' => '0.2', 'service_inter_check_delay_method' => 's', 'service_interleave_factor' => 's', 'max_concurrent_checks' => '400', 'max_service_check_spread' => '5', 'check_result_reaper_frequency' => '5', 'auto_reschedule_checks' => '2', 'enable_flap_detection' => '0', 'low_service_flap_threshold' => '25.0', 'high_service_flap_threshold' => '50.0', 'low_host_flap_threshold' => '25.0', 'high_host_flap_threshold' => '50.0', 'soft_state_dependencies' => '0', 'service_check_timeout' => '60', 'host_check_timeout' => '10', 'event_handler_timeout' => '30', 'notification_timeout' => '30', 'check_for_orphaned_services' => '0', 'check_for_orphaned_hosts' => '0', 'check_service_freshness' => '2', 'check_host_freshness' => '2', 'date_format' => 'euro', 'illegal_object_name_chars' => "~!$%^&*\"|'<>?,()=", 'illegal_macro_output_chars' => "`~$^&\"|'<>", 'use_regexp_matching' => '2', 'use_true_regexp_matching' => '2', 'admin_email' => 'admin@localhost', 'admin_pager' => 'admin', 'nagios_activate' => '1', 'event_broker_options' => '-1', 'enable_predictive_host_dependency_checks' => '2', 'enable_predictive_service_dependency_checks' => '2', 'host_down_disable_service_checks' => '0', 'enable_environment_macros' => '2', 'debug_level' => '0', 'debug_level_opt' => '0', 'debug_verbosity' => '2', 'cached_host_check_horizon' => '60', 'logger_version' => 'log_v2_enabled', ]; $this->nbOfCompulsoryParams = 3; $this->activateField = 'nagios_activate'; $this->action = 'ENGINECFG'; $this->insertParams = [$this->object->getUniqueLabelField(), 'nagios_server_id', 'nagios_comment']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['nagios_server_id'] = $this->instanceObj->getInstanceId($params[self::ORDER_INSTANCE]); $addParams['nagios_comment'] = $params[self::ORDER_COMMENT]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $commandColumns = ['global_host_event_handler', 'global_service_event_handler']; $loggerColumns = [ 'log_v2_logger', 'log_level_functions', 'log_level_config', 'log_level_events', 'log_level_checks', 'log_level_notifications', 'log_level_eventbroker', 'log_level_external_command', 'log_level_commands', 'log_level_downtimes', 'log_level_comments', 'log_level_macros', 'log_level_process', 'log_level_runtime', ]; $canUpdateParams = true; if ($params[1] == 'instance' || $params[1] == 'nagios_server_id') { $params[1] = 'nagios_server_id'; $params[2] = $this->instanceObj->getInstanceId($params[2]); } elseif ($params[1] == 'broker_module') { $this->setBrokerModule($objectId, $params[2]); $canUpdateParams = false; } elseif (preg_match('/(' . implode('|', $commandColumns) . ')/', $params[1], $matches)) { if ($params[2]) { $commandObj = new Centreon_Object_Command($this->dependencyInjector); $res = $commandObj->getIdByParameter($commandObj->getUniqueLabelField(), $params[2]); if (count($res)) { $params[2] = $res[0]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]); } } else { $params[2] = null; } } elseif ($params[1] === 'logger_version' && $params[2] === 'log_v2_enabled') { $this->createLoggerV2Cfg($objectId); } elseif (preg_match('/(' . implode('|', $loggerColumns) . ')/', $params[1], $matches)) { $this->updateLoggerV2Param($objectId, $params); $canUpdateParams = false; } if ($canUpdateParams) { $p = strtolower($params[1]); if ($params[2] == '') { $params[2] = isset($this->params[$p]) && $this->params[$p] == 2 ? $this->params[$p] : null; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['nagios_id', 'nagios_name', 'nagios_server_id', 'nagios_comment']; $paramString = str_replace('_', ' ', implode($this->delim, $params)); $paramString = str_replace('nagios server id', 'instance', $paramString); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { if ($key == 'nagios_server_id') { $value = $this->instanceObj->getInstanceName($value); } $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * Export * * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { $element = array_merge($element, $this->getLoggerV2Cfg($element['nagios_id'])); // ADD action $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { if ($param == 'nagios_server_id') { $element[$param] = $this->instanceObj->getInstanceName($element[$param]); } $addStr .= $this->delim . $element[$param]; } $addStr .= "\n"; echo $addStr; // SETPARAM action foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams) && ! is_null($value) && $value != '') { if ( $parameter === 'global_host_event_handler' || $parameter === 'global_service_event_handler' ) { $tmp = $this->commandObj->getParameters($value, $this->commandObj->getUniqueLabelField()); $value = $tmp[$this->commandObj->getUniqueLabelField()]; } $value = str_replace("\n", '<br/>', $value); $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } $modules = $this->brokerModuleObj->getList( 'broker_module', -1, 0, null, 'ASC', ['cfg_nagios_id' => $element[$this->object->getPrimaryKey()]], 'AND' ); $moduleList = []; foreach ($modules as $module) { array_push($moduleList, $module['broker_module']); } echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . 'broker_module' . $this->delim . implode('|', $moduleList) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addbrokermodule($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $this->addBkModule($objectId, $params[1]); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function delbrokermodule($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $this->delBkModule($objectId, $params[1]); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * This method is automatically called in CentreonObject * * @param int $nagiosId * * @throws PDOException */ public function insertRelations(int $nagiosId): void { $this->createLoggerV2Cfg($nagiosId); } /** * Set Broker Module * * @param int $objectId * @param string $brokerModule * * @throws PDOException * @return void * @todo we should implement this object in the centreon api so that we don't have to write our own query */ protected function setBrokerModule($objectId, $brokerModule) { $query = 'DELETE FROM cfg_nagios_broker_module WHERE cfg_nagios_id = ?'; $this->db->query($query, [$objectId]); $brokerModuleArray = explode('|', $brokerModule); foreach ($brokerModuleArray as $bkModule) { $this->db->query( 'INSERT INTO cfg_nagios_broker_module (cfg_nagios_id, broker_module) VALUES (?, ?)', [$objectId, $bkModule] ); } } /** * Set Broker Module * * @param int $objectId * @param string $brokerModule * * @throws CentreonClapiException * @throws PDOException * @return void * @todo we should implement this object in the centreon api so that we don't have to write our own query */ protected function addBkModule($objectId, $brokerModule) { $brokerModuleArray = explode('|', $brokerModule); foreach ($brokerModuleArray as $bkModule) { $res = $this->db->query( 'SELECT COUNT(*) as nbBroker FROM cfg_nagios_broker_module ' . 'WHERE cfg_nagios_id = ? AND broker_module = ?', [$objectId, $bkModule] ); $row = $res->fetch(); if ($row['nbBroker'] > 0) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS . ':' . $bkModule); } $this->db->query( 'INSERT INTO cfg_nagios_broker_module (cfg_nagios_id, broker_module) VALUES (?, ?)', [$objectId, $bkModule] ); } } /** * Set Broker Module * * @param int $objectId * @param string $brokerModule * * @throws CentreonClapiException * @throws PDOException * @return void * @todo we should implement this object in the centreon api so that we don't have to write our own query */ protected function delBkModule($objectId, $brokerModule) { $brokerModuleArray = explode('|', $brokerModule); foreach ($brokerModuleArray as $bkModule) { $tab = $this->brokerModuleObj->getIdByParameter('broker_module', [$bkModule]); if (count($tab)) { $this->db->query( 'DELETE FROM cfg_nagios_broker_module WHERE cfg_nagios_id = ? and broker_module = ?', [$objectId, $bkModule] ); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $bkModule); } } } /** * @param int $nagiosId * * @throws PDOException * @return bool */ private function doesLoggerV2CfgExist(int $nagiosId): bool { $statement = $this->db->prepare('SELECT id FROM cfg_nagios_logger WHERE cfg_nagios_id = :cfgNagiosId'); $statement->bindValue(':cfgNagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); return $statement->fetch() !== false; } /** * Create logger V2 config if it doesn't already exist * * @param int $nagiosId * * @throws PDOException */ private function createLoggerV2Cfg(int $nagiosId): void { if (! $this->doesLoggerV2CfgExist($nagiosId)) { $statement = $this->db->prepare('INSERT INTO cfg_nagios_logger (cfg_nagios_id) VALUES (:cfgNagiosId)'); $statement->bindValue(':cfgNagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); } } /** * @param int $nagiosId * * @throws PDOException * @return array */ private function getLoggerV2Cfg(int $nagiosId): array { $statement = $this->db->prepare('SELECT * FROM cfg_nagios_logger WHERE cfg_nagios_id = :cfgNagiosId'); $statement->bindValue(':cfgNagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); if ($result = $statement->fetch()) { unset($result['cfg_nagios_id'], $result['id']); } return empty($result) ? [] : $result; } /** * Update loggerV2 config * * @param int $nagiosId * @param string[] $params * * @throws CentreonClapiException if config isn't found in cfg_nagios_logger table * @throws PDOException */ private function updateLoggerV2Param(int $nagiosId, array $params): void { if (! $this->doesLoggerV2CfgExist($nagiosId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } $statement = $this->db->prepare( "UPDATE cfg_nagios_logger SET `{$params[1]}` = :paramValue WHERE cfg_nagios_id = :cfgNagiosId" ); $statement->bindValue(':paramValue', $params[2], PDO::PARAM_STR); $statement->bindValue(':cfgNagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonObject.class.php
centreon/www/class/centreon-clapi/centreonObject.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object; use Centreon_Object_Contact; use CentreonDB; use Exception; use PDOException; use Pimple\Container; require_once 'centreonAPI.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Contact.php'; require_once 'centreonClapiException.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon-clapi/centreonExported.class.php'; /** * Class * * @class CentreonObject * @package CentreonClapi */ abstract class CentreonObject { public const MISSINGPARAMETER = 'Missing parameters'; public const MISSINGNAMEPARAMETER = 'Missing name parameter'; public const OBJECTALREADYEXISTS = 'Object already exists'; public const OBJECT_NOT_FOUND = 'Object not found'; public const UNKNOWN_METHOD = 'Method not implemented into Centreon API'; public const NAMEALREADYINUSE = 'Name is already in use'; public const NB_UPDATE_PARAMS = 3; public const UNKNOWNPARAMETER = 'Unknown parameter'; public const OBJECTALREADYLINKED = 'Objects already linked'; public const OBJECTNOTLINKED = 'Objects are not linked'; public const SINGLE_VALUE = 0; public const MULTIPLE_VALUE = 1; /** @var CentreonApi */ public $api; /** @var array */ protected static $instances; /** @var CentreonDB */ protected $db; /** @var string */ protected string $action = ''; /** @var Container */ protected $dependencyInjector; /** * Version of Centreon * * @var string */ protected $version; /** * Centreon Configuration object type * * @var Centreon_Object */ protected $object; /** * Default params * * @var array */ protected $params = []; /** * Number of compulsory parameters when adding a new object * * @var int */ protected $nbOfCompulsoryParams; /** * Delimiter * * @var string */ protected $delim = ';'; /** * Table column used for activating and deactivating object * * @var string */ protected $activateField; /** * Export : Table columns that are used for 'add' action * * @var array */ protected $insertParams = []; /** * Export : Table columns which will not be exported for 'setparam' action * * @var array */ protected $exportExcludedParams = []; /** * cache to store object ids by object names * * @var array */ protected $objectIds = []; /** * CentreonObject constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { $this->db = $dependencyInjector['configuration_db']; $this->dependencyInjector = $dependencyInjector; $res = $this->db->query("SELECT `value` FROM informations WHERE `key` = 'version'"); $row = $res->fetch(); $this->version = $row['value']; $this->api = CentreonAPI::getInstance(); } /** * @return Centreon_Object */ public function getObject() { return $this->object; } /** * @param $dependencyInjector */ public function setDependencyInjector($dependencyInjector): void { $this->dependencyInjector = $dependencyInjector; } /** * Get Centreon Version * * @return string */ public function getVersion() { return $this->version; } /** * Get Object Id * * @param string $name * @return int */ public function getObjectId($name, int $type = self::SINGLE_VALUE) { if (isset($this->objectIds[$name])) { return $this->objectIds[$name]; } $ids = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$name]); if (count($ids)) { $this->objectIds[$name] = ($type === self::SINGLE_VALUE) ? $ids[0] : $ids; return $this->objectIds[$name]; } return 0; } /** * Get Object Name * * @param int $id * @return string */ public function getObjectName($id) { $tmp = $this->object->getParameters($id, [$this->object->getUniqueLabelField()]); return $tmp[$this->object->getUniqueLabelField()] ?? ''; } /** * Catch the beginning of the URL * * @return string */ public function getBaseUrl() { $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http'; $port = ''; if ( ($protocol == 'http' && $_SERVER['SERVER_PORT'] != 80) || ($protocol == 'https' && $_SERVER['SERVER_PORT'] != 443) ) { $port = ':' . $_SERVER['SERVER_PORT']; } $uri = 'centreon'; if (preg_match('/^(.+)\/api/', $_SERVER['REQUEST_URI'], $matches)) { $uri = $matches[1]; } return $protocol . '://' . $_SERVER['HTTP_HOST'] . $port . $uri; } /** * @param $parameters * * @throws CentreonClapiException * @return void */ public function add($parameters): void { $this->initInsertParameters($parameters); $id = $this->object->insert($this->params); if (isset($this->params[$this->object->getUniqueLabelField()])) { $this->addAuditLog( 'a', $id, $this->params[$this->object->getUniqueLabelField()], $this->params ); } if (method_exists($this, 'insertRelations')) { $this->insertRelations($id); } $aclObj = new CentreonACL($this->dependencyInjector); $aclObj->reload(true); } /** * @param $parameters * @return mixed */ public function initInsertParameters($parameters) { return $parameters; } /** * Del Action * * @param string $objectName * @throws CentreonClapiException * @return void */ public function del($objectName): void { $ids = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$objectName]); if (count($ids)) { $this->object->delete($ids[0]); $this->addAuditLog('d', $ids[0], $objectName); $aclObj = new CentreonACL($this->dependencyInjector); $aclObj->reload(true); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objectName); } } /** * Get a parameter * * @param string $parameters * @throws CentreonClapiException * @return void */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $p = $this->object->getParameters($params[0], $params[1]); echo $this->csvEscape($p[$params[1]]) . "\n"; } /** * @param array $parameters * @throws CentreonClapiException */ public function setparam($parameters = []): void { $params = method_exists($this, 'initUpdateParameters') ? $this->initUpdateParameters($parameters) : $parameters; if (! empty($params)) { $uniqueLabel = $this->object->getUniqueLabelField(); $objectId = $params['objectId']; unset($params['objectId']); if ( isset($params[$uniqueLabel]) && $this->objectExists($params[$uniqueLabel], $objectId) == true ) { throw new CentreonClapiException(self::NAMEALREADYINUSE); } $this->object->update($objectId, $params); $p = $this->object->getParameters($objectId, $uniqueLabel); if (isset($p[$uniqueLabel])) { $this->addAuditLog( 'c', $objectId, $p[$uniqueLabel], $params ); } } } /** * Shows list * * @param array $params * @param array $filters * * @throws Exception * @return void */ public function show($params = [], $filters = []): void { echo str_replace('_', ' ', implode($this->delim, $params)) . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * Enable object * * @param string $objectName * * @throws CentreonClapiException * @return void */ public function enable($objectName): void { $this->activate($objectName, '1'); } /** * Disable object * * @param string $objectName * * @throws CentreonClapiException * @return void */ public function disable($objectName): void { $this->activate($objectName, '0'); } /** * Export from a specific object * * @param string|null $filterName * * @throws Exception * @return bool */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $filterId = $this->getObjectId($filterName); $labelField = $this->getObject()->getUniqueLabelField(); $filters = []; if (! is_null($filterId) && $filterId !== 0) { $primaryKey = $this->getObject()->getPrimaryKey(); $filters[$primaryKey] = $filterId; } if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $elements = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters, 'AND' ); foreach ($elements as $element) { $addStr = $this->action . $this->delim . 'ADD'; foreach ($this->insertParams as $param) { $element[$param] = CentreonUtils::convertLineBreak($element[$param]); $addStr .= $this->delim . $element[$param]; } $addStr .= "\n"; echo $addStr; foreach ($element as $parameter => $value) { if (! in_array($parameter, $this->exportExcludedParams)) { if (! is_null($value) && $value != '') { $value = CentreonUtils::convertLineBreak($value); echo $this->action . $this->delim . 'setparam' . $this->delim . $element[$this->object->getUniqueLabelField()] . $this->delim . $parameter . $this->delim . $value . "\n"; } } } } CentreonExported::getInstance()->arianePop(); return true; } /** * Insert audit log * * @param $actionType * @param $objId * @param $objName * @param array $objValues * @param null $objectType * * @throws CentreonClapiException * @throws PDOException * @return void */ public function addAuditLog($actionType, $objId, $objName, $objValues = [], $objectType = null) { $objType = is_null($objectType) ? strtoupper($this->action) : $objectType; $objectTypes = ['HTPL' => 'host', 'STPL' => 'service', 'CONTACT' => 'contact', 'SG' => 'servicegroup', 'TP' => 'timeperiod', 'SERVICE' => 'service', 'CG' => 'contactgroup', 'CMD' => 'command', 'HOST' => 'host', 'HC' => 'hostcategories', 'HG' => 'hostgroup', 'SC' => 'servicecategories']; if (! isset($objectTypes[$objType])) { return null; } $objType = $objectTypes[$objType]; $contactObj = new Centreon_Object_Contact($this->dependencyInjector); $contact = $contactObj->getIdByParameter('contact_alias', CentreonUtils::getUserName()); $userId = $contact[0]; $dbstorage = $this->dependencyInjector['realtime_db']; $query = 'INSERT INTO log_action (action_log_date, object_type, object_id, object_name, action_type, log_contact_id) VALUES (?, ?, ?, ?, ?, ?)'; $time = time(); $dbstorage->query($query, [$time, $objType, $objId, $objName, $actionType, $userId]); $query = 'SELECT LAST_INSERT_ID() as action_log_id'; $stmt = $dbstorage->query($query); $row = $stmt->fetch(); if ($row === false) { throw new CentreonClapiException('Error while inserting log action'); } $stmt->closeCursor(); $actionId = $row['action_log_id']; $query = 'INSERT INTO log_action_modification (field_name, field_value, action_log_id) VALUES (?, ?, ?)'; foreach ($objValues as $name => $value) { try { if (is_array($value)) { $value = implode(',', $value); } if (is_null($value)) { $value = ''; } $dbstorage->query( $query, [$name, $value, $actionId] ); } catch (Exception $e) { throw $e; } } } /** * Check illegal char defined into nagios.cfg file * * @param string $name The string to sanitize * * @throws PDOException * @return string The string sanitized */ public function checkIllegalChar($name) { $dbResult = $this->db->query('SELECT illegal_object_name_chars FROM cfg_nagios'); while ($data = $dbResult->fetch()) { $name = str_replace(str_split($data['illegal_object_name_chars']), '', $name); } $dbResult->closeCursor(); return $name; } /** * @param null $dependencyInjector * @return mixed */ public static function getInstance($dependencyInjector = null) { $class = static::class; if (is_null($dependencyInjector)) { $dependencyInjector = loadDependencyInjector(); } if (! isset(self::$instances[$class])) { self::$instances[$class] = new $class($dependencyInjector); } return self::$instances[$class]; } /** * Checks if object exists * * @param string $name * @param null $updateId * * @throws Exception * @return bool */ protected function objectExists($name, $updateId = null) { $ids = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, [$this->object->getUniqueLabelField() => $name], 'AND' ); if (isset($updateId) && count($ids)) { return ! ($ids[0][$this->object->getPrimaryKey()] == $updateId); } return (bool) (count($ids)); } /** * @throws CentreonClapiException */ protected function checkParameters() { if (! isset($this->params[$this->object->getUniqueLabelField()])) { throw new CentreonClapiException(self::MISSINGNAMEPARAMETER); } if ($this->objectExists($this->params[$this->object->getUniqueLabelField()]) === true) { throw new CentreonClapiException( self::OBJECTALREADYEXISTS . ' (' . $this->params[$this->object->getUniqueLabelField()] . ')' ); } } /** * Set the activate field * * @param string $objectName * @param int $value * @throws CentreonClapiException */ protected function activate($objectName, $value) { if (! isset($objectName) || ! $objectName) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (isset($this->activateField)) { $ids = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$objectName]); if (count($ids)) { $this->object->update($ids[0], [$this->activateField => $value]); } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objectName); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param $filterName * * @return bool */ protected function canBeExported($filterName = null) { $exported = CentreonExported::getInstance(); if (is_null($this->action)) { return false; } if (is_null($filterName)) { return true; } $filterId = $this->getObjectId($filterName); $filterIds = is_array($filterId) ? $filterId : [$filterId]; foreach ($filterIds as $filterId) { $exported->arianePush($this->action, $filterId, $filterName); if ($exported->isExported($this->action, $filterId, $filterName)) { $exported->arianePop(); return false; } } return true; } /** * Escape a value for CSV output * * @param string $text The string to escape * @return string The string sanitized */ protected function csvEscape($text) { if (str_contains($text, '"') || str_contains($text, $this->delim) || str_contains($text, "\n")) { $text = '"' . str_replace('"', '""', $text) . '"'; } return $text; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonSettings.class.php
centreon/www/class/centreon-clapi/centreonSettings.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Timezone; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once _CENTREON_PATH_ . '/lib/Centreon/Object/Timezone/Timezone.php'; require_once _CENTREON_PATH_ . '/lib/Centreon/Object/Object.php'; /** * Class * * @class CentreonSettings * @package CentreonClapi */ class CentreonSettings extends CentreonObject { public const ISSTRING = 0; public const ISNUM = 1; public const KEYNOTALLOWED = 'This parameter cannot be modified'; public const VALUENOTALLOWED = 'This parameter value is not valid'; /** @var array */ protected $authorizedOptions = ['broker' => ['values' => ['ndo', 'broker']], 'centstorage' => ['values' => ['0', '1']], 'gmt' => ['format' => self::ISSTRING, 'getterFormatMethod' => 'getTimezonenameFromId', 'setterFormatMethod' => 'getTimezoneIdFromName'], 'mailer_path_bin' => ['format' => self::ISSTRING], 'snmptt_unknowntrap_log_file' => ['format' => self::ISSTRING], 'snmpttconvertmib_path_bin' => ['format' => self::ISSTRING], 'perl_library_path' => ['format' => self::ISSTRING], 'rrdtool_path_bin' => ['format' => self::ISSTRING], 'debug_path' => ['format' => self::ISSTRING], 'debug_auth' => ['values' => ['0', '1']], 'debug_nagios_import' => ['values' => ['0', '1']], 'debug_rrdtool' => ['values' => ['0', '1']], 'debug_ldap_import' => ['values' => ['0', '1']], 'enable_autologin' => ['values' => ['0', '1']], 'interval_length' => ['format' => self::ISNUM], 'enable_gmt' => ['values' => ['0', '1']]]; /** * CentreonSettings constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); } /** * @param null $params * @param array $filters * * @throws PDOException */ public function show($params = null, $filters = []): void { $sql = 'SELECT `key`, `value` FROM `options` ORDER BY `key`'; $stmt = $this->db->query($sql); $res = $stmt->fetchAll(); echo 'parameter' . $this->delim . "value\n"; foreach ($res as $row) { if (isset($this->authorizedOptions[$row['key']])) { if (isset($this->authorizedOptions[$row['key']]['getterFormatMethod'])) { $method = $this->authorizedOptions[$row['key']]['getterFormatMethod']; $row['value'] = $this->{$method}($row['value']); } echo $row['key'] . $this->delim . $row['value'] . "\n"; } } } /** * @param null $parameters * @return void */ public function add($parameters = null): void { $this->unsupportedMethod(__FUNCTION__); } /** * @param string|null $objectName * * @return void */ public function del($objectName = null): void { $this->unsupportedMethod(__FUNCTION__); } /** * Set parameters * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setparam($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } [$key, $value] = $params; if (! isset($this->authorizedOptions[$key])) { throw new CentreonClapiException(self::KEYNOTALLOWED); } if (isset($this->authorizedOptions[$key]['format'])) { if ($this->authorizedOptions[$key]['format'] == self::ISNUM && ! is_numeric($value)) { throw new CentreonClapiException(self::VALUENOTALLOWED); } if (is_array($this->authorizedOptions[$key]['format']) == self::ISSTRING && ! is_string($value)) { throw new CentreonClapiException(self::VALUENOTALLOWED); } } if (isset($this->authorizedOptions[$key]['values']) && ! in_array($value, $this->authorizedOptions[$key]['values'])) { throw new CentreonClapiException(self::VALUENOTALLOWED); } if (isset($this->authorizedOptions[$key]['setterFormatMethod'])) { $method = $this->authorizedOptions[$key]['setterFormatMethod']; $value = $this->{$method}($value); } $this->db->query('UPDATE `options` SET `value` = ? WHERE `key` = ?', [$value, $key]); } /** * Display unsupported method * * @param string $method * @return void */ protected function unsupportedMethod($method) { echo sprintf("The %s method is not supported on this object\n", $method); } /** * @param $value * @throws CentreonClapiException * @return mixed */ private function getTimezoneIdFromName($value) { $timezone = new Centreon_Object_Timezone($this->dependencyInjector); $timezoneId = $timezone->getIdByParameter('timezone_name', $value); if (! isset($timezoneId[0])) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND); } return $timezoneId[0]; } /** * @param $value * @throws CentreonClapiException * @return mixed */ private function getTimezonenameFromId($value) { $timezone = new Centreon_Object_Timezone($this->dependencyInjector); $timezoneName = $timezone->getParameters($value, ['timezone_name']); if (! isset($timezoneName['timezone_name'])) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND); } return $timezoneName['timezone_name']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonHost.class.php
centreon/www/class/centreon-clapi/centreonHost.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_DependencyHostParent; use Centreon_Object_Host; use Centreon_Object_Host_Category; use Centreon_Object_Host_Extended; use Centreon_Object_Host_Group; use Centreon_Object_Host_Macro_Custom; use Centreon_Object_Instance; use Centreon_Object_Relation_Contact_Group_Host; use Centreon_Object_Relation_Contact_Host; use Centreon_Object_Relation_Host_Category_Host; use Centreon_Object_Relation_Host_Group_Host; use Centreon_Object_Relation_Host_Parent_Host; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Host_Template_Host; use Centreon_Object_Relation_Instance_Host; use Centreon_Object_Service; use Centreon_Object_Service_Extended; use Centreon_Object_Timezone; use Core\Host\Domain\Model\NewHost; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonConfigurationChange.class.php'; require_once 'centreonUtils.class.php'; require_once 'centreonTimePeriod.class.php'; require_once 'centreonACL.class.php'; require_once 'centreonCommand.class.php'; require_once 'centreonExported.class.php'; require_once 'centreonTimezone.class.php'; require_once 'Centreon/Object/Instance/Instance.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Timeperiod/Timeperiod.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Extended.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Host/Category.php'; require_once 'Centreon/Object/Host/Template.php'; require_once 'Centreon/Object/Host/Macro/Custom.php'; require_once 'Centreon/Object/Service/Service.php'; require_once 'Centreon/Object/Service/Extended.php'; require_once 'Centreon/Object/Contact/Contact.php'; require_once 'Centreon/Object/Contact/Group.php'; require_once 'Centreon/Object/Relation/Host/Template/Host.php'; require_once 'Centreon/Object/Relation/Host/Parent/Host.php'; require_once 'Centreon/Object/Relation/Host/Group/Host.php'; require_once 'Centreon/Object/Relation/Host/Child/Host.php'; require_once 'Centreon/Object/Relation/Host/Category/Host.php'; require_once 'Centreon/Object/Relation/Instance/Host.php'; require_once 'Centreon/Object/Relation/Contact/Host.php'; require_once 'Centreon/Object/Relation/Contact/Group/Host.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Timezone/Timezone.php'; require_once 'Centreon/Object/Media/Media.php'; require_once 'Centreon/Object/Dependency/DependencyHostParent.php'; /** * Class * * @class CentreonHost * @package CentreonClapi */ class CentreonHost extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const ORDER_ADDRESS = 2; public const ORDER_TEMPLATE = 3; public const ORDER_POLLER = 4; public const ORDER_HOSTGROUP = 5; public const MISSING_INSTANCE = 'Instance name is mandatory'; public const UNKNOWN_NOTIFICATION_OPTIONS = 'Invalid notifications options'; public const INVALID_GEO_COORDS = 'Invalid geo coords'; public const UNKNOWN_TIMEZONE = 'Invalid timezone'; public const HOST_LOCATION = 'timezone'; public const NAME_IS_EMPTY = 'Host name is mandatory and cannot be left empty'; /** @var string[] */ public static $aDepends = ['CMD', 'TP', 'TRAP', 'INSTANCE', 'HTPL']; /** * @var array * Contains : list of authorized notifications_options for this object */ public static $aAuthorizedNotificationsOptions = ['d' => 'Down', 'u' => 'Unreachable', 'r' => 'Recovery', 'f' => 'Flapping', 's' => 'Downtime Scheduled', 'n' => 'None']; /** @var Centreon_Object_Timezone */ protected $timezoneObject; /** @var int */ protected $register = 1; /** @var array */ protected $templateIds; /** @var array */ protected $hostgroupIds; /** @var mixed */ protected $instanceId; /** * CentreonHost constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Host($dependencyInjector); $this->timezoneObject = new Centreon_Object_Timezone($dependencyInjector); $this->params = ['host_active_checks_enabled' => '2', 'host_passive_checks_enabled' => '2', 'host_checks_enabled' => '2', 'host_obsess_over_host' => '2', 'host_check_freshness' => '2', 'host_event_handler_enabled' => '2', 'host_flap_detection_enabled' => '2', 'host_process_perf_data' => '2', 'host_retain_status_information' => '2', 'host_retain_nonstatus_information' => '2', 'host_notifications_enabled' => '2', 'host_register' => '1', 'host_activate' => '1']; $this->insertParams = ['host_name', 'host_alias', 'host_address', 'template', 'instance', 'hostgroup']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey()], ['host_template_model_htm_id'] ); $this->action = 'HOST'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'host_activate'; } /** * Magic method * * @param string $name * @param array $arg * @throws CentreonClapiException * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { switch ($matches[2]) { case 'contact': $class = 'Centreon_Object_Contact'; $relclass = 'Centreon_Object_Relation_Contact_Host'; break; case 'contactgroup': $class = 'Centreon_Object_Contact_Group'; $relclass = 'Centreon_Object_Relation_Contact_Group_Host'; break; case 'hostgroup': $class = 'Centreon_Object_Host_Group'; $relclass = 'Centreon_Object_Relation_Host_Group_Host'; break; case 'template': $class = 'Centreon_Object_Host_Template'; $relclass = 'Centreon_Object_Relation_Host_Template_Host'; break; case 'parent': $class = 'Centreon_Object_Host'; $relclass = 'Centreon_Object_Relation_Host_Parent_Host'; break; case 'child': $class = 'Centreon_Object_Host'; $relclass = 'Centreon_Object_Relation_Host_Child_Host'; break; case 'hostcategory': $class = 'Centreon_Object_Host_Category'; $relclass = 'Centreon_Object_Relation_Host_Category_Host'; break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); break; } if (class_exists($relclass) && class_exists($class)) { // Test and get the first arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $hostIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($hostIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $hostId = $hostIds[0]; $relobj = new $relclass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getFirstKey(), $relobj->getSecondKey(), $hostId); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { if ($matches[2] == 'contact') { $tab = $obj->getIdByParameter('contact_alias', [$rel]); } else { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); } if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } if ($matches[1] == 'set') { $relobj->delete(null, $hostId); } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $hostId ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($relationId, $hostId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($relationId, $hostId); } } } if ($matches[2] == 'hostgroup') { $aclObj = new CentreonACL($this->dependencyInjector); $aclObj->reload(true); } $this->addAuditLog( 'c', $hostId, $args[0], [$matches[2] => str_replace('|', ',', $args[1])] ); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * We keep this method for retro compatibility with other objects * * @param string $name * @return int */ public function getHostID($name) { return $this->getObjectId($name); } /** * We keep this method for retro compatibility with other objects * * @param int $hostId * @return string */ public function getHostName($hostId) { return $this->getObjectName($hostId); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = ['host_register' => $this->register]; $labelField = $this->object->getUniqueLabelField(); if (isset($parameters)) { $filters[$labelField] = '%' . $parameters . '%'; } $params = ['host_id', 'host_name', 'host_alias', 'host_address', 'host_activate']; $paramString = str_replace('host_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters, 'AND' ); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function showbyaddress($parameters = null, $filters = []): void { $filters = ['host_register' => $this->register]; if (isset($parameters)) { $filters['host_address'] = '%' . $parameters . '%'; } $params = ['host_id', 'host_name', 'host_alias', 'host_address', 'host_activate']; $paramString = str_replace('host_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters, 'AND' ); foreach ($elements as $tab) { echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = NewHost::formatName($this->checkIllegalChar($params[self::ORDER_UNIQUENAME])); if ($addParams[$this->object->getUniqueLabelField()] === '') { throw new CentreonClapiException(self::NAME_IS_EMPTY); } $addParams['host_alias'] = $params[self::ORDER_ALIAS]; $addParams['host_address'] = $params[self::ORDER_ADDRESS]; $templates = explode('|', $params[self::ORDER_TEMPLATE]); $this->templateIds = []; foreach ($templates as $template) { if ($template) { $tmp = $this->object->getIdByParameter($this->object->getUniqueLabelField(), $template); if (count($tmp)) { $this->templateIds[] = $tmp[0]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $template); } } } $instanceName = $params[self::ORDER_POLLER]; $instanceObject = new Centreon_Object_Instance($this->dependencyInjector); $this->instanceId = null; if ($this->action == 'HOST') { if ($instanceName) { $tmp = $instanceObject->getIdByParameter($instanceObject->getUniqueLabelField(), $instanceName); if (! count($tmp)) { $defaultInstanceName = $instanceObject->getDefaultInstance(); $tmp = $instanceObject->getIdByParameter( $instanceObject->getUniqueLabelField(), $defaultInstanceName ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' :' . $instanceName); } } $this->instanceId = $tmp[0]; } else { throw new CentreonClapiException(self::MISSING_INSTANCE); } } $hostgroups = explode('|', $params[self::ORDER_HOSTGROUP]); $this->hostgroupIds = []; $hostgroupObject = new Centreon_Object_Host_Group($this->dependencyInjector); foreach ($hostgroups as $hostgroup) { if ($hostgroup) { $tmp = $hostgroupObject->getIdByParameter($hostgroupObject->getUniqueLabelField(), $hostgroup); if (count($tmp)) { $this->hostgroupIds[] = $tmp[0]; } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hostgroup); } } } $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $hostId * * @return void */ public function insertRelations($hostId): void { $i = 1; $templateRelationObject = new Centreon_Object_Relation_Host_Template_Host($this->dependencyInjector); foreach ($this->templateIds as $templateId) { $templateRelationObject->insert($templateId, $hostId); $i++; } $hostgroupRelationObject = new Centreon_Object_Relation_Host_Group_Host($this->dependencyInjector); foreach ($this->hostgroupIds as $hostgroupId) { $hostgroupRelationObject->insert($hostgroupId, $hostId); } if (! is_null($this->instanceId)) { $instanceRelationObject = new Centreon_Object_Relation_Instance_Host($this->dependencyInjector); $instanceRelationObject->insert($this->instanceId, $hostId); } $extended = new Centreon_Object_Host_Extended($this->dependencyInjector); $extended->insert([$extended->getUniqueLabelField() => $hostId]); } /** * @param $parameters * * @throws Exception * @return void */ public function add($parameters): void { parent::add($parameters); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostId = $this->getObjectId($this->params[$this->object->getUniqueLabelField()]); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_HOST, $hostId); } /** * Del Action * Must delete services as well * * @param string $objectName * * @throws CentreonClapiException * @throws PDOException * @return void */ public function del($objectName): void { $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostId = $this->getObjectId($objectName); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds([$hostId]); $parentDependency = new Centreon_Object_DependencyHostParent($this->dependencyInjector); $parentDependency->removeRelationLastHostDependency($hostId); parent::del($objectName); $this->db->query( "DELETE FROM service WHERE service_register = '1' " . 'AND service_id NOT IN (SELECT service_service_id FROM host_service_relation)' ); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOST, $hostId, $previousPollerIds ); } /** * @param array $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function setParam($parameters = []): void { $params = method_exists($this, 'initUpdateParameters') ? $this->initUpdateParameters($parameters) : $parameters; if (! empty($params)) { $hostId = $params['objectId']; $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds([$hostId]); parent::setparam($parameters); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_HOST, $hostId, $previousPollerIds ); } } /** * @param $objectName * * @throws CentreonClapiException * @return void */ public function enable($objectName): void { parent::enable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_HOST, $hostId); } /** * @param $objectName * * @throws CentreonClapiException * @return void */ public function disable($objectName): void { parent::disable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_HOST, $hostId, [], false); } /** * List instance (poller) for host * * @param string $parameters * @throws CentreonClapiException */ public function showinstance($parameters): void { $params = explode($this->delim, $parameters); if ($parameters == '') { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (($hostId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $relObj = new Centreon_Object_Relation_Instance_Host($this->dependencyInjector); $fields = ['id', 'name']; $elements = $relObj->getMergedParameters( $fields, [], -1, 0, 'host_name', 'ASC', ['host_id' => $hostId], 'AND' ); echo 'id' . $this->delim . 'name' . "\n"; foreach ($elements as $elem) { echo $elem['id'] . $this->delim . $elem['name'] . "\n"; } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } } /** * Tie host to instance (poller) * * @param string $parameters * @throws CentreonClapiException */ public function setinstance($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hostId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); $instanceObj = new Centreon_Object_Instance($this->dependencyInjector); $tmp = $instanceObj->getIdByParameter($instanceObj->getUniqueLabelField(), $params[1]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[1]); } $instanceId = $tmp[0]; $relationObj = new Centreon_Object_Relation_Instance_Host($this->dependencyInjector); $relationObj->delete(null, $hostId); $relationObj->insert($instanceId, $hostId); } /** * Get a parameter * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['2d_coords', '3d_coords', 'action_url', 'activate', 'active_checks_enabled', 'acknowledgement_timeout', 'address', 'alias', 'check_command', 'check_command_arguments', 'check_interval', 'check_freshness', 'check_period', 'comment', 'contact_additive_inheritance', 'cg_additive_inheritance', 'event_handler', 'event_handler_arguments', 'event_handler_enabled', 'first_notification_delay', 'flap_detection_enabled', 'flap_detection_options', 'freshness_threshold', 'geo_coords', 'host_high_flap_threshold', 'host_low_flap_threshold', 'host_notification_options', 'high_flap_threshold', 'icon_image', 'icon_image_alt', 'low_flap_threshold', 'max_check_attempts', 'name', 'notes', 'notes_url', 'notifications_enabled', 'notification_interval', 'notification_options', 'notification_period', 'recovery_notification_delay', 'obsess_over_host', 'passive_checks_enabled', 'process_perf_data', 'retain_nonstatus_information', 'retain_status_information', 'retry_check_interval', 'snmp_community', 'snmp_version', 'stalking_options', 'statusmap_image', 'timezone']; $unknownParam = []; if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ''; foreach ($listParam as $paramSearch) { $paramString = ! isset($paramString) || ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { $extended = false; switch ($paramSearch) { case 'check_command': $field = 'command_command_id'; break; case 'check_command_arguments': $field = 'command_command_id_arg1'; break; case 'event_handler': $field = 'command_command_id2'; break; case 'event_handler_arguments': $field = 'command_command_id_arg2'; break; case 'check_period': $field = 'timeperiod_tp_id'; break; case 'notification_period': $field = 'timeperiod_tp_id2'; break; case 'contact_additive_inheritance': case 'cg_additive_inheritance': case 'flap_detection_options': case 'geo_coords': break; case 'notes': case 'notes_url': case 'action_url': case 'icon_image': case 'icon_image_alt': case 'vrml_image': case 'statusmap_image': case '2d_coords': case '3d_coords': $extended = true; break; case self::HOST_LOCATION: $field = 'host_location'; break; default: if (! preg_match('/^host_/', $paramSearch)) { $field = 'host_' . $paramSearch; } break; } if (! $extended) { $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; } else { $field = 'ehi_' . $field; $extended = new Centreon_Object_Host_Extended($this->dependencyInjector); $ret = $extended->getParameters($objectId, $field); $ret = $ret[$field]; } switch ($paramSearch) { case 'check_command': case 'event_handler': $commandObject = new CentreonCommand($this->dependencyInjector); $field = $commandObject->object->getUniqueLabelField(); $ret = $commandObject->object->getParameters($ret, $field); $ret = $ret[$field]; break; case 'check_period': case 'notification_period': $tpObj = new CentreonTimePeriod($this->dependencyInjector); $field = $tpObj->object->getUniqueLabelField(); $ret = $tpObj->object->getParameters($ret, $field); $ret = $ret[$field]; break; case self::HOST_LOCATION: $field = $this->timezoneObject->getUniqueLabelField(); $ret = $this->timezoneObject->getParameters($ret, $field); $ret = $ret[$field]; break; } if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * @param null $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $extended = false; $commandObject = new CentreonCommand($this->dependencyInjector); switch ($params[1]) { case 'check_command': $params[1] = 'command_command_id'; $params[2] = $commandObject->getId($params[2]); break; case 'check_command_arguments': $params[1] = 'command_command_id_arg1'; break; case 'event_handler': $params[1] = 'command_command_id2'; $params[2] = $commandObject->getId($params[2]); break; case 'event_handler_arguments': $params[1] = 'command_command_id_arg2'; break; case 'check_period': $params[1] = 'timeperiod_tp_id'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[2] = $tpObj->getTimeperiodId($params[2]); break; case 'notification_period': $params[1] = 'timeperiod_tp_id2'; $tpObj = new CentreonTimePeriod($this->dependencyInjector); $params[2] = $tpObj->getTimeperiodId($params[2]); break; case 'geo_coords': if (! CentreonUtils::validateGeoCoords($params[2])) { throw new CentreonClapiException(self::INVALID_GEO_COORDS); } break; case 'contact_additive_inheritance': case 'cg_additive_inheritance': case 'flap_detection_options': break; case 'notes': case 'notes_url': case 'action_url': case 'icon_image': case 'icon_image_alt': case 'statusmap_image': case '2d_coords': case '3d_coords': $extended = true; break; case 'host_notification_options': $aNotifs = explode(',', $params[2]); foreach ($aNotifs as $notif) {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACLMenu.class.php
centreon/www/class/centreon-clapi/centreonACLMenu.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Acl_Group; use Centreon_Object_Acl_Menu; use Centreon_Object_Relation_Acl_Group_Menu; use CentreonTopology; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Group.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Menu.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Menu.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonTopology.class.php'; /** * Class * * @class CentreonACLMenu * @package CentreonClapi * @description Class for managing ACL Menu rules */ class CentreonACLMenu extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const LEVEL_1 = 0; public const LEVEL_2 = 1; public const LEVEL_3 = 2; public const LEVEL_4 = 3; /** @var Centreon_Object_Relation_Acl_Group_Menu */ protected $relObject; /** @var Centreon_Object_Acl_Group */ protected $aclGroupObj; /** @var CentreonTopology */ protected $topologyObj; /** * CentreonACLMenu constructor. * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Acl_Menu($dependencyInjector); $this->aclGroupObj = new Centreon_Object_Acl_Group($dependencyInjector); $this->relObject = new Centreon_Object_Relation_Acl_Group_Menu($dependencyInjector); $this->params = ['acl_topo_activate' => '1']; $this->nbOfCompulsoryParams = 2; $this->activateField = 'acl_topo_activate'; $this->action = 'ACLMENU'; $this->topologyObj = new CentreonTopology($dependencyInjector['configuration_db']); } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['acl_topo_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $params[1] = $params[1] == 'comment' ? 'acl_comments' : 'acl_topo_' . $params[1]; $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['acl_topo_id', 'acl_topo_name', 'acl_topo_alias', 'acl_comments', 'acl_topo_activate']; $paramString = str_replace('acl_topo_', '', implode($this->delim, $params)); $paramString = str_replace('acl_', '', $paramString); $paramString = str_replace('comments', 'comment', $paramString); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * Get Acl Group * * @param string $aclMenuName * * @throws CentreonClapiException * @return void */ public function getaclgroup($aclMenuName): void { if (! isset($aclMenuName) || ! $aclMenuName) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclMenuId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$aclMenuName]); if (! count($aclMenuId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $aclMenuName); } $groupIds = $this->relObject->getacl_group_idFromacl_topology_id($aclMenuId[0]); echo 'id;name' . "\n"; if (count($groupIds)) { foreach ($groupIds as $groupId) { $result = $this->aclGroupObj->getParameters($groupId, $this->aclGroupObj->getUniqueLabelField()); echo $groupId . $this->delim . $result[$this->aclGroupObj->getUniqueLabelField()] . "\n"; } } } /** * old Grant menu * * @param string $parameters * @return void */ public function grant($parameters): void { $this->grantRw($parameters); } /** * Grant menu * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function grantRw($parameters): void { [$aclMenuId, $menus, $topologies, $processChildren] = $this->splitParams($parameters); foreach ($menus as $level => $menuId) { $this->db->query( 'DELETE FROM acl_topology_relations WHERE acl_topo_id = ? AND topology_topology_id = ?', [$aclMenuId, $menuId] ); $this->db->query( 'INSERT INTO acl_topology_relations (acl_topo_id, topology_topology_id) VALUES (?, ?)', [$aclMenuId, $menuId] ); if ($processChildren && ! isset($menus[$level + 1]) && $level != self::LEVEL_4) { $this->processChildrenOf('grant', $aclMenuId, $topologies[$level]); } } } /** * Grant menu * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function grantRo($parameters): void { [$aclMenuId, $menus, $topologies, $processChildren] = $this->splitParams($parameters); foreach ($menus as $level => $menuId) { $this->db->query( 'DELETE FROM acl_topology_relations WHERE acl_topo_id = ? AND topology_topology_id = ?', [$aclMenuId, $menuId] ); $this->db->query( 'INSERT INTO acl_topology_relations (acl_topo_id, topology_topology_id, access_right) VALUES (?, ?, 2)', [$aclMenuId, $menuId] ); if ($processChildren && ! isset($menus[$level + 1]) && $level != self::LEVEL_4) { $this->processChildrenOf('grantro', $aclMenuId, $topologies[$level]); } } } /** * Revoke menu * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function revoke($parameters): void { [$aclMenuId, $menus, $topologies, $processChildren] = $this->splitParams($parameters); foreach ($menus as $level => $menuId) { if ($processChildren && ! isset($menus[$level + 1])) { $this->db->query( 'DELETE FROM acl_topology_relations WHERE acl_topo_id = ? AND topology_topology_id = ?', [$aclMenuId, $menuId] ); $this->processChildrenOf('revoke', $aclMenuId, $topologies[$level]); } } } /** * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $aclMenuList = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); $exportLine = ''; foreach ($aclMenuList as $aclMenu) { $exportLine .= $this->action . $this->delim . 'ADD' . $this->delim . $aclMenu['acl_topo_name'] . $this->delim . $aclMenu['acl_topo_alias'] . $this->delim . "\n"; $exportLine .= $this->action . $this->delim . 'SETPARAM' . $this->delim . $aclMenu['acl_topo_name'] . $this->delim; if (! empty($aclMenu['acl_comments'])) { $exportLine .= 'comment' . $this->delim . $aclMenu['acl_comments'] . $this->delim; } $exportLine .= 'activate' . $this->delim . $aclMenu['acl_topo_activate'] . $this->delim . "\n"; $exportLine .= $this->grantMenu($aclMenu['acl_topo_id'], $aclMenu['acl_topo_name']); echo $exportLine; $exportLine = ''; } } /** * Split params * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException * @return array */ protected function splitParams($parameters) { $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclMenuId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]); if (! count($aclMenuId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } $processChildren = ($params[1] == '0') ? false : true; $levels = []; $menus = []; $topologies = []; $levels[self::LEVEL_1] = $params[2]; if (isset($params[3])) { $levels[self::LEVEL_2] = $params[3]; } if (isset($params[4])) { $levels[self::LEVEL_3] = $params[4]; } if (isset($params[5])) { $levels[self::LEVEL_4] = $params[5]; } foreach ($levels as $level => $menu) { if ($menu) { switch ($level) { case self::LEVEL_1: $length = 1; break; case self::LEVEL_2: $length = 3; break; case self::LEVEL_3: $length = 5; break; case self::LEVEL_4: $length = 7; break; default: break; } if (is_numeric($menu)) { $sql = 'SELECT topology_id, topology_page FROM topology WHERE topology_page = ? AND LENGTH(topology_page) = ?'; $res = $this->db->query($sql, [$menu, $length]); } elseif ($level == self::LEVEL_1) { $sql = 'SELECT topology_id, topology_page FROM topology WHERE topology_name = ? AND LENGTH(topology_page) = ? AND topology_parent IS NULL'; $res = $this->db->query($sql, [$menu, $length]); } else { $sql = 'SELECT topology_id, topology_page FROM topology WHERE topology_name = ? AND LENGTH(topology_page) = ? AND topology_parent = ?'; $res = $this->db->query($sql, [$menu, $length, $topologies[($level - 1)]]); } $row = $res->fetch(); if (! isset($row['topology_id'])) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $menu); } unset($res); $menus[$level] = $row['topology_id']; $topologies[$level] = $row['topology_page']; } else { break; } } return [$aclMenuId[0], $menus, $topologies, $processChildren]; } /** * Process children of topology * Recursive method * * @param string $action * @param null $aclMenuId * @param null $parentTopologyId * * @throws PDOException * @return void */ protected function processChildrenOf( $action = 'grant', $aclMenuId = null, $parentTopologyId = null, ) { $sql = 'SELECT topology_id, topology_page FROM topology WHERE topology_parent = ?'; $res = $this->db->query($sql, [$parentTopologyId]); $rows = $res->fetchAll(); foreach ($rows as $row) { $this->db->query( 'DELETE FROM acl_topology_relations WHERE acl_topo_id = ? AND topology_topology_id = ?', [$aclMenuId, $row['topology_id']] ); if ($action == 'grant') { $this->db->query( 'INSERT INTO acl_topology_relations (acl_topo_id, topology_topology_id) VALUES (?, ?)', [$aclMenuId, $row['topology_id']] ); } if ($action == 'grantro') { $query = 'INSERT INTO acl_topology_relations (acl_topo_id, topology_topology_id, access_right) ' . 'VALUES (?, ?, 2)'; $this->db->query($query, [$aclMenuId, $row['topology_id']]); } $this->processChildrenOf($action, $aclMenuId, $row['topology_page']); } } /** * @param int $aclTopoId * @param string $aclTopoName * * @throws PDOException * @return string */ private function grantMenu($aclTopoId, $aclTopoName) { $grantedMenu = ''; $grantedMenuTpl = $this->action . $this->delim . '%s' . $this->delim . $aclTopoName . $this->delim . '%s' . $this->delim . '%s' . $this->delim . "\n"; $grantedPossibilities = ['1' => 'GRANTRW', '2' => 'GRANTRO']; $queryAclMenuRelations = 'SELECT t.topology_page, t.topology_id, t.topology_name, atr.access_right ' . 'FROM acl_topology_relations atr ' . 'LEFT JOIN topology t ON t.topology_id = atr.topology_topology_id ' . "WHERE atr.access_right <> '0' " . 'AND atr.acl_topo_id = :topoId'; $stmt = $this->db->prepare($queryAclMenuRelations); $stmt->bindParam(':topoId', $aclTopoId); $stmt->execute(); $grantedTopologyList = $stmt->fetchAll(); if (! empty($grantedTopologyList) && isset($grantedTopologyList)) { foreach ($grantedTopologyList as $grantedTopology) { $grantedTopologyBreadCrumb = $this->topologyObj->getBreadCrumbFromTopology( $grantedTopology['topology_page'], $grantedTopology['topology_name'], ';' ); $grantedMenu .= sprintf( $grantedMenuTpl, $grantedPossibilities[$grantedTopology['access_right']], '0', $grantedTopologyBreadCrumb ); } } return $grantedMenu; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreon.Config.Poller.class.php
centreon/www/class/centreon-clapi/centreon.Config.Poller.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use App\Kernel; use Centreon\Domain\Entity\Task; use CentreonDB; use CentreonRemote\ServiceProvider; use Core\Domain\Engine\Model\EngineCommandGenerator; use Exception; use Generate; use LogicException; use PDO; use PDOException; use Pimple\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; require_once 'centreonUtils.class.php'; require_once 'centreonClapiException.class.php'; require_once _CENTREON_PATH_ . 'www/class/config-generate/generate.class.php'; /** * Class * * @class CentreonConfigPoller * @package CentreonClapi */ class CentreonConfigPoller { public const MISSING_POLLER_ID = 'Missing poller ID'; public const UNKNOWN_POLLER_ID = 'Unknown poller ID'; public const CENTREON_SYSTEM_USER = 'centreon'; /** @var CentreonDB */ private $DB; /** @var CentreonDB */ private $DBC; /** @var Container */ private $dependencyInjector; /** @var int[] */ private $resultTest = ['warning' => 0, 'errors' => 0]; /** @var string */ private $brokerCachePath = _CENTREON_CACHEDIR_ . '/config/broker/'; /** @var string */ private $engineCachePath = _CENTREON_CACHEDIR_ . '/config/engine/'; /** @var string */ private $vmWareCachePath = _CENTREON_CACHEDIR_ . '/config/vmware/'; /** @var string */ private $centreon_path; /** @var EngineCommandGenerator|null */ private ?EngineCommandGenerator $commandGenerator = null; /** @var ContainerInterface */ private ContainerInterface $container; /** * CentreonConfigPoller constructor * * @param $centreon_path * @param Container $dependencyInjector * * @throws LogicException */ public function __construct($centreon_path, Container $dependencyInjector) { $this->dependencyInjector = $dependencyInjector; $this->DB = $this->dependencyInjector['configuration_db']; $this->DBC = $this->dependencyInjector['realtime_db']; $this->centreon_path = $centreon_path; $kernel = new Kernel('prod', false); $kernel->boot(); $this->container = $kernel->getContainer(); } /** * @param string $format * * @throws PDOException * @return int */ public function getPollerList($format) { $DBRESULT = $this->DB->query("SELECT id,name FROM nagios_server WHERE ns_activate = '1' ORDER BY id"); if ($format == 'xml') { echo ''; } echo "poller_id;name\n"; while ($data = $DBRESULT->fetchRow()) { echo $data['id'] . ';' . $data['name'] . "\n"; } $DBRESULT->closeCursor(); return 0; } /** * @param $variables * * @throws CentreonClapiException * @throws PDOException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return int */ public function pollerReload($variables) { if (! isset($variables)) { echo 'Cannot get poller'; return 1; } $poller_id = $this->ensurePollerId($variables); $statement = $this->DB->prepare( 'SELECT * FROM `nagios_server` WHERE `id` = :poller_id LIMIT 1' ); $statement->bindValue(':poller_id', (int) $poller_id, PDO::PARAM_INT); $statement->execute(); $host = $statement->fetch(PDO::FETCH_ASSOC); $statement->closeCursor(); $this->commandGenerator = $this->container->get(EngineCommandGenerator::class); $reloadCommand = $this->commandGenerator->getEngineCommand('RELOAD'); $return_code = $this->writeToCentcorePipe($reloadCommand, $host['id']); if ($return_code === 1) { echo "Error while writing the command {$reloadCommand} in centcore pipe file for host id {$host['id']}" . PHP_EOL; return $return_code; } $return_code = $this->writeToCentcorePipe('RELOADBROKER', $host['id']); if ($return_code === 1) { echo "Error while writing the command RELOADBROKER in centcore pipe file for host id {$host['id']}" . PHP_EOL; return $return_code; } $msg_restart = _("OK: A reload signal has been sent to '" . $host['name'] . "'"); echo $msg_restart . "\n"; $statement = $this->DB->prepare( "UPDATE `nagios_server` SET `last_restart` = :last_restart, `updated` = '0' WHERE `id` = :poller_id LIMIT 1" ); $statement->bindValue(':last_restart', time(), PDO::PARAM_INT); $statement->bindValue(':poller_id', (int) $poller_id, PDO::PARAM_INT); $statement->execute(); return $return_code; } /** * Execute post generation command * * @param int $pollerId * * @throws CentreonClapiException * @throws PDOException * @return int */ public function execCmd($pollerId) { $instanceClassFile = $this->centreon_path . 'www/class/centreonInstance.class.php'; if (! is_file($instanceClassFile)) { throw new CentreonClapiException('This action is not available in the version of Centreon you are using'); } require_once $instanceClassFile; $pollerId = $this->ensurePollerId($pollerId); $instanceObj = new \CentreonInstance($this->DB); $cmds = $instanceObj->getCommandData($pollerId); $result = 0; foreach ($cmds as $cmd) { echo "Executing command {$cmd['command_name']}... "; exec($cmd['command_line'], $output, $cmdResult); if ($cmdResult) { $resultStr = "Error: {$output}"; $result += $cmdResult; } else { $resultStr = 'OK'; } echo "{$resultStr}\n"; } // if result > 0, return 1, return 0 otherwise return $result ? 1 : 0; } /** * @param $variables * * @throws CentreonClapiException * @throws PDOException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return int */ public function pollerRestart($variables) { if (! isset($variables)) { echo 'Cannot get poller'; return 1; } $poller_id = $this->ensurePollerId($variables); $statement = $this->DB->prepare( 'SELECT * FROM `nagios_server` WHERE `id` = :poller_id LIMIT 1' ); $statement->bindValue(':poller_id', (int) $poller_id, PDO::PARAM_INT); $statement->execute(); $host = $statement->fetch(PDO::FETCH_ASSOC); $statement->closeCursor(); $this->commandGenerator = $this->container->get(EngineCommandGenerator::class); $restartCommand = $this->commandGenerator->getEngineCommand('RESTART'); $return_code = $this->writeToCentcorePipe($restartCommand, $host['id']); if ($return_code === 1) { echo "Error while writing the command {$restartCommand} in centcore pipe file for host id {$host['id']}" . PHP_EOL; return $return_code; } $return_code = $this->writeToCentcorePipe('RELOADBROKER', $host['id']); if ($return_code === 1) { echo "Error while writing the command RELOADBROKER in centcore pipe file for host id {$host['id']}" . PHP_EOL; return $return_code; } $msg_restart = _("OK: A restart signal has been sent to '" . $host['name'] . "'"); echo $msg_restart . "\n"; $statement = $this->DB->prepare( "UPDATE `nagios_server` SET `last_restart` = :last_restart, `updated` = '0' WHERE `id` = :poller_id LIMIT 1" ); $statement->bindValue(':last_restart', time(), PDO::PARAM_INT); $statement->bindValue(':poller_id', (int) $poller_id, PDO::PARAM_INT); $statement->execute(); return $return_code; } /** * @param $format * @param $variables * * @throws CentreonClapiException * @throws PDOException * @return int|void */ public function pollerTest($format, $variables) { if (! isset($variables)) { echo 'Cannot get poller'; exit(1); } $idPoller = $this->ensurePollerId($variables); /** * Get Nagios Bin */ $DBRESULT_Servers = $this->DB->query( "SELECT `nagios_bin` FROM `nagios_server` WHERE `localhost` = '1' ORDER BY `ns_activate` DESC LIMIT 1" ); $nagios_bin = $DBRESULT_Servers->fetchRow(); $DBRESULT_Servers->closeCursor(); // Launch test command if (isset($nagios_bin['nagios_bin'])) { exec( escapeshellcmd( $nagios_bin['nagios_bin'] . ' -v ' . $this->engineCachePath . '/' . $idPoller . '/centengine.DEBUG' ), $lines, $return_code ); } else { throw new CentreonClapiException("Can't find engine binary"); } $msg_debug = ''; foreach ($lines as $line) { if ( strncmp($line, 'Processing object config file', strlen('Processing object config file')) && strncmp($line, 'Website: http://www.nagios.org', strlen('Website: http://www.nagios.org')) ) { $msg_debug .= $line . "\n"; /** * Detect Errors */ if (preg_match('/Total Warnings: ([0-9])*/', $line, $matches)) { if (isset($matches[1])) { $this->resultTest['warning'] = $matches[1]; } } if (preg_match('/Total Errors: ([0-9])*/', $line, $matches)) { if (isset($matches[1])) { $this->resultTest['errors'] = $matches[1]; } } if (preg_match('/^Error:/', $line, $matches)) { $this->resultTest['errors']++; } if (preg_match('/^Errors:/', $line, $matches)) { $this->resultTest['errors']++; } } } if ($this->resultTest['errors'] != 0) { echo "Error: Centreon Poller {$variables} cannot restart. configuration broker. Please see debug bellow :\n"; echo '-----------------------------------------------------------' . "----------------------------------------\n"; echo $msg_debug . "\n"; echo '---------------------------------------------------' . "------------------------------------------------\n"; } elseif ($this->resultTest['warning'] != 0) { echo "Warning: Centreon Poller {$variables} can restart but " . "configuration is not optimal. Please see debug bellow :\n"; echo '-----------------------------------------------' . "----------------------------------------------------\n"; echo $msg_debug . "\n"; echo '------------------------------------------------' . "---------------------------------------------------\n"; } elseif ($return_code) { echo implode("\n", $lines); } else { echo "OK: Centreon Poller {$variables} can restart without problem...\n"; } return $return_code; } /** * Generate configuration files for a specific poller * * @param $variables * @param string $login * @param string $password * * @throws CentreonClapiException * @throws PDOException * @return int */ public function pollerGenerate($variables, $login, $password) { $config_generate = new Generate($this->dependencyInjector); $poller_id = $this->ensurePollerId($variables); $config_generate->configPollerFromId($poller_id, $login); // Change files owner $apacheUser = $this->getApacheUser(); $setFilesOwner = 1; if (posix_getuid() === 0 && $apacheUser != '') { // Change engine Path mod chown($this->engineCachePath . "/{$poller_id}", $apacheUser); chgrp($this->engineCachePath . "/{$poller_id}", $apacheUser); foreach (glob($this->engineCachePath . "/{$poller_id}/*.cfg") as $file) { chown($file, $apacheUser); chgrp($file, $apacheUser); } foreach (glob($this->engineCachePath . "/{$poller_id}/*.DEBUG") as $file) { chown($file, $apacheUser); chgrp($file, $apacheUser); } // Change broker Path mod chown($this->brokerCachePath . "/{$poller_id}", $apacheUser); chgrp($this->brokerCachePath . "/{$poller_id}", $apacheUser); foreach (glob($this->brokerCachePath . "/{$poller_id}/*.{xml,json,cfg}", GLOB_BRACE) as $file) { chown($file, $apacheUser); chgrp($file, $apacheUser); } // Change VMWare Path mod chown($this->vmWareCachePath . "/{$poller_id}", $apacheUser); chgrp($this->vmWareCachePath . "/{$poller_id}", self::CENTREON_SYSTEM_USER); /** * Change VMWare files owner to '660 apache centreon' * RW for centreon group are necessary for Gorgone Daemon. */ foreach (glob($this->vmWareCachePath . "/{$poller_id}/*.{json}", GLOB_BRACE) as $file) { chmod($file, 0660); chown($file, $apacheUser); chgrp($file, self::CENTREON_SYSTEM_USER); } } else { $setFilesOwner = 0; } if ($setFilesOwner == 0) { echo "Cannot set configuration file owner after the generation. \n"; echo 'Please check that files in the followings directory are writable by apache user : ' . $this->engineCachePath . "/{$poller_id}/\n"; echo 'Please check that files in the followings directory are writable by apache user : ' . $this->brokerCachePath . "/{$poller_id}/\n"; } echo "Configuration files generated for poller '" . $variables . "'\n"; return 0; } /** * Move configuration files to servers * * @param mixed|null $variables * * @throws CentreonClapiException * @throws PDOException * @return int|void */ public function cfgMove($variables = null) { global $pearDB, $pearDBO; $pearDB = $this->DB; $pearDBO = $this->DBC; require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/DB-Func.php'; if (! isset($variables)) { echo 'Cannot get poller'; exit(1); } $return = 0; $pollerId = $this->ensurePollerId($variables); $statement = $pearDB->prepare('SELECT * FROM `nagios_server` WHERE `id` = :pollerId'); $statement->bindValue(':pollerId', $pollerId, PDO::PARAM_INT); $statement->execute(); $host = $statement->fetchRow(); $statement->closeCursor(); // Move files $msg_copy = ''; if (isset($host['localhost']) && $host['localhost'] == 1) { // Get Apache user name $apacheUser = $this->getApacheUser(); $statement = $pearDB->prepare('SELECT `cfg_dir` FROM `cfg_nagios` WHERE `nagios_server_id` = :pollerId'); $statement->bindValue(':pollerId', $pollerId, PDO::PARAM_INT); $statement->execute(); $Nagioscfg = $statement->fetchRow(); $statement->closeCursor(); foreach (glob($this->engineCachePath . '/' . $pollerId . '/*.{json,cfg}', GLOB_BRACE) as $filename) { $bool = @copy($filename, $Nagioscfg['cfg_dir'] . '/' . basename($filename)); $result = explode('/', $filename); $filename = array_pop($result); if (! $bool) { $msg_copy .= $this->displayCopyingFile($filename, ' - ' . _('movement') . ' KO'); $return = 1; } } // Change files owner if ($apacheUser != '') { foreach (glob($Nagioscfg['cfg_dir'] . '/*.{json,cfg}', GLOB_BRACE) as $file) { if ($file === $Nagioscfg['cfg_dir'] . '/engine-context.json') { continue; } // handle path traversal vulnerability if (str_contains($file, '..')) { throw new Exception('Path traversal found'); } if (posix_getuid() === 0) { @chown($file, $apacheUser); @chgrp($file, $apacheUser); } } foreach (glob($Nagioscfg['cfg_dir'] . '/*.DEBUG') as $file) { // handle path traversal vulnerability if (str_contains($file, '..')) { throw new Exception('Path traversal found'); } if (posix_getuid() === 0) { @chown($file, $apacheUser); @chgrp($file, $apacheUser); } } } else { echo 'Please check that files in the followings directory are writable by apache user : ' . $Nagioscfg['cfg_dir'] . "\n"; } // Centreon Broker configuration $listBrokerFile = glob($this->brokerCachePath . '/' . $host['id'] . '/*.{xml,json,cfg}', GLOB_BRACE); if (count($listBrokerFile) > 0) { $centreonBrokerDirCfg = getCentreonBrokerDirCfg($host['id']); if (! is_null($centreonBrokerDirCfg)) { if (! is_dir($centreonBrokerDirCfg)) { if (! mkdir($centreonBrokerDirCfg, 0755)) { throw new Exception( sprintf( _("Centreon Broker's configuration directory '%s' does not exist and could not be " . "created for monitoring engine '%s'. Please check it's path or create it"), $centreonBrokerDirCfg, $host['name'] ) ); } } foreach ($listBrokerFile as $fileCfg) { $succeded = @copy($fileCfg, rtrim($centreonBrokerDirCfg, '/') . '/' . basename($fileCfg)); if (! $succeded) { throw new Exception( sprintf( _("Could not write to Centreon Broker's configuration file '%s' for monitoring " . "engine '%s'. Please add writing permissions for the webserver's user"), basename($fileCfg), $host['name'] ) ); } } } // Change files owner if ($apacheUser != '') { foreach (glob(rtrim($centreonBrokerDirCfg, '/') . '/' . '/*.{xml,json,cfg}', GLOB_BRACE) as $file) { // handle path traversal vulnerability if (str_contains($file, '..')) { throw new Exception('Path traversal found'); } @chown($file, $apacheUser); @chgrp($file, $apacheUser); } } else { echo 'Please check that files in the followings directory are writable by apache user : ' . rtrim($centreonBrokerDirCfg, '/') . "/\n"; } } if (strlen($msg_copy) == 0) { $msg_copy .= _('OK: All configuration files copied with success.'); } } else { // Get Parent Remote Servers of the Poller $statementRemotes = $pearDB->prepare( 'SELECT ns.id FROM nagios_server AS ns JOIN platform_topology AS pt ON (ns.id = pt.server_id) WHERE ns.id = :pollerId AND pt.type = "remote" UNION SELECT ns1.id FROM nagios_server AS ns1 JOIN platform_topology AS pt ON (ns1.id = pt.server_id) JOIN nagios_server AS ns2 ON ns1.id = ns2.remote_id WHERE ns2.id = :pollerId AND pt.type = "remote" UNION SELECT ns1.id FROM nagios_server AS ns1 JOIN platform_topology AS pt ON (ns1.id = pt.server_id) JOIN rs_poller_relation AS rspr ON rspr.remote_server_id = ns1.id WHERE rspr.poller_server_id = :pollerId AND pt.type = "remote"' ); $statementRemotes->bindValue(':pollerId', $pollerId, PDO::PARAM_INT); $statementRemotes->execute(); $remotesResults = $statementRemotes->fetchAll(PDO::FETCH_ASSOC); // If the poller is linked to one or many remotes foreach ($remotesResults as $remote) { $linkedStatement = $pearDB->prepare( 'SELECT id FROM nagios_server WHERE remote_id = :remoteId UNION SELECT poller_server_id AS id FROM rs_poller_relation WHERE remote_server_id = :remoteId' ); $linkedStatement->bindValue(':remoteId', $remote['id'], PDO::PARAM_INT); $linkedStatement->execute(); $linkedResults = $linkedStatement->fetchAll(PDO::FETCH_ASSOC); $exportParams = [ 'server' => $remote['id'], 'pollers' => [], ]; $exportParams['pollers'] = ! empty($linkedResults) ? array_column($linkedResults, 'id') : [$remote['id']]; $this->dependencyInjector[ServiceProvider::CENTREON_TASKSERVICE]->addTask( Task::TYPE_EXPORT, ['params' => $exportParams] ); } $return = $this->writeToCentcorePipe('SENDCFGFILE', $host['id']); $msg_copy .= _( "OK: All configuration will be send to '" . $host['name'] . "' by centcore in several minutes." ); } echo $msg_copy . "\n"; return $return; } /** * Get apache user to set file access * * @return string */ public function getApacheUser() { // Change files owner $installFile = '/etc/centreon/instCentWeb.conf'; if (file_exists($installFile)) { $stream = file_get_contents($installFile); $lines = preg_split("/\n/", $stream); foreach ($lines as $line) { if (preg_match('/WEB\_USER\=([a-zA-Z\_\-]*)/', $line, $tabUser)) { if (isset($tabUser[1])) { return $tabUser[1]; } return ''; } } } return ''; } /** * Send Trap configuration files to poller * * @param int|null $pollerId * * @throws CentreonClapiException * @throws PDOException * @return int */ public function sendTrapCfg($pollerId = null) { if (is_null($pollerId)) { throw new CentreonClapiException(self::MISSING_POLLER_ID); } $pollerId = $this->ensurePollerId($pollerId); $centreonDir = $this->centreon_path; $pearDB = $this->dependencyInjector['configuration_db']; $statement = $pearDB->prepare('SELECT snmp_trapd_path_conf FROM nagios_server WHERE id = :pollerId'); $statement->bindValue(':pollerId', $pollerId, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); $trapdPath = $row['snmp_trapd_path_conf']; if (! is_dir("{$trapdPath}/{$pollerId}")) { mkdir("{$trapdPath}/{$pollerId}"); } $filename = "{$trapdPath}/{$pollerId}/centreontrapd.sdb"; // handle path traversal vulnerability if (str_contains($filename, '..')) { throw new Exception('Path traversal found'); } $cmd = sprintf( '%s %d %s 2>&1', escapeshellarg($centreonDir . '/bin/generateSqlLite'), $pollerId, escapeshellarg($filename) ); passthru($cmd); return $this->writeToCentcorePipe('SYNCTRAP', $pollerId); } /** * @throws PDOException * @return array */ public function getPollerState() { $pollerState = []; $dbResult = $this->DBC->query('SELECT instance_id, running, name FROM instances'); while ($row = $dbResult->fetchRow()) { $pollerState[$row['instance_id']] = $row['running']; } return $pollerState; } /** * Write command to centcore pipe, using the dynamic centcore pipe file * when possible * * @param string $cmd * @param int $id * @return int */ private function writeToCentcorePipe($cmd, $id): int { if (is_dir(_CENTREON_VARLIB_ . '/centcore')) { $pipe = _CENTREON_VARLIB_ . '/centcore/' . hrtime(true) . '-externalcommand.cmd'; } else { $pipe = _CENTREON_VARLIB_ . '/centcore.cmd'; } $fullCommand = sprintf('%s:%d' . PHP_EOL, $cmd, $id); $result = file_put_contents($pipe, $fullCommand, FILE_APPEND); return ($result !== false) ? 0 : 1; } /** * Check for the existence of poller with ID or name $poller, and return * the ID of that poller. If the poller does not exist, raise an exception. * * @param string|int $poller * * @throws CentreonClapiException * @throws PDOException * @return int */ private function ensurePollerId($poller) { if (is_numeric($poller)) { $statement = $this->DB->prepare('SELECT id FROM nagios_server WHERE id = :poller'); $statement->bindValue(':poller', $poller, PDO::PARAM_INT); } else { $statement = $this->DB->prepare('SELECT id FROM nagios_server WHERE name = :poller'); $statement->bindValue(':poller', $poller, PDO::PARAM_STR); } $statement->execute(); if ($statement->rowCount() > 0) { $row = $statement->fetchRow(); return $row['id']; } throw new CentreonClapiException(self::UNKNOWN_POLLER_ID); } /** * Display Copying files * * @param string|null $filename * @param string|null $status * * @return string|void */ private function displayCopyingFile($filename = null, $status = null) { if (! isset($filename)) { return; } return '- ' . $filename . ' -> ' . $status . "\n"; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonService.class.php
centreon/www/class/centreon-clapi/centreonService.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Command; use Centreon_Object_DependencyServiceParent; use Centreon_Object_Graph_Template; use Centreon_Object_Host; use Centreon_Object_Relation_Contact_Group_Service; use Centreon_Object_Relation_Contact_Service; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Service_Category_Service; use Centreon_Object_Relation_Trap_Service; use Centreon_Object_Service; use Centreon_Object_Service_Category; use Centreon_Object_Service_Extended; use Centreon_Object_Service_Macro_Custom; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonConfigurationChange.class.php'; require_once 'centreonUtils.class.php'; require_once 'centreonTimePeriod.class.php'; require_once 'centreonACL.class.php'; require_once 'centreonCommand.class.php'; require_once 'Centreon/Object/Instance/Instance.php'; require_once 'Centreon/Object/Command/Command.php'; require_once 'Centreon/Object/Timeperiod/Timeperiod.php'; require_once 'Centreon/Object/Graph/Template/Template.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Extended.php'; require_once 'Centreon/Object/Host/Group.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Host/Macro/Custom.php'; require_once 'Centreon/Object/Service/Service.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Service/Category.php'; require_once 'Centreon/Object/Service/Macro/Custom.php'; require_once 'Centreon/Object/Service/Extended.php'; require_once 'Centreon/Object/Contact/Contact.php'; require_once 'Centreon/Object/Contact/Group.php'; require_once 'Centreon/Object/Trap/Trap.php'; require_once 'Centreon/Object/Relation/Host/Template/Host.php'; require_once 'Centreon/Object/Relation/Contact/Service.php'; require_once 'Centreon/Object/Relation/Contact/Group/Service.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Relation/Host/Group/Service/Service.php'; require_once 'Centreon/Object/Relation/Trap/Service.php'; require_once 'Centreon/Object/Relation/Service/Category/Service.php'; require_once 'Centreon/Object/Relation/Service/Group/Service.php'; require_once 'Centreon/Object/Dependency/DependencyServiceParent.php'; /** * Class * * @class CentreonService * @package CentreonClapi */ class CentreonService extends CentreonObject { public const ORDER_HOSTNAME = 0; public const ORDER_SVCDESC = 1; public const ORDER_SVCTPL = 2; public const NB_UPDATE_PARAMS = 4; public const UNKNOWN_NOTIFICATION_OPTIONS = 'Invalid notifications options'; public const INVALID_GEO_COORDS = 'Invalid geo coords'; /** @var string[] */ public static $aDepends = ['CMD', 'TP', 'TRAP', 'HOST', 'STPL']; /** * @var array * Contains : list of authorized notifications_options for this objects */ public static $aAuthorizedNotificationsOptions = ['w' => 'Warning', 'u' => 'Unreachable', 'c' => 'Critical', 'r' => 'Recovery', 'f' => 'Flapping', 's' => 'Downtime Scheduled']; /** @var int */ public $register = 1; /** @var int */ protected $hostId; /** * CentreonService constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Service($dependencyInjector); $this->params = ['service_is_volatile' => '2', 'service_active_checks_enabled' => '2', 'service_passive_checks_enabled' => '2', 'service_parallelize_check' => '2', 'service_obsess_over_service' => '2', 'service_check_freshness' => '2', 'service_event_handler_enabled' => '2', 'service_flap_detection_enabled' => '2', 'service_process_perf_data' => '2', 'service_retain_status_information' => '2', 'service_retain_nonstatus_information' => '2', 'service_notifications_enabled' => '2', 'service_register' => '1', 'service_activate' => '1']; $this->insertParams = ['host_name', 'service_description', 'service_template_model_stm_id']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'SERVICE'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'service_activate'; } /** * Magic method * * @param string $name * @param array $arg * * @throws CentreonClapiException * @throws PDOException * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) { switch ($matches[2]) { case 'host': $class = 'Centreon_Object_Host'; $relclass = 'Centreon_Object_Relation_Host_Service'; break; case 'contact': $class = 'Centreon_Object_Contact'; $relclass = 'Centreon_Object_Relation_Contact_Service'; break; case 'contactgroup': $class = 'Centreon_Object_Contact_Group'; $relclass = 'Centreon_Object_Relation_Contact_Group_Service'; break; case 'trap': $class = 'Centreon_Object_Trap'; $relclass = 'Centreon_Object_Relation_Trap_Service'; break; case 'servicegroup': $class = 'Centreon_Object_Service_Group'; $relclass = 'Centreon_Object_Relation_Service_Group_Service'; break; case 'category': $class = 'Centreon_Object_Service_Category'; $relclass = 'Centreon_Object_Relation_Service_Category_Service'; break; default: throw new CentreonClapiException(self::UNKNOWN_METHOD); break; } if (class_exists($relclass) && class_exists($class)) { // Parse arguments if (! isset($arg[0]) || ! $arg[0]) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $args[0], 'service_description' => $args[1], 'host_register' => '1'], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0] . '/' . $args[1]); } $serviceId = $elements[0]['service_id']; $hostId = $elements[0]['host_id']; $relobj = new $relclass($this->dependencyInjector); $obj = new $class($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $serviceId ); echo 'id' . $this->delim . 'name' . "\n"; foreach ($tab as $value) { if ($value) { $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]); echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n"; } } } else { if (! isset($args[1]) || ! isset($args[2])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceIds([$serviceId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $relation = $args[2]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { if ($matches[1] != 'del' && $matches[2] == 'host' && $this->serviceExists($rel, $args[1])) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } if ($matches[2] == 'contact') { $tab = $obj->getIdByParameter('contact_alias', [$rel]); } elseif ($matches[2] == 'host') { $tab = []; if (($hostId = $this->getHostIdByName($rel)) !== null) { $tab[] = $hostId; } } else { $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]); } if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]; } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getFirstKey(), $relobj->getSecondKey(), $serviceId ); if ($matches[1] == 'set') { $relobj->delete(null, $serviceId); $existingRelationIds = []; } foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($relationId, $serviceId); } elseif ($matches[1] == 'set' || $matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { if ($matches[2] == 'servicegroup') { $relobj->insert($relationId, ['hostId' => $hostId, 'serviceId' => $serviceId]); } else { $relobj->insert($relationId, $serviceId); } } } } $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $hostId, $previousPollerIds ); if (in_array($matches[2], ['servicegroup', 'host'])) { $aclObj = new CentreonACL($this->dependencyInjector); $aclObj->reload(true); } } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * Get Object Id * * @param string $name * @param int $type * * @throws PDOException * @return int */ public function getObjectId($name, int $type = CentreonObject::SINGLE_VALUE) { if (isset($this->objectIds[$name])) { return $this->objectIds[$name]; } if (preg_match('/^(.+);(.+)$/', $name, $matches)) { $ids = $this->getHostAndServiceId($matches[1], $matches[2]); if (isset($ids[1])) { $this->objectIds[$name] = $ids[1]; return $this->objectIds[$name]; } } else { return parent::getObjectId($name, $type); } return 0; } /** * Return the host id and service id if the combination does exist * * @param string $host * @param string $service * * @throws PDOException * @return array */ public function getHostAndServiceId($host, $service) { // Regular services $sql = 'SELECT h.host_id, s.service_id FROM host h, service s, host_service_relation hsr WHERE h.host_id = hsr.host_host_id AND hsr.service_service_id = s.service_id AND h.host_name = ? AND s.service_description = ?'; $res = $this->db->query($sql, [$host, $service]); $row = $res->fetchAll(); if (count($row)) { return [$row[0]['host_id'], $row[0]['service_id']]; } // Service by hostgroup $sql = 'SELECT h.host_id, s.service_id FROM host h, service s, host_service_relation hsr, hostgroup_relation hgr WHERE h.host_id = hgr.host_host_id AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id AND hsr.service_service_id = s.service_id AND h.host_name = ? AND s.service_description = ?'; $res = $this->db->query($sql, [$host, $service]); $row = $res->fetchAll(); if (count($row)) { return [$row[0]['host_id'], $row[0]['service_id']]; } // nothing found, return empty array return []; } /** * Returns type of host service relation * * @param int $serviceId * * @throws PDOException * @return int */ public function hostTypeLink($serviceId) { $sql = 'SELECT host_host_id, hostgroup_hg_id FROM host_service_relation WHERE service_service_id = ?'; $res = $this->db->query($sql, [$serviceId]); $rows = $res->fetch(); if (count($rows)) { if (isset($rows['host_host_id']) && $rows['host_host_id']) { return 1; } if (isset($rows['hostgroup_hg_id']) && $rows['hostgroup_hg_id']) { return 2; } } return 0; } /** * Check parameters * * @param string $hostName * @param string $serviceDescription * * @throws Exception * @return bool */ public function serviceExists($hostName, $serviceDescription) { $relObj = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObj->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $hostName, 'service_description' => $serviceDescription], 'AND' ); return (bool) (count($elements)); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = ['service_register' => $this->register]; if (isset($parameters)) { $params = explode($this->delim, $parameters); if (count($params) == 2) { $filters['host_name'] = '%' . $params[0] . '%'; $filters['service_description'] = '%' . $params[1] . '%'; } else { $filters['service_description'] = '%' . $parameters . '%'; } } $commandObject = new Centreon_Object_Command($this->dependencyInjector); $paramsHost = ['host_id', 'host_name']; $paramsSvc = ['service_id', 'service_description', 'command_command_id', 'command_command_id_arg', 'service_normal_check_interval', 'service_retry_check_interval', 'service_max_check_attempts', 'service_active_checks_enabled', 'service_passive_checks_enabled', 'service_activate']; $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( $paramsHost, $paramsSvc, -1, 0, 'host_name,service_description', 'ASC', $filters, 'AND' ); $paramHostString = str_replace('_', ' ', implode($this->delim, $paramsHost)); echo $paramHostString . $this->delim; $paramSvcString = str_replace('service_', '', implode($this->delim, $paramsSvc)); $paramSvcString = str_replace('command_command_id', 'check command', $paramSvcString); $paramSvcString = str_replace('command_command_id_arg', 'check command arguments', $paramSvcString); $paramSvcString = str_replace('_', ' ', $paramSvcString); echo $paramSvcString . "\n"; foreach ($elements as $tab) { if (isset($tab['command_command_id']) && $tab['command_command_id']) { $tmp = $commandObject->getParameters( $tab['command_command_id'], [$commandObject->getUniqueLabelField()] ); if (isset($tmp[$commandObject->getUniqueLabelField()])) { $tab['command_command_id'] = $tmp[$commandObject->getUniqueLabelField()]; } } echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function add($parameters): void { parent::add($parameters); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $serviceId = $this->getObjectId($this->params[$this->object->getUniqueLabelField()]); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $serviceId); } /** * Delete service * * @param string $objectName * * @throws CentreonClapiException * @throws PDOException * @return void */ public function del($objectName): void { $params = explode($this->delim, $objectName); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hostName = $params[0]; $serviceDesc = $params[1]; $serviceId = $this->getObjectId($serviceDesc); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceIds([$serviceId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $hostName, 'service_description' => $serviceDesc], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hostName . '/' . $serviceDesc); } $parentDependency = new Centreon_Object_DependencyServiceParent($this->dependencyInjector); $parentDependency->removeRelationLastServiceDependency($elements[0]['service_id']); $this->object->delete($elements[0]['service_id']); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $serviceId, $previousPollerIds ); $this->addAuditLog('d', $elements[0]['service_id'], $hostName . ' - ' . $serviceDesc); } /** * Enable object * * @param string $objectName * * @throws CentreonClapiException * @throws PDOException * @return void */ public function enable($objectName): void { parent::enable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $servciveId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange(CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $servciveId); } /** * Disable object * * @param string $objectName * * @throws CentreonClapiException * @throws PDOException * @return void */ public function disable($objectName): void { parent::disable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $serviceId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $serviceId, [], false ); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($this->serviceExists($params[self::ORDER_HOSTNAME], $params[self::ORDER_SVCDESC]) == true) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS); } $hostObject = new Centreon_Object_Host($this->dependencyInjector); $tmp = $hostObject->getIdByParameter($hostObject->getUniqueLabelField(), $params[self::ORDER_HOSTNAME]); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_HOSTNAME]); } $this->hostId = $tmp[0]; $addParams = []; $addParams['service_description'] = $this->checkIllegalChar($params[self::ORDER_SVCDESC]); $template = $params[self::ORDER_SVCTPL]; $tmp = $this->object->getList( $this->object->getPrimaryKey(), -1, 0, null, null, ['service_description' => $template, 'service_register' => '0'], 'AND' ); if (! count($tmp)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $template); } $addParams['service_template_model_stm_id'] = $tmp[0][$this->object->getPrimaryKey()]; $this->params = array_merge($this->params, $addParams); } /** * @param $serviceId */ public function insertRelations($serviceId): void { $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $relObject->insert($this->hostId, $serviceId); $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $extended->insert([$extended->getUniqueLabelField() => $serviceId]); } /** * Get a parameter * * @param null $parameters * * @throws CentreonClapiException * @throws PDOException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['activate', 'description', 'template', 'is_volatile', 'check_period', 'check_command', 'check_command_arguments', 'max_check_attempts', 'normal_check_interval', 'retry_check_interval', 'active_checks_enabled', 'passive_checks_enabled', 'notifications_enabled', 'contact_additive_inheritance', 'cg_additive_inheritance', 'notification_interval', 'notification_period', 'notification_options', 'first_notification_delay', 'obsess_over_service', 'check_freshness', 'freshness_threshold', 'event_handler_enabled', 'flap_detection_enabled', 'retain_status_information', 'retain_nonstatus_information', 'event_handler', 'event_handler_arguments', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_image_alt', 'comment']; $unknownParam = []; $hostName = $params[0]; $serviceDesc = $params[1]; $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $hostName, 'service_description' => $serviceDesc], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hostName . '/' . $serviceDesc); } $objectId = $elements[0]['service_id']; $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceIds([$objectId]); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $listParam = explode('|', $params[2]); $exportedFields = []; $resultString = ''; foreach ($listParam as $paramSearch) { $paramString = ! isset($paramString) ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { $extended = false; switch ($paramSearch) { case 'check_command': $field = 'command_command_id'; break; case 'check_command_arguments': $field = 'command_command_id_arg'; break; case 'event_handler': $field = 'command_command_id2'; break; case 'event_handler_arguments': $field = 'command_command_id_arg2'; break; case 'check_period': $field = 'timeperiod_tp_id'; break; case 'notification_period': $field = 'timeperiod_tp_id2'; break; case 'template': $field = 'service_template_model_stm_id'; break; case 'contact_additive_inheritance': case 'cg_additive_inheritance': case 'geo_coords': break; case 'notes': $extended = true; break; case 'notes_url': $extended = true; break; case 'action_url': $extended = true; break; case 'icon_image': $extended = true; break; case 'icon_image_alt': $extended = true; break; default: if (! preg_match('/^service_/', $paramSearch)) { $field = 'service_' . $paramSearch; } break; } if (! $extended) { $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; } else { $field = 'esi_' . $field; $extended = new Centreon_Object_Service_Extended($this->dependencyInjector); $ret = $extended->getParameters($objectId, $field); $ret = $ret[$field]; } if ($ret !== null) { switch ($paramSearch) { case 'check_command': case 'event_handler': $commandObject = new CentreonCommand($this->dependencyInjector); $field = $commandObject->object->getUniqueLabelField(); $ret = $commandObject->object->getParameters($ret, $field); $ret = $ret[$field]; break; case 'check_period': case 'notification_period': $tpObj = new CentreonTimePeriod($this->dependencyInjector); $field = $tpObj->object->getUniqueLabelField(); $ret = $tpObj->object->getParameters($ret, $field); $ret = $ret[$field]; break; case 'template': $tplObj = new CentreonServiceTemplate($this->dependencyInjector); $field = $tplObj->object->getUniqueLabelField(); $ret = $tplObj->object->getParameters($ret, $field); $ret = $ret[$field]; break; } } if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICE, $objectId, $previousPollerIds ); echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * @param null $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $hostName = $params[0]; $serviceDesc = $params[1]; $relObject = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $elements = $relObject->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $hostName, 'service_description' => $serviceDesc], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $hostName . '/' . $serviceDesc); } $objectId = $elements[0]['service_id']; $extended = false; $commandObject = new CentreonCommand($this->dependencyInjector); switch ($params[2]) { case 'check_command': $params[2] = 'command_command_id'; $params[3] = $commandObject->getId($params[3]); break; case 'check_command_arguments': $params[2] = 'command_command_id_arg'; break; case 'event_handler': $params[2] = 'command_command_id2'; $params[3] = $commandObject->getId($params[3]); break; case 'event_handler_arguments':
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACLAction.class.php
centreon/www/class/centreon-clapi/centreonACLAction.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; require_once 'centreonObject.class.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Group.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Acl/Action.php'; require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Acl/Group/Action.php'; require_once __DIR__ . '/Repository/AclGroupRepository.php'; require_once __DIR__ . '/Repository/SessionRepository.php'; use App\Kernel; use Centreon_Object_Acl_Action; use Centreon_Object_Acl_Group; use Centreon_Object_Relation_Acl_Group_Action; use CentreonClapi\Repository\AclGroupRepository; use CentreonClapi\Repository\SessionRepository; use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface; use Exception; use InvalidArgumentException; use LogicException; use PDOException; use Pimple\Container; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Throwable; /** * Class * * @class CentreonACLAction * @package CentreonClapi * @description Class for managing ACL Actions */ class CentreonACLAction extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_DESCRIPTION = 1; public const UNKNOWN_ACTION = 'Unknown action'; /** @var Centreon_Object_Relation_Acl_Group_Action */ protected $relObject; /** @var Centreon_Object_Acl_Group */ protected $aclGroupObj; /** @var string[] */ protected $availableActions = ['generate_cfg', 'create_edit_poller_cfg', 'delete_poller_cfg', 'generate_trap', 'global_event_handler', 'global_flap_detection', 'global_host_checks', 'global_host_obsess', 'global_host_passive_checks', 'global_notifications', 'global_perf_data', 'global_restart', 'global_service_checks', 'global_service_obsess', 'global_service_passive_checks', 'global_shutdown', 'host_acknowledgement', 'host_checks', 'host_checks_for_services', 'host_comment', 'host_disacknowledgement', 'host_event_handler', 'host_flap_detection', 'host_notifications', 'host_notifications_for_services', 'host_schedule_check', 'host_schedule_downtime', 'host_schedule_forced_check', 'host_submit_result', 'poller_listing', 'poller_stats', 'service_acknowledgement', 'service_checks', 'service_comment', 'service_disacknowledgement', 'service_display_command', 'service_event_handler', 'service_flap_detection', 'service_notifications', 'service_passive_checks', 'service_schedule_check', 'service_schedule_downtime', 'service_schedule_forced_check', 'service_submit_result', 'top_counter', 'manage_tokens']; /** @var AclGroupRepository */ private AclGroupRepository $aclGroupRepository; /** @var SessionRepository */ private SessionRepository $sessionRepository; /** * CentreonACLAction constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $db = $dependencyInjector['configuration_db']; $this->aclGroupRepository = new AclGroupRepository($db); $this->sessionRepository = new SessionRepository($db); $this->object = new Centreon_Object_Acl_Action($dependencyInjector); $this->aclGroupObj = new Centreon_Object_Acl_Group($dependencyInjector); $this->relObject = new Centreon_Object_Relation_Acl_Group_Action($dependencyInjector); $this->params = ['acl_action_activate' => '1']; $this->nbOfCompulsoryParams = 2; $this->activateField = 'acl_action_activate'; $this->action = 'ACLACTION'; } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['acl_action_description'] = $params[self::ORDER_DESCRIPTION]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { $params[1] = 'acl_action_' . $params[1]; $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['acl_action_id', 'acl_action_name', 'acl_action_description', 'acl_action_activate']; $paramString = str_replace('acl_action_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $str = ''; foreach ($tab as $key => $value) { $str .= $value . $this->delim; } $str = trim($str, $this->delim) . "\n"; echo $str; } } /** * @param $aclActionName * @throws CentreonClapiException */ public function getaclgroup($aclActionName): void { if (! isset($aclActionName) || ! $aclActionName) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclActionId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$aclActionName]); if (! count($aclActionId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $aclActionName); } $groupIds = $this->relObject->getacl_group_idFromacl_action_id($aclActionId[0]); echo 'id;name' . "\n"; if (count($groupIds)) { foreach ($groupIds as $groupId) { $result = $this->aclGroupObj->getParameters($groupId, $this->aclGroupObj->getUniqueLabelField()); echo $groupId . $this->delim . $result[$this->aclGroupObj->getUniqueLabelField()] . "\n"; } } } /** * @param $parameters * * @throws CentreonClapiException * @throws InvalidArgumentException * @throws PDOException * @throws Throwable */ public function grant($parameters): void { [$aclActionId, $action] = $this->splitParams($parameters); if ($action == '*') { $actions = $this->availableActions; } else { $actions = explode('|', $action); foreach ($actions as $act) { if (! in_array($act, $this->availableActions)) { throw new CentreonClapiException(self::UNKNOWN_ACTION . ':' . $act); } } } foreach ($actions as $act) { $res = $this->db->query( 'SELECT COUNT(*) as nb FROM acl_actions_rules WHERE acl_action_rule_id = ? AND acl_action_name = ?', [$aclActionId, $act] ); $row = $res->fetchAll(); if (! $row[0]['nb']) { $this->db->query( 'INSERT INTO acl_actions_rules (acl_action_rule_id, acl_action_name) VALUES (?, ?)', [$aclActionId, $act] ); } unset($res); } $this->updateAclActionsForAuthentifiedUsers($aclActionId); } /** * @param $parameters * * @throws CentreonClapiException * @throws InvalidArgumentException * @throws PDOException * @throws Throwable */ public function revoke($parameters): void { [$aclActionId, $action] = $this->splitParams($parameters); if ($action == '*') { $this->db->query( 'DELETE FROM acl_actions_rules WHERE acl_action_rule_id = ?', [$aclActionId] ); } else { $actions = explode('|', $action); foreach ($actions as $act) { if (! in_array($act, $this->availableActions)) { throw new CentreonClapiException(self::UNKNOWN_ACTION . ':' . $act); } } foreach ($actions as $act) { $this->db->query( 'DELETE FROM acl_actions_rules WHERE acl_action_rule_id = ? AND acl_action_name = ?', [$aclActionId, $act] ); } } $this->updateAclActionsForAuthentifiedUsers($aclActionId); } /** * @param null $filterName * * @throws Exception * @return bool|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $aclActionRuleList = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); $exportLine = ''; foreach ($aclActionRuleList as $aclActionRule) { $exportLine .= $this->action . $this->delim . 'ADD' . $this->delim . $aclActionRule['acl_action_name'] . $this->delim . $aclActionRule['acl_action_description'] . $this->delim . "\n"; $exportLine .= $this->action . $this->delim . 'SETPARAM' . $this->delim . $aclActionRule['acl_action_name'] . $this->delim; $exportLine .= 'activate' . $this->delim . $aclActionRule['acl_action_activate'] . $this->delim . "\n"; $exportLine .= $this->exportGrantActions( $aclActionRule['acl_action_id'], $aclActionRule['acl_action_name'] ); echo $exportLine; $exportLine = ''; } } /** * Del Action * * @param string $objectName * * @throws CentreonClapiException * @throws InvalidArgumentException * @throws Throwable * @return void */ public function del($objectName): void { // $ids will always be an array of 1 or 0 elements as we cannot delete multiple action acl at the same time. $ids = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$objectName]); if (empty($ids)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objectName); } $id = (int) $ids[0]; $this->updateAclActionsForAuthentifiedUsers($id); $this->object->delete($id); $this->addAuditLog('d', $id, $objectName); $aclObj = new CentreonACL($this->dependencyInjector); $aclObj->reload(true); } /** * @param array $parameters * * @throws CentreonClapiException * @throws InvalidArgumentException * @throws Throwable */ public function setparam($parameters = []): void { $params = method_exists($this, 'initUpdateParameters') ? $this->initUpdateParameters($parameters) : $parameters; if (! empty($params)) { $uniqueLabel = $this->object->getUniqueLabelField(); $objectId = $params['objectId']; unset($params['objectId']); if ( isset($params[$uniqueLabel]) && $this->objectExists($params[$uniqueLabel], $objectId) == true ) { throw new CentreonClapiException(self::NAMEALREADYINUSE); } $this->object->update($objectId, $params); if (array_key_exists('acl_action_activate', $params)) { $this->updateAclActionsForAuthentifiedUsers((int) $objectId); } $p = $this->object->getParameters($objectId, $uniqueLabel); if (isset($p[$uniqueLabel])) { $this->addAuditLog( 'c', $objectId, $p[$uniqueLabel], $params ); } } } /** * @param $parameters * @throws CentreonClapiException * @return array */ protected function splitParams($parameters) { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $aclActionId = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]); if (! count($aclActionId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } return [$aclActionId[0], $params[1]]; } /** * @param $aclActionRuleId * @param $aclActionName * * @throws PDOException * @return string */ private function exportGrantActions($aclActionRuleId, $aclActionName) { $grantActions = ''; $query = 'SELECT * FROM acl_actions_rules WHERE acl_action_rule_id = :ruleId'; $stmt = $this->db->prepare($query); $stmt->bindParam(':ruleId', $aclActionRuleId); $stmt->execute(); $aclActionList = $stmt->fetchAll(); foreach ($aclActionList as $aclAction) { $grantActions .= $this->action . $this->delim . 'GRANT' . $this->delim . $aclActionName . $this->delim . $aclAction['acl_action_name'] . $this->delim . "\n"; } return $grantActions; } /** * Updates ACL actions for an authentified user from ACL Action ID * * @param int $aclActionId * * @throws InvalidArgumentException * @throws Throwable */ private function updateAclActionsForAuthentifiedUsers(int $aclActionId): void { $aclGroupIds = $this->aclGroupRepository->getAclGroupIdsByActionId($aclActionId); $this->flagUpdatedAclForAuthentifiedUsers($aclGroupIds); } /** * This method flags updated ACL for authentified users. * * @param int[] $aclGroupIds * * @throws InvalidArgumentException * @throws Throwable */ private function flagUpdatedAclForAuthentifiedUsers(array $aclGroupIds): void { $userIds = $this->aclGroupRepository->getUsersIdsByAclGroupIds($aclGroupIds); $readSessionRepository = $this->getReadSessionRepository(); foreach ($userIds as $userId) { $sessionIds = $readSessionRepository->findSessionIdsByUserId($userId); $this->sessionRepository->flagUpdateAclBySessionIds($sessionIds); } } /** * This method gets SessionRepository from Service container * * @throws LogicException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return ReadSessionRepositoryInterface */ private function getReadSessionRepository(): ReadSessionRepositoryInterface { $kernel = Kernel::createForWeb(); return $kernel->getContainer()->get( ReadSessionRepositoryInterface::class ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonAPI.class.php
centreon/www/class/centreon-clapi/centreonAPI.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use CentreonAuth; use CentreonAuthLDAP; use CentreonDB; use CentreonLog; use CentreonUserLog; use CentreonXML; use DateTime; use Exception; use HtmlAnalyzer; use LogicException; use PDO; use PDOException; use Pimple\Container; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; require_once _CENTREON_PATH_ . 'www/class/centreon-clapi/centreonExported.class.php'; require_once realpath(__DIR__ . '/../centreonDB.class.php'); require_once realpath(__DIR__ . '/../centreonXML.class.php'); require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/DB-Func.php'; require_once _CENTREON_PATH_ . 'www/class/config-generate/generate.class.php'; require_once __DIR__ . '/../centreonAuth.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonAuth.LDAP.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonLog.class.php'; require_once realpath(__DIR__ . '/../centreonSession.class.php'); // General Centreon Management require_once 'centreon.Config.Poller.class.php'; /** * Class * * @class CentreonAPI * @package CentreonClapi */ class CentreonAPI { /** @var int */ public $dateStart; /** @var string */ public $login; /** @var string */ public $password; /** @var string */ public $action; /** @var string */ public $object; /** @var array */ public $options; /** @var CentreonDB */ public $DB; /** @var CentreonDB */ public $DBC; /** @var string */ public $format; /** @var CentreonXML */ public $xmlObj; /** @var int */ public $debug = 0; /** @var mixed|string */ public $variables; /** @var string */ public $centreon_path; /** @var string */ public $delim = ';'; /** @var null */ private static $instance = null; /** @var int */ private $return_code = 0; /** @var Container */ private $dependencyInjector; /** @var array */ private $relationObject; /** @var array */ private $objectTable; /** @var array */ private $aExport = []; /** * CentreonAPI constructor * * @param string $user * @param string $password * @param string $action * @param string $centreon_path * @param array $options * @param Container $dependencyInjector * * @throws PDOException */ public function __construct( $user, $password, $action, $centreon_path, $options, Container $dependencyInjector, ) { $this->dependencyInjector = $dependencyInjector; if (isset($user)) { $this->login = htmlentities($user, ENT_QUOTES); } if (isset($password)) { $this->password = HtmlAnalyzer::sanitizeAndRemoveTags($password); } if (isset($action)) { $this->action = htmlentities(strtoupper($action), ENT_QUOTES); } $this->options = $options; $this->centreon_path = $centreon_path; $this->variables = $options['v'] ?? ''; $this->object = isset($options['o']) ? htmlentities(strtoupper($options['o']), ENT_QUOTES) : ''; $this->objectTable = []; /** * Centreon DB Connexion */ $this->DB = $this->dependencyInjector['configuration_db']; $this->DBC = $this->dependencyInjector['realtime_db']; $this->dateStart = time(); $this->relationObject = []; $this->relationObject['CMD'] = [ 'module' => 'core', 'class' => 'Command', 'export' => true, ]; $this->relationObject['HOST'] = [ 'module' => 'core', 'class' => 'Host', 'libs' => [ 'centreonService.class.php', 'centreonHostGroup.class.php', 'centreonContact.class.php', 'centreonContactGroup.class.php', ], 'export' => true, ]; $this->relationObject['SERVICE'] = [ 'module' => 'core', 'class' => 'Service', 'libs' => [ 'centreonHost.class.php', ], 'export' => true, ]; $this->relationObject['HGSERVICE'] = [ 'module' => 'core', 'class' => 'HostGroupService', 'export' => true, ]; $this->relationObject['VENDOR'] = [ 'module' => 'core', 'class' => 'Manufacturer', 'export' => true, ]; $this->relationObject['TRAP'] = [ 'module' => 'core', 'class' => 'Trap', 'export' => true, ]; $this->relationObject['HG'] = [ 'module' => 'core', 'class' => 'HostGroup', 'export' => true, ]; $this->relationObject['HC'] = [ 'module' => 'core', 'class' => 'HostCategory', 'export' => true, ]; $this->relationObject['SG'] = [ 'module' => 'core', 'class' => 'ServiceGroup', 'export' => true, ]; $this->relationObject['SC'] = [ 'module' => 'core', 'class' => 'ServiceCategory', 'export' => true, ]; $this->relationObject['CONTACT'] = [ 'module' => 'core', 'class' => 'Contact', 'libs' => [ 'centreonCommand.class.php', ], 'export' => true, ]; $this->relationObject['LDAPCONTACT'] = [ 'module' => 'core', 'class' => 'LDAPContactRelation', 'export' => true, ]; $this->relationObject['LDAP'] = [ 'module' => 'core', 'class' => 'LDAP', 'export' => true, ]; $this->relationObject['CONTACTTPL'] = [ 'module' => 'core', 'class' => 'ContactTemplate', 'export' => true, ]; $this->relationObject['CG'] = [ 'module' => 'core', 'class' => 'ContactGroup', 'export' => true, ]; // Dependencies $this->relationObject['DEP'] = [ 'module' => 'core', 'class' => 'Dependency', 'export' => true, ]; // Downtimes $this->relationObject['DOWNTIME'] = [ 'module' => 'core', 'class' => 'Downtime', 'export' => true, ]; // RtDowntimes $this->relationObject['RTDOWNTIME'] = [ 'module' => 'core', 'class' => 'RtDowntime', 'export' => false, ]; // RtAcknowledgement $this->relationObject['RTACKNOWLEDGEMENT'] = [ 'module' => 'core', 'class' => 'RtAcknowledgement', 'export' => false, ]; // Templates $this->relationObject['HTPL'] = [ 'module' => 'core', 'class' => 'HostTemplate', 'export' => true, ]; $this->relationObject['STPL'] = [ 'module' => 'core', 'class' => 'ServiceTemplate', 'export' => true, ]; $this->relationObject['TP'] = [ 'module' => 'core', 'class' => 'TimePeriod', 'export' => true, ]; $this->relationObject['INSTANCE'] = [ 'module' => 'core', 'class' => 'Instance', 'export' => true, ]; $this->relationObject['ENGINECFG'] = [ 'module' => 'core', 'class' => 'EngineCfg', 'export' => true, ]; $this->relationObject['CENTBROKERCFG'] = [ 'module' => 'core', 'class' => 'CentbrokerCfg', 'export' => true, ]; $this->relationObject['RESOURCECFG'] = [ 'module' => 'core', 'class' => 'ResourceCfg', 'export' => true, ]; $this->relationObject['ACL'] = [ 'module' => 'core', 'class' => 'ACL', 'export' => false, ]; $this->relationObject['ACLGROUP'] = [ 'module' => 'core', 'class' => 'ACLGroup', 'export' => true, ]; $this->relationObject['ACLACTION'] = [ 'module' => 'core', 'class' => 'ACLAction', 'export' => true, ]; $this->relationObject['ACLMENU'] = [ 'module' => 'core', 'class' => 'ACLMenu', 'export' => true, ]; $this->relationObject['ACLRESOURCE'] = [ 'module' => 'core', 'class' => 'ACLResource', 'export' => true, ]; $this->relationObject['SETTINGS'] = [ 'module' => 'core', 'class' => 'Settings', 'export' => false, ]; // Get objects from modules $objectsPath = []; $DBRESULT = $this->DB->query('SELECT name FROM modules_informations'); while ($row = $DBRESULT->fetch()) { $objectsPath = array_merge( $objectsPath, glob(_CENTREON_PATH_ . 'www/modules/' . $row['name'] . '/centreon-clapi/class/*.php') ); } foreach ($objectsPath as $objectPath) { if (preg_match('/([\w-]+)\/centreon-clapi\/class\/centreon(\w+).class.php/', $objectPath, $matches)) { if (isset($matches[1], $matches[2])) { $finalNamespace = substr($matches[1], 0, stripos($matches[1], '-server')); $finalNamespace = implode( '', array_map( function ($n) { return ucfirst($n); }, explode('-', $finalNamespace) ) ); $this->relationObject[strtoupper($matches[2])] = [ 'module' => $matches[1], 'namespace' => $finalNamespace, 'class' => $matches[2], 'export' => true, ]; } } } } /** * @param string|null $user * @param string|null $password * @param string|null $action * @param string|null $centreon_path * @param array|null $options * @param Container|null $dependencyInjector * * @throws PDOException * @return CentreonAPI|null */ public static function getInstance( $user = null, $password = null, $action = null, $centreon_path = null, $options = null, $dependencyInjector = null, ) { if (is_null(self::$instance)) { if (is_null($dependencyInjector)) { $dependencyInjector = loadDependencyInjector(); } self::$instance = new CentreonAPI( $user, $password, $action, $centreon_path, $options, $dependencyInjector ); } return self::$instance; } /** * @return Container */ public function getDependencyInjector() { return $this->dependencyInjector; } /** * Set Return Code * * @param int $returnCode * @return void */ public function setReturnCode($returnCode): void { $this->return_code = $returnCode; } /** * @param string $login * * @return void */ public function setLogin($login): void { $this->login = $login; } /** * @param string $password * * @return void */ public function setPassword($password): void { $this->password = trim($password); } /** * Check user access and password * * @param bool $useSha1 * @param bool $isWorker * * @throws PDOException * @return int|void 1 if user can login */ public function checkUser($useSha1 = false, $isWorker = false) { if (! isset($this->login) || $this->login == '') { echo "ERROR: Can not connect to centreon without login.\n"; $this->printHelp(); exit(); } if (! isset($this->password) || $this->password == '') { echo 'ERROR: Can not connect to centreon without password.'; $this->printHelp(); } /** * Check Login / Password */ $DBRESULT = $this->DB->prepare( "SELECT `contact`.*, `contact_password`.`password` AS `contact_passwd`, `contact_password`.`creation_date` AS `password_creation` FROM `contact` LEFT JOIN `contact_password` ON `contact_password`.`contact_id` = `contact`.`contact_id` WHERE `contact_alias` = :contactAlias AND `contact_activate` = '1' AND `contact_register` = '1' ORDER BY contact_password.creation_date DESC LIMIT 1" ); $DBRESULT->bindParam(':contactAlias', $this->login, PDO::PARAM_STR); $DBRESULT->execute(); if ($DBRESULT->rowCount()) { $row = $DBRESULT->fetchRow(); if ($row['contact_admin'] == 0) { echo "You don't have permissions for CLAPI.\n"; exit(1); } $contact = new \CentreonContact($this->DB); // Get Security Policy $securityPolicy = $contact->getPasswordSecurityPolicy(); // Remove any blocking if it's not in the policy if ($securityPolicy['blocking_duration'] === null) { $this->removeBlockingTimeOnUser(); $row['login_attempts'] = null; $row['blocking_time'] = null; } // Check if user is blocked if ($row['blocking_time'] !== null) { // If he is block and blocking duration is expired, unblock him if ((int) $row['blocking_time'] + (int) $securityPolicy['blocking_duration'] < time()) { $this->removeBlockingTimeOnUser(); $row['login_attempts'] = null; $row['blocking_time'] = null; } else { $now = new DateTime(); $expirationDate = (new DateTime())->setTimestamp( $row['blocking_time'] + $securityPolicy['blocking_duration'] ); $interval = (date_diff($now, $expirationDate))->format('%Dd %Hh %Im %Ss'); echo "Authentication failed.\n"; $CentreonLog = new CentreonLog(); $CentreonLog->insertLog( 1, "Authentication failed for '" . $row['contact_alias'] . "'," . " max login attempts has been reached. {$interval} left\n" ); exit(1); } } $passwordExpirationDelay = $securityPolicy['password_expiration']['expiration_delay']; if ( $row['contact_auth_type'] !== CentreonAuth::AUTH_TYPE_LDAP && $passwordExpirationDelay !== null && (int) $row['password_creation'] + (int) $passwordExpirationDelay < time() // Do not check expiration for excluded users of local security policy && ! in_array($row['contact_alias'], $securityPolicy['password_expiration']['excluded_users']) ) { echo "Unable to login, your password has expired.\n"; exit(1); } // Update password from md5 to bcrypt if old md5 password is valid. if ( (str_starts_with($row['contact_passwd'], 'md5__') && $row['contact_passwd'] === $this->dependencyInjector['utils']->encodePass($this->password, 'md5')) || 'md5__' . $row['contact_passwd'] === $this->dependencyInjector['utils']->encodePass( $this->password, 'md5' ) ) { $hashedPassword = password_hash($this->password, CentreonAuth::PASSWORD_HASH_ALGORITHM); $contact->replacePasswordByContactId( (int) $row['contact_id'], $row['contact_passwd'], $hashedPassword ); CentreonUtils::setUserId($row['contact_id']); $this->removeBlockingTimeOnUser(); return 1; } if (password_verify($this->password, $row['contact_passwd'])) { CentreonUtils::setUserId($row['contact_id']); $this->removeBlockingTimeOnUser(); return 1; } if ($row['contact_auth_type'] == 'ldap') { $CentreonLog = new CentreonUserLog(-1, $this->DB); $centreonAuth = new CentreonAuthLDAP( $this->DB, $CentreonLog, $this->login, $this->password, $row, $row['ar_id'] ); if ($centreonAuth->checkPassword() == CentreonAuth::PASSWORD_VALID) { CentreonUtils::setUserId($row['contact_id']); return 1; } } if ($securityPolicy['attempts'] !== null && $securityPolicy['blocking_duration'] !== null) { $this->exitOnInvalidCredentials( (int) $row['login_attempts'], (int) $securityPolicy['attempts'], (int) $securityPolicy['blocking_duration'] ); } } echo "Authentication failed.\n"; exit(1); } /** * return (print) a "\n" * * @return void */ public function endOfLine(): void { echo "\n"; } /** * close the current action * * @return void */ public function close(): void { echo "\n"; exit($this->return_code); } /** * Print usage for using CLAPI ... * * @param bool $dbOk | whether db is ok * @param int $returnCode */ public function printHelp($dbOk = true, $returnCode = 0): void { if ($dbOk) { $this->printLegals(); } echo "This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n"; echo "and you are welcome to modify and redistribute it under the GPL license\n\n"; echo "usage: ./centreon -u <LOGIN> -p <PASSWORD> [-s] -o <OBJECT> -a <ACTION> [-v]\n"; echo " -s Use SHA1 on password (default is MD5)\n"; echo " -v variables \n"; echo " -h Print help \n"; echo " -V Print version \n"; echo " -o Object type \n"; echo " -a Launch action on Centreon\n"; echo " Actions are the followings :\n"; echo " - POLLERGENERATE: Build nagios configuration for a poller (poller id in -v parameters)\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERGENERATE -v 1 \n"; echo " - POLLERTEST: Test nagios configuration for a poller (poller id in -v parameters)\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERTEST -v 1 \n"; echo " - CFGMOVE: move nagios configuration for a poller to final directory\n"; echo " (poller id in -v parameters)\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a CFGMOVE -v 1 \n"; echo " - POLLERRESTART: Restart a poller (poller id in -v parameters)\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERRESTART -v 1 \n"; echo " - POLLERRELOAD: Reload a poller (poller id in -v parameters)\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERRELOAD -v 1 \n"; echo " - POLLERLIST: list all pollers\n"; echo " #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERLIST\n"; echo "\n"; echo " For more information about configuration objects, please refer to CLAPI wiki:\n"; echo " - https://docs.centreon.com/docs/api/clapi/ \n"; echo "\n"; echo "Notes:\n"; echo " - Actions can be written in lowercase chars\n"; echo " - LOGIN and PASSWORD is an admin account of Centreon\n"; echo "\n"; exit($returnCode); } /** * Get variable passed in parameters * * @param string $str * * @return string */ public function getVar($str) { $res = explode('=', $str); return $res[1]; } /** * Init XML Flow * * @return void */ public function initXML(): void { $this->xmlObj = new CentreonXML(); } /** * Main function : Launch action * * @param bool $exit If exit or return the return code * * @return int|void */ public function launchAction($exit = true) { $action = strtoupper($this->action); // Debug if ($this->debug) { echo "DEBUG : {$action}\n"; } // Check method availability before using it. if ($this->object) { $isService = $this->dependencyInjector['centreon.clapi']->has($this->object); if ($isService === true) { $objName = $this->dependencyInjector['centreon.clapi']->get($this->object); } else { // Require needed class $this->requireLibs($this->object); // Check class declaration if (isset($this->relationObject[$this->object]['class'])) { if ($this->relationObject[$this->object]['module'] === 'core') { $objName = "\CentreonClapi\centreon" . $this->relationObject[$this->object]['class']; } else { $objName = $this->relationObject[$this->object]['namespace'] . "\CentreonClapi\Centreon" . $this->relationObject[$this->object]['class']; } } else { $objName = ''; } if (! isset($this->relationObject[$this->object]['class']) || ! class_exists($objName)) { echo "Object {$this->object} not found in Centreon API.\n"; return 1; } } $obj = new $objName($this->dependencyInjector); if (method_exists($obj, $action) || method_exists($obj, '__call')) { $this->return_code = $obj->{$action}($this->variables); } else { echo "Method not implemented into Centreon API.\n"; return 1; } } elseif (method_exists($this, $action)) { $this->return_code = $this->{$action}(); } else { echo "Method not implemented into Centreon API.\n"; $this->return_code = 1; } if ($exit) { if ($this->return_code !== null) { echo 'Return code end : ' . $this->return_code . "\n"; } exit($this->return_code); } return $this->return_code; } /** * Import Scenario file * * @param string $filename * * @return int */ public function import($filename) { $globalReturn = 0; $this->fileExists($filename); // Open File in order to read it. $handle = fopen($filename, 'r'); if ($handle) { $i = 0; while (($string = fgets($handle)) !== false) { $i++; $string = trim($string); if ( $string === '' || str_starts_with($string, '#') || str_starts_with($string, '{OBJECT_TYPE}') ) { continue; } $tab = explode(';', $string, 3); $this->object = trim($tab[0]); $this->action = trim($tab[1]); $this->variables = trim($tab[2]); if ($this->debug == 1) { echo 'Object : ' . $this->object . "\n"; echo 'Action : ' . $this->action . "\n"; echo 'VARIABLES : ' . $this->variables . "\n\n"; } try { $this->launchActionForImport(); } catch (CentreonClapiException|Exception $e) { echo "Line {$i} : " . $e->getMessage() . "\n"; } if ($this->return_code) { $globalReturn = 1; } } fclose($handle); } return $globalReturn; } /** * @return int|void */ public function launchActionForImport() { $action = strtoupper($this->action); // Debug if ($this->debug) { echo "DEBUG : {$action}\n"; } // Check method availability before using it. if ($this->object) { $this->iniObject($this->object); // Check class declaration $obj = $this->objectTable[$this->object]; if (method_exists($obj, $action) || method_exists($obj, '__call')) { $this->return_code = $obj->{$action}($this->variables); } else { echo "Method not implemented into Centreon API.\n"; return 1; } } elseif (method_exists($this, $action) || method_exists($this, '__call')) { $this->return_code = $this->{$action}(); } else { echo "Method not implemented into Centreon API.\n"; $this->return_code = 1; } } /** * @param $newOption * * @return void */ public function setOption($newOption): void { $this->options = $newOption; } /** * @param $newVariables * * @return void */ public function setVariables($newVariables): void { $this->variables = $newVariables; } /** * @param $newPath * * @return void */ public function setCentreonPath($newPath): void { $this->centreon_path = $newPath; } /** * Export All configuration * * @param bool $withoutClose disable using of PHP exit function (default: false) * * @return int|void */ public function export($withoutClose = false) { $this->requireLibs(''); $this->sortClassExport(); $this->initAllObjects(); if (isset($this->options['select'])) { CentreonExported::getInstance()->setFilter(1); CentreonExported::getInstance()->setOptions($this->options); $selected = $this->options['select']; if (! is_array($this->options['select'])) { $selected = [$this->options['select']]; } foreach ($selected as $select) { $splits = explode(';', $select); $splits[0] ??= null; $splits[1] ??= null; if (! isset($this->objectTable[$splits[0]])) { echo "Unknown object : {$splits[0]}\n"; $this->setReturnCode(1); if ($withoutClose === false) { $this->close(); } else { return; } } elseif (! is_null($splits[1])) { $name = $splits[1]; if (isset($splits[2])) { $name .= ';' . $splits[2]; } if ($this->objectTable[$splits[0]]->getObjectId($name, CentreonObject::MULTIPLE_VALUE) == 0) { echo "Unknown object : {$splits[0]};{$splits[1]}\n"; $this->setReturnCode(1); if ($withoutClose === false) { $this->close(); } else { return; } } else { $this->objectTable[$splits[0]]->export($name); } } else { $this->objectTable[$splits[0]]->export(); } } return $this->return_code; } // header echo "{OBJECT_TYPE}{$this->delim}{COMMAND}{$this->delim}{PARAMETERS}\n"; if (count($this->aExport) > 0) { foreach ($this->aExport as $oObjet) { if (method_exists($this->objectTable[$oObjet], 'export')) { $this->objectTable[$oObjet]->export(); } } } } /** * Print centreon version and legal use * * @throws PDOException * @return void */ public function printLegals(): void { $DBRESULT = $this->DB->query("SELECT * FROM informations WHERE `key` = 'version'"); $data = $DBRESULT->fetchRow(); echo 'Centreon version ' . $data['value'] . ' - '; echo "Copyright Centreon - www.centreon.com\n"; unset($data); } /** * Print centreon version * * @throws PDOException * @return void */ public function printVersion(): void { $res = $this->DB->query("SELECT * FROM informations WHERE `key` = 'version'"); $data = $res->fetchRow(); echo 'Centreon version ' . $data['value'] . "\n"; } // API Possibilities /** * List all poller declared in Centreon * * @throws PDOException * @throws LogicException * @return int */ public function POLLERLIST() { $poller = new CentreonConfigPoller($this->centreon_path, $this->dependencyInjector); return $poller->getPollerList($this->format); } /** * Launch poller restart * * @throws CentreonClapiException * @throws PDOException * @throws LogicException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return int|null */ public function POLLERRESTART() { $poller = new CentreonConfigPoller($this->centreon_path, $this->dependencyInjector); return $poller->pollerRestart($this->variables); } /** * Launch poller reload * * @throws CentreonClapiException * @throws PDOException * @throws LogicException * @throws ServiceCircularReferenceException * @throws ServiceNotFoundException * @return int|mixed */ public function POLLERRELOAD() { $poller = new CentreonConfigPoller($this->centreon_path, $this->dependencyInjector); return $poller->pollerReload($this->variables); } /** * Launch poller configuration files generation * * @throws CentreonClapiException * @throws PDOException * @throws LogicException * @return int */ public function POLLERGENERATE() { $poller = new CentreonConfigPoller($this->centreon_path, $this->dependencyInjector); return $poller->pollerGenerate($this->variables, $this->login, $this->password); } /** * Launch poller configuration test * * @throws CentreonClapiException * @throws PDOException * @throws LogicException * @return int|null */ public function POLLERTEST() {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonContactTemplate.class.php
centreon/www/class/centreon-clapi/centreonContactTemplate.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use PDOException; use Pimple\Container; require_once 'centreonContact.class.php'; /** * Class * * @class CentreonContactTemplate * @package CentreonClapi */ class CentreonContactTemplate extends CentreonContact { public const ORDER_NAME = 0; public const ORDER_UNIQUENAME = 1; public const ORDER_MAIL = 2; public const ORDER_ADMIN = 3; public const ORDER_ACCESS = 4; public const ORDER_LANG = 5; public const ORDER_AUTHTYPE = 6; public const ORDER_DEFAULT_PAGE = 7; /** @var string[] */ public static $aDepends = ['CMD', 'TP']; /** * CentreonContactTemplate constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->params['contact_register'] = 0; $this->register = 0; $this->action = 'CONTACTTPL'; $this->insertParams = [ 'contact_name', 'contact_alias', 'contact_email', 'contact_admin', 'contact_oreon', 'contact_lang', 'contact_auth_type', ]; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $this->addParams = []; $this->initUniqueField($params); $this->initUserInformation($params); $this->initUserAccess($params); $this->initLang($params); $this->initAuthenticationType($params); $this->initDefaultPage($params); $this->params = array_merge($this->params, $this->addParams); $this->checkParameters(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonLDAP.class.php
centreon/www/class/centreon-clapi/centreonLDAP.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace CentreonClapi; use Centreon_Object_Configuration_Ldap; use Centreon_Object_Contact; use Centreon_Object_Contact_Group; use Centreon_Object_Ldap; use Centreon_Object_Server_Ldap; use Exception; use PDO; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonContact.class.php'; require_once 'Centreon/Object/Ldap/ConfigurationLdap.php'; require_once 'Centreon/Object/Ldap/ObjectLdap.php'; require_once 'Centreon/Object/Ldap/ServerLdap.php'; /** * Class * * @class CentreonLDAP * @package CentreonClapi * @description Class for managing ldap servers */ class CentreonLDAP extends CentreonObject { public const NB_ADD_PARAM = 2; public const AR_NOT_EXIST = 'LDAP configuration ID not found'; /** @var array|string[] */ public array $aDepends = [ 'CG', 'CONTACTTPL', ]; /** @var array<string,string> */ protected array $baseParams = [ 'alias' => '', 'bind_dn' => '', 'bind_pass' => '', 'group_base_search' => '', 'group_filter' => '', 'group_member' => '', 'group_name' => '', 'ldap_auto_import' => '', 'ldap_contact_tmpl' => '', 'ldap_default_cg' => '', 'ldap_dns_use_domain' => '', 'ldap_connection_timeout' => '', 'ldap_search_limit' => '', 'ldap_search_timeout' => '', 'ldap_srv_dns' => '', 'ldap_store_password' => '', 'ldap_template' => '', 'protocol_version' => '', 'user_base_search' => '', 'user_email' => '', 'user_filter' => '', 'user_firstname' => '', 'user_lastname' => '', 'user_name' => '', 'user_pager' => '', 'user_group' => '', 'ldap_auto_sync' => '', 'ldap_sync_interval' => '', ]; /** @var string[] */ protected array $serverParams = ['host_address', 'host_port', 'host_order', 'use_ssl', 'use_tls']; /** * CentreonLDAP constructor. * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Ldap($dependencyInjector); $this->action = 'LDAP'; } /** * Get Ldap Configuration Id. * * @param string $name * * @throws PDOException * @return mixed returns null if no ldap id is found */ public function getLdapId($name) { $res = $this->db->prepare( <<<'SQL' SELECT ar_id FROM auth_ressource WHERE ar_name = :name SQL ); $res->bindValue(':name', $name, PDO::PARAM_STR); $res->execute(); $row = $res->fetch(); if (! isset($row['ar_id'])) { return; } $ldapId = $row['ar_id']; unset($res); return $ldapId; } /** * @param $id * * @throws PDOException * @return array */ public function getLdapServers($id) { $res = $this->db->prepare( <<<'SQL' SELECT host_address, host_port FROM auth_ressource_host WHERE auth_ressource_id = :id SQL ); $res->bindValue(':id', $id, PDO::PARAM_INT); $res->execute(); return $res->fetchAll(); } /** * @param array $params * @param array $filters * * @throws PDOException */ public function show($params = [], $filters = []): void { $sql = 'SELECT ar_id, ar_name, ar_description, ar_enable FROM auth_ressource ORDER BY ar_name'; $res = $this->db->query($sql); $row = $res->fetchAll(); echo "id;name;description;status\n"; foreach ($row as $ldap) { echo $ldap['ar_id'] . $this->delim . $ldap['ar_name'] . $this->delim . $ldap['ar_description'] . $this->delim . $ldap['ar_enable'] . "\n"; } } /** * @param string|null $arName * * @throws CentreonClapiException * @throws PDOException */ public function showserver($arName = null): void { if (! $arName) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $arId = $this->getLdapId($arName); if (is_null($arId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' ' . $arName); } $sql = 'SELECT ldap_host_id, host_address, host_port, use_ssl, use_tls, host_order FROM auth_ressource_host WHERE auth_ressource_id = :auth_ressource_id ORDER BY host_order'; $statement = $this->db->prepare($sql); $statement->bindValue(':auth_ressource_id', (int) $arId, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchAll(PDO::FETCH_ASSOC); echo "id;address;port;ssl;tls;order\n"; foreach ($row as $srv) { echo $srv['ldap_host_id'] . $this->delim . $srv['host_address'] . $this->delim . $srv['host_port'] . $this->delim . $srv['use_ssl'] . $this->delim . $srv['use_tls'] . $this->delim . $srv['host_order'] . "\n"; } } /** * Add a new ldap configuration. * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException */ public function add($parameters): void { if (! isset($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < self::NB_ADD_PARAM) { throw new CentreonClapiException(self::MISSINGPARAMETER); } [$name, $description] = $params; if (! $this->isUnique($name)) { throw new CentreonClapiException(self::NAMEALREADYINUSE . ' (' . $name . ')'); } $stmt = $this->db->prepare( "INSERT INTO auth_ressource (ar_name, ar_description, ar_enable, ar_type) VALUES (:arName, :description, '1', 'ldap')" ); $stmt->bindValue(':arName', $name, PDO::PARAM_STR); $stmt->bindValue(':description', $description, PDO::PARAM_STR); $stmt->execute(); } /** * Add server to ldap configuration. * * @param string $parameters * * @throws CentreonClapiException * @throws PDOException */ public function addserver($parameters): void { if (! isset($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < 5) { throw new CentreonClapiException(self::MISSINGPARAMETER); } [$arName, $address, $port, $ssl, $tls] = $params; if (! is_numeric($port)) { throw new CentreonClapiException('Incorrect port parameters'); } if (! is_numeric($ssl)) { throw new CentreonClapiException('Incorrect ssl parameters'); } if (! is_numeric($tls)) { throw new CentreonClapiException('Incorrect tls parameters'); } $arId = $this->getLdapId($arName); if (is_null($arId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' ' . $arName); } $serverList = $this->getLdapServers($arId); $newServer = ['host_address' => $address, 'host_port' => $port]; if (in_array($newServer, $serverList, true)) { throw new CentreonClapiException(self::OBJECTALREADYEXISTS . ' ' . $address); } $statement = $this->db->prepare( <<<'SQL' INSERT INTO auth_ressource_host (auth_ressource_id, host_address, host_port, use_ssl, use_tls) VALUES (:arId, :address, :port, :ssl, :tls) SQL ); $statement->bindValue(':arId', $arId, PDO::PARAM_INT); $statement->bindValue(':address', $address, PDO::PARAM_STR); $statement->bindValue(':port', $port, PDO::PARAM_INT); $statement->bindValue(':ssl', $ssl, PDO::PARAM_INT); $statement->bindValue(':tls', $tls, PDO::PARAM_INT); $statement->execute(); } /** * Delete configuration. * * @param null|mixed $arName * * @throws CentreonClapiException * @throws PDOException */ public function del($arName = null): void { if (! isset($arName)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $arId = $this->getLdapId($arName); if (is_null($arId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ' ' . $arName); } $statement = $this->db->prepare( <<<'SQL' DELETE FROM auth_ressource WHERE ar_id = :arId SQL ); $statement->bindValue(':arId', $arId, PDO::PARAM_INT); $statement->execute(); } /** * @param $serverId * * @throws CentreonClapiException * @throws PDOException */ public function delserver($serverId): void { if (! isset($serverId)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (! is_numeric($serverId)) { throw new CentreonClapiException('Incorrect server id parameters'); } $statement = $this->db->prepare( <<<'SQL' DELETE FROM auth_ressource_host WHERE ldap_host_id = :serverId SQL ); $statement->bindValue(':serverId', $serverId, PDO::PARAM_INT); $statement->execute(); } /** * Set parameters. * * @param array $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setparam($parameters = []): void { if (empty($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $arId = $this->getLdapId($params[0]); if (is_null($arId)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]); } if (in_array(mb_strtolower($params[1]), ['name', 'description', 'enable'], true)) { if (mb_strtolower($params[1]) === 'name') { if (! $this->isUnique($params[2], $arId)) { throw new CentreonClapiException(self::NAMEALREADYINUSE . ' (' . $params[2] . ')'); } } $statement = $this->db->prepare( <<<SQL UPDATE auth_ressource SET ar_{$params[1]} = :param WHERE ar_id = :arId SQL ); $statement->bindValue(':param', $params[2], PDO::PARAM_STR); $statement->bindValue(':arId', $arId, PDO::PARAM_INT); $statement->execute(); } elseif (isset($this->baseParams[mb_strtolower($params[1])])) { if (mb_strtolower($params[1]) === 'ldap_contact_tmpl') { if (empty($params[2])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $contactObj = new CentreonContact($this->dependencyInjector); $params[2] = $contactObj->getContactID($params[2]); } if (mb_strtolower($params[1]) === 'ldap_default_cg' && ! empty($params[2])) { $contactGroupObj = new CentreonContactGroup($this->dependencyInjector); $params[2] = $contactGroupObj->getContactGroupID($params[2]); } $statement = $this->db->prepare( <<<'SQL' DELETE FROM auth_ressource_info WHERE ari_name = :name AND ar_id = :arId SQL ); $statement->bindValue(':name', $params[1], PDO::PARAM_STR); $statement->bindValue(':arId', $arId, PDO::PARAM_INT); $statement->execute(); $statement = $this->db->prepare( <<<'SQL' INSERT INTO auth_ressource_info (ari_value, ari_name, ar_id) VALUES (:value, :name, :arId) SQL ); $statement->bindValue(':value', $params[2], PDO::PARAM_STR); $statement->bindValue(':name', $params[1], PDO::PARAM_STR); $statement->bindValue(':arId', $arId, PDO::PARAM_INT); $statement->execute(); } else { throw new CentreonClapiException(self::UNKNOWNPARAMETER); } } /** * Set server param. * * @param null|mixed $parameters * * @throws CentreonClapiException * @throws PDOException */ public function setparamserver($parameters = null): void { if (is_null($parameters)) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $params = explode($this->delim, $parameters); if (count($params) < 3) { throw new CentreonClapiException(self::MISSINGPARAMETER); } [$serverId, $key, $value] = $params; $key = mb_strtolower($key); if (! in_array($key, $this->serverParams, true)) { throw new CentreonClapiException(self::UNKNOWNPARAMETER); } $statement = $this->db->prepare( <<<SQL UPDATE auth_ressource_host SET {$key} = :value WHERE ldap_host_id = :id SQL ); $statement->bindValue(':value', $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR); $statement->bindValue(':id', $serverId, PDO::PARAM_INT); $statement->execute(); } /** * @param mixed|null $filterName * * @throws Exception * @return int|void */ public function export($filterName = null) { if (! $this->canBeExported($filterName)) { return 0; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $configurationLdapObj = new Centreon_Object_Configuration_Ldap($this->dependencyInjector); $serverLdapObj = new Centreon_Object_Server_Ldap($this->dependencyInjector); $ldapList = $this->object->getList( '*', -1, 0, $labelField, 'ASC', $filters ); foreach ($ldapList as $ldap) { echo $this->action . $this->delim . 'ADD' . $this->delim . $ldap['ar_name'] . $this->delim . $ldap['ar_description'] . $this->delim . "\n"; echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $ldap['ar_name'] . $this->delim . 'enable' . $this->delim . $ldap['ar_enable'] . $this->delim . "\n"; $filters = ['`auth_ressource_id`' => $ldap['ar_id']]; $ldapServerLabelField = $serverLdapObj->getUniqueLabelField(); $ldapServerList = $serverLdapObj->getList( '*', -1, 0, $ldapServerLabelField, 'ASC', $filters ); foreach ($ldapServerList as $server) { echo $this->action . $this->delim . 'ADDSERVER' . $this->delim . $ldap['ar_name'] . $this->delim . $server['host_address'] . $this->delim . $server['host_port'] . $this->delim . $server['use_ssl'] . $this->delim . $server['use_tls'] . $this->delim . "\n"; } $filters = ['`ar_id`' => $ldap['ar_id']]; $ldapConfigurationLabelField = $configurationLdapObj->getUniqueLabelField(); $ldapConfigurationList = $configurationLdapObj->getList( '*', -1, 0, $ldapConfigurationLabelField, 'ASC', $filters ); foreach ($ldapConfigurationList as $configuration) { if ($configuration['ari_name'] !== 'ldap_dns_use_ssl' && $configuration['ari_name'] !== 'ldap_dns_use_tls' ) { if ($configuration['ari_name'] === 'ldap_contact_tmpl') { $contactObj = new Centreon_Object_Contact($this->dependencyInjector); $contactName = $contactObj->getParameters($configuration['ari_value'], 'contact_name'); $configuration['ari_value'] = $contactName['contact_name']; } if ($configuration['ari_name'] === 'ldap_default_cg') { $contactGroupObj = new Centreon_Object_Contact_Group($this->dependencyInjector); $contactGroupName = $contactGroupObj->getParameters($configuration['ari_value'], 'cg_name'); $configuration['ari_value'] = ! empty($contactGroupName['cg_name']) ? $contactGroupName['cg_name'] : null; } echo $this->action . $this->delim . 'SETPARAM' . $this->delim . $ldap['ar_name'] . $this->delim . $configuration['ari_name'] . $this->delim . $configuration['ari_value'] . $this->delim . "\n"; } } } } /** * Checks if configuration name is unique. * * @param string $name * @param int $arId * * @throws PDOException * @return bool */ protected function isUnique($name = '', $arId = 0) { $stmt = $this->db->prepare( <<<'SQL' SELECT ar_name FROM auth_ressource WHERE ar_name = :name AND ar_id != :id SQL ); $stmt->bindValue(':name', $name, PDO::PARAM_STR); $stmt->bindValue(':id', $arId, PDO::PARAM_INT); $stmt->execute(); $res = $stmt->fetchAll(); return ! (count($res)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonServiceCategory.class.php
centreon/www/class/centreon-clapi/centreonServiceCategory.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Service_Category_Service; use Centreon_Object_Service; use Centreon_Object_Service_Category; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonSeverityAbstract.class.php'; require_once 'centreonACL.class.php'; require_once 'Centreon/Object/Service/Category.php'; require_once 'Centreon/Object/Service/Service.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Relation/Service/Category/Service.php'; /** * Class * * @class CentreonServiceCategory * @package CentreonClapi * @description Class for managing service categories */ class CentreonServiceCategory extends CentreonSeverityAbstract { /** @var string[] */ public static $aDepends = ['SERVICE']; /** * CentreonServiceCategory constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Service_Category($dependencyInjector); $this->params = ['sc_activate' => '1']; $this->insertParams = ['sc_name', 'sc_description']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'level', 'icon_id'] ); $this->action = 'SC'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'sc_activate'; } /** * @param $name * @param $arg * * @throws CentreonClapiException * @return void */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|add|del|set)(service|servicetemplate)$/', $name, $matches)) { // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $hcIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($hcIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $categoryId = $hcIds[0]; $obj = new Centreon_Object_Service($this->dependencyInjector); $relobj = new Centreon_Object_Relation_Service_Category_Service($this->dependencyInjector); $hostServiceRel = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); if ($matches[1] == 'get') { $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $hcIds); if ($matches[2] == 'servicetemplate') { echo 'template id' . $this->delim . "service template description\n"; } elseif ($matches[2] == 'service') { echo 'host id' . $this->delim . 'host name' . $this->delim . 'service id' . $this->delim . "service description\n"; } foreach ($tab as $value) { $p = $obj->getParameters($value, ['service_description', 'service_register']); if ($p['service_register'] == 1 && $matches[2] == 'service') { $elements = $hostServiceRel->getMergedParameters( ['host_name', 'host_id'], ['service_description'], -1, 0, 'host_name,service_description', 'ASC', ['service_id' => $value], 'AND' ); if (isset($elements[0])) { echo $elements[0]['host_id'] . $this->delim . $elements[0]['host_name'] . $this->delim . $value . $this->delim . $elements[0]['service_description'] . "\n"; } } elseif ($p['service_register'] == 0 && $matches[2] == 'servicetemplate') { echo $value . $this->delim . $p['service_description'] . "\n"; } } } elseif ($matches[1] == 'set') { if ($matches[2] == 'servicetemplate') { $this->setServiceTemplate($args, $relobj, $obj, $categoryId); } elseif ($matches[2] == 'service') { $this->setService($args, $relobj, $categoryId, $hostServiceRel, $obj); } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; foreach ($relations as $rel) { if ($matches[2] == 'service') { $tmp = explode(',', $rel); if (count($tmp) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $elements = $hostServiceRel->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $tmp[0], 'service_description' => $tmp[1]], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $tmp[0] . '/' . $tmp[1]); } $relationTable[] = $elements[0]['service_id']; } elseif ($matches[2] == 'servicetemplate') { $tab = $obj->getList( 'service_id', -1, 0, null, null, ['service_description' => $rel, 'service_register' => 0], 'AND' ); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]['service_id']; } } $existingRelationIds = $relobj->getTargetIdFromSourceId( $relobj->getSecondKey(), $relobj->getFirstKey(), [$categoryId] ); foreach ($relationTable as $relationId) { if ($matches[1] == 'del') { $relobj->delete($categoryId, $relationId); } elseif ($matches[1] == 'add') { if (! in_array($relationId, $existingRelationIds)) { $relobj->insert($categoryId, $relationId); } } } $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['sc_id', 'sc_name', 'sc_description', 'level']; $paramString = str_replace('sc_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { if (! $tab['level']) { $tab['level'] = 'none'; } echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['sc_description'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^sc_/', $params[1])) { $params[1] = 'sc_' . $params[1]; } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * Export * * @param string|null $filterName * * @throws Exception * @return false|void */ public function export($filterName = null) { if (! parent::export($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $scs = $this->object->getList( [$this->object->getPrimaryKey(), $labelField], -1, 0, $labelField, 'ASC', $filters ); $relobj = new Centreon_Object_Relation_Service_Category_Service($this->dependencyInjector); $hostServiceRel = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $svcObj = new Centreon_Object_Service($this->dependencyInjector); foreach ($scs as $sc) { $scId = $sc[$this->object->getPrimaryKey()]; $scName = $sc[$labelField]; $relations = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $scId); foreach ($relations as $serviceId) { $svcParam = $svcObj->getParameters($serviceId, ['service_description', 'service_register']); if ($svcParam['service_register'] == 1) { $elements = $hostServiceRel->getMergedParameters( ['host_name'], ['service_description'], -1, 0, null, null, ['service_id' => $serviceId], 'AND' ); foreach ($elements as $element) { echo $this->action . $this->delim . 'addservice' . $this->delim . $scName . $this->delim . $element['host_name'] . ',' . $element['service_description'] . "\n"; } } else { echo $this->action . $this->delim . 'addservicetemplate' . $this->delim . $scName . $this->delim . $svcParam['service_description'] . "\n"; } } } } /** * @param $args * @param $relobj * @param $categoryId * @param $hostServiceRel * @param $obj * * @throws CentreonClapiException * @return void */ private function setService($args, $relobj, $categoryId, $hostServiceRel, $obj): void { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; $excludedList = $obj->getList( 'service_id', -1, 0, null, null, ['service_register' => '1'], 'AND' ); foreach ($relations as $rel) { $tmp = explode(',', $rel); if (count($tmp) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if (count($tmp) > 2) { throw new CentreonClapiException('One Service by Host Name please!'); } $elements = $hostServiceRel->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $tmp[0], 'service_description' => $tmp[1], 'service_register' => '1'], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $tmp[0] . '/' . $tmp[1]); } $relationTable[] = $elements[0]['service_id']; } foreach ($excludedList as $excluded) { $relobj->delete($categoryId, $excluded['service_id']); } foreach ($relationTable as $relationId) { $relobj->insert($categoryId, $relationId); } $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } /** * @param $args * @param $relobj * @param $obj * @param $categoryId * * @throws CentreonClapiException * @return void */ private function setServiceTemplate($args, $relobj, $obj, $categoryId): void { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; $excludedList = $obj->getList( 'service_id', -1, 0, null, null, ['service_register' => 0], 'AND' ); foreach ($relations as $rel) { $tab = $obj->getList( 'service_id', -1, 0, null, null, ['service_description' => $rel, 'service_register' => 0], 'AND' ); if (! count($tab)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel); } $relationTable[] = $tab[0]['service_id']; } foreach ($excludedList as $excluded) { $relobj->delete($categoryId, $excluded['service_id']); } foreach ($relationTable as $relationId) { $relobj->insert($categoryId, $relationId); } $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonConfigurationChange.class.php
centreon/www/class/centreon-clapi/centreonConfigurationChange.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use CentreonDB; use Exception; use PDO; use PDOException; /** * Class * * @class CentreonConfigurationChange * @package CentreonClapi */ class CentreonConfigurationChange { public const UNKNOWN_RESOURCE_TYPE = 'Unknown resource type'; public const RESOURCE_TYPE_HOST = 'host'; public const RESOURCE_TYPE_HOSTGROUP = 'hostgroup'; public const RESOURCE_TYPE_SERVICE = 'service'; public const RESOURCE_TYPE_SERVICEGROUP = 'servicegroup'; /** * CentreonConfigurationChange constructor * * @param CentreonDB $db */ public function __construct( private CentreonDB $db, ) { } /** * Return ids of hosts linked to hostgroups * * @param int[] $hostgroupIds * @param bool $shouldHostgroupBeEnabled (default true) * @throws Exception * @return int[] */ public function findHostsForConfigChangeFlagFromHostGroupIds( array $hostgroupIds, bool $shouldHostgroupBeEnabled = true, ): array { if ($hostgroupIds === []) { return []; } $bindedParams = []; foreach ($hostgroupIds as $key => $hostgroupId) { $bindedParams[':hostgroup_id_' . $key] = $hostgroupId; } if ($shouldHostgroupBeEnabled) { $query = "SELECT DISTINCT(hgr.host_host_id) FROM hostgroup_relation hgr JOIN hostgroup ON hostgroup.hg_id = hgr.hostgroup_hg_id WHERE hostgroup.hg_activate = '1' AND hgr.hostgroup_hg_id IN (" . implode(', ', array_keys($bindedParams)) . ')'; } else { $query = 'SELECT DISTINCT(hgr.host_host_id) FROM hostgroup_relation hgr WHERE hgr.hostgroup_hg_id IN (' . implode(', ', array_keys($bindedParams)) . ')'; } $stmt = $this->db->prepare($query); foreach ($bindedParams as $bindedParam => $bindedValue) { $stmt->bindValue($bindedParam, $bindedValue, PDO::PARAM_INT); } $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_COLUMN); } /** * Return ids of hosts linked to services * * @param int[] $serviceIds * @param bool $shoudlServiceBeEnabled * * @throws PDOException * @return int[] */ public function findHostsForConfigChangeFlagFromServiceIds( array $serviceIds, bool $shoudlServiceBeEnabled = true, ): array { if ($serviceIds === []) { return []; } $bindedParams = []; foreach ($serviceIds as $key => $serviceId) { $bindedParams[':service_id_' . $key] = $serviceId; } if ($shoudlServiceBeEnabled) { $query = "SELECT DISTINCT(hsr.host_host_id) FROM host_service_relation hsr JOIN service ON service.service_id = hsr.service_service_id WHERE service.service_activate = '1' AND hsr.service_service_id IN (" . implode(', ', array_keys($bindedParams)) . ')'; } else { $query = 'SELECT DISTINCT(hsr.host_host_id) FROM host_service_relation hsr WHERE hsr.service_service_id IN (' . implode(', ', array_keys($bindedParams)) . ')'; } $stmt = $this->db->prepare($query); foreach ($bindedParams as $bindedParam => $bindedValue) { $stmt->bindValue($bindedParam, $bindedValue, PDO::PARAM_INT); } $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_COLUMN); } /** * Return ids of hosts linked to service * * @param int $servicegroupId * @param bool $shouldServicegroupBeEnabled (default true) * @throws Exception * @return int[] */ public function findHostsForConfigChangeFlagFromServiceGroupId( int $servicegroupId, bool $shouldServicegroupBeEnabled = true, ): array { $query = "SELECT sgr.*, service.service_register FROM servicegroup_relation sgr JOIN servicegroup ON servicegroup.sg_id = sgr.servicegroup_sg_id JOIN service ON service.service_id = sgr.service_service_id WHERE service.service_activate = '1' AND sgr.servicegroup_sg_id = :servicegroup_id" . ($shouldServicegroupBeEnabled ? " AND servicegroup.sg_activate = '1'" : ''); $stmt = $this->db->prepare($query); $stmt->bindValue(':servicegroup_id', $servicegroupId, PDO::PARAM_INT); $stmt->execute(); $hostIds = []; $hostgroupIds = []; $serviceTemplateIds = []; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) { if ($value['service_register'] === '0') { $serviceTemplateIds[] = $value['service_service_id']; } elseif ($value['hostgroup_hg_id'] !== null) { $hostgroupIds[] = $value['hostgroup_hg_id']; } else { $hostIds[] = $value['host_host_id']; } } $serviceIds = $this->findServicesForConfigChangeFlagFromServiceTemplateIds($serviceTemplateIds); return array_merge( $hostIds, $this->findHostsForConfigChangeFlagFromHostGroupIds($hostgroupIds), $this->findHostsForConfigChangeFlagFromServiceIds($serviceIds) ); } /** * Return ids of pollers linked to hosts * * @param int[] $hostIds * @param bool $shouldHostBeEnabled (default true) * @throws Exception * @return int[] */ public function findPollersForConfigChangeFlagFromHostIds(array $hostIds, bool $shouldHostBeEnabled = true): array { if ($hostIds === []) { return []; } $bindedParams = []; foreach ($hostIds as $key => $hostId) { $bindedParams[':host_id_' . $key] = $hostId; } if ($shouldHostBeEnabled) { $query = "SELECT DISTINCT(phr.nagios_server_id) FROM ns_host_relation phr JOIN host ON host.host_id = phr.host_host_id WHERE host.host_activate = '1' AND phr.host_host_id IN (" . implode(', ', array_keys($bindedParams)) . ')'; } else { $query = 'SELECT DISTINCT(phr.nagios_server_id) FROM ns_host_relation phr WHERE phr.host_host_id IN (' . implode(', ', array_keys($bindedParams)) . ')'; } $stmt = $this->db->prepare($query); foreach ($bindedParams as $bindedParam => $bindedValue) { $stmt->bindValue($bindedParam, $bindedValue, PDO::PARAM_INT); } $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_COLUMN); } /** * Set relevent pollers as updated * * @param string $resourceType * @param int $resourceId * @param int[] $previousPollers * @param bool $shouldResourceBeEnabled (default true) * @throws Exception */ public function signalConfigurationChange( string $resourceType, int $resourceId, array $previousPollers = [], bool $shouldResourceBeEnabled = true, ): void { $hostIds = []; switch ($resourceType) { case self::RESOURCE_TYPE_HOST: $hostIds[] = $resourceId; break; case self::RESOURCE_TYPE_HOSTGROUP: $hostIds = array_merge( $hostIds, $this->findHostsForConfigChangeFlagFromHostGroupIds([$resourceId], $shouldResourceBeEnabled) ); break; case self::RESOURCE_TYPE_SERVICE: $hostIds = array_merge( $hostIds, $this->findHostsForConfigChangeFlagFromServiceIds([$resourceId], $shouldResourceBeEnabled) ); break; case self::RESOURCE_TYPE_SERVICEGROUP: $hostIds = array_merge( $hostIds, $this->findHostsForConfigChangeFlagFromServiceGroupId($resourceId, $shouldResourceBeEnabled) ); break; default: throw new CentreonClapiException(self::UNKNOWN_RESOURCE_TYPE . ':' . $resourceType); break; } $pollerIds = $this->findPollersForConfigChangeFlagFromHostIds( $hostIds, $resourceType === self::RESOURCE_TYPE_HOST ? $shouldResourceBeEnabled : true ); $this->definePollersToUpdated(array_merge($pollerIds, $previousPollers)); } /** * Return ids of services linked to templates recursively * * @param int[] $serviceTemplateIds * @throws Exception * @return int[] */ private function findServicesForConfigChangeFlagFromServiceTemplateIds(array $serviceTemplateIds): array { if ($serviceTemplateIds === []) { return []; } $bindedParams = []; foreach ($serviceTemplateIds as $key => $serviceTemplateId) { $bindedParams[':servicetemplate_id_' . $key] = $serviceTemplateId; } $query = "SELECT service_id, service_register FROM service WHERE service.service_activate = '1' AND service_template_model_stm_id IN (" . implode(', ', array_keys($bindedParams)) . ')'; $stmt = $this->db->prepare($query); foreach ($bindedParams as $bindedParam => $bindedValue) { $stmt->bindValue($bindedParam, $bindedValue, PDO::PARAM_INT); } $stmt->execute(); $serviceIds = []; $serviceTemplateIds2 = []; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) { if ($value['service_register'] === '0') { $serviceTemplateIds2[] = $value['service_id']; } else { $serviceIds[] = $value['service_id']; } } return array_merge( $serviceIds, $this->findServicesForConfigChangeFlagFromServiceTemplateIds($serviceTemplateIds2) ); } /** * Set 'updated' flag to '1' for all listed poller ids * * @param int[] $pollerIds * @throws Exception */ private function definePollersToUpdated(array $pollerIds): void { if ($pollerIds === []) { return; } $bindedParams = []; foreach ($pollerIds as $key => $pollerId) { $bindedParams[':poller_id_' . $key] = $pollerId; } $query = "UPDATE nagios_server SET updated = '1' WHERE id IN (" . implode(', ', array_keys($bindedParams)) . ')'; $stmt = $this->db->prepare($query); foreach ($bindedParams as $bindedParam => $bindedValue) { $stmt->bindValue($bindedParam, $bindedValue, PDO::PARAM_INT); } $stmt->execute(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonUtils.class.php
centreon/www/class/centreon-clapi/centreonUtils.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use CentreonDB; use PDOException; /** * Class * * @class CentreonUtils * @package CentreonClapi */ class CentreonUtils { /** @var string */ private static $clapiUserName; /** @var int */ private static $clapiUserId; /** * Converts strings such as #S# #BS# #BR# * * @param string $pattern * @return string */ public static function convertSpecialPattern($pattern) { $pattern = str_replace('#S#', '/', $pattern); $pattern = str_replace('#BS#', '\\', $pattern); return str_replace('#BR#', "\n", $pattern); } /** * @param string $imagename * @param CentreonDB|null $db * * @throws PDOException * @return int|null */ public static function getImageId($imagename, $db = null) { if (is_null($db)) { $db = new CentreonDB('centreon'); } $tab = preg_split("/\//", $imagename); $dirname = $tab[0] ?? null; $imagename = $tab[1] ?? null; if (! isset($imagename) || ! isset($dirname)) { return null; } $query = 'SELECT img.img_id FROM view_img_dir dir, view_img_dir_relation rel, view_img img ' . 'WHERE dir.dir_id = rel.dir_dir_parent_id ' . 'AND rel.img_img_id = img.img_id ' . "AND img.img_path = '" . $imagename . "' " . "AND dir.dir_name = '" . $dirname . "' " . 'LIMIT 1'; $res = $db->query($query); $img_id = null; $row = $res->fetchRow(); if (isset($row['img_id']) && $row['img_id']) { $img_id = (int) $row['img_id']; } return $img_id; } /** * Convert Line Breaks \n or \r\n to <br/> * * @param string $str | string to convert * @return string */ public static function convertLineBreak($str) { $str = str_replace("\r\n", '<br/>', $str); return str_replace("\n", '<br/>', $str); } /** * @param string $coords -90.0,180.0 * @return bool */ public static function validateGeoCoords($coords): bool { return (bool) ( preg_match( '/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/', $coords ) ); } /** * @param string $userName * * @return void */ public static function setUserName($userName): void { self::$clapiUserName = $userName; } /** * @return string */ public static function getUserName() { return self::$clapiUserName; } /** * @param int $userId * * @return void */ public static function setUserId($userId): void { self::$clapiUserId = $userId; } /** * @return int */ public static function getuserId() { return self::$clapiUserId; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonTimezone.class.php
centreon/www/class/centreon-clapi/centreonTimezone.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Timezone; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'Centreon/Object/Timezone/Timezone.php'; /** * Class * * @class CentreonTimezone * @package CentreonClapi */ class CentreonTimezone extends CentreonObject { /** * CentreonTimezone constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Timezone($dependencyInjector); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACLResources.class.php
centreon/www/class/centreon-clapi/centreonACLResources.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use CentreonDB; use PDOException; use Pimple\Container; /** * Class * * @class CentreonACLResources * @package CentreonClapi */ class CentreonACLResources { /** @var CentreonDB */ public $_DB; /** * CentreonACLResources constructor * * @param Container $dependencyInjector */ public function __construct(Container $dependencyInjector) { $this->_DB = $dependencyInjector['configuration_db']; } /** * @param string $name * * @throws PDOException * @return int */ public function getACLResourceID($name) { $request = "SELECT acl_group_id FROM acl_groups WHERE acl_group_name LIKE '" . htmlentities($name, ENT_QUOTES) . "'"; $DBRESULT = $this->_DB->query($request); $data = $DBRESULT->fetchRow(); if ($data['acl_group_id']) { return $data['acl_group_id']; } return 0; } /** * @param $contact_id * @param $aclid * * @throws PDOException * @return int */ public function addContact($contact_id, $aclid) { $request = 'DELETE FROM acl_group_contacts_relations ' . "WHERE acl_group_id = '{$aclid}' AND contact_contact_id = '{$contact_id}'"; $this->_DB->query($request); $request = 'INSERT INTO acl_group_contacts_relations ' . '(acl_group_id, contact_contact_id) ' . "VALUES ('" . $aclid . "', '" . $contact_id . "')"; $this->_DB->query($request); return 0; } /** * @param $contact_id * @param $aclid * * @throws PDOException * @return int */ public function delContact($contact_id, $aclid) { $request = 'DELETE FROM acl_group_contacts_relations ' . "WHERE acl_group_id = '{$aclid}' AND contact_contact_id = '{$contact_id}'"; $this->_DB->query($request); return 0; } /** * @throws PDOException * @return int */ public function updateACL() { $request = "UPDATE `acl_resources` SET `changed` = '1'"; $this->_DB->query($request); return 0; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonACL.class.php
centreon/www/class/centreon-clapi/centreonACL.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Pimple\Container; require_once 'centreonUtils.class.php'; /** * Class * * @class CentreonACL * @package CentreonClapi */ class CentreonACL { // hack to get rid of warning messages /** @var array */ public $topology = []; /** @var string */ public $topologyStr = ''; /** @var CentreonDB */ protected $db; /** * CentreonACL constructor * * @param Container $dependencyInjector */ public function __construct(Container $dependencyInjector) { $this->db = $dependencyInjector['configuration_db']; } /** * Reload * * @param mixed $flagOnly * @return void */ public function reload($flagOnly = false): void { $this->db->query('UPDATE acl_groups SET acl_group_changed = 1'); $this->db->query('UPDATE acl_resources SET changed = 1'); if ($flagOnly == false) { $centreonDir = realpath(__DIR__ . '/../../../'); passthru($centreonDir . '/cron/centAcl.php'); } } /** * Print timestamp at when ACL was last reloaded * * @param null|mixed $timeformat * @return void */ public function lastreload($timeformat = null): void { $res = $this->db->query("SELECT time_launch FROM cron_operation WHERE name LIKE 'centAcl%'"); $row = $res->fetch(); $time = $row['time_launch']; if (isset($timeformat) && $timeformat) { $time = date($timeformat, $time); } echo $time . "\n"; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonManufacturer.class.php
centreon/www/class/centreon-clapi/centreonManufacturer.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Manufacturer; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonUtils.class.php'; require_once 'Centreon/Object/Manufacturer/Manufacturer.php'; /** * Class * * @class CentreonManufacturer * @package CentreonClapi */ class CentreonManufacturer extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const FILE_NOT_FOUND = 'Could not find file'; /** * CentreonManufacturer constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Manufacturer($dependencyInjector); $this->params = []; $this->insertParams = ['name', 'alias']; $this->action = 'VENDOR'; $this->nbOfCompulsoryParams = count($this->insertParams); } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['id', 'name', 'alias']; parent::show($params, $filters); } /** * @param null $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters = null) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $this->getId($params[0]); return $updateParams; } /** * Will generate traps from a mib file * * @param null $parameters * @throws CentreonClapiException */ public function generatetraps($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $vendorId = $this->getId($params[0]); $mibFile = $params[1]; $tmpMibFile = '/tmp/' . basename($mibFile); if (! is_file($mibFile)) { throw new CentreonClapiException(self::FILE_NOT_FOUND . ': ' . $mibFile); } copy($mibFile, $tmpMibFile); $centreonDir = realpath(__DIR__ . '/../../../'); passthru("export MIBS=ALL && {$centreonDir}/bin/snmpttconvertmib --in={$tmpMibFile} --out={$tmpMibFile}.conf"); passthru("{$centreonDir}/bin/centFillTrapDB -f {$tmpMibFile}.conf -m {$vendorId}"); unlink($tmpMibFile); if (file_exists($tmpMibFile . '.conf')) { unlink($tmpMibFile . '.conf'); } } /** * Get manufacturer name from id * * @param int $id * @return string */ public function getName($id) { $name = $this->object->getParameters($id, [$this->object->getUniqueLabelField()]); return $name[$this->object->getUniqueLabelField()]; } /** * Get id from name * * @param $name * @throws CentreonClapiException * @return mixed */ public function getId($name) { $ids = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$name]); if (! count($ids)) { throw new CentreonClapiException('Unknown instance'); } return $ids[0]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonServiceGroup.class.php
centreon/www/class/centreon-clapi/centreonServiceGroup.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_DependencyServicegroupParent; use Centreon_Object_Relation_Host_Group_Service; use Centreon_Object_Relation_Host_Service; use Centreon_Object_Relation_Service_Group_Host_Group_Service; use Centreon_Object_Relation_Service_Group_Service; use Centreon_Object_Service_Group; use Exception; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreonConfigurationChange.class.php'; require_once 'centreonACL.class.php'; require_once 'Centreon/Object/Service/Group.php'; require_once 'Centreon/Object/Relation/Host/Service.php'; require_once 'Centreon/Object/Relation/Host/Group/Service/Service.php'; require_once 'Centreon/Object/Relation/Service/Group/Service.php'; require_once 'Centreon/Object/Relation/Service/Group/Host/Group/Service.php'; require_once 'Centreon/Object/Dependency/DependencyServicegroupParent.php'; /** * Class * * @class CentreonServiceGroup * @package CentreonClapi * @description Class for managing Service groups */ class CentreonServiceGroup extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ALIAS = 1; public const INVALID_GEO_COORDS = 'Invalid geo coords'; /** @var string[] */ public static $aDepends = ['HOST', 'SERVICE']; /** * CentreonServiceGroup constructor * * @param Container $dependencyInjector * * @throws PDOException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Service_Group($dependencyInjector); $this->params = ['sg_activate' => '1']; $this->insertParams = ['sg_name', 'sg_alias']; $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]); $this->action = 'SG'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'sg_activate'; } /** * Magic method for get/set/add/del relations * * @param string $name * @param array $arg * @throws CentreonClapiException */ public function __call($name, $arg) { // Get the method name $name = strtolower($name); // Get the action and the object if (preg_match('/^(get|add|del|set)(service|hostgroupservice)$/', $name, $matches)) { // Parse arguments if (! isset($arg[0])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $args = explode($this->delim, $arg[0]); $sgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]); if (! count($sgIds)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]); } $sgId = $sgIds[0]; if ($matches[2] == 'service') { $relobj = new Centreon_Object_Relation_Service_Group_Service($this->dependencyInjector); $obj = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $existingRelationIds = $relobj->getHostIdServiceIdFromServicegroupId($sgId); $hstring = 'host_id'; } else { $relobj = new Centreon_Object_Relation_Service_Group_Host_Group_Service($this->dependencyInjector); $obj = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); $existingRelationIds = $relobj->getHostGroupIdServiceIdFromServicegroupId($sgId); $hstring = 'hostgroup_id'; } if ($matches[1] == 'get') { if ($matches[2] == 'service') { echo 'host id' . $this->delim . 'host name' . $this->delim . 'service id' . $this->delim . "service description\n"; } elseif ($matches[2] == 'hostgroupservice') { echo 'hostgroup id' . $this->delim . 'hostgroup name' . $this->delim . 'service id' . $this->delim . "service description\n"; } foreach ($existingRelationIds as $val) { if ($matches[2] == 'service') { $elements = $obj->getMergedParameters( ['host_name', 'host_id'], ['service_description', 'service_id'], -1, 0, 'host_name,service_description', 'ASC', ['service_id' => $val['service_id'], 'host_id' => $val['host_id']], 'AND' ); if (isset($elements[0])) { echo $elements[0]['host_id'] . $this->delim . $elements[0]['host_name'] . $this->delim . $elements[0]['service_id'] . $this->delim . $elements[0]['service_description'] . "\n"; } } else { $elements = $obj->getMergedParameters( ['hg_name', 'hg_id'], ['service_description', 'service_id'], -1, 0, 'hg_name,service_description', 'ASC', ['service_id' => $val['service_id'], 'hg_id' => $val['hostgroup_id']], 'AND' ); if (isset($elements[0])) { echo $elements[0]['hg_id'] . $this->delim . $elements[0]['hg_name'] . $this->delim . $elements[0]['service_id'] . $this->delim . $elements[0]['service_description'] . "\n"; } } } } else { if (! isset($args[1])) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceGroupId($sgId); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $relation = $args[1]; $relations = explode('|', $relation); $relationTable = []; $i = 0; foreach ($relations as $rel) { $tmp = explode(',', $rel); if (count($tmp) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } if ($matches[2] == 'service') { $elements = $obj->getMergedParameters( ['host_id'], ['service_id'], -1, 0, null, null, ['host_name' => $tmp[0], 'service_description' => $tmp[1]], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $tmp[0] . '/' . $tmp[1]); } $relationTable[$i]['host_id'] = $elements[0]['host_id']; $relationTable[$i]['service_id'] = $elements[0]['service_id']; } elseif ($matches[2] == 'hostgroupservice') { $elements = $obj->getMergedParameters( ['hg_id'], ['service_id'], -1, 0, null, null, ['hg_name' => $tmp[0], 'service_description' => $tmp[1]], 'AND' ); if (! count($elements)) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $tmp[0] . '/' . $tmp[1]); } $relationTable[$i]['hostgroup_id'] = $elements[0]['hg_id']; $relationTable[$i]['service_id'] = $elements[0]['service_id']; } $i++; } if ($matches[1] == 'set') { foreach ($existingRelationIds as $key => $existrel) { $relobj->delete($sgId, $existrel[$hstring], $existrel['service_id']); unset($existingRelationIds[$key]); } } foreach ($relationTable as $relation) { if ($matches[1] == 'del') { $relobj->delete($sgId, $relation[$hstring], $relation['service_id']); } elseif ($matches[1] == 'add' || $matches[1] == 'set') { $insert = true; foreach ($existingRelationIds as $existrel) { if (($existrel[$hstring] == $relation[$hstring]) && $existrel['service_id'] == $relation['service_id']) { $insert = false; break; } } if ($insert == true) { $key = ['hostId' => $relation[$hstring], 'serviceId' => $relation['service_id']]; $relobj->insert($sgId, $key); } } } $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $sgId, $previousPollerIds ); $acl = new CentreonACL($this->dependencyInjector); $acl->reload(true); } } else { throw new CentreonClapiException(self::UNKNOWN_METHOD); } } /** * @param mixed|null $parameters * @param array $filters * * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $params = ['sg_id', 'sg_name', 'sg_alias']; $paramString = str_replace('sg_', '', implode($this->delim, $params)); echo $paramString . "\n"; $elements = $this->object->getList( $params, -1, 0, null, null, $filters ); foreach ($elements as $tab) { $tab = array_map('html_entity_decode', $tab); $tab = array_map(function ($s) { return mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1'); }, $tab); echo implode($this->delim, $tab) . "\n"; } } /** * @param $parameters * * @throws CentreonClapiException * @throws PDOException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]); $addParams['sg_alias'] = $params[self::ORDER_ALIAS]; $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * Get a parameter * * @param string|null $parameters * @throws CentreonClapiException */ public function getparam($parameters = null): void { $params = explode($this->delim, $parameters); if (count($params) < 2) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $authorizeParam = ['alias', 'comment', 'name', 'activate', 'geo_coords']; $unknownParam = []; if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) { $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ''; foreach ($listParam as $paramSearch) { $paramString = ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch; $field = $paramSearch; if (! in_array($field, $authorizeParam)) { $unknownParam[] = $field; } else { switch ($paramSearch) { case 'geo_coords': break; default: if (! preg_match('/^sg_/', $paramSearch)) { $field = 'sg_' . $paramSearch; } break; } $ret = $this->object->getParameters($objectId, $field); $ret = $ret[$field]; if (! isset($exportedFields[$paramSearch])) { $resultString .= $this->csvEscape($ret) . $this->delim; $exportedFields[$paramSearch] = 1; } } } } else { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } if ($unknownParam !== []) { throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam)); } echo implode(';', array_unique(explode(';', $paramString))) . "\n"; echo substr($resultString, 0, -1) . "\n"; } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($objectId != 0) { if (! preg_match('/^sg_/', $params[1]) && $params[1] != 'geo_coords') { $params[1] = 'sg_' . $params[1]; } elseif ($params[1] === 'geo_coords') { if (! CentreonUtils::validateGeoCoords($params[2])) { throw new CentreonClapiException(self::INVALID_GEO_COORDS); } } $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param $parameters * * @throws CentreonClapiException * @return void */ public function add($parameters): void { parent::add($parameters); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $servicegroupId = $this->getObjectId($this->params[$this->object->getUniqueLabelField()]); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $servicegroupId ); } /** * Delete Action * Must delete services as well * * @param string $objectName * @throws CentreonClapiException * @return void */ public function del($objectName): void { $sgId = $this->getObjectId($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceGroupId($sgId); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); $parentDependency = new Centreon_Object_DependencyServicegroupParent($this->dependencyInjector); $parentDependency->removeRelationLastServicegroupDependency($sgId); parent::del($objectName); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $sgId, $previousPollerIds ); } /** * @param $parameters * * @throws CentreonClapiException * @return void */ public function setParam($parameters = []): void { $params = method_exists($this, 'initUpdateParameters') ? $this->initUpdateParameters($parameters) : $parameters; if (! empty($params)) { $servicegroupId = $params['objectId']; $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $hostIds = $centreonConfig->findHostsForConfigChangeFlagFromServiceGroupId($servicegroupId); $previousPollerIds = $centreonConfig->findPollersForConfigChangeFlagFromHostIds($hostIds); parent::setparam($parameters); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $servicegroupId, $previousPollerIds ); } } /** * @param $objectName * * @throws CentreonClapiException * @return void */ public function enable($objectName): void { parent::enable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $servicegroupId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $servicegroupId ); } /** * @param $objectName * * @throws CentreonClapiException * @return void */ public function disable($objectName): void { parent::disable($objectName); $centreonConfig = new CentreonConfigurationChange($this->dependencyInjector['configuration_db']); $servicegroupId = $this->getObjectId($objectName); $centreonConfig->signalConfigurationChange( CentreonConfigurationChange::RESOURCE_TYPE_SERVICEGROUP, $servicegroupId, [], false ); } /** * Export * * @param null $filterName * * @throws Exception * @return void */ public function export($filterName = null) { if (! parent::export($filterName)) { return false; } $labelField = $this->object->getUniqueLabelField(); $filters = []; if (! is_null($filterName)) { $filters[$labelField] = $filterName; } $sgs = $this->object->getList( [$this->object->getPrimaryKey(), $labelField], -1, 0, $labelField, 'ASC', $filters ); $relobjSvc = new Centreon_Object_Relation_Service_Group_Service($this->dependencyInjector); $objSvc = new Centreon_Object_Relation_Host_Service($this->dependencyInjector); $relobjHgSvc = new Centreon_Object_Relation_Service_Group_Host_Group_Service($this->dependencyInjector); $objHgSvc = new Centreon_Object_Relation_Host_Group_Service($this->dependencyInjector); foreach ($sgs as $sg) { $sgId = $sg[$this->object->getPrimaryKey()]; $sgName = $sg[$this->object->getUniqueLabelField()]; $existingRelationIds = $relobjSvc->getHostIdServiceIdFromServicegroupId($sgId); foreach ($existingRelationIds as $val) { $elements = $objSvc->getMergedParameters( ['host_name'], ['service_description'], -1, 0, 'host_name,service_description', 'ASC', ['service_id' => $val['service_id'], 'host_id' => $val['host_id']], 'AND' ); foreach ($elements as $element) { echo $this->action . $this->delim . 'addservice' . $this->delim . $sgName . $this->delim . $element['host_name'] . ',' . $element['service_description'] . "\n"; } } $existingRelationIds = $relobjHgSvc->getHostGroupIdServiceIdFromServicegroupId($sgId); foreach ($existingRelationIds as $val) { $elements = $objHgSvc->getMergedParameters( ['hg_name'], ['service_description'], -1, 0, null, null, ['hg_id' => $val['hostgroup_id'], 'service_id' => $val['service_id']], 'AND' ); foreach ($elements as $element) { echo $this->action . $this->delim . 'addhostgroupservice' . $this->delim . $sgName . $this->delim . $element['hg_name'] . ',' . $element['service_description'] . "\n"; } } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonExported.class.php
centreon/www/class/centreon-clapi/centreonExported.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; /** * Class * * @class CentreonExported * @package CentreonClapi */ class CentreonExported { /** @var array */ private $exported = []; /** @var array */ private $ariane = []; /** @var int */ private $filter = 0; /** @var array|null */ private $filter_type = null; /** @var array|null */ private $filter_ariane = null; /** @var CentreonExported|null */ private static $instance = null; /** * @param $object * @param $id * @param $name * * @return void */ public function arianePush($object, $id, $name): void { array_push($this->ariane, $object . ':' . $name . ':' . $id); } /** * @return void */ public function arianePop(): void { array_pop($this->ariane); } /** * @param $value * * @return void */ public function setFilter($value = 1): void { $this->filter = $value; } /** * @param $options * * @return void */ public function setOptions($options): void { if (isset($options['filter-type'])) { $this->filter_type = $options['filter-type']; if (! is_array($options['filter-type'])) { $this->filter_type = [$options['filter-type']]; } } if (isset($options['filter-ariane'])) { $this->filter_ariane = $options['filter-ariane']; if (! is_array($options['filter-ariane'])) { $this->filter_ariane = [$options['filter-ariane']]; } } } /** * @param string $object * @param int $id * * @return void */ public function setExported(string $object, int $id): void { $this->exported[$object][$id] = 1; } /** * @param $object * @param $id * @param $name * * @return int */ public function isExported($object, $id, $name) { if ($this->filter == 0) { return 1; } if (isset($this->exported[$object][$id])) { return 1; } // check if there is some filters if ($this->checkFilter($object, $id, $name)) { return 1; } if ($this->checkAriane($object, $id, $name)) { return 1; } if (! isset($this->exported[$object]) || ! is_array($this->exported[$object])) { $this->exported[$object] = []; } $this->exported[$object][$id] = 1; return 0; } /** * @return CentreonExported */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new CentreonExported(); } return self::$instance; } /** * @param $object * @param $id * @param $name * * @return int */ private function checkAriane($object, $id, $name) { if (! is_null($this->filter_ariane)) { $ariane = join('#', $this->ariane); foreach ($this->filter_ariane as $filter) { if (preg_match('/' . $filter . '/', $ariane)) { return 0; } } return 1; } return 0; } /** * @param $object * @param $id * @param $name * * @return int */ private function checkFilter($object, $id, $name) { if (! is_null($this->filter_type)) { foreach ($this->filter_type as $filter) { if (preg_match('/' . $filter . '/', $object)) { return 0; } } return 1; } return 0; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonClapiException.class.php
centreon/www/class/centreon-clapi/centreonClapiException.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; /** * Class * * @class CentreonClapiException * @package CentreonClapi */ class CentreonClapiException extends \Exception { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/centreonInstance.class.php
centreon/www/class/centreon-clapi/centreonInstance.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi; use Centreon_Object_Instance; use Centreon_Object_Relation_Instance_Host; use Exception; use LogicException; use PDOException; use Pimple\Container; require_once 'centreonObject.class.php'; require_once 'centreon.Config.Poller.class.php'; require_once 'Centreon/Object/Instance/Instance.php'; require_once 'Centreon/Object/Host/Host.php'; require_once 'Centreon/Object/Relation/Instance/Host.php'; /** * Class * * @class CentreonInstance * @package CentreonClapi */ class CentreonInstance extends CentreonObject { public const ORDER_UNIQUENAME = 0; public const ORDER_ADDRESS = 1; public const ORDER_SSH_PORT = 2; public const ORDER_GORGONE_PROTOCOL = 3; public const ORDER_GORGONE_PORT = 4; public const GORGONE_COMMUNICATION = ['ZMQ' => '1', 'SSH' => '2']; public const INCORRECTIPADDRESS = 'Invalid IP address format'; /** @var CentreonConfigPoller */ public $centreonConfigPoller; /** * CentreonInstance constructor * * @param Container $dependencyInjector * * @throws PDOException * @throws LogicException */ public function __construct(Container $dependencyInjector) { parent::__construct($dependencyInjector); $this->object = new Centreon_Object_Instance($dependencyInjector); $this->params = [ 'localhost' => '0', 'ns_activate' => '1', 'ssh_port' => '22', 'gorgone_communication_type' => self::GORGONE_COMMUNICATION['ZMQ'], 'gorgone_port' => '5556', 'nagios_bin' => '/usr/sbin/centengine', 'nagiostats_bin' => '/usr/bin/centenginestats', 'engine_start_command' => 'service centengine start', 'engine_stop_command' => 'service centengine stop', 'engine_restart_command' => 'service centengine restart', 'engine_reload_command' => 'service centengine reload', 'broker_reload_command' => 'service cbd reload', 'centreonbroker_cfg_path' => '/etc/centreon-broker', 'centreonbroker_module_path' => '/usr/share/centreon/lib/centreon-broker', 'centreonconnector_path' => '/usr/lib64/centreon-connector', ]; $this->insertParams = ['name', 'ns_ip_address', 'ssh_port', 'gorgone_communication_type', 'gorgone_port']; $this->exportExcludedParams = array_merge( $this->insertParams, [$this->object->getPrimaryKey(), 'last_restart'] ); $this->action = 'INSTANCE'; $this->nbOfCompulsoryParams = count($this->insertParams); $this->activateField = 'ns_activate'; $this->centreonConfigPoller = new CentreonConfigPoller(_CENTREON_PATH_, $dependencyInjector); } /** * @param $parameters * @throws CentreonClapiException * @return void */ public function initInsertParameters($parameters): void { $params = explode($this->delim, $parameters); if (count($params) < $this->nbOfCompulsoryParams) { throw new CentreonClapiException(self::MISSINGPARAMETER); } $addParams = []; $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME]; $addParams['ns_ip_address'] = $params[self::ORDER_ADDRESS]; if (is_numeric($params[self::ORDER_GORGONE_PROTOCOL])) { $revertGorgoneCom = array_flip(self::GORGONE_COMMUNICATION); $params[self::ORDER_GORGONE_PROTOCOL] = $revertGorgoneCom[$params[self::ORDER_GORGONE_PROTOCOL]]; } if (isset(self::GORGONE_COMMUNICATION[strtoupper($params[self::ORDER_GORGONE_PROTOCOL])])) { $addParams['gorgone_communication_type'] = self::GORGONE_COMMUNICATION[strtoupper($params[self::ORDER_GORGONE_PROTOCOL])]; } else { throw new CentreonClapiException('Incorrect connection protocol'); } if (! is_numeric($params[self::ORDER_GORGONE_PORT]) || ! is_numeric($params[self::ORDER_SSH_PORT])) { throw new CentreonClapiException('Incorrect port parameters'); } $addParams['ssh_port'] = $params[self::ORDER_SSH_PORT]; $addParams['gorgone_port'] = $params[self::ORDER_GORGONE_PORT]; // Check IPv6, IPv4 and FQDN format if ( ! filter_var($addParams['ns_ip_address'], FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && ! filter_var($addParams['ns_ip_address'], FILTER_VALIDATE_IP) ) { throw new CentreonClapiException(self::INCORRECTIPADDRESS); } if ($addParams['ns_ip_address'] == '127.0.0.1' || strtolower($addParams['ns_ip_address']) == 'localhost') { $this->params['localhost'] = '1'; } $this->params = array_merge($this->params, $addParams); $this->checkParameters(); } /** * @param $parameters * @throws CentreonClapiException * @return array */ public function initUpdateParameters($parameters) { $params = explode($this->delim, $parameters); if (count($params) < self::NB_UPDATE_PARAMS) { throw new CentreonClapiException(self::MISSINGPARAMETER); } // Check IPv6, IPv4 and FQDN format if ( $params[1] == 'ns_ip_address' && ! filter_var($params[2], FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && ! filter_var($params[2], FILTER_VALIDATE_IP) ) { throw new CentreonClapiException(self::INCORRECTIPADDRESS); } $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]); if ($params[1] === 'gorgone_communication_type') { $params[2] = self::GORGONE_COMMUNICATION[$params[2]]; } if ($objectId != 0) { $updateParams = [$params[1] => $params[2]]; $updateParams['objectId'] = $objectId; return $updateParams; } throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]); } /** * @param null $parameters * @param array $filters * @throws Exception */ public function show($parameters = null, $filters = []): void { $filters = []; if (isset($parameters)) { $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%']; } $pollerState = $this->centreonConfigPoller->getPollerState(); $params = [ 'id', 'name', 'localhost', 'ns_ip_address', 'ns_activate', 'ns_status', 'engine_restart_command', 'engine_reload_command', 'broker_reload_command', 'nagios_bin', 'nagiostats_bin', 'ssh_port', 'gorgone_communication_type', 'gorgone_port', ]; $paramString = str_replace('_', ' ', implode($this->delim, $params)); $paramString = str_replace('ns ', '', $paramString); $paramString = str_replace('nagios ', '', $paramString); $paramString = str_replace('nagiostats', 'stats', $paramString); $paramString = str_replace('communication type', 'protocol', $paramString); echo $paramString . "\n"; $elements = $this->object->getList($params, -1, 0, null, null, $filters); foreach ($elements as $tab) { $tab['ns_status'] = $pollerState[$tab['id']] ?? '-'; $tab['gorgone_communication_type'] = array_search($tab['gorgone_communication_type'], self::GORGONE_COMMUNICATION); echo implode($this->delim, $tab) . "\n"; } } /** * Get instance Id * * @param $name * @throws CentreonClapiException * @return mixed */ public function getInstanceId($name) { $instanceIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$name]); if (! count($instanceIds)) { throw new CentreonClapiException('Unknown instance'); } return $instanceIds[0]; } /** * Get instance name * * @param int $instanceId * @return string */ public function getInstanceName($instanceId) { $instanceName = $this->object->getParameters($instanceId, [$this->object->getUniqueLabelField()]); return $instanceName[$this->object->getUniqueLabelField()]; } /** * Get hosts monitored by instance * * @param string $instanceName * * @throws Exception * @return void */ public function getHosts($instanceName): void { $relObj = new Centreon_Object_Relation_Instance_Host($this->dependencyInjector); $fields = ['host_id', 'host_name', 'host_address']; $elems = $relObj->getMergedParameters( [], $fields, -1, 0, 'host_name', 'ASC', ['name' => $instanceName], 'AND' ); echo "id;name;address\n"; foreach ($elems as $elem) { if (! preg_match('/^_Module_/', $elem['host_name'])) { echo $elem['host_id'] . $this->delim . $elem['host_name'] . $this->delim . $elem['host_address'] . "\n"; } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/Validator/RtValidator.php
centreon/www/class/centreon-clapi/Validator/RtValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi\Validator; use CentreonClapi\CentreonHost; use CentreonClapi\CentreonRtAcknowledgement; use CentreonClapi\CentreonRtDowntime; use CentreonClapi\CentreonService; use PDOException; /** * Class * * @class RtValidator * @package CentreonClapi\Validator * @description This class is used to validate inputs for RT clapi endpoints. * * @see CentreonRtAcknowledgement * @see CentreonRtDowntime */ class RtValidator { /** @var CentreonHost */ private $hostObject; /** @var CentreonService */ private $serviceObject; /** * RtValidator constructor * * @param CentreonHost $hostObject * @param CentreonService $serviceObject */ public function __construct(CentreonHost $hostObject, CentreonService $serviceObject) { $this->hostObject = $hostObject; $this->serviceObject = $serviceObject; } /** * Data storage perform an insensitive case search. We want to enforce the strictness here. * This also automatically checks the existence of the object. * * @param string $host * @param string $service * * @throws PDOException * @return bool */ public function isServiceNameValid(string $host, string $service): bool { $hostIdAndServiceId = $this->serviceObject->getHostAndServiceId($host, $service); if ($hostIdAndServiceId === []) { return false; } $realHostName = $this->hostObject->getHostName($hostIdAndServiceId[0]); $realServiceName = $this->serviceObject->getObjectName($hostIdAndServiceId[1]); return $realHostName === $host && $realServiceName === $service && $this->serviceObject->serviceExists($host, $service); } /** * Data storage perform an insensitive case search. We want to enforce the strictness here. * This also automatically checks the existence of the object. * * @param string $name * @return bool */ public function isHostNameValid(string $name): bool { $hostId = $this->hostObject->getHostID($name); $realHostName = $this->hostObject->getHostName($hostId); return $realHostName === $name; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/Repository/AclGroupRepository.php
centreon/www/class/centreon-clapi/Repository/AclGroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi\Repository; use InvalidArgumentException; use PDO; use PDOException; /** * Class * * @class AclGroupRepository * @package CentreonClapi\Repository */ class AclGroupRepository { /** * AclGroupRepository constructor * * @param PDO $db */ public function __construct(private PDO $db) { } /** * Get Acl Group Ids by their action id. * * @param int $actionId * * @throws PDOException * @return int[] */ public function getAclGroupIdsByActionId(int $actionId): array { $aclGroupIds = []; $statement = $this->db->prepare( 'SELECT DISTINCT acl_group_id FROM acl_group_actions_relations WHERE acl_action_id = :aclActionId' ); $statement->bindValue(':aclActionId', $actionId, PDO::PARAM_INT); $statement->execute(); while ($result = $statement->fetch()) { $aclGroupIds[] = (int) $result['acl_group_id']; } return $aclGroupIds; } /** * Get User ids by their acl group. * * @param array $aclGroupIds * * @throws InvalidArgumentException * @throws PDOException * @return int[] */ public function getUsersIdsByAclGroupIds(array $aclGroupIds): array { if ($aclGroupIds === []) { return []; } $queryValues = []; foreach ($aclGroupIds as $index => $aclGroupId) { $sanitizedAclGroupId = filter_var($aclGroupId, FILTER_VALIDATE_INT); if ($sanitizedAclGroupId === false) { throw new InvalidArgumentException('Invalid ID'); } $queryValues[':acl_group_id_' . $index] = $sanitizedAclGroupId; } $aclGroupIdQueryString = '(' . implode(', ', array_keys($queryValues)) . ')'; $statement = $this->db->prepare( "SELECT DISTINCT `contact_contact_id` FROM `acl_group_contacts_relations` WHERE `acl_group_id` IN {$aclGroupIdQueryString}" ); foreach ($queryValues as $bindParameter => $bindValue) { $statement->bindValue($bindParameter, $bindValue, PDO::PARAM_INT); } $statement->execute(); $userIds = []; while ($result = $statement->fetch()) { $userIds[] = (int) $result['contact_contact_id']; } return $userIds; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-clapi/Repository/SessionRepository.php
centreon/www/class/centreon-clapi/Repository/SessionRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonClapi\Repository; use PDO; use PDOException; /** * Class * * @class SessionRepository * @package CentreonClapi\Repository */ class SessionRepository { /** * @param PDO $db */ public function __construct(private PDO $db) { } /** * Flag that acl has been updated * * @param int[] $sessionIds * * @throws PDOException */ public function flagUpdateAclBySessionIds(array $sessionIds): void { $statement = $this->db->prepare("UPDATE session SET update_acl = '1' WHERE session_id = :sessionId"); foreach ($sessionIds as $sessionId) { $statement->bindValue(':sessionId', $sessionId, PDO::PARAM_STR); $statement->execute(); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/exceptions/CentreonDbException.php
centreon/www/class/exceptions/CentreonDbException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Core\Common\Domain\Exception\BusinessLogicException; /** * Class CentreonDbException * * @class CentreonDbException */ class CentreonDbException extends BusinessLogicException { /** * @param string $message * @param array $context * @param Throwable|null $previous */ public function __construct(string $message, array $context = [], ?Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_REPOSITORY, $context, $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/exceptions/StatisticException.php
centreon/www/class/exceptions/StatisticException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Core\Common\Domain\Exception\BusinessLogicException; /** * Class * * @class StatisticException */ class StatisticException extends BusinessLogicException { /** * StatisticException constructor * * @param string $message * @param array $context * @param Throwable|null $previous */ public function __construct( string $message, array $context = [], ?Throwable $previous = null, ) { parent::__construct($message, self::ERROR_CODE_INTERNAL, $context, $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-partition/options.class.php
centreon/www/class/centreon-partition/options.class.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * Class * * @class Options * @description Class that checks program options */ class Options { public const INFO = 'info'; public const DEBUG = 'debug'; public const WARNING = 'warning'; public const ERROR = 'error'; /** @var array|false|false[]|string[] */ public $options; /** @var string */ public $shortopts; /** @var string */ public $verbosity = 'info'; /** @var mixed */ public $confFile; /** @var string */ public $version = '1.1'; /** * Options constructor */ public function __construct() { $this->shortopts .= 'o:'; /** Optimize */ $this->shortopts .= 'm:'; /** Migrate Partition */ $this->shortopts .= 'c:'; /** Create table with Partition */ $this->shortopts .= 'b:'; /** Backup Partitions */ $this->shortopts .= 'p:'; /** Purge Partitions */ $this->shortopts .= 'l:'; /** List all partitions from a table */ $this->shortopts .= 's:'; /** Schema for table which table partitions will be listed */ $this->shortopts .= 'h'; /** Help */ $this->options = getopt($this->shortopts); $this->updateVerboseLevel(); } /** * get option value * * @param string $label * * @return false|mixed|string|null */ public function getOptionValue($label) { return $this->options[$label] ?? null; } /** * Check options and print help if necessary * * @return bool */ public function isMissingOptions() { if (! isset($this->options) || count($this->options) == 0) { return true; } if (isset($this->options['h'])) { return true; } return (bool) (! isset($this->options['m']) && ! isset($this->options['u']) && ! isset($this->options['c']) && ! isset($this->options['p']) && ! isset($this->options['l']) && ! isset($this->options['b']) && ! isset($this->options['o'])); } /** * Check if migration option is set * * @return bool */ public function isMigration() { if (isset($this->options['m']) && file_exists($this->options['m'])) { $this->confFile = $this->options['m']; return true; } return false; } /** * Check if partitions initialization option is set * * @return bool */ public function isCreation() { if (isset($this->options['c']) && file_exists($this->options['c'])) { $this->confFile = $this->options['c']; return true; } return false; } /** * Check if partitionned table update option is set * * @return bool */ public function isUpdate() { if (isset($this->options['u']) && file_exists($this->options['u'])) { $this->confFile = $this->options['u']; return true; } return false; } /** * Check if backup option is set * * @return bool */ public function isBackup() { if (isset($this->options['b']) && is_writable($this->options['b'])) { $this->confFile = $this->options['b']; return true; } return false; } /** * Check if optimize option is set * * @return bool */ public function isOptimize() { if (isset($this->options['o']) && is_writable($this->options['o'])) { $this->confFile = $this->options['o']; return true; } return false; } /** * Check if purge option is set * * @return bool */ public function isPurge() { if (isset($this->options['p']) && is_writable($this->options['p'])) { $this->confFile = $this->options['p']; return true; } return false; } /** * Check if parts list option is set * * @return bool */ public function isPartList() { return (bool) (isset($this->options['l']) && $this->options['l'] != '' && isset($this->options['s']) && $this->options['s'] != ''); } /** * returns verbose level of program * * @return mixed|string */ public function getVerboseLevel() { return $this->verbosity; } /** * returns centreon partitioning $confFile * * @return mixed */ public function getConfFile() { return $this->confFile; } /** * Print program usage * * @return void */ public function printHelp(): void { echo "Version: {$this->version}\n"; echo "Program options:\n"; echo " -h print program usage\n"; echo "Execution mode:\n"; echo " -c <configuration file> create tables and create partitions\n"; echo " -m <configuration file> migrate existing table to partitioned table\n"; echo " -u <configuration file> update partitionned tables with new partitions\n"; echo " -o <configuration file> optimize tables\n"; echo " -p <configuration file> purge tables\n"; echo " -b <configuration file> backup last part for each table\n"; echo " -l <table> -s <database name> List all partitions for a table.\n"; } /** * Update verbose level of program * * @return void */ private function updateVerboseLevel(): void { if (isset($this->options, $this->options['v'])) { $this->verbosity = $verbosity; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false