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/include/common/javascript/commandGetArgs/cmdGetExample.php
centreon/www/include/common/javascript/commandGetArgs/cmdGetExample.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 * */ // return argument for specific command in txt format // use by ajax require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; function myDecodeService($arg) { $arg = str_replace('#BR#', '\\n', $arg ?? ''); $arg = str_replace('#T#', '\\t', $arg); $arg = str_replace('#R#', '\\r', $arg); $arg = str_replace('#S#', '/', $arg); $arg = str_replace('#BS#', '\\', $arg); return html_entity_decode($arg, ENT_QUOTES, 'UTF-8'); } header('Content-type: text/html; charset=utf-8'); $pearDB = new CentreonDB(); if (isset($_POST['index'])) { if (is_numeric($_POST['index']) === false) { header('HTTP/1.1 406 Not Acceptable'); exit(); } $statement = $pearDB->prepare( 'SELECT `command_example` FROM `command` WHERE `command_id` = :command_id' ); $statement->bindValue(':command_id', (int) $_POST['index'], PDO::PARAM_INT); $statement->execute(); while ($arg = $statement->fetch(PDO::FETCH_ASSOC)) { echo myDecodeService($arg['command_example']); } unset($arg, $statement); $pearDB = null; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/myAccount/formMyAccount.php
centreon/www/include/Administration/myAccount/formMyAccount.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\Log\LoggerPassword; if (! isset($centreon)) { exit(); } require_once __DIR__ . '/../../../class/centreon.class.php'; require_once './include/common/common-Func.php'; require_once './class/centreonFeature.class.php'; require_once __DIR__ . '/../../../class/centreonContact.class.php'; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Path to the configuration dir $path = './include/Administration/myAccount/'; // PHP Functions require_once $path . 'DB-Func.php'; if (! isset($centreonFeature)) { $centreonFeature = new CentreonFeature($pearDB); } /** * Get the Security Policy for automatic generation password. */ $passwordSecurityPolicy = (new CentreonContact($pearDB))->getPasswordSecurityPolicy(); $encodedPasswordPolicy = json_encode($passwordSecurityPolicy); // Database retrieve information for the User $cct = []; if ($o == 'c') { $query = 'SELECT contact_id, contact_name, contact_alias, contact_lang, contact_email, contact_pager, contact_autologin_key, default_page, show_deprecated_pages, contact_auth_type, show_deprecated_custom_views FROM contact WHERE contact_id = :id'; $DBRESULT = $pearDB->prepare($query); $DBRESULT->bindValue(':id', $centreon->user->get_id(), PDO::PARAM_INT); $DBRESULT->execute(); // Set base value $cct = array_map('myDecode', $DBRESULT->fetch()); $res = $pearDB->prepare( 'SELECT cp_key, cp_value FROM contact_param WHERE cp_contact_id = :id' ); $res->bindValue(':id', $centreon->user->get_id(), PDO::PARAM_INT); $res->execute(); while ($row = $res->fetch()) { $cct[$row['cp_key']] = $row['cp_value']; } // selected by default is Resources status page $cct['default_page'] = $cct['default_page'] ?: CentreonAuth::DEFAULT_PAGE; } /* * Database retrieve information for different elements list we need on the page * * Langs -> $langs Array */ $langs = []; $langs = getLangs(); $attrsText = ['size' => '35']; $cct['contact_auth_type'] = $centreon->user->authType; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Change my settings')); $form->addElement('header', 'information', _('General Information')); if ($cct['contact_auth_type'] === 'local') { $form->addElement('text', 'contact_name', _('Name'), $attrsText); $form->addElement('text', 'contact_alias', _('Alias / Login'), $attrsText); $form->addElement('text', 'contact_email', _('Email'), $attrsText); } else { $form->addElement('text', 'contact_name', _('Name'), $attrsText)->freeze(); $form->addElement('text', 'contact_alias', _('Alias / Login'), $attrsText)->freeze(); $form->addElement('text', 'contact_email', _('Email'), $attrsText)->freeze(); } $form->addElement('text', 'contact_pager', _('Pager'), $attrsText); // Password Management if ($cct['contact_auth_type'] === 'local') { $form->addFormRule('validatePasswordModification'); $statement = $pearDB->prepare( 'SELECT creation_date FROM contact_password WHERE contact_id = :contactId ORDER BY creation_date DESC LIMIT 1' ); $statement->bindValue(':contactId', $centreon->user->get_id(), PDO::PARAM_INT); $statement->execute(); $result = $statement->fetchColumn(); if ($result) { $passwordCreationDate = (int) $result; $passwordExpirationDate = $passwordCreationDate + $passwordSecurityPolicy['password_expiration']['expiration_delay']; $isPasswordExpired = time() > $passwordExpirationDate; if (! in_array($centreon->user->get_alias(), $passwordSecurityPolicy['password_expiration']['excluded_users'])) { if ($isPasswordExpired) { $expirationMessage = _('Your password has expired. Please change it.'); } else { $expirationMessage = sprintf( _('Your password will expire in %s days.'), ceil(($passwordExpirationDate - time()) / 86400) ); } } } // Password Management $form->addElement( 'password', 'current_password', _('Current password'), [ 'size' => '30', 'autocomplete' => 'off', 'id' => 'current_password', ] ); $form->addElement( 'password', 'contact_passwd', _('Password'), ['size' => '30', 'autocomplete' => 'new-password', 'id' => 'passwd1', 'onkeypress' => 'resetPwdType(this);'] ); $form->addElement( 'password', 'contact_passwd2', _('Confirm Password'), ['size' => '30', 'autocomplete' => 'new-password', 'id' => 'passwd2', 'onkeypress' => 'resetPwdType(this);'] ); $form->addElement( 'button', 'contact_gen_passwd', _('Generate'), ['onclick' => "generatePassword('passwd', '{$encodedPasswordPolicy}');", 'class' => 'btc bt_info'] ); // Autologin Key Management $form->addElement('text', 'contact_autologin_key', _('Autologin Key'), ['size' => '30', 'id' => 'aKey']); $form->addElement( 'button', 'contact_gen_akey', _('Generate'), ['onclick' => "generatePassword('aKey', '{$encodedPasswordPolicy}');", 'class' => 'btc bt_info', 'id' => 'generateAutologinKeyButton', 'data-testid' => _('Generate')] ); } // Preferences $form->addElement('select', 'contact_lang', _('Language'), $langs); if (! isCloudPlatform()) { $form->addElement('checkbox', 'show_deprecated_pages', _('Use deprecated monitoring pages'), null, $attrsText); } $form->addElement('checkbox', 'show_deprecated_custom_views', _('Use deprecated custom views'), null, $attrsText); // ------------------------ Topology ---------------------------- $pages = []; $aclUser = $centreon->user->lcaTStr; if (! empty($aclUser)) { $acls = array_flip(explode(',', $aclUser)); /** * Transform [1, 2, 101, 202, 10101, 20201] to : * * 1 * 101 * 10101 * 2 * 202 * 20201 */ $createTopologyTree = function (array $topologies): array { ksort($topologies, \SORT_ASC); $parentsLvl = []; // Classify topologies by parents foreach (array_keys($topologies) as $page) { if (strlen($page) == 1) { // MENU level 1 if (! array_key_exists($page, $parentsLvl)) { $parentsLvl[$page] = []; } } elseif (strlen($page) == 3) { // MENU level 2 $parentLvl1 = substr($page, 0, 1); if (! array_key_exists($parentLvl1, $parentsLvl)) { $parentsLvl[$parentLvl1] = []; } if (! array_key_exists($page, $parentsLvl[$parentLvl1])) { $parentsLvl[$parentLvl1][$page] = []; } } elseif (strlen($page) == 5) { // MENU level 3 $parentLvl1 = substr($page, 0, 1); $parentLvl2 = substr($page, 0, 3); if (! array_key_exists($parentLvl1, $parentsLvl)) { $parentsLvl[$parentLvl1] = []; } if (! array_key_exists($parentLvl2, $parentsLvl[$parentLvl1])) { $parentsLvl[$parentLvl1][$parentLvl2] = []; } if (! in_array($page, $parentsLvl[$parentLvl1][$parentLvl2])) { $parentsLvl[$parentLvl1][$parentLvl2][] = $page; } } } return $parentsLvl; }; /** * Check if at least one child can be shown */ $oneChildCanBeShown = function () use (&$childrenLvl3, &$translatedPages): bool { $isCanBeShow = false; foreach ($childrenLvl3 as $topologyPage) { if ($translatedPages[$topologyPage]['show']) { $isCanBeShow = true; break; } } return $isCanBeShow; }; $topologies = $createTopologyTree($acls); /** * Retrieve the name of all topologies available for this user */ $aclResults = $pearDB->query( 'SELECT topology_page, topology_name, topology_show ' . 'FROM topology ' . "WHERE topology_page IN ({$aclUser})" ); $translatedPages = []; while ($acl = $aclResults->fetch(PDO::FETCH_ASSOC)) { $translatedPages[$acl['topology_page']] = [ 'i18n' => _($acl['topology_name']), 'show' => ((int) $acl['topology_show'] === 1), ]; } /** * Create flat tree for menu with the topologies names * [item1Id] = menu1 > submenu1 > item1 * [item2Id] = menu2 > submenu2 > item2 */ foreach ($topologies as $parentLvl1 => $childrenLvl2) { $parentNameLvl1 = $translatedPages[$parentLvl1]['i18n']; foreach ($childrenLvl2 as $parentLvl2 => $childrenLvl3) { $parentNameLvl2 = $translatedPages[$parentLvl2]['i18n']; $isThirdLevelMenu = false; $parentLvl3 = null; if ($oneChildCanBeShown()) { /** * There is at least one child that can be shown then we can * process the third level */ foreach ($childrenLvl3 as $parentLvl3) { if ($translatedPages[$parentLvl3]['show']) { $parentNameLvl3 = $translatedPages[$parentLvl3]['i18n']; if ($parentNameLvl2 === $parentNameLvl3) { /** * The name between lvl2 and lvl3 are equals. * We keep only lvl1 and lvl3 */ $pages[$parentLvl3] = $parentNameLvl1 . ' > ' . $parentNameLvl3; } else { $pages[$parentLvl3] = $parentNameLvl1 . ' > ' . $parentNameLvl2 . ' > ' . $parentNameLvl3; } } } $isThirdLevelMenu = true; } // select parent from level 2 if level 3 is missing $pageId = $parentLvl3 ?: $parentLvl2; if (! $isThirdLevelMenu && $translatedPages[$pageId]['show']) { /** * We show only first and second level */ $pages[$pageId] = $parentNameLvl1 . ' > ' . $parentNameLvl2; } } } } $form->addElement('select', 'default_page', _('Default page'), $pages); $form->addElement('checkbox', 'monitoring_host_notification_0', _('Show Up status')); $form->addElement('checkbox', 'monitoring_host_notification_1', _('Show Down status')); $form->addElement('checkbox', 'monitoring_host_notification_2', _('Show Unreachable status')); $form->addElement('checkbox', 'monitoring_svc_notification_0', _('Show OK status')); $form->addElement('checkbox', 'monitoring_svc_notification_1', _('Show Warning status')); $form->addElement('checkbox', 'monitoring_svc_notification_2', _('Show Critical status')); $form->addElement('checkbox', 'monitoring_svc_notification_3', _('Show Unknown status')); // Add feature information $features = $centreonFeature->getFeatures(); $defaultFeatures = []; foreach ($features as $feature) { $featRadio = []; $featRadio[] = $form->createElement('radio', $feature['version'], null, _('New version'), '1'); $featRadio[] = $form->createElement('radio', $feature['version'], null, _('Legacy version'), '0'); $feat = $form->addGroup($featRadio, 'features[' . $feature['name'] . ']', $feature['name'], '&nbsp;'); $defaultFeatures['features'][$feature['name']][$feature['version']] = '0'; } $sound_files = scandir(_CENTREON_PATH_ . 'www/sounds/'); $sounds = [null => null]; foreach ($sound_files as $f) { if ($f == '.' || $f == '..') { continue; } $info = pathinfo($f); $fname = basename($f, '.' . $info['extension']); $sounds[$fname] = $fname; } $form->addElement('select', 'monitoring_sound_host_notification_0', _('Sound for Up status'), $sounds); $form->addElement('select', 'monitoring_sound_host_notification_1', _('Sound for Down status'), $sounds); $form->addElement('select', 'monitoring_sound_host_notification_2', _('Sound for Unreachable status'), $sounds); $form->addElement('select', 'monitoring_sound_svc_notification_0', _('Sound for OK status'), $sounds); $form->addElement('select', 'monitoring_sound_svc_notification_1', _('Sound for Warning status'), $sounds); $form->addElement('select', 'monitoring_sound_svc_notification_2', _('Sound for Critical status'), $sounds); $form->addElement('select', 'monitoring_sound_svc_notification_3', _('Sound for Unknown status'), $sounds); $availableRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timezone&action=list'; $defaultRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timezone' . '&action=defaultValues&target=contact&field=contact_location&id=' . $centreon->user->get_id(); $attrTimezones = [ 'datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $availableRoute, 'defaultDatasetRoute' => $defaultRoute, 'multiple' => false, 'linkedObject' => 'centreonGMT', ]; $form->addElement('select2', 'contact_location', _('Timezone / Location'), [], $attrTimezones); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); function myReplace() { global $form; $ret = $form->getSubmitValues(); return str_replace(' ', '_', $ret['contact_name']); } $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('contact_name', 'myReplace'); $form->addRule('contact_name', _('Compulsory name'), 'required'); $form->addRule('contact_alias', _('Compulsory alias'), 'required'); $form->addRule('contact_email', _('Valid Email'), 'required'); if ($cct['contact_auth_type'] === 'local') { $form->addRule(['contact_passwd', 'contact_passwd2'], _('Passwords do not match'), 'compare'); } $form->registerRule('exist', 'callback', 'testExistence'); $form->addRule('contact_name', _('Name already in use'), 'exist'); $form->registerRule('existAlias', 'callback', 'testAliasExistence'); $form->addRule('contact_alias', _('Name already in use'), 'existAlias'); $form->setRequiredNote("<span style='color: red;'>*</span>" . _('Required fields')); $form->addFormRule('checkAutologinValue'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $form->setDefaults($defaultFeatures); // remove illegal chars in data sent by the user $cct['contact_name'] = CentreonUtils::escapeSecure($cct['contact_name'], CentreonUtils::ESCAPE_ILLEGAL_CHARS); $cct['contact_alias'] = CentreonUtils::escapeSecure($cct['contact_alias'], CentreonUtils::ESCAPE_ILLEGAL_CHARS); // Modify a contact information if ($o == 'c') { $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $form->setDefaults($cct); // Add saved value for feature testing $userFeatures = $centreonFeature->userFeaturesValue($centreon->user->get_id()); $defaultUserFeatures = []; foreach ($userFeatures as $feature) { $defaultUserFeatures['features'][$feature['name']][$feature['version']] = $feature['enabled']; } $form->setDefaults($defaultUserFeatures); } $sessionKeyFreeze = 'administration-form-my-account-freeze'; if ($form->validate()) { if ($cct['contact_auth_type'] === 'local') { updateContactByMyAccountInDB($centreon->user->get_id()); } else { updateNonLocalContactByMyAccountInDB($centreon->user->get_id()); } $o = null; $features = $form->getSubmitValue('features'); if ($features === null) { $features = []; } $centreonFeature->saveUserFeaturesValue($centreon->user->get_id(), $features); $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=c'", 'class' => 'btc bt_info'] ); $form->freeze(); $showDeprecatedPages = $form->getSubmitValue('show_deprecated_pages') ? '1' : '0'; $showDeprecatedCustomViews = $form->getSubmitValue('show_deprecated_custom_views') ?: '0'; if ( $form->getSubmitValue('contact_lang') !== $cct['contact_lang'] || $showDeprecatedPages !== $cct['show_deprecated_pages'] || $showDeprecatedCustomViews !== $cct['show_deprecated_custom_views'] ) { /** @var Centreon $centreon */ $centreon = $_SESSION['centreon']; $centreon->user->set_lang($form->getSubmitValue('contact_lang')); $centreon->user->setShowDeprecatedPages((bool) $showDeprecatedPages); $centreon->user->setShowDeprecatedCustomViews((bool) $showDeprecatedCustomViews); $_SESSION['centreon'] = $centreon; $_SESSION[$sessionKeyFreeze] = true; echo '<script>parent.location.href = "main.php?p=' . $p . '&o=c";</script>'; exit; } if (array_key_exists($sessionKeyFreeze, $_SESSION)) { unset($_SESSION[$sessionKeyFreeze]); } } else { if ( $form->getElementError('contact_passwd') === _('Passwords do not match') || $form->getElementError('contact_passwd2') === _('Passwords do not match') ) { LoggerPassword::create()->warning( reason: 'password confirmation does not match', initiatorId: $centreon->user->get_id(), targetId: $centreon->user->get_id(), ); } if (array_key_exists($sessionKeyFreeze, $_SESSION) && $_SESSION[$sessionKeyFreeze] === true) { unset($_SESSION[$sessionKeyFreeze]); $o = null; $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=c'", 'class' => 'btc bt_info'] ); $form->freeze(); } } // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); if (isset($expirationMessage)) { $tpl->assign('expirationMessage', $expirationMessage); } $tpl->assign('cct', $cct); $tpl->assign('o', $o); $tpl->assign('featuresFlipping', (count($features) > 0)); $tpl->assign('contactIsAdmin', $centreon->user->get_admin()); $tpl->assign('isRemote', $isRemote); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $tpl->display('formMyAccount.ihtml'); ?> <script type='text/javascript' src='./include/common/javascript/keygen.js'></script> <script type="text/javascript"> jQuery(function () { jQuery("select[name*='_notification_']").change(function () { if (jQuery(this).val()) { var snd = new buzz.sound("sounds/" + jQuery(this).val(), { formats: ["ogg", "mp3"] }); } snd.play(); }); }); </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/myAccount/help.php
centreon/www/include/Administration/myAccount/help.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 * */ $help = []; $help['contact_platform_data_sending'] = dgettext( 'help', "No: You don't consent to share your platform data. " . 'Contact Details: You consent to share your platform data including your alias and email. ' . 'Anonymized: You consent to share your platform data, but your alias and email will be anonymized.' ); $help['show_deprecated_pages'] = dgettext( 'help', 'If checked this option will restore the use of the deprecated pages.' . 'This includes display of the deprecated pages and internal redirection between pages' . 'If not checked this option will enable the full use of the new Monitoring page Resource Status' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/myAccount/DB-Func.php
centreon/www/include/Administration/myAccount/DB-Func.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\Exception\ConnectionException; use Adaptation\Database\Connection\ValueObject\QueryParameter; use Adaptation\Log\LoggerPassword; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Domain\Exception\RepositoryException; use Core\Common\Domain\Exception\ValueObjectException; require_once __DIR__ . '/../../../class/centreonContact.class.php'; require_once __DIR__ . '/../../../class/centreonAuth.class.php'; function testExistence($name = null) { global $pearDB, $centreon; $query = "SELECT contact_name, contact_id FROM contact WHERE contact_name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'"; $dbResult = $pearDB->query($query); $contact = $dbResult->fetch(); // Modif case if ($dbResult->rowCount() >= 1 && $contact['contact_id'] == $centreon->user->get_id()) { return true; } return ! ($dbResult->rowCount() >= 1 && $contact['contact_id'] != $centreon->user->get_id()); // Duplicate entry } function testAliasExistence($alias = null) { global $pearDB, $centreon; $query = 'SELECT contact_alias, contact_id FROM contact ' . "WHERE contact_alias = '" . htmlentities($alias, ENT_QUOTES, 'UTF-8') . "'"; $dbResult = $pearDB->query($query); $contact = $dbResult->fetch(); // Modif case if ($dbResult->rowCount() >= 1 && $contact['contact_id'] == $centreon->user->get_id()) { return true; } return ! ($dbResult->rowCount() >= 1 && $contact['contact_id'] != $centreon->user->get_id()); // Duplicate entry } function updateNotificationOptions($userIdConnected) { global $form, $pearDB; $pearDB->query('DELETE FROM contact_param WHERE cp_contact_id = ' . $pearDB->escape($userIdConnected) . " AND cp_key LIKE 'monitoring%notification%'"); $data = $form->getSubmitValues(); foreach ($data as $k => $v) { if (preg_match('/^monitoring_(host|svc)_notification/', $k)) { $query = 'INSERT INTO contact_param (cp_key, cp_value, cp_contact_id) ' . "VALUES ('" . $pearDB->escape($k) . "', '1', " . $pearDB->escape($userIdConnected) . ')'; $pearDB->query($query); } elseif (preg_match('/^monitoring_sound/', $k)) { $query = 'INSERT INTO contact_param (cp_key, cp_value, cp_contact_id) ' . "VALUES ('" . $pearDB->escape($k) . "', '" . $pearDB->escape($v) . "', " . $pearDB->escape($userIdConnected) . ')'; $pearDB->query($query); } } unset($_SESSION['centreon_notification_preferences']); } /** * @throws RepositoryException */ function updateContactByMyAccountInDB(mixed $userIdConnected): void { $userIdConnected = (int) $userIdConnected; if (! $userIdConnected > 0) { throw new RepositoryException( message: 'Invalid connected user ID provided to update contact from my account page for contact id ' . $userIdConnected, context: ['contact_id' => $userIdConnected] ); } updateContactByMyAccount($userIdConnected); updateNotificationOptions($userIdConnected); } /** * @throws RepositoryException */ function updateContactByMyAccount(int $userIdConnected): void { global $form, $pearDB, $centreon; if (! $userIdConnected > 0) { throw new RepositoryException( message: 'Invalid connected user ID provided to update contact from my account page for contact id ' . $userIdConnected, context: ['contact_id' => $userIdConnected] ); } $submitValues = $form->getSubmitValues(); // remove illegal chars in data sent by the user $submitValues['contact_name'] = CentreonUtils::escapeSecure($submitValues['contact_name'], CentreonUtils::ESCAPE_ILLEGAL_CHARS); $submitValues['contact_alias'] = CentreonUtils::escapeSecure($submitValues['contact_alias'], CentreonUtils::ESCAPE_ILLEGAL_CHARS); $submitValues['contact_email'] = ! empty($submitValues['contact_email']) ? CentreonUtils::escapeSecure($submitValues['contact_email'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $submitValues['contact_pager'] = ! empty($submitValues['contact_pager']) ? CentreonUtils::escapeSecure($submitValues['contact_pager'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $submitValues['contact_autologin_key'] = ! empty($submitValues['contact_autologin_key']) ? CentreonUtils::escapeSecure($submitValues['contact_autologin_key'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $submitValues['contact_lang'] = ! empty($submitValues['contact_lang']) ? CentreonUtils::escapeSecure($submitValues['contact_lang'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $rq = 'UPDATE contact SET ' . 'contact_name = :contactName, ' . 'contact_alias = :contactAlias, ' . 'contact_location = :contactLocation, ' . 'contact_lang = :contactLang, ' . 'contact_email = :contactEmail, ' . 'contact_pager = :contactPager, ' . 'default_page = :defaultPage, ' . 'show_deprecated_pages = :showDeprecatedPages, ' . 'contact_autologin_key = :contactAutologinKey, ' . 'show_deprecated_custom_views = :showDeprecatedCustomViews'; $rq .= ' WHERE contact_id = :contactId'; try { $stmt = $pearDB->prepare($rq); $stmt->bindValue(':contactName', $submitValues['contact_name'], PDO::PARAM_STR); $stmt->bindValue(':contactAlias', $submitValues['contact_alias'], PDO::PARAM_STR); $stmt->bindValue(':contactLang', $submitValues['contact_lang'], PDO::PARAM_STR); $stmt->bindValue( ':contactEmail', ! empty($submitValues['contact_email']) ? $submitValues['contact_email'] : null, PDO::PARAM_STR ); $stmt->bindValue( ':contactPager', ! empty($submitValues['contact_pager']) ? $submitValues['contact_pager'] : null, PDO::PARAM_STR ); $stmt->bindValue( ':contactAutologinKey', ! empty($submitValues['contact_autologin_key']) ? $submitValues['contact_autologin_key'] : null, PDO::PARAM_STR ); $stmt->bindValue( ':contactLocation', ! empty($submitValues['contact_location']) ? $submitValues['contact_location'] : null, PDO::PARAM_INT ); $stmt->bindValue( ':defaultPage', ! empty($submitValues['default_page']) ? $submitValues['default_page'] : null, PDO::PARAM_INT ); $stmt->bindValue(':showDeprecatedPages', isset($submitValues['show_deprecated_pages']) ? 1 : 0, PDO::PARAM_STR); $stmt->bindValue( ':showDeprecatedCustomViews', isset($submitValues['show_deprecated_custom_views']) ? '1' : '0', PDO::PARAM_STR ); $stmt->bindValue(':contactId', $userIdConnected, PDO::PARAM_INT); $stmt->execute(); } catch (PDOException $e) { throw new RepositoryException( message: 'Unable to update contact from my account for contact id ' . $userIdConnected, context: ['userIdConnected' => $userIdConnected], previous: $e ); } if (isset($submitValues['contact_passwd']) && $submitValues['contact_passwd'] !== '') { $hashedPassword = password_hash($submitValues['contact_passwd'], CentreonAuth::PASSWORD_HASH_ALGORITHM); try { $contact = new CentreonContact($pearDB); $contact->renewPasswordByContactId($userIdConnected, $hashedPassword); $centreon->user->setPasswd($hashedPassword); LoggerPassword::create()->success( initiatorId: $userIdConnected, targetId: $userIdConnected, ); } catch (PDOException $e) { LoggerPassword::create()->warning( reason: 'password update failed', initiatorId: $userIdConnected, targetId: $userIdConnected, exception: $e ); throw new RepositoryException( message: 'Unable to update password from my account for contact id ' . $userIdConnected, context: ['userIdConnected' => $userIdConnected], previous: $e ); } } // Update user object.. $centreon->user->name = $submitValues['contact_name']; $centreon->user->alias = $submitValues['contact_alias']; $centreon->user->lang = $submitValues['contact_lang']; $centreon->user->email = $submitValues['contact_email']; $centreon->user->setToken($submitValues['contact_autologin_key'] ?? "''"); } /** * @param array<string,mixed> $fields * * @throws InvalidArgumentException * * @return array<string,string>|true */ function validatePasswordModification(array $fields): array|true { global $pearDB, $centreon; $newPassword = $fields['contact_passwd']; $confirmPassword = $fields['contact_passwd2']; $currentPassword = $fields['current_password']; $userIdConnected = (int) $centreon->user->get_id(); if (! $userIdConnected > 0) { throw new InvalidArgumentException('Invalid connected user ID provided for password modification validation'); } // If the user does not want to change his password, we do not need to check it if (empty($newPassword) && empty($confirmPassword) && empty($currentPassword)) { return true; } // If the user only provided a confirmation password, he must provide a new password and a current password if (empty($newPassword) && ! empty($confirmPassword) && empty($currentPassword)) { LoggerPassword::create()->warning( reason: 'new password or current password not provided', initiatorId: $userIdConnected, targetId: $userIdConnected, ); return ['contact_passwd2' => _('Please fill in all password fields')]; } // If the user only provided his current password, he must provide a new password if (empty($newPassword) && ! empty($currentPassword)) { LoggerPassword::create()->warning( reason: 'new password not provided', initiatorId: $userIdConnected, targetId: $userIdConnected, ); return ['current_password' => _('Please fill in all password fields')]; } // If the user wants to change his password, he must provide his current password if (! empty($newPassword) && empty($currentPassword)) { LoggerPassword::create()->warning( reason: 'current password not provided', initiatorId: $userIdConnected, targetId: $userIdConnected, ); return ['current_password' => _('Please fill in all password fields')]; } // If the user provided a current password, we check if it matches the one in the database if (! empty($currentPassword) && password_verify($currentPassword, $centreon->user->passwd) === false) { LoggerPassword::create()->warning( reason: 'current password wrong', initiatorId: $userIdConnected, targetId: $userIdConnected, ); return ['current_password' => _('Authentication failed')]; } try { $contact = new CentreonContact($pearDB); $contact->respectPasswordPolicyOrFail($newPassword, $userIdConnected); return true; } catch (Exception $e) { LoggerPassword::create()->warning( reason: 'new password does not respect password policy', initiatorId: $userIdConnected, targetId: $userIdConnected, exception: $e, ); return ['contact_passwd' => $e->getMessage()]; } } /** * @param array<string,mixed> $fields * * @throws RepositoryException * @throws InvalidArgumentException * * @return array<string,string>|bool */ function checkAutologinValue(array $fields): array|true { global $pearDB, $centreon; $errors = []; if (! empty($fields['contact_autologin_key'])) { $userIdConnected = (int) $centreon->user->get_id(); if (! $userIdConnected > 0) { throw new InvalidArgumentException('Invalid connected user ID provided for autologin key check'); } $query = <<<'SQL' SELECT * FROM `contact_password` WHERE contact_id = :contactId ORDER BY creation_date DESC LIMIT 1 SQL; try { $contactPassword = $pearDB->fetchAssociative( $query, QueryParameters::create([QueryParameter::int('contactId', $userIdConnected)]) ); } catch (ValueObjectException|CollectionException|ConnectionException $e) { throw new RepositoryException( message: 'Unable to fetch contact password for contact id ' . $userIdConnected, context: ['userIdConnected' => $userIdConnected], previous: $e ); } if (password_verify($fields['contact_autologin_key'], $contactPassword['password'])) { $errors['contact_autologin_key'] = _('Your autologin key must be different than your current password'); } elseif ( ! empty($fields['contact_passwd']) && $fields['contact_passwd'] === $fields['contact_autologin_key'] ) { $errorMessage = _('Your new password and autologin key must be different'); $errors['contact_passwd'] = $errorMessage; $errors['contact_autologin_key'] = $errorMessage; LoggerPassword::create()->warning( reason: 'new password and autologin key are the same', initiatorId: $userIdConnected, targetId: $userIdConnected, ); } } return $errors !== [] ? $errors : true; } function updateNonLocalContactByMyAccountInDB($userIdConnected = null): void { global $pearDB, $centreon, $form; if (! $userIdConnected) { return; } $ret = $form->getSubmitValues(); $ret['contact_pager'] = ! empty($ret['contact_pager']) ? CentreonUtils::escapeSecure($ret['contact_pager'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $ret['contact_lang'] = ! empty($ret['contact_lang']) ? CentreonUtils::escapeSecure($ret['contact_lang'], CentreonUtils::ESCAPE_ILLEGAL_CHARS) : ''; $rq = 'UPDATE contact SET ' . 'contact_location = :contactLocation, ' . 'contact_lang = :contactLang, ' . 'contact_pager = :contactPager, ' . 'default_page = :defaultPage, ' . 'show_deprecated_pages = :showDeprecatedPages, ' . 'show_deprecated_custom_views = :showDeprecatedCustomViews'; $rq .= ' WHERE contact_id = :contactId'; $stmt = $pearDB->prepare($rq); $stmt->bindValue(':contactLang', $ret['contact_lang'], PDO::PARAM_STR); $stmt->bindValue( ':contactPager', ! empty($ret['contact_pager']) ? $ret['contact_pager'] : null, PDO::PARAM_STR ); $stmt->bindValue( ':contactLocation', ! empty($ret['contact_location']) ? $ret['contact_location'] : null, PDO::PARAM_INT ); $stmt->bindValue(':defaultPage', ! empty($ret['default_page']) ? $ret['default_page'] : null, PDO::PARAM_INT); $stmt->bindValue(':showDeprecatedPages', isset($ret['show_deprecated_pages']) ? 1 : 0, PDO::PARAM_STR); $stmt->bindValue( ':showDeprecatedCustomViews', isset($ret['show_deprecated_custom_views']) ? '1' : '0', PDO::PARAM_STR ); $stmt->bindValue(':contactId', $userIdConnected, PDO::PARAM_INT); $stmt->execute(); $stmt->closeCursor(); // Update user object.. $centreon->user->lang = $ret['contact_lang']; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/performance/viewMetrics.php
centreon/www/include/Administration/performance/viewMetrics.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 * */ if (! isset($centreon)) { exit(); } require_once './class/centreonBroker.class.php'; const DELETE_GRAPH = 'ed'; const RRD_ABSOLUTE = 'dst_a'; const RRD_COUNTER = 'dst_c'; const RRD_DERIVE = 'dst_d'; const RRD_GAUGE = 'dst_g'; const HIDE_GRAPH = 'hg'; const SHOW_GRAPH = 'nhg'; const LOCK_SERVICE = 'lk'; const UNLOCK_SERVICE = 'nlk'; $indexId = filter_var($_GET['index_id'], FILTER_VALIDATE_INT); if ((isset($_POST['o1']) && $_POST['o1']) || (isset($_POST['o2']) && $_POST['o2'])) { // filter integer keys $selected = array_filter( $_POST['select'], function ($k) { if (is_int($k)) { return $k; } }, ARRAY_FILTER_USE_KEY ); if ($_POST['o1'] == DELETE_GRAPH || $_POST['o2'] == DELETE_GRAPH) { $listMetricsId = array_keys($selected); if ($listMetricsId !== []) { $brk = new CentreonBroker($pearDB); $pearDBO->query('UPDATE metrics SET to_delete = 1 WHERE metric_id IN (' . implode(', ', $listMetricsId) . ')'); $brk->reload(); $pearDB->query('DELETE FROM ods_view_details WHERE metric_id IN (' . implode(', ', $listMetricsId) . ')'); } } elseif ($_POST['o1'] == HIDE_GRAPH || $_POST['o2'] == HIDE_GRAPH) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `hidden` = '1' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == SHOW_GRAPH || $_POST['o2'] == SHOW_GRAPH) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `hidden` = '0' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == LOCK_SERVICE || $_POST['o2'] == LOCK_SERVICE) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `locked` = '1' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == UNLOCK_SERVICE || $_POST['o2'] == UNLOCK_SERVICE) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `locked` = '0' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == RRD_GAUGE || $_POST['o2'] == RRD_GAUGE) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `data_source_type` = '0' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == RRD_COUNTER || $_POST['o2'] == RRD_COUNTER) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `data_source_type` = '1' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == RRD_DERIVE || $_POST['o2'] == RRD_DERIVE) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `data_source_type` = '2' WHERE `metric_id` = " . (int) $id); } } elseif ($_POST['o1'] == RRD_ABSOLUTE || $_POST['o2'] == RRD_ABSOLUTE) { foreach (array_keys($selected) as $id) { $pearDBO->query("UPDATE metrics SET `data_source_type` = '3' WHERE `metric_id` = " . (int) $id); } } } $query = 'SELECT COUNT(*) FROM metrics WHERE to_delete = 0 AND index_id = :indexId'; $stmt = $pearDBO->prepare($query); $stmt->bindParam(':indexId', $indexId, PDO::PARAM_INT); $stmt->execute(); $tmp = $stmt->fetch(PDO::FETCH_ASSOC); $rows = $tmp['COUNT(*)']; $tab_class = ['0' => 'list_one', '1' => 'list_two']; $storage_type = [0 => 'RRDTool', 2 => 'RRDTool & MySQL']; $yesOrNo = [null => 'No', 0 => 'No', 1 => 'Yes', 2 => 'Rebuilding']; $rrd_dst = [0 => 'GAUGE', 1 => 'COUNTER', 2 => 'DERIVE', 3 => 'ABSOLUTE']; $query = 'SELECT * FROM metrics WHERE to_delete = 0 AND index_id = :indexId ORDER BY metric_name'; $stmt2 = $pearDBO->prepare($query); $stmt2->bindParam(':indexId', $indexId, PDO::PARAM_INT); $stmt2->execute(); unset($data); for ($im = 0; $metrics = $stmt2->fetch(PDO::FETCH_ASSOC); $im++) { $metric = []; $metric['metric_id'] = $metrics['metric_id']; $metric['class'] = $tab_class[$im % 2]; $metric['metric_name'] = str_replace('#S#', '/', $metrics['metric_name']); $metric['metric_name'] = str_replace('#BS#', '\\', $metric['metric_name']); $metric['unit_name'] = $metrics['unit_name']; if (! isset($metrics['data_source_type']) || isset($metrics['data_source_type']) && $metrics['data_source_type'] == null ) { $metric['data_source_type'] = $rrd_dst['0']; } else { $metric['data_source_type'] = $rrd_dst[$metrics['data_source_type']]; } $metric['hidden'] = $yesOrNo[$metrics['hidden']]; $metric['locked'] = $yesOrNo[$metrics['locked']]; $metric['min'] = $metrics['min']; $metric['max'] = $metrics['max']; $metric['warn'] = $metrics['warn']; $metric['crit'] = $metrics['crit']; $metric['path'] = _CENTREON_VARLIB_ . '/metrics/' . $metric['metric_id'] . '.rrd'; $data[$im] = $metric; unset($metric); } include_once './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p); // Toolbar select ?> <script type="text/javascript"> var confirm_messages = [ '<?php echo _('Do you confirm the deletion ?'); ?>', '<?php echo _('Do you confirm the change of the RRD data source type ? ' . 'If yes, you must rebuild the RRD Database'); ?>', '<?php echo _('Do you confirm the change of the RRD data source type ? ' . 'If yes, you must rebuild the RRD Database'); ?>', '<?php echo _('Do you confirm the change of the RRD data source type ? ' . 'If yes, you must rebuild the RRD Database'); ?>', '<?php echo _('Do you confirm the change of the RRD data source type ? ' . 'If yes, you must rebuild the RRD Database'); ?>' ]; function setO(_i) { document.forms['form'].elements['o'].value = _i; } function on_action_change(id) { var selected_id = this.form.elements[id].selectedIndex - 1; if (selected_id in confirm_messages && !confirm(confirm_messages[selected_id])) { return; } setO(this.form.elements[id].value); document.forms['form'].submit(); } </script> <?php $actions = [null => _('More actions...'), 'ed' => _('Delete graphs'), 'dst_a' => _('Set RRD Data Source Type to ABSOLUTE'), 'dst_c' => _('Set RRD Data Source Type to COUNTER'), 'dst_d' => _('Set RRD Data Source Type to DERIVE'), 'dst_g' => _('Set RRD Data Source Type to GAUGE'), 'hg' => _('Hide graphs of selected Services'), 'nhg' => _('Stop hiding graphs of selected Services'), 'lk' => _('Lock Services'), 'nlk' => _('Unlock Services')]; $form->addElement('select', 'o1', null, $actions, ['onchange' => "javascript:on_action_change('o1')"]); $form->setDefaults(['o1' => null]); $form->addElement('select', 'o2', null, $actions, ['onchange' => "javascript:on_action_change('o2')"]); $form->setDefaults(['o2' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $o1->setSelected(null); $o2 = $form->getElement('o2'); $o2->setValue(null); $o2->setSelected(null); $tpl->assign('limit', $limit); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('Metric', _('Metric')); $tpl->assign('Unit', _('Unit')); $tpl->assign('Warning', _('Warning')); $tpl->assign('Critical', _('Critical')); $tpl->assign('Min', _('Min')); $tpl->assign('Max', _('Max')); $tpl->assign('NumberOfValues', _('Number of values')); $tpl->assign('DataSourceType', _('Data source type')); $tpl->assign('Hidden', _('Hidden')); $tpl->assign('Locked', _('Locked')); $tpl->assign('data', $data); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('viewMetrics.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/performance/viewData.php
centreon/www/include/Administration/performance/viewData.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 * */ if (! isset($centreon)) { exit(); } require_once './class/centreonDuration.class.php'; require_once './class/centreonBroker.class.php'; include_once './include/monitoring/common-Func.php'; // Path to the option dir $path = './include/Administration/performance/'; // Set URL for search $url = 'viewData.php'; // PHP functions require_once './include/Administration/parameters/DB-Func.php'; require_once './include/common/common-Func.php'; require_once './class/centreonDB.class.php'; include './include/common/autoNumLimit.php'; const REBUILD_RRD = 'rg'; const STOP_REBUILD_RRD = 'nrg'; const DELETE_GRAPH = 'ed'; const HIDE_GRAPH = 'hg'; const SHOW_GRAPH = 'nhg'; const LOCK_SERVICE = 'lk'; const UNLOCK_SERVICE = 'nlk'; // Prepare search engine $inputGet = ['Search' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['Search'] ?? ''), 'searchH' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['searchH'] ?? ''), 'num' => filter_input(INPUT_GET, 'num', FILTER_SANITIZE_NUMBER_INT), 'limit' => filter_input(INPUT_GET, 'limit', FILTER_SANITIZE_NUMBER_INT), 'searchS' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['searchS'] ?? ''), 'searchP' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['searchP'] ?? ''), 'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o'] ?? ''), 'o1' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o1'] ?? ''), 'o2' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o2'] ?? ''), 'select' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['select'] ?? ''), 'id' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['id'] ?? '')]; $sanitizedPostSelect = []; if (isset($_POST['select']) && is_array($_POST['select'])) { foreach ($_POST['select'] as $key => $value) { $sanitizedPostSelect[$key] = HtmlAnalyzer::sanitizeAndRemoveTags($value); } } $inputPost = ['Search' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['Search'] ?? ''), 'searchH' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchH'] ?? ''), 'num' => filter_input(INPUT_POST, 'num', FILTER_SANITIZE_NUMBER_INT), 'limit' => filter_input(INPUT_POST, 'limit', FILTER_SANITIZE_NUMBER_INT), 'searchS' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchS'] ?? ''), 'searchP' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchP'] ?? ''), 'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['o'] ?? ''), 'o1' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['o1'] ?? ''), 'o2' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['o2'] ?? ''), 'select' => $sanitizedPostSelect, 'id' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['id'] ?? '')]; $inputs = []; foreach ($inputGet as $argumentName => $argumentValue) { if ( ! empty($inputPost[$argumentName]) && ( (is_array($inputPost[$argumentName]) && $inputPost[$argumentName]) || (! is_array($inputPost[$argumentName]) && trim($inputPost[$argumentName]) != '') ) ) { $inputs[$argumentName] = $inputPost[$argumentName]; } else { $inputs[$argumentName] = $inputGet[$argumentName]; } } $searchS = null; $searchH = null; $searchP = null; if (isset($inputs['Search']) && $inputs['Search'] !== '') { $centreon->historySearch[$url] = []; $searchH = $inputs['searchH']; $centreon->historySearch[$url]['searchH'] = $searchH; $searchS = $inputs['searchS']; $centreon->historySearch[$url]['searchS'] = $searchS; $searchP = $inputs['searchP']; $centreon->historySearch[$url]['searchP'] = $searchP; } else { if (isset($centreon->historySearch[$url]['searchH'])) { $searchH = $centreon->historySearch[$url]['searchH']; } if (isset($centreon->historySearch[$url]['searchS'])) { $searchS = $centreon->historySearch[$url]['searchS']; } if (isset($centreon->historySearch[$url]['searchP'])) { $searchP = $centreon->historySearch[$url]['searchP']; } } // Get broker type $brk = new CentreonBroker($pearDB); if ((isset($inputs['o1']) && $inputs['o1']) || (isset($inputs['o2']) && $inputs['o2'])) { // filter integer keys $selected = array_filter( $inputs['select'], function ($k) { if (is_int($k)) { return $k; } }, ARRAY_FILTER_USE_KEY ); if ($inputs['o'] == REBUILD_RRD && $selected !== []) { foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query("UPDATE index_data SET `must_be_rebuild` = '1' WHERE id = " . $id); } $brk->reload(); } elseif ($inputs['o'] == STOP_REBUILD_RRD && $selected !== []) { foreach (array_keys($selected) as $id) { $query = "UPDATE index_data SET `must_be_rebuild` = '0' WHERE `must_be_rebuild` = '1' AND id = " . $id; $pearDBO->query($query); } } elseif ($inputs['o'] == DELETE_GRAPH && $selected !== []) { $listMetricsToDelete = []; foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query('SELECT metric_id FROM metrics WHERE `index_id` = ' . $id); while ($metrics = $DBRESULT->fetchRow()) { $listMetricsToDelete[] = $metrics['metric_id']; } } $listMetricsToDelete = array_unique($listMetricsToDelete); if ($listMetricsToDelete !== []) { $query = 'UPDATE metrics SET to_delete = 1 WHERE metric_id IN (' . implode(', ', $listMetricsToDelete) . ')'; $pearDBO->query($query); $query = 'UPDATE index_data SET to_delete = 1 WHERE id IN (' . implode(', ', array_keys($selected)) . ')'; $pearDBO->query($query); $query = 'DELETE FROM ods_view_details WHERE metric_id IN (' . implode(', ', $listMetricsToDelete) . ')'; $pearDB->query($query); $brk->reload(); } } elseif ($inputs['o'] == HIDE_GRAPH && $selected !== []) { foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query("UPDATE index_data SET `hidden` = '1' WHERE id = " . $id); } } elseif ($inputs['o'] == SHOW_GRAPH && $selected !== []) { foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query("UPDATE index_data SET `hidden` = '0' WHERE id = " . $id); } } elseif ($inputs['o'] == LOCK_SERVICE && $selected !== []) { foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query("UPDATE index_data SET `locked` = '1' WHERE id = " . $id); } } elseif ($inputs['o'] == UNLOCK_SERVICE && $selected !== []) { foreach (array_keys($selected) as $id) { $DBRESULT = $pearDBO->query("UPDATE index_data SET `locked` = '0' WHERE id = " . $id); } } } if (isset($inputs['o']) && $inputs['o'] == 'd' && isset($inputs['id'])) { $query = "UPDATE index_data SET `trashed` = '1' WHERE id = '" . htmlentities($inputs['id'], ENT_QUOTES, 'UTF-8') . "'"; $pearDBO->query($query); } if (isset($inputs['o']) && $inputs['o'] == 'rb' && isset($inputs['id'])) { $query = "UPDATE index_data SET `must_be_rebuild` = '1' WHERE id = '" . htmlentities($inputs['id'], ENT_QUOTES, 'UTF-8') . "'"; $pearDBO->query($query); } $search_string = ''; $extTables = ''; $queryParams = []; if ($searchH != '' || $searchS != '' || $searchP != '') { if ($searchH != '') { $search_string .= ' AND i.host_name LIKE :searchH '; $queryParams[':searchH'] = '%' . htmlentities($searchH, ENT_QUOTES, 'UTF-8') . '%'; } if ($searchS != '') { $search_string .= ' AND s.display_name LIKE :searchS '; $queryParams[':searchS'] = '%' . htmlentities($searchS, ENT_QUOTES, 'UTF-8') . '%'; } if ($searchP != '') { // Centron Broker $extTables = 'JOIN hosts h ON h.host_id = i.host_id'; $search_string .= ' AND i.host_id = h.host_id AND h.instance_id = :searchP '; $queryParams[':searchP'] = $searchP; } } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $storage_type = [0 => 'RRDTool', 2 => 'RRDTool & MySQL']; $yesOrNo = [0 => 'No', 1 => 'Yes', 2 => 'Rebuilding']; $data = []; $query = <<<SQL SELECT SQL_CALC_FOUND_ROWS DISTINCT i.* , s.display_name FROM index_data i JOIN services s ON i.service_id = s.service_id JOIN metrics m ON i.id = m.index_id {$extTables} WHERE i.id = m.index_id {$search_string} ORDER BY host_name, display_name LIMIT :offset, :limit SQL; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':offset', $num * $limit, PDO::PARAM_INT); $stmt->bindValue(':limit', $limit, PDO::PARAM_INT); // loop and inject search values into queries foreach ($queryParams as $param => $value) { $stmt->bindValue($param, $value, PDO::PARAM_STR); } $stmt->execute(); $stmt2 = $pearDBO->query('SELECT FOUND_ROWS()'); $rows = $stmt2->fetchColumn(); $query = 'SELECT * FROM metrics WHERE index_id = :indexId ORDER BY metric_name'; $stmt2 = $pearDBO->prepare($query); for ($i = 0; $indexData = $stmt->fetch(PDO::FETCH_ASSOC); $i++) { $stmt2->bindValue(':indexId', $indexData['id'], PDO::PARAM_INT); $stmt2->execute(); $metric = ''; for ($im = 0; $metrics = $stmt2->fetch(PDO::FETCH_ASSOC); $im++) { if ($im) { $metric .= ' - '; } $metric .= $metrics['metric_name']; if (isset($metrics['unit_name']) && $metrics['unit_name']) { $metric .= '(' . $metrics['unit_name'] . ')'; } } $indexData['metrics_name'] = $metric; $indexData['service_description'] = "<a href='./main.php?p=50119&o=msvc&index_id=" . $indexData['id'] . "'>" . $indexData['display_name'] . '</a>'; $indexData['storage_type'] = $storage_type[$indexData['storage_type']]; $indexData['must_be_rebuild'] = $yesOrNo[$indexData['must_be_rebuild']]; $indexData['to_delete'] = $yesOrNo[$indexData['to_delete']]; $indexData['trashed'] = $yesOrNo[$indexData['trashed']]; $indexData['hidden'] = $yesOrNo[$indexData['hidden']]; $indexData['locked'] = isset($indexData['locked']) ? $yesOrNo[$indexData['locked']] : $yesOrNo[0]; $indexData['class'] = $tab_class[$i % 2]; $data[$i] = $indexData; } // select2 Poller $poller = $searchP ?? ''; $pollerRoute = './api/internal.php?object=centreon_configuration_poller&action=list'; $attrPoller = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $pollerRoute, 'multiple' => false, 'defaultDataset' => $poller, 'linkedObject' => 'centreonInstance']; include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p); $form->addElement('select2', 'searchP', '', [], $attrPoller); $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['o'].value = _i; } </script> <?php $attrs1 = ['onchange' => 'javascript: ' . "if (this.form.elements['o1'].selectedIndex == 1) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 2) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 3 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 4) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 5) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 6) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 7) {" . " setO(this.form.elements['o1'].value); submit();} " . '']; $form->addElement('select', 'o1', null, [null => _('More actions...'), 'rg' => _('Rebuild RRD Database'), 'nrg' => _('Stop rebuilding RRD Databases'), 'ed' => _('Delete graphs'), 'hg' => _('Hide graphs of selected Services'), 'nhg' => _('Stop hiding graphs of selected Services'), 'lk' => _('Lock Services'), 'nlk' => _('Unlock Services')], $attrs1); $form->setDefaults(['o1' => null]); $attrs2 = ['onchange' => 'javascript: ' . "if (this.form.elements['o2'].selectedIndex == 1) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 2) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 3 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 4) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 5) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 6) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 7) {" . " setO(this.form.elements['o2'].value); submit();} " . '']; $form->addElement('select', 'o2', null, [null => _('More actions...'), 'rg' => _('Rebuild RRD Database'), 'nrg' => _('Stop rebuilding RRD Databases'), 'ed' => _('Delete graphs'), 'hg' => _('Hide graphs of selected Services'), 'nhg' => _('Stop hiding graphs of selected Services'), 'lk' => _('Lock Services'), 'nlk' => _('Unlock Services')], $attrs2); $form->setDefaults(['o2' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $o1->setSelected(null); $o2 = $form->getElement('o2'); $o2->setValue(null); $o2->setSelected(null); $tpl->assign('limit', $limit); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('data', $data); if (isset($instances)) { $tpl->assign('instances', $instances); } $tpl->assign('Host', _('Host')); $tpl->assign('Service', _('Service')); $tpl->assign('Metrics', _('Metrics')); $tpl->assign('RebuildWaiting', _('Rebuild Waiting')); $tpl->assign('Delete', _('Delete')); $tpl->assign('Hidden', _('Hidden')); $tpl->assign('Locked', _('Locked')); $tpl->assign('StorageType', _('Storage Type')); $tpl->assign('Actions', _('Actions')); $tpl->assign('Services', _('Services')); $tpl->assign('Hosts', _('Hosts')); $tpl->assign('Pollers', _('Pollers')); $tpl->assign('Search', _('Search')); if (isset($searchH)) { $tpl->assign('searchH', $searchH); } if (isset($searchS)) { $tpl->assign('searchS', $searchS); } $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('viewData.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/performance/DB-Func.php
centreon/www/include/Administration/performance/DB-Func.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 * */ if (! isset($oreon)) { exit(); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/performance/manageData.php
centreon/www/include/Administration/performance/manageData.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 * */ if (! isset($centreon)) { exit(); } include './include/common/autoNumLimit.php'; require_once './class/centreonDuration.class.php'; include_once './include/monitoring/common-Func.php'; // Path to the option dir $path = './include/Administration/performance/'; // PHP functions require_once './include/Administration/parameters/DB-Func.php'; require_once './include/common/common-Func.php'; require_once './class/centreonDB.class.php'; $pearDBO = new CentreonDB('centstorage'); switch ($o) { case 'msvc': require_once $path . 'viewMetrics.php'; break; default: require_once $path . 'viewData.php'; break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/corePerformance/nagiosStats.php
centreon/www/include/Administration/corePerformance/nagiosStats.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 * */ if (! isset($oreon)) { exit(); } require_once './include/monitoring/common-Func.php'; unset($tpl, $path); // Time period select $form = new HTML_QuickFormCustom('form', 'post', '?p=' . $p); // Get Poller List $pollerList = []; $defaultPoller = []; $DBRESULT = $pearDB->query('SELECT * FROM `nagios_server` WHERE `ns_activate` = 1 ORDER BY `name`'); while ($data = $DBRESULT->fetchRow()) { if (isset($_POST['pollers']) && $_POST['pollers'] != '') { if ($_POST['pollers'] == $data['id']) { $defaultPoller[$data['name']] = $data['id']; $pollerId = $data['id']; } } elseif ($data['localhost']) { $defaultPoller[$data['name']] = $data['id']; $pollerId = $data['id']; } } $DBRESULT->closeCursor(); $selectedPoller = isset($_POST['pollers']) && $_POST['pollers'] != '' ? $_POST['pollers'] : $defaultPoller; $attrPollers = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => './include/common/webServices/rest/internal.php?object=centreon_monitoring_poller&action=list', 'multiple' => false, 'defaultDataset' => $defaultPoller, 'linkedObject' => 'centreonInstance']; $form->addElement('select2', 'pollers', _('Poller'), [], $attrPollers); // Get Period $time_period = ['last3hours' => _('Last 3 hours'), 'today' => _('Today'), 'yesterday' => _('Yesterday'), 'last4days' => _('Last 4 days'), 'lastweek' => _('Last week'), 'lastmonth' => _('Last month'), 'last6month' => _('Last 6 months'), 'lastyear' => _('Last year')]; $defaultPeriod = []; $currentPeriod = ''; if (isset($_POST['start']) && ($_POST != '')) { $defaultPeriod[$time_period[$_POST['start']]] = $_POST['start']; $currentPeriod .= $_POST['start']; } else { $defaultPeriod[$time_period['today']] = 'today'; $currentPeriod .= 'today'; } switch ($currentPeriod) { case 'last3hours': $start = time() - (60 * 60 * 3); break; case 'today': $start = time() - (60 * 60 * 24); break; case 'yesterday': $start = time() - (60 * 60 * 48); break; case 'last4days': $start = time() - (60 * 60 * 96); break; case 'lastweek': $start = time() - (60 * 60 * 168); break; case 'lastmonth': $start = time() - (60 * 60 * 24 * 30); break; case 'last6month': $start = time() - (60 * 60 * 24 * 30 * 6); break; case 'lastyear': $start = time() - (60 * 60 * 24 * 30 * 12); break; } // Get end values $end = time(); $periodSelect = ['allowClear' => false, 'multiple' => false, 'defaultDataset' => $defaultPeriod]; $selTP = $form->addElement('select2', 'start', _('Period'), $time_period, $periodSelect); $options = ['active_host_check' => 'nagios_active_host_execution.rrd', 'active_service_check' => 'nagios_active_service_execution.rrd', 'active_host_last' => 'nagios_active_host_last.rrd', 'active_service_last' => 'nagios_active_service_last.rrd', 'host_latency' => 'nagios_active_host_latency.rrd', 'service_latency' => 'nagios_active_service_latency.rrd', 'host_states' => 'nagios_hosts_states.rrd', 'service_states' => 'nagios_services_states.rrd', 'cmd_buffer' => 'nagios_cmd_buffer.rrd']; $title = ['active_host_check' => _('Host Check Execution Time'), 'active_host_last' => _('Hosts Actively Checked'), 'host_latency' => _('Host check latency'), 'active_service_check' => _('Service Check Execution Time'), 'active_service_last' => _('Services Actively Checked'), 'service_latency' => _('Service check latency'), 'cmd_buffer' => _('Commands in buffer'), 'host_states' => _('Host status'), 'service_states' => _('Service status')]; $path = './include/Administration/corePerformance/'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, './'); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); // Assign values $tpl->assign('form', $renderer->toArray()); if (isset($_POST['start'])) { $tpl->assign('startPeriod', $_POST['start']); } else { $tpl->assign('startPeriod', 'today'); } if (isset($host_list) && $host_list) { $tpl->assign('host_list', $host_list); } if (isset($tab_server) && $tab_server) { $tpl->assign('tab_server', $tab_server); } $tpl->assign('p', $p); if (isset($pollerName)) { $tpl->assign('pollerName', $pollerName); } $tpl->assign('options', $options); $tpl->assign('startTime', $start); $tpl->assign('endTime', $end); $tpl->assign('pollerId', $pollerId); $tpl->assign('title', $title); $tpl->assign('session_id', session_id()); $tpl->display('nagiosStats.html');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/brokerPerformance/brokerPerformance.php
centreon/www/include/Administration/brokerPerformance/brokerPerformance.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 * */ if (! isset($centreon)) { exit(); } require_once './include/monitoring/common-Func.php'; require_once './class/centreonDB.class.php'; require_once './class/centreonGMT.class.php'; require_once realpath(__DIR__ . '/../../../../config/centreon.config.php'); function createArrayStats($arrayFromJson) { $io = ['class' => 'stats_lv1']; if (isset($arrayFromJson['state'])) { $io[_('State')]['value'] = $arrayFromJson['state']; if ($arrayFromJson['state'] == 'disconnected') { $io[_('State')]['class'] = 'badge service_critical'; } elseif ( $arrayFromJson['state'] == 'listening' || $arrayFromJson['state'] == 'connected' || $arrayFromJson['state'] == 'connecting' ) { $io[_('State')]['class'] = 'badge service_ok'; } elseif ($arrayFromJson['state'] == 'sleeping' || $arrayFromJson['state'] == 'blocked') { $io[_('State')]['class'] = 'badge service_warning'; } } if (isset($arrayFromJson['status']) && $arrayFromJson['status']) { $io[_('Status')] = ['value' => $arrayFromJson['status'], 'isTimestamp' => false]; } if (isset($arrayFromJson['last_event_at']) && $arrayFromJson['last_event_at'] != -1) { $io[_('Last event at')] = ['value' => $arrayFromJson['last_event_at'], 'isTimestamp' => true]; } if (isset($arrayFromJson['last_connection_attempt']) && $arrayFromJson['last_connection_attempt'] != -1) { $io[_('Last connection attempt')] = ['value' => $arrayFromJson['last_connection_attempt'], 'isTimestamp' => true]; } if (isset($arrayFromJson['last_connection_success']) && $arrayFromJson['last_connection_success'] != -1) { $io[_('Last connection success')] = ['value' => $arrayFromJson['last_connection_success'], 'isTimestamp' => true]; } if (isset($arrayFromJson['one_peer_retention_mode'])) { $io[_('One peer retention mode')] = ['value' => $arrayFromJson['one_peer_retention_mode'], 'isTimestamp' => false]; } if (isset($arrayFromJson['event_processing_speed'])) { $io[_('Event processing speed')] = ['value' => sprintf('%.2f events/s', $arrayFromJson['event_processing_speed']), 'isTimestamp' => false]; } if ( isset($arrayFromJson['queue file'], $arrayFromJson['queue file enabled']) && $arrayFromJson['queue file enabled'] != 'no' ) { $io[_('Queue file')] = ['value' => $arrayFromJson['queue file'], 'isTimestamp' => false]; } if (isset($arrayFromJson['queue file enabled'])) { $io[_('Queued file enabled')] = ['value' => $arrayFromJson['queue file enabled'], 'isTimestamp' => false]; } if (isset($arrayFromJson['queued_events'])) { $io[_('Queued events')] = ['value' => $arrayFromJson['queued_events'], 'isTimestamp' => false]; } if (isset($arrayFromJson['memory file'])) { $io[_('Memory file')] = ['value' => $arrayFromJson['memory file'], 'isTimestamp' => false]; } if (isset($arrayFromJson['read_filters']) && $arrayFromJson['read_filters']) { if ($arrayFromJson['read_filters'] != 'all') { $io[_('Input accepted events type')] = ['value' => substr($arrayFromJson['read_filters'], 22), 'isTimestamp' => false]; } else { $io[_('Input accepted events type')] = ['value' => $arrayFromJson['read_filters'], 'isTimestamp' => false]; } } if (isset($arrayFromJson['write_filters']) && $arrayFromJson['write_filters']) { if ($arrayFromJson['write_filters'] != 'all') { $io[_('Output accepted events type')] = ['value' => substr($arrayFromJson['write_filters'], 2), 'isTimestamp' => false]; } else { $io[_('Output accepted events type')] = ['value' => $arrayFromJson['write_filters'], 'isTimestamp' => false]; } } return $io; } function parseStatsFile($statfile) { // handle path traversal vulnerability if (str_contains($statfile, '..')) { throw new Exception('Path traversal found'); } $jsonc_content = file_get_contents($statfile); $json_stats = json_decode($jsonc_content, true); $lastmodif = $json_stats['now']; $result = ['lastmodif' => $lastmodif, 'modules' => [], 'io' => []]; foreach ($json_stats as $key => $value) { if (preg_match('/endpoint \(?(.*[^()])\)?/', $key, $matches)) { if (preg_match('/.*external commands.*/', $matches[1])) { $matches[1] = 'external-commands'; } if ( (preg_match('/.*external commands.*/', $key) && $json_stats[$key]['state'] != 'disconnected') || ! preg_match('/.*external commands.*/', $key) ) { $keySepByDash = explode('-', $key); $keySepBySpace = explode(' ', $key); $result['io'][$matches[1]] = createArrayStats($json_stats[$key]); $result['io'][$matches[1]]['type'] = end($keySepByDash); $result['io'][$matches[1]]['id'] = end($keySepBySpace); $result['io'][$matches[1]]['id'] = rtrim($result['io'][$matches[1]]['id'], ')'); // force type of io if (preg_match('/.*external commands.*/', $key)) { $result['io'][$matches[1]]['type'] = 'input'; } elseif ( preg_match( '/.*(central-broker-master-sql|centreon-broker-master-rrd' . '|central-broker-master-perfdata|central-broker-master-unified-sql).*/', $key ) ) { $result['io'][$matches[1]]['type'] = 'output'; } elseif (preg_match('/.*(centreon-bam-monitoring|centreon-bam-reporting).*/', $key)) { $result['io'][$matches[1]]['type'] = 'output'; } // manage failover output if (isset($json_stats[$key]['failover'])) { $result['io'][$matches[1] . '-failover'] = createArrayStats($json_stats[$key]['failover']); $result['io'][$matches[1] . '-failover']['type'] = 'output'; $result['io'][$matches[1] . '-failover']['class'] = 'stats_lv2'; $result['io'][$matches[1] . '-failover']['id'] = $matches[1] . '-failover'; } // manage peers input if (isset($json_stats[$key]['peers'])) { $arrayPeers = explode(',', $json_stats[$key]['peers']); $counter = count($arrayPeers); for ($i = 1; $i < $counter; $i++) { $peerName = trim($arrayPeers[$i]); $id = str_replace(':', '_', $peerName); $id = str_replace('.', '_', $id); $result['io'][$matches[1]]['peers'][$i] = $peerName; $result['io'][$peerName] = createArrayStats($json_stats[$key][$matches[1] . '-' . $i]); $result['io'][$peerName]['type'] = 'input'; $result['io'][$peerName]['class'] = 'stats_lv2'; $result['io'][$peerName]['id'] = $id . '-peers'; } } } } // Create list of loaded modules if (preg_match('/module\s*\/.*\/\d+\-(.*)\.so/', $key, $matches)) { $result['modules'][$matches[1]] = $json_stats[$key]['state']; } } return $result; } // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); $form = new HTML_QuickFormCustom('form', 'post', '?p=' . $p); // Get Poller List $pollerList = []; $DBRESULT = $pearDB->query('SELECT * FROM `nagios_server` WHERE `ns_activate` = 1 ORDER BY `name`'); while ($data = $DBRESULT->fetchRow()) { if ($data['localhost']) { $defaultPoller = $data['id']; } $pollerList[$data['id']] = HtmlSanitizer::createFromString($data['name'])->sanitize()->getString(); } $DBRESULT->closeCursor(); // Get poller ID $selectedPoller = isset($_POST['pollers']) && $_POST['pollers'] != '' ? $_POST['pollers'] : $defaultPoller; if (! isset($selectedPoller)) { $tmpKeys = array_keys($pollerList); $selectedPoller = $tmpKeys[0]; unset($tmpKeys); } $form->addElement('select', 'pollers', _('Poller'), $pollerList, ['onChange' => 'this.form.submit();']); $form->setDefaults(['pollers' => $selectedPoller]); $pollerName = $pollerList[$selectedPoller]; $path = './include/Administration/brokerPerformance/'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, './'); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); // Message $lang = []; $lang['modules'] = _('Modules'); $lang['updated'] = _('Last update'); $lang['peers'] = _('Peers'); $lang['input'] = _('Input'); $lang['output'] = _('Output'); $tpl->assign('lang', $lang); $tpl->assign('poller_name', $pollerName); // Get the stats file name $queryStatName = 'SELECT config_name, cache_directory ' . 'FROM cfg_centreonbroker ' . "WHERE stats_activate = '1' " . 'AND ns_nagios_server = :id'; try { $stmt = $pearDB->prepare($queryStatName); $stmt->bindParam(':id', $selectedPoller, PDO::PARAM_INT); $stmt->execute(); if (! $stmt->rowCount()) { $tpl->assign('msg_err', _('No statistics file defined for this poller')); } $perf_info = []; $perf_err = []; while ($row = $stmt->fetch()) { $statsfile = $row['cache_directory'] . '/' . basename($row['config_name']) . '-stats.json'; if ($defaultPoller != $selectedPoller) { $statsfile = _CENTREON_CACHEDIR_ . '/broker-stats/' . $selectedPoller . '/' . $row['config_name'] . '.json'; } /** * check if file exists, is readable and inside proper folder */ if ( ! file_exists($statsfile) || ! is_readable($statsfile) || ((! str_starts_with(realpath($statsfile), _CENTREON_VARLIB_)) && (! str_starts_with(realpath($statsfile), _CENTREON_CACHEDIR_))) ) { $perf_err[$row['config_name']] = _('Cannot open statistics file'); } else { $perf_info[$row['config_name']] = parseStatsFile($statsfile); } } $tpl->assign('perf_err', $perf_err); $tpl->assign('perf_info_array', $perf_info); } catch (PDOException $e) { $tpl->assign('msg_err', _('Error in getting stats filename')); } $tpl->display('brokerPerformance.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/configChangelog/viewLogs.php
centreon/www/include/Administration/configChangelog/viewLogs.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\ActionLog\Domain\Model\ActionLog; if (! isset($centreon)) { exit(); } require_once './include/common/autoNumLimit.php'; /** * Search a contact by username or alias * * @global CentreonDB $pearDB * @param string $username Username to search * @return int[] Returns a contact ids list */ function searchUserName($username) { global $pearDB; $contactIds = []; $prepareContact = $pearDB->prepare( 'SELECT contact_id FROM contact ' . 'WHERE contact_name LIKE :contact_name ' . 'OR contact_alias LIKE :contact_alias' ); $prepareContact->bindValue(':contact_name', '%' . $username . '%', PDO::PARAM_STR); $prepareContact->bindValue(':contact_alias', '%' . $username . '%', PDO::PARAM_STR); if ($prepareContact->execute()) { while ($contact = $prepareContact->fetch(PDO::FETCH_ASSOC)) { $contactIds[] = (int) $contact['contact_id']; } } return $contactIds; } // Path to the configuration dir $path = './include/Administration/configChangelog/'; // PHP functions require_once './include/common/common-Func.php'; require_once './class/centreonDB.class.php'; // Connect to Centstorage Database $pearDBO = new CentreonDB('centstorage'); $contactList = []; $dbResult = $pearDB->query( 'SELECT contact_id, contact_name, contact_alias FROM contact' ); while ($row = $dbResult->fetch()) { $contactList[$row['contact_id']] = $row['contact_name'] . ' (' . $row['contact_alias'] . ')'; } $searchO = null; $searchU = null; $searchP = null; if (isset($_POST['SearchB'])) { $centreon->historySearch[$url] = []; $searchO = $_POST['searchO']; $centreon->historySearch[$url]['searchO'] = $searchO; $searchU = $_POST['searchU']; $centreon->historySearch[$url]['searchU'] = $searchU; $otype = $_POST['otype']; $centreon->historySearch[$url]['otype'] = $otype; } elseif (isset($_GET['SearchB'])) { $centreon->historySearch[$url] = []; $searchO = $_GET['searchO']; $centreon->historySearch[$url]['searchO'] = $searchO; $searchU = $_GET['searchU']; $centreon->historySearch[$url]['searchU'] = $searchU; $otype = $_GET['otype']; $centreon->historySearch[$url]['otype'] = $otype; } else { if (isset($centreon->historySearch[$url]['searchO'])) { $searchO = $centreon->historySearch[$url]['searchO']; } if (isset($centreon->historySearch[$url]['searchU'])) { $searchU = $centreon->historySearch[$url]['searchU']; } if (isset($centreon->historySearch[$url]['otype'])) { $otype = $centreon->historySearch[$url]['otype']; } } /** * XSS secure */ $otype = isset($otype) ? (int) $otype : null; // Init QuickForm $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'SearchB', _('Search'), $attrBtnSuccess); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $tabAction = []; $tabAction['a'] = _('Added'); $tabAction['c'] = _('Changed'); $tabAction['mc'] = _('Mass Change'); $tabAction['enable'] = _('Enabled'); $tabAction['disable'] = _('Disabled'); $tabAction['d'] = _('Deleted'); $badge = [ _('Added') => 'ok', _('Changed') => 'warning', _('Mass Change') => 'warning', _('Deleted') => 'critical', _('Enabled') => 'ok', _('Disabled') => 'critical', ]; $tpl->assign('object_id', _('Object ID')); $tpl->assign('action', _('Action')); $tpl->assign('contact_name', _('Contact Name')); $tpl->assign('field_name', _('Field Name')); $tpl->assign('field_value', _('Field Value')); $tpl->assign('before', _('Before')); $tpl->assign('after', _('After')); $tpl->assign('logs', _('Logs for ')); $tpl->assign('objTypeLabel', _('Object type : ')); $tpl->assign('objNameLabel', _('Object name : ')); $tpl->assign('noModifLabel', _('No modification was made.')); // Add an All Option to existing types. $objectTypes = ActionLog::AVAILABLE_OBJECT_TYPES; array_unshift($objectTypes, _('All')); $options = ''; foreach ($objectTypes as $key => $name) { $name = _("{$name}"); $options .= "<option value='{$key}' " . (($otype == $key) ? 'selected' : '') . ">{$name}</option>"; } $tpl->assign('obj_type', $options); $logQuery = <<<'SQL' SELECT SQL_CALC_FOUND_ROWS object_id, object_type, object_name, action_log_date, action_type, log_contact_id, action_log_id FROM log_action SQL; $valuesToBind = []; if (! empty($searchO) || ! empty($searchU) || $otype != 0) { $logQuery .= ' WHERE '; $hasMultipleSubRequest = false; if (! empty($searchO)) { $logQuery .= 'object_name LIKE :object_name '; $valuesToBind[':object_name'] = '%' . $searchO . '%'; $hasMultipleSubRequest = true; } if (! empty($searchU)) { $contactIds = searchUserName($searchU); if (empty($contactIds)) { $contactIds[] = -1; } if ($hasMultipleSubRequest) { $logQuery .= ' AND '; } $logQuery .= ' log_contact_id IN (' . implode(',', $contactIds) . ') '; $hasMultipleSubRequest = true; } if (! is_null($otype) && $otype != 0) { if ($hasMultipleSubRequest) { $logQuery .= ' AND '; } $logQuery .= ' object_type = :object_type'; $valuesToBind[':object_type'] = $objectTypes[$otype]; } } $logQuery .= ' ORDER BY action_log_date DESC LIMIT :from, :nbrElement'; $prepareSelect = $pearDBO->prepare($logQuery); foreach ($valuesToBind as $label => $value) { $prepareSelect->bindValue($label, $value, PDO::PARAM_STR); } $prepareSelect->bindValue(':from', $num * $limit, PDO::PARAM_INT); $prepareSelect->bindValue(':nbrElement', $limit, PDO::PARAM_INT); $elemArray = []; $rows = 0; if ($prepareSelect->execute()) { $rows = $pearDBO->query('SELECT FOUND_ROWS()')->fetchColumn(); while ($res = $prepareSelect->fetch(PDO::FETCH_ASSOC)) { if ($res['object_id']) { $objectName = myDecode($res['object_name']); $objectName = stripslashes($objectName); $objectName = str_replace( ['#S#', '#BS#'], ['/', '\\'], $objectName ); $objectName = CentreonUtils::escapeSecure( $objectName, CentreonUtils::ESCAPE_ALL_EXCEPT_LINK ); $author = empty($contactList[$res['log_contact_id']]) ? _('unknown') : $contactList[$res['log_contact_id']]; $element = [ 'date' => $res['action_log_date'] ?? null, 'type' => $res['object_type'] ?? null, 'object_name' => $objectName ?? null, 'action_log_id' => $res['action_log_id'] ?? null, 'object_id' => $res['object_id'] ?? null, 'modification_type' => $tabAction[$res['action_type']] ?? null, 'author' => $author ?? null, 'change' => $tabAction[$res['action_type']] ?? null, 'badge' => $badge[$tabAction[$res['action_type']]] ?? null, ]; if ($res['object_type'] == 'service') { $tmp = $centreon->CentreonLogAction->getHostId($res['object_id']); if ($tmp != -1) { if (isset($tmp['h'])) { $tmp2 = $centreon->CentreonLogAction->getHostId($res['object_id']); $tabHost = explode(',', $tmp2['h']); if (count($tabHost) == 1) { $host_name = CentreonUtils::escapeSecure( $centreon->CentreonLogAction->getHostName($tmp2['h']), CentreonUtils::ESCAPE_ALL_EXCEPT_LINK ); // If we can't find the host name in the DB, we can get it in the object name if ( ((int) $host_name === -1 && str_contains($objectName, '/')) || str_contains($objectName, $host_name . '/') ) { $objectValues = explode('/', $objectName, 2); $host_name = $objectValues[0]; $objectName = $objectValues[1]; } } elseif (count($tabHost) > 1) { $hosts = []; foreach ($tabHost as $key => $value) { $hosts[] = $centreon->CentreonLogAction->getHostName($value); } } } elseif (isset($tmp['hg'])) { $tmp2 = $centreon->CentreonLogAction->getHostId($res['object_id']); $tabHost = explode(',', $tmp2['hg']); if (count($tabHost) == 1) { $hg_name = $centreon->CentreonLogAction->getHostGroupName($tmp2['hg']); } elseif (count($tabHost) > 1) { $hostgroups = []; foreach ($tabHost as $key => $value) { $hostgroups[] = $centreon->CentreonLogAction->getHostGroupName($value); } } } } if (isset($host_name) && $host_name != '') { $element['host'] = $host_name; } elseif (isset($hosts) && count($hosts) != 1) { $element['hosts'] = $hosts; } elseif (isset($hg_name) && $hg_name != '') { $element['hostgroup'] = $hg_name; } elseif (isset($hostgroups) && count($hostgroups) != 1) { $element['hostgroups'] = $hostgroups; } else { // as the relation may have been deleted since the event, // some relations can't be found for this service, while events have been saved for it in the DB $element['host'] = '<i>Linked resource has changed</i>'; } unset($host_name, $hg_name, $hosts, $hostgroups); } $elemArray[] = $element; } } } include './include/common/checkPagination.php'; // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('search_object_str', _('Object')); $tpl->assign('search_user_str', _('User')); $tpl->assign('Search', _('Search')); $tpl->assign('searchO', htmlentities($searchO ?? '')); $tpl->assign('searchU', htmlentities($searchU ?? '')); $tpl->assign('obj_str', _('Object Type')); $tpl->assign('type_id', $otype); $tpl->assign('event_type', _('Event Type')); $tpl->assign('time', _('Time')); $tpl->assign('contact', _('Contact')); // Pagination $tpl->assign('limit', $limit); $tpl->assign('rows', $rows); $tpl->assign('p', $p); $tpl->assign('elemArray', $elemArray); if (isset($_POST['searchO']) || isset($_POST['searchU']) || isset($_POST['otype']) || ! isset($_GET['object_id']) ) { $tpl->display('viewLogs.ihtml'); } else { $listAction = $centreon->CentreonLogAction->listAction( (int) $_GET['object_id'], $_GET['object_type'] ); $listModification = $centreon->CentreonLogAction->listModification( (int) $_GET['object_id'], $_GET['object_type'] ); if (isset($listAction)) { $tpl->assign('action', $listAction); } if (isset($listModification)) { $tpl->assign('modification', $listModification); } $tpl->display('viewLogsDetails.ihtml'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/parameters.php
centreon/www/include/Administration/parameters/parameters.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 * */ if (! isset($centreon)) { exit(); } $gopt_id = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['gopt_id'] ?? null); if ((! isset($cg) || is_null($cg))) { $gopt_id = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['gopt_id'] ?? null); } // Path to the option dir $path = './include/Administration/parameters/'; // PHP functions require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; switch ($o) { case 'engine': require_once $path . 'engine/form.php'; break; case 'snmp': require_once $path . 'snmp/form.php'; break; case 'rrdtool': require_once $path . 'rrdtool/form.php'; break; case 'ldap': require_once $path . 'ldap/ldap.php'; break; case 'debug': require_once $path . 'debug/form.php'; break; case 'css': require_once $path . 'css/form.php'; break; case 'storage': require_once $path . 'centstorage/form.php'; break; case 'gorgone': require_once $path . 'gorgone/gorgone.php'; break; case 'knowledgeBase': require_once $path . 'knowledgeBase/formKnowledgeBase.php'; break; case 'api': require_once $path . 'api/api.php'; break; case 'backup': require_once $path . 'backup/formBackup.php'; break; case 'remote': require_once $path . 'remote/formRemote.php'; break; case 'general': default: require_once $path . 'general/form.php'; break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/DB-Func.php
centreon/www/include/Administration/parameters/DB-Func.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 __DIR__ . '/../../common/vault-functions.php'; use App\Kernel; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Common\Infrastructure\Repository\AbstractVaultRepository; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; use Core\Security\Vault\Domain\Model\VaultConfiguration; /** * Used to update fields in the 'centreon.options' table * * @param CentreonDB $pearDB : database connection * @param string $key : name of the row * @param string $value : value of the row */ function updateOption($pearDB, $key, $value) { $stmt = $pearDB->prepare('DELETE FROM `options` WHERE `key` = :key'); $stmt->bindValue(':key', $key, PDO::PARAM_STR); $stmt->execute(); $stmt = $pearDB->prepare('INSERT INTO `options` (`key`, `value`) VALUES (:key, :value)'); $stmt->bindValue(':key', $key, PDO::PARAM_STR); $stmt->bindValue(':value', $value, PDO::PARAM_STR); $stmt->execute(); } /** * Used to update fields in the 'centreon.informations' table * * @param object $pearDB : database connection * @param string $key : name of the row * @param string $value : value of the row */ function updateInformations($pearDB, string $key, string $value): void { $stmt = $pearDB->prepare('DELETE FROM `informations` WHERE `key` = :key'); $stmt->bindValue(':key', $key, PDO::PARAM_STR); $stmt->execute(); $stmt = $pearDB->prepare('INSERT INTO `informations` (`key`, `value`) VALUES (:key, :value)'); $stmt->bindValue(':key', $key, PDO::PARAM_STR); $stmt->bindValue(':value', $value, PDO::PARAM_STR); $stmt->execute(); } function is_valid_path_images($path) { if (trim($path) == '') { return true; } return (bool) (is_dir($path)); } function is_valid_path($path) { return (bool) (is_dir($path)); } function is_readable_path($path) { return (bool) (is_dir($path) && is_readable($path)); } function is_executable_binary($path) { return (bool) (is_file($path) && is_executable($path)); } function is_writable_path($path) { return (bool) (is_dir($path) && is_writable($path)); } function is_writable_file($path) { return (bool) (is_file($path) && is_writable($path)); } function is_writable_file_if_exist($path = null) { if (! $path) { return true; } return (bool) (is_file($path) && is_writable($path)); } function is_greater_than($value, $minValue) { return is_numeric($value) && $value >= $minValue; } /** * rule to check the session duration value chosen by the user * @param int $value * @param int $valueMax * * @return bool */ function isSessionDurationValid(?int $value = null) { return $value > 0 && $value <= SESSION_DURATION_LIMIT; } function updateGeneralOptInDB($gopt_id = null) { if (! $gopt_id) { return; } updateGeneralOpt($gopt_id); } function updateNagiosConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'nagios_path_plugins', isset($ret['nagios_path_plugins']) && $ret['nagios_path_plugins'] != null ? $pearDB->escape($ret['nagios_path_plugins']) : 'NULL' ); updateOption( $pearDB, 'mailer_path_bin', isset($ret['mailer_path_bin']) && $ret['mailer_path_bin'] != null ? $pearDB->escape($ret['mailer_path_bin']) : 'NULL' ); updateOption( $pearDB, 'interval_length', isset($ret['interval_length']) && $ret['interval_length'] != null ? $pearDB->escape($ret['interval_length']) : 'NULL' ); updateOption( $pearDB, 'broker', isset($ret['broker']) && $ret['broker'] != null ? $pearDB->escape($ret['broker']) : 'broker' ); $pearDB->query('UPDATE acl_resources SET changed = 1'); // Tactical Overview part updateOption($pearDB, 'tactical_host_limit', $ret['tactical_host_limit']); updateOption($pearDB, 'tactical_service_limit', $ret['tactical_service_limit']); updateOption($pearDB, 'tactical_refresh_interval', $ret['tactical_refresh_interval']); // Acknowledgement part updateOption( $pearDB, 'monitoring_ack_sticky', isset($ret['monitoring_ack_sticky']) && $ret['monitoring_ack_sticky'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_ack_notify', isset($ret['monitoring_ack_notify']) && $ret['monitoring_ack_notify'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_ack_persistent', isset($ret['monitoring_ack_persistent']) && $ret['monitoring_ack_persistent'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_ack_active_checks', isset($ret['monitoring_ack_active_checks']) && $ret['monitoring_ack_active_checks'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_ack_svc', isset($ret['monitoring_ack_svc']) && $ret['monitoring_ack_svc'] ? 1 : 0 ); // Downtime part updateOption( $pearDB, 'monitoring_dwt_duration', isset($ret['monitoring_dwt_duration']) && $ret['monitoring_dwt_duration'] ? $pearDB->escape($ret['monitoring_dwt_duration']) : 3600 ); updateOption( $pearDB, 'monitoring_dwt_duration_scale', isset($ret['monitoring_dwt_duration_scale']) && $ret['monitoring_dwt_duration_scale'] ? $pearDB->escape($ret['monitoring_dwt_duration_scale']) : 's' ); updateOption( $pearDB, 'monitoring_dwt_fixed', isset($ret['monitoring_dwt_fixed']) && $ret['monitoring_dwt_fixed'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_dwt_svc', isset($ret['monitoring_dwt_svc']) && $ret['monitoring_dwt_svc'] ? 1 : 0 ); // Misc updateOption( $pearDB, 'monitoring_console_notification', isset($ret['monitoring_console_notification']) && $ret['monitoring_console_notification'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_host_notification_0', isset($ret['monitoring_host_notification_0']) && $ret['monitoring_host_notification_0'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_host_notification_1', isset($ret['monitoring_host_notification_1']) && $ret['monitoring_host_notification_1'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_host_notification_2', isset($ret['monitoring_host_notification_2']) && $ret['monitoring_host_notification_2'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_svc_notification_0', isset($ret['monitoring_svc_notification_0']) && $ret['monitoring_svc_notification_0'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_svc_notification_1', isset($ret['monitoring_svc_notification_1']) && $ret['monitoring_svc_notification_1'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_svc_notification_2', isset($ret['monitoring_svc_notification_2']) && $ret['monitoring_svc_notification_2'] ? 1 : 0 ); updateOption( $pearDB, 'monitoring_svc_notification_3', isset($ret['monitoring_svc_notification_3']) && $ret['monitoring_svc_notification_3'] ? 1 : 0 ); $centreon->initOptGen($pearDB); } function updateGorgoneConfigData($db, $form, $centreon) { $ret = $form->getSubmitValues(); updateOption($db, 'enable_broker_stats', isset($ret['enable_broker_stats']) && $ret['enable_broker_stats'] ? 1 : 0); updateOption( $db, 'gorgone_cmd_timeout', $ret['gorgone_cmd_timeout'] ?? 0 ); updateOption( $db, 'gorgone_illegal_characters', $ret['gorgone_illegal_characters'] ?? '' ); // API updateOption( $db, 'gorgone_api_address', $ret['gorgone_api_address'] ?? '127.0.0.1' ); updateOption( $db, 'gorgone_api_port', $ret['gorgone_api_port'] ?? '8085' ); updateOption( $db, 'gorgone_api_username', $ret['gorgone_api_username'] ?? '' ); updateOption( $db, 'gorgone_api_password', $ret['gorgone_api_password'] ?? '' ); updateOption( $db, 'gorgone_api_ssl', $ret['gorgone_api_ssl'] ?? '0' ); updateOption( $db, 'gorgone_api_allow_self_signed', $ret['gorgone_api_allow_self_signed'] ?? '1' ); $centreon->initOptGen($db); } function updateSNMPConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'snmp_community', isset($ret['snmp_community']) && $ret['snmp_community'] != null ? $ret['snmp_community'] : 'NULL' ); updateOption( $pearDB, 'snmp_version', isset($ret['snmp_version']) && $ret['snmp_version'] != null ? $ret['snmp_version'] : 'NULL' ); updateOption( $pearDB, 'snmp_trapd_path_conf', isset($ret['snmp_trapd_path_conf']) && $ret['snmp_trapd_path_conf'] != null ? $ret['snmp_trapd_path_conf'] : 'NULL' ); updateOption( $pearDB, 'snmptt_unknowntrap_log_file', isset($ret['snmptt_unknowntrap_log_file']) && $ret['snmptt_unknowntrap_log_file'] != null ? $ret['snmptt_unknowntrap_log_file'] : 'NULL' ); updateOption( $pearDB, 'snmpttconvertmib_path_bin', isset($ret['snmpttconvertmib_path_bin']) && $ret['snmpttconvertmib_path_bin'] != null ? $ret['snmpttconvertmib_path_bin'] : 'NULL' ); updateOption( $pearDB, 'perl_library_path', isset($ret['perl_library_path']) && $ret['perl_library_path'] != null ? $ret['perl_library_path'] : 'NULL' ); $centreon->initOptGen($pearDB); } function updateDebugConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'debug_path', isset($ret['debug_path']) && $ret['debug_path'] != null ? $ret['debug_path'] : 'NULL' ); updateOption($pearDB, 'debug_auth', isset($ret['debug_auth']) && $ret['debug_auth'] ? 1 : 0); updateOption( $pearDB, 'debug_nagios_import', isset($ret['debug_nagios_import']) && $ret['debug_nagios_import'] ? 1 : 0 ); updateOption($pearDB, 'debug_rrdtool', isset($ret['debug_rrdtool']) && $ret['debug_rrdtool'] ? 1 : 0); updateOption($pearDB, 'debug_ldap_import', isset($ret['debug_ldap_import']) && $ret['debug_ldap_import'] ? 1 : 0); updateOption($pearDB, 'debug_sql', isset($ret['debug_sql']) && $ret['debug_sql'] ? 1 : 0); updateOption($pearDB, 'debug_gorgone', isset($ret['debug_gorgone']) && $ret['debug_gorgone'] ? 1 : 0); updateOption($pearDB, 'debug_centstorage', isset($ret['debug_centstorage']) && $ret['debug_centstorage'] ? 1 : 0); updateOption( $pearDB, 'debug_centreontrapd', isset($ret['debug_centreontrapd']) && $ret['debug_centreontrapd'] ? 1 : 0 ); updateOption( $pearDB, 'debug_level', $ret['debug_level'] ); enableApplicationDebug((int) $ret['debug_level']); $centreon->initOptGen($pearDB); } function updateLdapConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'ldap_host', isset($ret['ldap_host']) && $ret['ldap_host'] != null ? htmlentities($ret['ldap_host'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_port', isset($ret['ldap_port']) && $ret['ldap_port'] != null ? htmlentities($ret['ldap_port'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_base_dn', isset($ret['ldap_base_dn']) && $ret['ldap_base_dn'] != null ? htmlentities($ret['ldap_base_dn'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_login_attrib', isset($ret['ldap_login_attrib']) && $ret['ldap_login_attrib'] != null ? htmlentities($ret['ldap_login_attrib'], ENT_QUOTES, 'UTF-8') : '' ); updateOption( $pearDB, 'ldap_ssl', isset($ret['ldap_ssl']['ldap_ssl']) && $ret['ldap_ssl']['ldap_ssl'] != null ? htmlentities($ret['ldap_ssl']['ldap_ssl'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_auth_enable', isset($ret['ldap_auth_enable']['ldap_auth_enable']) && $ret['ldap_auth_enable']['ldap_auth_enable'] != null ? htmlentities($ret['ldap_auth_enable']['ldap_auth_enable'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_search_user', isset($ret['ldap_search_user']) && $ret['ldap_search_user'] != null ? htmlentities($ret['ldap_search_user'], ENT_QUOTES, 'UTF-8') : '' ); updateOption( $pearDB, 'ldap_search_user_pwd', isset($ret['ldap_search_user_pwd']) && $ret['ldap_search_user_pwd'] != null ? htmlentities($ret['ldap_search_user_pwd'], ENT_QUOTES, 'UTF-8') : '' ); updateOption( $pearDB, 'ldap_search_filter', isset($ret['ldap_search_filter']) && $ret['ldap_search_filter'] != null ? htmlentities($ret['ldap_search_filter'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_connection_timeout', ! empty($ret['ldap_connection_timeout']) ? htmlentities($ret['ldap_connection_timeout'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_search_timeout', isset($ret['ldap_search_timeout']) && $ret['ldap_search_timeout'] != null ? htmlentities($ret['ldap_search_timeout'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_search_limit', isset($ret['ldap_search_limit']) && $ret['ldap_search_limit'] != null ? htmlentities($ret['ldap_search_limit'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'ldap_protocol_version', isset($ret['ldap_protocol_version']) && $ret['ldap_protocol_version'] != null ? htmlentities($ret['ldap_protocol_version'], ENT_QUOTES, 'UTF-8') : 'NULL' ); $centreon->initOptGen($pearDB); } function updateGeneralConfigData() { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); if (! isset($ret['AjaxTimeReloadStatistic'])) { throw new InvalidArgumentException('Missing submitted values'); } if (! isset($ret['session_expire']) || $ret['session_expire'] == 0) { $ret['session_expire'] = 2; } updateOption( $pearDB, 'oreon_path', isset($ret['oreon_path']) && $ret['oreon_path'] != null ? htmlentities($ret['oreon_path'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'oreon_refresh', isset($ret['oreon_refresh']) && $ret['oreon_refresh'] != null ? htmlentities($ret['oreon_refresh'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'inheritance_mode', ! empty($ret['inheritance_mode']['inheritance_mode']) ? (int) $ret['inheritance_mode']['inheritance_mode'] : 3 // default cumulative inheritance ); updateOption( $pearDB, 'session_expire', isset($ret['session_expire']) && $ret['session_expire'] != null ? htmlentities($ret['session_expire'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'maxViewMonitoring', isset($ret['maxViewMonitoring']) && $ret['maxViewMonitoring'] != null ? htmlentities($ret['maxViewMonitoring'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'maxViewConfiguration', isset($ret['maxViewConfiguration']) && $ret['maxViewConfiguration'] != null ? htmlentities($ret['maxViewConfiguration'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'maxGraphPerformances', isset($ret['maxGraphPerformances']) && $ret['maxGraphPerformances'] != null ? htmlentities($ret['maxGraphPerformances'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'selectPaginationSize', isset($ret['selectPaginationSize']) && $ret['selectPaginationSize'] != null ? htmlentities($ret['selectPaginationSize'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'AjaxTimeReloadMonitoring', isset($ret['AjaxTimeReloadMonitoring']) && $ret['AjaxTimeReloadMonitoring'] != null ? htmlentities($ret['AjaxTimeReloadMonitoring'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'AjaxTimeReloadStatistic', isset($ret['AjaxTimeReloadStatistic']) && $ret['AjaxTimeReloadStatistic'] != null ? htmlentities($ret['AjaxTimeReloadStatistic'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'enable_gmt', isset($ret['enable_gmt']['yes']) && $ret['enable_gmt']['yes'] != null ? htmlentities($ret['enable_gmt']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption( $pearDB, 'gmt', isset($ret['gmt']) && $ret['gmt'] != null ? htmlentities($ret['gmt'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'global_sort_type', isset($ret['global_sort_type']) && $ret['global_sort_type'] != null ? htmlentities($ret['global_sort_type'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'global_sort_order', isset($ret['global_sort_order']) && $ret['global_sort_order'] != null ? htmlentities($ret['global_sort_order'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'problem_sort_type', isset($ret['problem_sort_type']) && $ret['problem_sort_type'] != null ? htmlentities($ret['problem_sort_type'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'problem_sort_order', isset($ret['problem_sort_order']) && $ret['problem_sort_order'] != null ? htmlentities($ret['problem_sort_order'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'proxy_url', isset($ret['proxy_url']) && $ret['proxy_url'] != null ? htmlentities($ret['proxy_url'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'proxy_port', isset($ret['proxy_port']) && $ret['proxy_port'] != null ? htmlentities($ret['proxy_port'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'proxy_user', isset($ret['proxy_user']) && $ret['proxy_user'] != null ? htmlentities($ret['proxy_user'], ENT_QUOTES, 'UTF-8') : null ); if (isset($ret['proxy_password']) && $ret['proxy_password'] != CentreonAuth::PWS_OCCULTATION) { updateOption( $pearDB, 'proxy_password', $ret['proxy_password'] != null ? htmlentities($ret['proxy_password'], ENT_QUOTES, 'UTF-8') : null ); } updateOption( $pearDB, 'display_downtime_chart', isset($ret['display_downtime_chart']['yes']) && $ret['display_downtime_chart']['yes'] != null ? htmlentities($ret['display_downtime_chart']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption( $pearDB, 'display_comment_chart', isset($ret['display_comment_chart']['yes']) && $ret['display_comment_chart']['yes'] != null ? htmlentities($ret['display_comment_chart']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption( $pearDB, 'enable_autologin', isset($ret['enable_autologin']['yes']) && $ret['enable_autologin']['yes'] != null ? htmlentities($ret['enable_autologin']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption( $pearDB, 'display_autologin_shortcut', isset($ret['display_autologin_shortcut']['yes']) && $ret['display_autologin_shortcut']['yes'] != null ? htmlentities($ret['display_autologin_shortcut']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption( $pearDB, 'centreon_support_email', isset($ret['centreon_support_email']) && $ret['centreon_support_email'] != null ? htmlentities($ret['centreon_support_email'], ENT_QUOTES, 'UTF-8') : null ); updateOption( $pearDB, 'send_statistics', isset($ret['send_statistics']['yes']) && $ret['send_statistics']['yes'] != null ? htmlentities($ret['send_statistics']['yes'], ENT_QUOTES, 'UTF-8') : '0' ); $resourceStatusSearchMode = isset($ret['resource_status_search_mode']['resource_status_search_mode']) && $ret['resource_status_search_mode']['resource_status_search_mode'] !== null ? (int) $ret['resource_status_search_mode']['resource_status_search_mode'] : RESOURCE_STATUS_FULL_SEARCH; updateOption( $pearDB, 'resource_status_search_mode', $resourceStatusSearchMode ); $centreon->initOptGen($pearDB); } function updateRRDToolConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'rrdtool_path_bin', isset($ret['rrdtool_path_bin']) && $ret['rrdtool_path_bin'] != null ? htmlentities($ret['rrdtool_path_bin'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'rrdtool_version', isset($ret['rrdtool_version']) && $ret['rrdtool_version'] != null ? htmlentities($ret['rrdtool_version'], ENT_QUOTES, 'UTF-8') : 'NULL' ); updateOption( $pearDB, 'rrdcached_enable', $ret['rrdcached_enable']['rrdcached_enable'] ?? '0' ); updateOption( $pearDB, 'rrdcached_port', $ret['rrdcached_port'] ?? '' ); updateOption( $pearDB, 'rrdcached_unix_path', isset($ret['rrdcached_unix_path']) ? htmlentities($ret['rrdcached_unix_path'], ENT_QUOTES, 'UTF-8') : '' ); $centreon->initOptGen($pearDB); } function updatePartitioningConfigData($db, $form, $centreon) { $ret = $form->getSubmitValues(); foreach ($ret as $key => $value) { if (preg_match('/^partitioning_/', $key)) { updateOption($db, $key, $value); } } $centreon->initOptGen($db); } function updateODSConfigData() { global $form, $pearDBO, $pearDB; $ret = []; $ret = $form->getSubmitValues(); if (! isset($ret['audit_log_option'])) { $ret['audit_log_option'] = '0'; } if (! isset($ret['len_storage_rrd'])) { $ret['len_storage_rrd'] = 1; } if (! isset($ret['len_storage_mysql'])) { $ret['len_storage_mysql'] = 1; } if (! isset($ret['autodelete_rrd_db'])) { $ret['autodelete_rrd_db'] = 0; } if (! isset($ret['purge_interval']) || $ret['purge_interval'] <= 20) { $ret['purge_interval'] = 20; } if (! isset($ret['archive_log'])) { $ret['archive_log'] = '0'; } if (! $ret['purge_interval']) { $ret['purge_interval'] = 60; } if ($ret['RRDdatabase_path'][strlen($ret['RRDdatabase_path']) - 1] != '/') { $ret['RRDdatabase_path'] .= '/'; } if (! isset($ret['len_storage_downtimes'])) { $ret['len_storage_downtimes'] = 0; } if (! isset($ret['len_storage_comments'])) { $ret['len_storage_comments'] = 0; } if (! isset($ret['audit_log_retention'])) { $ret['audit_log_retention'] = 0; } $rq = "UPDATE `config` SET `RRDdatabase_path` = '" . $ret['RRDdatabase_path'] . "', `RRDdatabase_status_path` = '" . $ret['RRDdatabase_status_path'] . "', `RRDdatabase_nagios_stats_path` = '" . $ret['RRDdatabase_nagios_stats_path'] . "', `len_storage_rrd` = '" . $ret['len_storage_rrd'] . "', `len_storage_mysql` = '" . $ret['len_storage_mysql'] . "', `autodelete_rrd_db` = '" . $ret['autodelete_rrd_db'] . "', `purge_interval` = '" . $ret['purge_interval'] . "', `archive_log` = '" . $ret['archive_log'] . "', `archive_retention` = '" . $ret['archive_retention'] . "', `reporting_retention` = '" . $ret['reporting_retention'] . "', `audit_log_option` = '" . $ret['audit_log_option'] . "', `storage_type` = " . ($ret['storage_type'] ?? 'NULL') . ", `len_storage_downtimes` = '" . $ret['len_storage_downtimes'] . "', `audit_log_retention` = '" . $ret['audit_log_retention'] . "', `len_storage_comments` = '" . $ret['len_storage_comments'] . "' " . ' WHERE `id` = 1 LIMIT 1 ;'; $DBRESULT = $pearDBO->query($rq); updateOption( $pearDB, 'centstorage', isset($ret['enable_centstorage']) && $ret['enable_centstorage'] != null ? htmlentities($ret['enable_centstorage'], ENT_QUOTES, 'UTF-8') : '0' ); updateOption($pearDB, 'centstorage_auto_drop', isset($ret['centstorage_auto_drop']) ? '1' : '0'); updateOption( $pearDB, 'centstorage_drop_file', isset($ret['centstorage_drop_file']) ? $pearDB->escape($ret['centstorage_drop_file']) : '' ); } function updateCASConfigData($gopt_id = null) { global $form, $pearDB, $centreon; $ret = []; $ret = $form->getSubmitValues(); updateOption( $pearDB, 'auth_cas_enable', isset($ret['auth_cas_enable']['auth_cas_enable']) && $ret['auth_cas_enable']['auth_cas_enable'] != null ? $ret['auth_cas_enable']['auth_cas_enable'] : 'NULL' ); updateOption( $pearDB, 'cas_server', isset($ret['cas_server']) && $ret['cas_server'] != null ? $ret['cas_server'] : 'NULL' ); updateOption($pearDB, 'cas_port', isset($ret['cas_port']) && $ret['cas_port'] != null ? $ret['cas_port'] : 'NULL'); updateOption($pearDB, 'cas_url', isset($ret['cas_url']) && $ret['cas_url'] != null ? $ret['cas_url'] : 'NULL'); updateOption( $pearDB, 'cas_version', isset($ret['cas_version']) && $ret['cas_version'] != null ? $ret['cas_version'] : 'NULL' ); $centreon->initOptGen($pearDB); } function updateBackupConfigData($db, $form, $centreon) { $ret = $form->getSubmitValues(); $radiobutton = ['backup_enabled', 'backup_database_type', 'backup_export_scp_enabled']; foreach ($radiobutton as $value) { $ret[$value] = isset($ret[$value], $ret[$value][$value]) && $ret[$value][$value] ? 1 : 0; } $checkbox = [ 'backup_configuration_files', 'backup_database_centreon', 'backup_database_centreon_storage', ]; foreach ($checkbox as $value) { $ret[$value] = isset($ret[$value]) && $ret[$value] ? 1 : 0; } $checkboxGroup = ['backup_database_full', 'backup_database_partial']; foreach ($checkboxGroup as $value) { if (isset($ret[$value]) && count($ret[$value])) { $valueKeys = array_keys($ret[$value]); $ret[$value] = implode(',', $valueKeys); } else { $ret[$value] = ''; } } foreach ($ret as $key => $value) { if (preg_match('/^backup_/', $key)) { updateOption($db, $key, $value); } } $centreon->initOptGen($db); } function updateKnowledgeBaseData($db, $form, $centreon, ?string $originalPassword) { $ret = $form->getSubmitValues(); if (! isset($ret['kb_wiki_certificate']) || ! filter_var($ret['kb_wiki_certificate'], FILTER_VALIDATE_INT)) { $ret['kb_wiki_certificate'] = 0; } if (isset($ret['kb_wiki_password']) && $ret['kb_wiki_password'] === CentreonAuth::PWS_OCCULTATION) { unset($ret['kb_wiki_password']); } if (isset($ret['kb_wiki_url']) && ! filter_var($ret['kb_wiki_url'], FILTER_VALIDATE_URL)) { unset($ret['kb_wiki_url']); } foreach ($ret as $key => $value) { if ($key === 'kb_wiki_password') { $vaultPath = saveKnowledgeBasePasswordInVault($value, $originalPassword); $value = $vaultPath ?? $value; updateOption($db, $key, $value); } elseif (preg_match('/^kb_/', $key)) { updateOption($db, $key, $value); } } $centreon->initOptGen($db); } /** * @param string $password * @param string $originalPassword * * @throws Throwable * @return string|null */ function saveKnowledgeBasePasswordInVault(string $password, ?string $originalPassword): ?string { $kernel = Kernel::createForWeb(); $readVaultConfigurationRepository = $kernel->getContainer()->get( ReadVaultConfigurationRepositoryInterface::class ); $vaultConfiguration = $readVaultConfigurationRepository->find(); if ($vaultConfiguration === null) { return null; } $uuid = null; if ($originalPassword !== null && str_starts_with($originalPassword, VaultConfiguration::VAULT_PATH_PATTERN)) { $uuid = preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $originalPassword, $matches ) && isset($matches[2]) ? $matches[2] : null; } /** @var WriteVaultRepositoryInterface $writeVaultRepository */ $writeVaultRepository = $kernel->getContainer()->get(WriteVaultRepositoryInterface::class); $writeVaultRepository->setCustomPath(AbstractVaultRepository::KNOWLEDGE_BASE_PATH); return upsertKnowledgeBasePasswordInVault($writeVaultRepository, $password, $uuid); } /** * Used to update Central's credentials on a remote server * * @param object $db : database connection * @param object $form : form data * @param Security\Encryption $centreonEncryption : Encryption object */ function updateRemoteAccessCredentials($db, $form, $centreonEncryption): void { $ret = $form->getSubmitValues(); $passApi = $ret['apiCredentials']; // clean useless values unset($ret['submitC'], $ret['o'], $ret['centreon_token'], $ret['apiCredentials']); // convert values $ret['apiPeerValidation'] = (int) $ret['apiPeerValidation'] === 1 ? 'no' : 'yes'; // update information foreach ($ret as $key => $value) { updateInformations($db, $key, $value); } if ($passApi !== CentreonAuth::PWS_OCCULTATION) { try { updateInformations( $db, 'apiCredentials', $centreonEncryption->crypt($passApi) ); } catch (Exception $e) { $errorMsg = _('The password cannot be crypted. Please re-submit the form'); echo "<div class='msg' align='center'>" . $errorMsg . '</div>'; } } } /** * Add or remove the debug level from environments files. * * @param bool $enable * @param int $level */ function enableApplicationDebug(int $level = 100) { $env = new Utility\EnvironmentFileManager(_CENTREON_PATH_); $env->load(); if ($level !== 0) { $env->add('DEBUG_LEVEL', $level); } else { $env->delete('DEBUG_LEVEL'); } $env->save(); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/centstorage/help.php
centreon/www/include/Administration/parameters/centstorage/help.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 * */ $help = []; /** * Engine Status */ $help['tip_path_to_rrdtool_database_for_metrics'] = dgettext('help', 'Path to RRDTool database for graphs of metrics.'); $help['tip_path_to_rrdtool_database_for_status'] = dgettext('help', 'Path to RRDTool database for graphs of status.'); $help['tip_path_to_rrdtool_database_for_nagios_statistics'] = dgettext( 'help', 'Path to RRDTool database for graphs of monitoring engine stats.' ); /** * Retention durations */ $help['tip_rrdtool_database_size'] = dgettext('help', 'RRDTool database size (in days).'); $help['tip_retention_duration_for_data_in_mysql'] = dgettext( 'help', 'Duration of retention regarding performance data stored in database. 0 means that no retention will be applied.' ); $help['tip_retention_duration_for_data_in_downtimes'] = dgettext( 'help', 'Duration of retention regarding downtimes stored in database. 0 means that no retention will be applied.' ); $help['tip_retention_duration_for_data_in_comments'] = dgettext( 'help', 'Duration of retention regarding comments stored in database. 0 means that no retention will be applied.' ); /** * Logs Integration Properties */ $help['tip_logs_retention_duration'] = dgettext( 'help', 'Retention duration of logs. 0 means that no retention will be applied.' ); /** * Reporting Dashboard */ $help['tip_reporting_retention'] = dgettext( 'help', 'Retention duration of reporting data. 0 means that no retention will be applied.' ); /** * Partitioning retention options */ $help['tip_partitioning_retention'] = dgettext( 'help', 'Retention time for partitioned tables (data_bin, logs, log_archive_host, log_archive_service), by default 365 days.' ); $help['tip_partitioning_retention_forward'] = dgettext( 'help', 'number of partitions created in advance to prevent issues, by default 10 days.' ); $help['tip_partitioning_backup_directory'] = dgettext( 'help', 'Backup directory to store partition, by default /var/cache/centreon/backup.' ); /** * Audit Logs */ $help['tip_audit_log_option'] = dgettext('help', 'Enable/Disable logging of all modifications in Centreon');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/centstorage/form.php
centreon/www/include/Administration/parameters/centstorage/form.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 * */ if (! isset($centreon)) { exit(); } if (isset($_POST['o']) && $_POST['o']) { $o = $_POST['o']; } // Get data into config table of centstorage $DBRESULT = $pearDBO->query('SELECT * FROM `config` LIMIT 1'); $gopt = array_map('myDecode', $DBRESULT->fetchRow()); // Get centstorage state $DBRESULT2 = $pearDB->query("SELECT * FROM `options` WHERE `key` LIKE 'centstorage%'"); while ($data = $DBRESULT2->fetchRow()) { if (isset($data['value']) && $data['key'] == 'centstorage') { $gopt['enable_centstorage'] = $data['value']; } else { $gopt[$data['key']] = $data['value']; } } // Get insert_data state $DBRESULT2 = $pearDB->query("SELECT * FROM `options` WHERE `key` = 'index_data'"); while ($data = $DBRESULT2->fetchRow()) { if (isset($data['value']) && $data['key'] == 'index_data') { if ($data['value'] == '1') { $gopt['insert_in_index_data'] = '0'; } elseif ($data['value'] == '0') { $gopt['insert_in_index_data'] = '1'; } else { $gopt['insert_in_index_data'] = '1'; } } } // Partitioning options $DBRESULT3 = $pearDB->query("SELECT * FROM `options` WHERE `key` LIKE 'partitioning%'"); while ($data = $DBRESULT3->fetchRow()) { $gopt[$data['key']] = $data['value']; } // Format of text input $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify General Options')); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->setDefaults($gopt); // Header information $form->addElement('header', 'enable', _('Engine Status')); $form->addElement('header', 'insert', _('Resources storage')); $form->addElement('header', 'folder', _('Storage folders')); $form->addElement('header', 'retention', _('Retention durations')); $form->addElement('header', 'partitioning', _('Partitioning retention options')); $form->addElement('header', 'Input', _('Input treatment options')); $form->addElement('header', 'reporting', _('Dashboard Integration Properties')); $form->addElement('header', 'audit', _('Audit log activation')); // inputs declaration $form->addElement('text', 'RRDdatabase_path', _('Path to RRDTool Database For Metrics'), $attrsText); $form->addElement('text', 'RRDdatabase_status_path', _('Path to RRDTool Database For Status'), $attrsText); $form->addElement( 'text', 'RRDdatabase_nagios_stats_path', _('Path to RRDTool Database For Monitoring Engine Statistics'), $attrsText ); $form->addElement('text', 'len_storage_rrd', _('Retention duration for performance data in RRDTool databases'), $attrsText2); $form->addElement('text', 'len_storage_mysql', _('Retention duration for performance data in MySQL database'), $attrsText2); $form->addElement('text', 'len_storage_downtimes', _('Retention duration for downtimes'), $attrsText2); $form->addElement('text', 'len_storage_comments', _('Retention duration for comments'), $attrsText2); $form->addElement('text', 'archive_retention', _('Retention duration for logs'), $attrsText2); $form->addElement('text', 'reporting_retention', _('Retention duration for reporting data (Dashboard)'), $attrsText2); $form->addElement('checkbox', 'audit_log_option', _('Enable/Disable audit logs')); $form->addElement('text', 'audit_log_retention', _('Retention duration for audit logs'), $attrsText2); $form->addRule('len_storage_downtimes', _('Mandatory field'), 'required'); $form->addRule('len_storage_downtimes', _('Must be a number'), 'numeric'); // Parameters for Partitioning $form->addElement('text', 'partitioning_retention', _('Retention duration for partitioning'), $attrsText2); $form->addElement('text', 'partitioning_retention_forward', _('Forward provisioning'), $attrsText2); $form->addElement('text', 'partitioning_backup_directory', _('Backup directory for partitioning'), $attrsText); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('RRDdatabase_path', 'slash'); $form->applyFilter('RRDdatabase_status_path', 'slash'); $form->applyFilter('RRDdatabase_nagios_stats_path', 'slash'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'centstorage/'); $form->setDefaults($gopt); $centreon->initOptGen($pearDB); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $valid = false; if ($form->validate()) { // Update in DB updateODSConfigData(); updatePartitioningConfigData($pearDB, $form, $centreon); $centreon->initOptGen($pearDB); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('Impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=storage'", 'class' => 'btc bt_info'] ); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('ods_log_retention_unit', _('days')); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $tpl->assign('form', $renderer->toArray()); $tpl->assign('valid', $valid); $tpl->assign('o', $o); $tpl->display('form.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/remote/formRemote.php
centreon/www/include/Administration/parameters/remote/formRemote.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 Security\Encryption; if (! isset($centreon)) { exit(); } require_once 'DB-Func.php'; // Set encryption parameters require_once _CENTREON_PATH_ . '/src/Security/Encryption.php'; if (file_exists(_CENTREON_PATH_ . '/.env.local.php')) { $localEnv = @include _CENTREON_PATH_ . '/.env.local.php'; } if (empty($localEnv) || ! isset($localEnv['APP_SECRET'])) { exit(); } define('SECOND_KEY', base64_encode('api_remote_credentials')); // Check ACL if (! $centreon->user->admin && $contactId) { $aclOptions = [ 'fields' => ['contact_id', 'contact_name'], 'keys' => ['contact_id'], 'get_row' => 'contact_name', 'conditions' => ['contact_id' => $contactId], ]; $contacts = $acl->getContactAclConf($aclOptions); if (! count($contacts)) { include_once _CENTREON_PATH_ . '/www/include/core/errors/alt_error.php'; return null; } } // Retrieve data and Check if this server is a Remote Server $result = []; $dbResult = $pearDB->query('SELECT * FROM `informations`'); while ($row = $dbResult->fetch(PDO::FETCH_ASSOC)) { $result[$row['key']] = $row['value']; } if ($result['isRemote'] !== 'yes') { include_once _CENTREON_PATH_ . '/www/include/core/errors/alt_error.php'; return null; } $dbResult->closeCursor(); /** * Decrypt credentials */ $centreonEncryption = new Encryption(); $decrypted = ''; try { $centreonEncryption->setFirstKey($localEnv['APP_SECRET'])->setSecondKey(SECOND_KEY); if (! empty($result['apiUsername'])) { $decryptResult = $centreonEncryption->decrypt($result['apiCredentials'] ?? ''); } } catch (Exception $e) { unset($result['apiCredentials']); $errorMsg = _('The password cannot be decrypted. Please re-enter the account password and submit the form'); echo "<div class='msg' align='center'>" . $errorMsg . '</div>'; } /** * form */ $attrsText = ['size' => '40']; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'remote'); $form->addElement('header', 'title', _('Remote access')); $form->addElement('header', 'information', _("Central's API credentials")); $form->addElement( 'text', 'apiUsername', _('Username'), $attrsText ); $form->addRule('apiUsername', _('Required Field'), 'required'); $form->addElement( 'password', 'apiCredentials', _('Password'), ['size' => '40', 'autocomplete' => 'new-password', 'id' => 'passwd1', 'onFocus' => 'resetPwdType(this);'] ); $form->addRule('apiCredentials', _('Required Field'), 'required'); $form->setRequiredNote("<font style='color: red;'>*</font>&nbsp;" . _('Required fields')); // default values $form->setDefaults( [ 'apiUsername' => $result['apiUsername'], 'apiCredentials' => (! empty($decryptResult) ? CentreonAuth::PWS_OCCULTATION : ''), ] ); // URI $form->addElement('header', 'informationUri', _("Central's API URI")); $form->addElement( 'select', 'apiScheme', _('Build full URI (SCHEME://IP:PORT/PATH).'), ['http' => 'http', 'https' => 'https'], ['id' => 'apiScheme', 'onChange' => 'checkSsl(this.value)'] ); $apiScheme = $result['apiScheme'] ?: 'http'; $sslVisibility = $apiScheme === 'http' ? 'hidden' : 'visible'; $form->setDefaults($apiScheme); $form->addElement('header', 'informationIp', $result['authorizedMaster']); $form->addElement( 'text', 'apiPath', _('apiPath'), $attrsText ); $form->addRule('apiPath', _('Required Field'), 'required'); $form->registerRule('validateApiPort', 'callback', 'validateApiPort'); $form->addElement('text', 'apiPort', _('Port'), ['size' => '8', 'id' => 'apiPort']); $form->addRule('apiPort', _('Must be a number between 1 and 65335 included.'), 'validateApiPort'); $form->addRule('apiPort', _('Required Field'), 'required'); $form->addElement( 'checkbox', 'apiPeerValidation', _('Allow self signed certificate'), null ); $form->setDefaults(1); $form->setDefaults( [ 'apiPath' => $result['apiPath'], 'apiPort' => $result['apiPort'], 'apiScheme' => $result['apiScheme'], 'apiPeerValidation' => ($result['apiPeerValidation'] == 'yes' ? 0 : 1), ] ); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { // Update or insert data in DB updateRemoteAccessCredentials($pearDB, $form, $centreonEncryption); $o = 'remote'; $valid = true; $form->freeze(); } $form->addElement( 'button', 'change', _('Modify'), [ 'onClick' => "javascript:window.location.href='?p=" . $p . "&o=remote'", 'class' => 'btc bt_info', ] ); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<style color="red" size="1">*</style>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('sslVisibility', $sslVisibility); $tpl->assign('valid', $valid); $tpl->display('formRemote.ihtml'); ?> <script type='text/javascript' src='./include/common/javascript/keygen.js'></script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/remote/help.php
centreon/www/include/Administration/parameters/remote/help.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 * */ $help = []; $help['username'] = dgettext( 'help', "Enter the name of an active contact who have the right to 'reach API configuration' on the Central." . 'This user will be used to call the API from the Remote to the Central.' ); $help['password'] = dgettext( 'help', 'Enter the current password of this account.' ); $help['tip_api_uri'] = dgettext( 'help', "Full URL allowing access to the API of the Centreon's central server." ); $help['tip_api_peer_validation'] = dgettext( 'help', "Allows to skip the SSL certificate check on the Centreon's central server." );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/remote/DB-Func.php
centreon/www/include/Administration/parameters/remote/DB-Func.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 * */ function validateApiPort($port) { $port = filter_var($port, FILTER_VALIDATE_INT); return ! ($port === false || $port < 1 || $port > 65335); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/list.php
centreon/www/include/Administration/parameters/ldap/list.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 * */ include './include/common/autoNumLimit.php'; require_once __DIR__ . '/listFunction.php'; $labels = ['name' => _('Name'), 'description' => _('Description'), 'status' => _('Status'), 'enabled' => _('Enabled'), 'disabled' => _('Disabled')]; $searchLdap = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchLdap'] ?? $_GET['searchLdap'] ?? null ); $ldapConf = new CentreonLdapAdmin($pearDB); if (isset($_POST['searchLdap']) || isset($_GET['searchLdap'])) { $centreon->historySearch = []; $centreon->historySearch[$url]['searchLdap'] = $searchLdap; } else { $searchLdap = $centreon->historySearch[$url]['searchLdap'] ?? null; } $list = $ldapConf->getLdapConfigurationList($searchLdap); $rows = count($list); $enableLdap = 0; foreach ($list as $k => $v) { if ($v['ar_enable']) { $enableLdap = 1; } } $statement = $pearDB->prepare("UPDATE options SET `value` = :value WHERE `key` = 'ldap_auth_enable'"); $statement->bindValue(':value', $enableLdap, PDO::PARAM_STR); $statement->execute(); include './include/common/checkPagination.php'; $list = $ldapConf->getLdapConfigurationList($searchLdap, ($num * $limit), $limit); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'ldap/'); $form = new HTML_QuickFormCustom('select_form', 'POST', '?o=ldap&p=' . $p); $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "&o=ldap');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); $tpl->assign('list', $list); $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=ldap&new=1', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')], getActionList('o1') ); $form->setDefaults(['o1' => null]); $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')], getActionList('o2') ); $form->setDefaults(['o2' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $o1->setSelected(null); $o2 = $form->getElement('o2'); $o2->setValue(null); $o2->setSelected(null); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('limit', $limit); $tpl->assign('form', $renderer->toArray()); $tpl->assign('labels', $labels); $tpl->assign('searchLdap', $searchLdap); $tpl->assign('p', $p); $tpl->display('list.ihtml'); ?> <script type="text/javascript"> function setA(_i) { document.forms['form'].elements['a'].value = _i; } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/ldap.php
centreon/www/include/Administration/parameters/ldap/ldap.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/centreonLDAP.class.php'; require_once _CENTREON_PATH_ . 'www/class/CentreonLDAPAdmin.class.php'; $tpl = new Smarty(); if (isset($_REQUEST['ar_id']) || isset($_REQUEST['new'])) { include _CENTREON_PATH_ . 'www/include/Administration/parameters/ldap/form.php'; } else { $ldapAction = $_REQUEST['a'] ?? null; if (! is_null($ldapAction) && isset($_REQUEST['select']) && is_array($_REQUEST['select'])) { $select = $_REQUEST['select']; $ldapConf = new CentreonLdapAdmin($pearDB); switch ($ldapAction) { case 'd': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $ldapConf->deleteConfiguration($select); } else { unvalidFormMessage(); } break; case 'ms': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $ldapConf->setStatus(1, $select); } else { unvalidFormMessage(); } break; case 'mu': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $ldapConf->setStatus(0, $select); } else { unvalidFormMessage(); } break; default: break; } } include _CENTREON_PATH_ . 'www/include/Administration/parameters/ldap/list.php'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/help.php
centreon/www/include/Administration/parameters/ldap/help.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 * */ $help = []; // LDAP Information $help['ar_name'] = dgettext('help', 'Name of configuration'); $help['ar_description'] = dgettext('help', 'Short description of configuration'); $help['ldap_auth_enable'] = dgettext('help', 'Enable LDAP authentication'); $help['ldap_store_password'] = dgettext('help', 'Whether or not the password should be stored in database'); $help['ldap_auto_import'] = dgettext('help', 'Can connect with LDAP without import'); $help['ldap_contact_tmpl'] = dgettext( 'help', 'The contact template for auto imported user.<br/>' . 'This template is applied for Monitoring Engine contact configuration and ACLs.' ); $help['ldap_default_cg'] = dgettext( 'help', 'Default contact group applied to new users.<br/>' . 'All imported users will join this contactgroup.' ); $help['ldap_srv_dns'] = dgettext('help', 'Use the DNS service for get LDAP host'); $help['ldap_srv_dns_ssl'] = dgettext('help', 'Enable SSL connection'); $help['ldap_srv_dns_tls'] = dgettext('help', 'Enable TLS connection'); $help['ldap_dns_use_domain'] = dgettext('help', 'Set the domain for search the service'); $help['ldap_connection_timeout'] = dgettext('help', 'Connection timeout'); $help['ldap_search_limit'] = dgettext('help', 'Search size limit'); $help['ldap_search_timeout'] = dgettext('help', 'Search timeout'); $help['ldapConf'] = dgettext( 'help', 'Ldap server. Failover will take place if multiple servers are defined.<br/>' . 'If TLS is enabled, make sure to configure the certificate requirements on the ldap.conf' . ' file and restart your web server.' ); $help['bind_dn'] = dgettext('help', 'User DN for connect to LDAP in read only'); $help['bind_pass'] = dgettext('help', 'Password for connect to LDAP in read only'); $help['protocol_version'] = dgettext( 'help', 'The version protocol for connect to LDAP<br/>Use version 3 for Active Directory' ); $help['ldap_template'] = dgettext('help', 'Template for LDAP attribute'); $help['user_base_search'] = dgettext('help', 'The base DN for search users'); $help['group_base_search'] = dgettext('help', 'The base DN for search groups'); $help['user_filter'] = dgettext( 'help', 'The LDAP search filter for users<br/>' . 'Use %s in filter. The %s will replaced by login in autologin or * in LDAP import' ); $help['group_filter'] = dgettext( 'help', 'The LDAP search filter for groups<br/>' . 'Use %s in filter. The %s will replaced by group name in autologin or * in contactgroup field' ); $help['alias'] = dgettext('help', 'The login attribute<br/>In Centreon : Alias / Login'); $help['user_group'] = dgettext('help', 'The group attribute for user'); $help['user_name'] = dgettext('help', 'The user name<br/>In Centreon : Full Name'); $help['user_firstname'] = dgettext('help', 'The user firstname<br/>In Centreon : givenname'); $help['user_lastname'] = dgettext('help', 'The user lastname<br/>In Centreon : sn'); $help['user_email'] = dgettext('help', 'The user email<br/>In Centreon : Email'); $help['user_pager'] = dgettext('help', 'The user pager<br/>In Centreon : Pager'); $help['group_name'] = dgettext('help', 'The group name<br/>In Centreon : Contact Group Name'); $help['group_member'] = dgettext('help', 'The LDAP attribute for relation between group and user'); $help['ldap_sync_interval'] = dgettext( 'help', 'This field is used to specify the interval, in hours, between two LDAP data synchronization. By default 1 hour.' ); $help['ldap_auto_sync'] = dgettext( 'help', "If enabled, a user LDAP synchronization will be performed on login to update contact's data and calculate " . 'new Centreon ACLs.' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/listFunction.php
centreon/www/include/Administration/parameters/ldap/listFunction.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 * */ /** * Get toolbar action list * * @param string $domName * @return array */ function getActionList($domName) { return ['onchange' => 'javascript: ' . "if (this.form.elements['{$domName}'].selectedIndex == 1 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setA(this.form.elements['{$domName}'].value); submit();} " . "else if (this.form.elements['{$domName}'].selectedIndex == 2) {" . " setA(this.form.elements['{$domName}'].value); submit();} " . "else if (this.form.elements['{$domName}'].selectedIndex == 3) {" . " setA(this.form.elements['{$domName}'].value); submit();} " . "this.form.elements['{$domName}'].selectedIndex = 0"]; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/DB-Func.php
centreon/www/include/Administration/parameters/ldap/DB-Func.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 * */ /** * @param $value integer * @return bool : the compliance state of the rule */ function minimalValue(int $value): bool { $value = filter_var( $value, FILTER_VALIDATE_INT ); return (bool) (is_int($value) && $value >= 1); } /** * BAsic check if the LDAP filter syntax is valid according to RFC4515 * * @param string $filterValue * @return bool */ function checkLdapFilterSyntax(string $filterValue): bool { if ($filterValue === '') { return false; } // check for parentheses if (substr_count($filterValue, '(') !== substr_count($filterValue, ')') || ! str_starts_with($filterValue, '(') || ! str_ends_with($filterValue, ')')) { return false; } // reject multiple top-level filters if (preg_match('/^\([^()]*\)(.+)$/', $filterValue)) { return false; } $cleanFilter = preg_replace('/\\\\./', 'X', $filterValue); // filter should have at least one valid comparison if (! preg_match('/([a-zA-Z0-9][a-zA-Z0-9\.\-_]*|[0-9]+(?:\.[0-9]+)*)(?:=\*?[^=()]*\*?|>=|<=|~=|:(?:[^:=]*)?:=)[^=()]*/i', $cleanFilter)) { return false; } // first char after opening parenthesis should be &, |, !, or a valid attribute name starter if (! preg_match('/^\((&|\||!|[a-zA-Z0-9])/', $cleanFilter)) { return false; } // logical operators should be followed by an opening parenthesis if (preg_match('/\((&|\||!)[^(]/', $cleanFilter)) { return false; } // ! operator should be followed by exactly one filter if (preg_match('/^\(!\(/', $cleanFilter)) { if (! preg_match('/^\(!\([^()]*(?:\([^()]*\)[^()]*)*\)\)$/', $cleanFilter)) { return false; } } // reject double colons return ! (preg_match('/::/', $cleanFilter)); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/form.php
centreon/www/include/Administration/parameters/ldap/form.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 * */ if (! isset($oreon)) { exit(); } require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php'; require_once _CENTREON_PATH_ . 'www/class/CentreonLDAPAdmin.class.php'; require_once __DIR__ . '/DB-Func.php'; $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsTextarea = ['rows' => '4', 'cols' => '60']; $attrsAdvSelect = null; $arId = filter_var( $_POST['ar_id'] ?? $_GET['ar_id'] ?? 0, FILTER_VALIDATE_INT ); /** * Ldap form */ $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p . '&o=' . $o); $form->addElement('header', 'title', _('Modify General Options')); /** * Ldap info */ $form->addElement('header', 'ldap', _('General information')); $form->addElement('text', 'ar_name', _('Configuration name'), $attrsText); $form->addElement('textarea', 'ar_description', _('Description'), $attrsTextarea); $ldapEnable[] = $form->createElement('radio', 'ldap_auth_enable', null, _('Yes'), '1'); $ldapEnable[] = $form->createElement('radio', 'ldap_auth_enable', null, _('No'), '0'); $form->addGroup($ldapEnable, 'ldap_auth_enable', _('Enable LDAP authentication'), '&nbsp;'); $ldapStorePassword[] = $form->createElement('radio', 'ldap_store_password', null, _('Yes'), '1'); $ldapStorePassword[] = $form->createElement('radio', 'ldap_store_password', null, _('No'), '0'); $form->addGroup($ldapStorePassword, 'ldap_store_password', _('Store LDAP password'), '&nbsp;'); $ldapAutoImport[] = $form->createElement('radio', 'ldap_auto_import', null, _('Yes'), '1'); $ldapAutoImport[] = $form->createElement('radio', 'ldap_auto_import', null, _('No'), '0'); $form->addGroup($ldapAutoImport, 'ldap_auto_import', _('Auto import users'), '&nbsp;'); $ldapUseDns[] = $form->createElement( 'radio', 'ldap_srv_dns', null, _('Yes'), '1', ['id' => 'ldap_srv_dns_y', 'onclick' => 'toggleParams(false);'] ); $ldapUseDns[] = $form->createElement( 'radio', 'ldap_srv_dns', null, _('No'), '0', ['id' => 'ldap_srv_dns_n', 'onclick' => 'toggleParams(true);'] ); $form->addGroup($ldapUseDns, 'ldap_srv_dns', _('Use service DNS'), '&nbsp;'); $form->addElement('text', 'ldap_dns_use_domain', _('Alternative domain for ldap'), $attrsText); $form->addElement('text', 'ldap_connection_timeout', _('LDAP connection timeout'), $attrsText2); $form->addElement('text', 'ldap_search_limit', _('LDAP search size limit'), $attrsText2); $form->addElement('text', 'ldap_search_timeout', _('LDAP search timeout'), $attrsText2); /** * LDAP's scanning options sub menu */ $form->addElement('header', 'ldapScanOption', _('Synchronization Options')); // option to disable the auto-scan of the LDAP - by default auto-scan is enabled $ldapAutoScan[] = $form->createElement( 'radio', 'ldap_auto_sync', null, _('Yes'), '1', ['id' => 'ldap_auto_sync_y', 'onclick' => 'toggleParamSync(false);'] ); $ldapAutoScan[] = $form->createElement( 'radio', 'ldap_auto_sync', null, _('No'), '0', ['id' => 'ldap_auto_sync_n', 'onclick' => 'toggleParamSync(true);'] ); $form->addGroup($ldapAutoScan, 'ldap_auto_sync', _('Enable LDAP synchronization on login'), '&nbsp;'); // default interval before re-scanning the whole LDAP. By default, a duration of one hour is set $form->addElement('text', 'ldap_sync_interval', _('LDAP synchronization interval (in hours)'), $attrsText2); $form->addRule('ldap_sync_interval', _('Compulsory field'), 'required'); // A minimum value of 1 hour is required and it should be an integer $form->registerRule('minimalValue', 'callback', 'minimalValue'); $form->addRule('ldap_sync_interval', _('An integer with a minimum value of 1 is required'), 'minimalValue'); /** * list of contact template available */ $res = $pearDB->query( "SELECT contact_id, contact_name FROM contact WHERE contact_register = '0'" ); $LdapContactTplList = []; while ($row = $res->fetch()) { $LdapContactTplList[$row['contact_id']] = $row['contact_name']; } $res->closeCursor(); $form->addElement( 'select', 'ldap_contact_tmpl', _('Contact template'), $LdapContactTplList, ['id' => 'ldap_contact_tmpl'] ); $form->addRule('ldap_contact_tmpl', _('Compulsory Field'), 'required'); /** * Default contactgroup for imported contact */ $cgAvRoute = './api/internal.php?object=centreon_configuration_contactgroup&action=list'; $cgDeRoute = './api/internal.php?object=centreon_configuration_contactgroup' . '&action=defaultValues&target=contact&field=ldap_default_cg&id=' . $arId; $attrContactGroup = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $cgAvRoute, 'defaultDatasetRoute' => $cgDeRoute, 'multiple' => false, 'linkedObject' => 'centreonContactgroup']; $form->addElement('select2', 'ldap_default_cg', _('Default contactgroup'), [], $attrContactGroup); $form->addElement('header', 'ldapinfo', _('LDAP Information')); $form->addElement('header', 'ldapserver', _('LDAP Servers')); $form->addElement('text', 'bind_dn', _('Bind user'), ['size' => '40', 'autocomplete' => 'off']); $form->addElement('password', 'bind_pass', _('Bind password'), ['size' => '40', 'autocomplete' => 'new-password']); $form->addElement('select', 'protocol_version', _('Protocol version'), ['3' => 3, '2' => 2]); $form->addElement( 'select', 'ldap_template', _('Template'), ['0' => '', 'Active Directory' => _('Active Directory'), 'Okta' => _('Okta'), 'Posix' => _('Posix')], ['id' => 'ldap_template', 'onchange' => 'applyTemplate(this.value);'] ); $form->registerRule('checkLdapFilter', 'callback', 'checkLdapFilterSyntax'); $form->addElement('text', 'user_base_search', _('Search user base DN'), $attrsText); $form->addElement('text', 'group_base_search', _('Search group base DN'), $attrsText); $form->addElement('text', 'user_filter', _('User filter'), $attrsText); $form->addRule('user_filter', _('Incorrect LDAP filter syntax'), 'checkLdapFilter'); $form->addElement('text', 'alias', _('Login attribute'), $attrsText); $form->addElement('text', 'user_group', _('User group attribute'), $attrsText); $form->addElement('text', 'user_name', _('User displayname attribute'), $attrsText); $form->addElement('text', 'user_firstname', _('User firstname attribute'), $attrsText); $form->addElement('text', 'user_lastname', _('User lastname attribute'), $attrsText); $form->addElement('text', 'user_email', _('User email attribute'), $attrsText); $form->addElement('text', 'user_pager', _('User pager attribute'), $attrsText); $form->addElement('text', 'group_filter', _('Group filter'), $attrsText); $form->addRule('group_filter', _('Incorrect LDAP filter syntax'), 'checkLdapFilter'); $form->addElement('text', 'group_name', _('Group attribute'), $attrsText); $form->addElement('text', 'group_member', _('Group member attribute'), $attrsText); $form->addRule('ar_name', _('Compulsory field'), 'required'); $form->addRule('ar_description', _('Compulsory field'), 'required'); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'ldap/'); $ldapAdmin = new CentreonLdapAdmin($pearDB); $defaultOpt = [ 'ldap_auth_enable' => '0', 'ldap_store_password' => '1', 'ldap_auto_import' => '0', 'ldap_srv_dns' => '0', 'ldap_template' => '1', 'ldap_version_protocol' => '3', 'ldap_dns_use_ssl' => '0', 'ldap_dns_use_tls' => '0', 'ldap_contact_tmpl' => '0', 'ldap_default_cg' => '0', 'ldap_connection_timeout' => '5', 'ldap_search_limit' => '60', 'ldap_auto_sync' => '1', // synchronization on user's login is enabled by default 'ldap_sync_interval' => '1', // minimal value of the interval between two LDAP synchronizations 'ldap_search_timeout' => '60', ]; $gopt = []; if ($arId) { $gopt = $ldapAdmin->getGeneralOptions($arId); $res = $pearDB->prepare( 'SELECT `ar_name`, `ar_description`, `ar_enable`, `ar_sync_base_date` FROM `auth_ressource` WHERE ar_id = :arId' ); $res->bindValue('arId', $arId, PDO::PARAM_INT); $res->execute(); while ($row = $res->fetch()) { // sanitize name and description $gopt['ar_name'] = HtmlAnalyzer::sanitizeAndRemoveTags($row['ar_name']); $gopt['ar_description'] = HtmlAnalyzer::sanitizeAndRemoveTags($row['ar_description']); $gopt['ldap_auth_enable'] = $row['ar_enable']; $gopt['ar_sync_base_date'] = $row['ar_sync_base_date']; } unset($res); // Preset values of ldap servers $cdata = CentreonData::getInstance(); $serversArray = $ldapAdmin->getServersFromResId($arId); $cdata->addJsData('clone-values-ldapservers', htmlspecialchars(json_encode($serversArray), ENT_QUOTES)); $cdata->addJsData('clone-count-ldapservers', count($serversArray)); } // LDAP servers $cloneSet = []; $cloneSet[] = $form->addElement( 'text', 'address[#index#]', _('Host address'), ['size' => '30', 'id' => 'address_#index#'] ); $cloneSet[] = $form->addElement( 'text', 'port[#index#]', _('Port'), ['size' => '10', 'id' => 'port_#index#'] ); $cbssl = $form->addElement( 'checkbox', 'ssl[#index#]', _('SSL'), '', ['id' => 'ssl_#index#'] ); $cbssl->setText(''); $cloneSet[] = $cbssl; $cbtls = $form->addElement( 'checkbox', 'tls[#index#]', _('TLS'), '', ['id' => 'tls_#index#'] ); $cbtls->setText(''); $cloneSet[] = $cbtls; $gopt = array_merge($defaultOpt, $gopt); $form->setDefaults($gopt); $ar = $form->addElement('hidden', 'ar_id'); $ar->setValue($arId); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $nbOfInitialRows = 0; $maxHostId = 1; if ($arId) { $res = $pearDB->prepare( 'SELECT COUNT(*) as nb FROM auth_ressource_host WHERE auth_ressource_id = :arId' ); $res->bindValue(':arId', (int) $arId, PDO::PARAM_INT); $res->execute(); $row = $res->fetch(); $nbOfInitialRows = $row['nb']; $res = $pearDB->prepare( 'SELECT MAX(ldap_host_id) as cnt FROM auth_ressource_host WHERE auth_ressource_id = :arId' ); $res->bindValue(':arId', (int) $arId, PDO::PARAM_INT); $res->execute(); if ($res->rowCount()) { $row = $res->fetch(); $maxHostId = $row['cnt']; } } require_once $path . 'ldap/javascript/ldapJs.php'; $valid = false; $filterValid = true; $validNameOrDescription = true; $allHostsOk = true; if ($form->validate()) { $values = $form->getSubmitValues(); // sanitize name and description $values['ar_name'] = HtmlAnalyzer::sanitizeAndRemoveTags($values['ar_name']); $values['ar_description'] = HtmlAnalyzer::sanitizeAndRemoveTags($values['ar_description']); // Check if sanitized name and description are not empty if ( $values['ar_name'] === '' || $values['ar_description'] === '' ) { $validNameOrDescription = false; } else { // Test if filter string is valid if (! CentreonLDAP::validateFilterPattern($values['user_filter'])) { $filterValid = false; } if (isset($_POST['ldapHosts'])) { foreach ($_POST['ldapHosts'] as $ldapHost) { if ($ldapHost['hostname'] == '' || $ldapHost['port'] == '') { $allHostsOk = false; } } } if ($filterValid && $allHostsOk) { if (! isset($values['ldap_contact_tmpl'])) { $values['ldap_contact_tmpl'] = ''; } if (! isset($values['ldap_default_cg'])) { $values['ldap_default_cg'] = ''; } // setting a reference time to calculate the expected synchronization $currentTime = time(); $values['ar_sync_base_date'] = $currentTime; // updating the next expected auto-sync at login if the admin has changed the sync options // or it never occurred if ( isset($values['ldap_auto_sync']['ldap_auto_sync']) && $gopt['ldap_auto_sync'] === $values['ldap_auto_sync']['ldap_auto_sync'] && ! empty($gopt['ar_sync_base_date']) && ($gopt['ar_sync_base_date'] + ($values['ldap_sync_interval'] * 3600)) > $currentTime && $currentTime > $gopt['ar_sync_base_date'] ) { // distinguishing the enabled and disabled cases if ( $values['ldap_auto_sync']['ldap_auto_sync'] == 0 || ($values['ldap_auto_sync']['ldap_auto_sync'] == 1 && $gopt['ldap_sync_interval'] == $values['ldap_sync_interval']) ) { // synchronization parameters have not changed, the reference time shouldn't be updated $values['ar_sync_base_date'] = $gopt['ar_sync_base_date']; } } $arId = $ldapAdmin->setGeneralOptions($values, $values['ar_id']); $o = 'w'; $valid = true; if (! isset($values['ldap_srv_dns']['ldap_srv_dns']) || ! $values['ldap_srv_dns']['ldap_srv_dns']) { $tpl->assign('hideDnsOptions', 1); } else { $tpl->assign('hideDnsOptions', 0); } $tpl->assign('hideSyncInterval', (int) $values['ldap_auto_sync']['ldap_auto_sync'] ?? 0); $form->freeze(); } } } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('Impossible to validate, one or more field is incorrect') . '</div>'; } elseif ($filterValid === false) { echo "<div class='msg' align='center'>" . _('Bad ldap filter: missing %s pattern. Check user or group filter') . '</div>'; } elseif ($allHostsOk === false) { echo "<div class='msg' align='center'>" . _('Invalid LDAP Host parameters') . '</div>'; } elseif ($validNameOrDescription === false) { echo "<div class='msg' align='center'>" . _('Invalid name or description') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=ldap&ar_id=' . $arId . "'"] ); // Prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); if ($valid) { require_once $path . 'ldap/list.php'; } else { // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('hideSyncInterval', 0); $tpl->assign('form', $renderer->toArray()); $tpl->assign('centreon_path', $centreon->optGen['oreon_path']); $tpl->assign('cloneSet', $cloneSet); $tpl->assign('o', $o); $tpl->assign('optGen_ldap_properties', _('LDAP Properties')); $tpl->assign('addNewHostLabel', _('LDAP servers')); $tpl->assign('manualImport', _('Import users manually')); $tpl->assign('valid', $valid); $tpl->display('form.ihtml'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/ldap/javascript/ldapJs.php
centreon/www/include/Administration/parameters/ldap/javascript/ldapJs.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 * */ ?> <script type="text/javascript"> function mk_pagination() {} function mk_paginationFF() {} function set_header_title() {} let ldapTemplates = []; /* * called when the use _dns is to set at no is clicked */ function toggleParams(checkValue) { if (checkValue === true) { jQuery('#ldap_dns_use_ssl').fadeOut({duration: 0}); jQuery('#ldap_dns_use_tls').fadeOut({duration: 0}); jQuery('#ldap_dns_use_domain').fadeOut({duration: 0}); jQuery('#ldap_header_tr').fadeIn({duration: 0}); jQuery('#ldap_tr').fadeIn({duration: 0}); } else { jQuery('#ldap_header_tr').fadeOut({duration: 0}); jQuery('#ldap_tr').fadeOut({duration: 0}); if (document.getElementById('ldap_dns_use_ssl')) { jQuery('#ldap_dns_use_ssl').fadeIn({duration: 0}); } if (document.getElementById('ldap_dns_use_tls')) { jQuery('#ldap_dns_use_tls').fadeIn({duration: 0}); } if (document.getElementById('ldap_dns_use_domain')) { jQuery('#ldap_dns_use_domain').fadeIn({duration: 0}); } } } /* * called when LDAP is enabled or not */ function toggleParamSync(checkValue) { if (checkValue === true) { jQuery('#ldap_sync_interval').fadeOut({duration: 0}); } else { jQuery('#ldap_sync_interval').fadeIn({duration: 0}); } } /* * Initialises advanced parameters */ function initParams() { initTemplates(); let noDns = false; if (document.getElementById('ldap_srv_dns_n')) { if (document.getElementById('ldap_srv_dns_n').type === 'radio') { if (document.getElementById('ldap_srv_dns_n').checked) { noDns = true; } } } // getting saved synchronization interval's time field state let loginSync = false; let loginCheckbox = document.getElementById('ldap_auto_sync_n'); if (loginCheckbox && loginCheckbox.type === 'radio' && loginCheckbox.checked ) { loginSync = true; } // displaying or hiding toggling fields toggleParams(noDns); toggleParamSync(loginSync); } /* * Initializes templates */ function initTemplates() { ldapTemplates = []; ldapTemplates['Active Directory'] = []; ldapTemplates['Active Directory']['user_filter'] = '(&(samAccountName=%s)(objectClass=user)(samAccountType=805306368))'; ldapTemplates['Active Directory']['alias'] = 'samaccountname'; ldapTemplates['Active Directory']['user_group'] = 'memberOf'; ldapTemplates['Active Directory']['user_name'] = 'name'; ldapTemplates['Active Directory']['user_firstname'] = 'givenname'; ldapTemplates['Active Directory']['user_lastname'] = 'sn'; ldapTemplates['Active Directory']['user_email'] = 'mail'; ldapTemplates['Active Directory']['user_pager'] = 'mobile'; ldapTemplates['Active Directory']['group_filter'] = '(&(samAccountName=%s)(objectClass=group)(samAccountType=268435456))'; ldapTemplates['Active Directory']['group_name'] = 'samaccountname'; ldapTemplates['Active Directory']['group_member'] = 'member'; ldapTemplates['Posix'] = []; ldapTemplates['Posix']['user_filter'] = '(&(uid=%s)(objectClass=inetOrgPerson))'; ldapTemplates['Posix']['alias'] = 'uid'; ldapTemplates['Posix']['user_group'] = ''; ldapTemplates['Posix']['user_name'] = 'cn'; ldapTemplates['Posix']['user_firstname'] = 'givenname'; ldapTemplates['Posix']['user_lastname'] = 'sn'; ldapTemplates['Posix']['user_email'] = 'mail'; ldapTemplates['Posix']['user_pager'] = 'mobile'; ldapTemplates['Posix']['group_filter'] = '(&(cn=%s)(objectClass=groupOfNames))'; ldapTemplates['Posix']['group_name'] = 'cn'; ldapTemplates['Posix']['group_member'] = 'member'; ldapTemplates['Okta'] = []; ldapTemplates['Okta']['user_filter'] = '(&(nickName=%s)(objectclass=inetorgperson))'; ldapTemplates['Okta']['alias'] = 'nickname'; ldapTemplates['Okta']['user_group'] = 'memberof'; ldapTemplates['Okta']['user_name'] = 'cn'; ldapTemplates['Okta']['user_firstname'] = 'givenname'; ldapTemplates['Okta']['user_lastname'] = 'sn'; ldapTemplates['Okta']['user_email'] = 'mail'; ldapTemplates['Okta']['user_pager'] = 'mobile'; ldapTemplates['Okta']['group_filter'] = '(&(cn=%s)(objectclass=groupofuniquenames))'; ldapTemplates['Okta']['group_name'] = 'cn'; ldapTemplates['Okta']['group_member'] = 'uniquemember'; } /* * Apply template is called from the template selectbox */ function applyTemplate(templateValue) { jQuery('input[type^=text]').each(function (index, el) { let attr = el.getAttribute('name'); if (typeof(ldapTemplates[templateValue]) !== 'undefined') { if (typeof(ldapTemplates[templateValue][attr]) !== 'undefined') { el.value = ldapTemplates[templateValue][attr]; } } }); } jQuery(document).ready(function () { initParams(); }); </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/api/help.php
centreon/www/include/Administration/parameters/api/help.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 * */ $help = []; /** * Centreon Gorgone Settings */ $help['tip_gorgone_cmd_timeout'] = dgettext( 'help', 'Timeout value in seconds. Used to make actions calls timeout.' ); $help['tip_enable_broker_stats'] = dgettext( 'help', 'Enable Centreon Broker statistics collection into the central server in order to reduce the network load ' . 'generated by Centcore. Be carefull: broker statistics will not be available into Home > Broker statistics.' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/api/api.php
centreon/www/include/Administration/parameters/api/api.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 * */ if (! isset($centreon)) { exit(); } $DBRESULT = $pearDB->query('SELECT * FROM `options`'); while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt['key']] = myDecode($opt['value']); } $DBRESULT->closeCursor(); $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify Centcore options')); // Centcore Options $form->addElement('checkbox', 'enable_broker_stats', _('Enable Broker Statistics Collection')); $form->addElement('text', 'gorgone_cmd_timeout', _('Timeout value for Gorgone commands'), $attrsText2); $attrContacts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './include/common/webServices/rest/internal.php?' . 'object=centreon_configuration_contact&action=list', 'multiple' => true, 'linkedObject' => 'centreonContact']; $attrContact1 = array_merge( $attrContacts, ['defaultDatasetRoute' => './include/common/webServices/rest/internal.php?' . 'object=centreon_configuration_contact&action=defaultValues&target=contactgroup&field=cg_contacts&id=' . $cg_id] ); $form->addElement('select2', 'cg_contacts', _('Linked Contacts'), [], $attrContact1); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . '/api'); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { // Update in DB updateAPIConfigData($pearDB, $form, $centreon); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=centcore'", 'class' => 'btc bt_info'] ); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('valid', $valid); $tpl->display('api.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/general/help.php
centreon/www/include/Administration/parameters/general/help.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 * */ $help = []; /** * Centreon statistics */ $help['tip_send_statistics'] = dgettext( 'help', 'I agree to participate to the Centreon Customer Experience Improvement Program whereby anonymous information ' . 'about the usage of this server may be sent to Centreon. This information will solely be used to improve the ' . 'software user experience. I will be able to opt-out at anytime. Refer to ' . '<a style="text-decoration: underline" href="http://ceip.centreon.com/">ceip.centreon.com</a> ' . ' for further details.' ); /** * Centreon information */ $help['tip_directory'] = dgettext('help', 'Application directory of Centreon.'); $help['tip_centreon_web_directory'] = dgettext('help', 'Centreon Web URI.'); /** * Maximum page size */ $help['tip_limit_per_page'] = dgettext('help', 'Default number of displayed elements in listing pages.'); $help['tip_limit_per_page_for_monitoring'] = dgettext( 'help', 'Default number of displayed elements in monitoring consoles.' ); $help['tip_graph_per_page_for_performances'] = dgettext('help', 'Number of performance graphs displayed per page.'); $help['tip_select_paginagion_size'] = dgettext('help', 'The number elements loaded in async select.'); /** * Sessions Properties */ $help['tip_sessions_expiration_time'] = dgettext( 'help', 'Life duration of sessions. The value in minutes cannot be greater than the session.gc_maxlifetime value set ' . 'in your php centreon.ini file.' ); /** * Refresh Properties */ $help['tip_refresh_interval'] = dgettext('help', 'Refresh interval.'); $help['tip_refresh_interval_for_statistics'] = dgettext('help', 'Refresh interval used for statistics (top counters). Minimum value: 10'); $help['tip_refresh_interval_for_monitoring'] = dgettext('help', 'Refresh interval used in monitoring consoles. Minimum value: 10'); $help['tip_first_refresh_delay_for_statistics'] = dgettext( 'help', 'First refresh delay for statistics (top counters).' ); $help['tip_first_refresh_delay_for_monitoring'] = dgettext('help', 'First refresh delay for monitoring.'); /** * Display Options */ $help['tip_display_template'] = dgettext('help', 'CSS theme.'); /** * Problem display properties */ $help['tip_sort_problems_by'] = dgettext('help', 'Default sort in monitoring consoles.'); $help['tip_order_sort_problems'] = dgettext('help', 'Default order in monitoring consoles.'); /** * Notification */ $help['tip_notification_inheritance'] = dgettext( 'help', 'Notification inheritance for hosts and services. Vertical for the legacy mode, Close for the first valid object ' . 'and Cumulative for all valid object.' ); /** * Authentication properties */ $help['tip_enable_autologin'] = dgettext('help', 'Enables Autologin.'); $help['tip_display_autologin_shortcut'] = dgettext('help', 'Displays Autologin shortcut.'); /** * Time Zone */ $help['tip_default_timezone'] = dgettext('help', 'Default host and contact timezone.'); /** * SSO */ $help['sso_enable'] = dgettext( 'help', 'Whether SSO authentication is enabled. SSO feature have only to be enabled in a secured and dedicated environment' . ' for SSO. Direct access to Centreon UI from users have to be disabled.' ); $help['sso_mode'] = dgettext( 'help', 'Authentication can be solely based on SSO or it can work with both SSO and local authentication systems.' ); $help['sso_trusted_clients'] = dgettext( 'help', 'IP/DNS of trusted clients. Use coma as delimiter in case of multiple clients.' ); $help['sso_blacklist_clients'] = dgettext( 'help', 'IP/DNS of blacklist clients. Use coma as delimiter in case of multiple clients.' ); $help['sso_header_username'] = dgettext( 'help', 'The header variable that will be used as login. i.e: $_SERVER[\'HTTP_AUTH_USER\']' ); $help['sso_username_pattern'] = dgettext( 'help', 'The pattern to search for in the username. If i want to remove the domain of the email: /@.*/' ); $help['sso_username_replace'] = dgettext( 'help', 'The string to replace.' ); /** * OpenId Connect */ $help['openid_connect_enable'] = dgettext( 'help', 'Enable login with OpenId Connect.' ); $help['openid_connect_mode'] = dgettext( 'help', 'Authentication can be solely based on OpenId Connect or it can work with both OpenId Connect and local authentication systems.' ); $help['openid_connect_trusted_clients'] = dgettext( 'help', 'IP/DNS of trusted clients. Use coma as delimiter in case of multiple clients.' ); $help['openid_connect_blacklist_clients'] = dgettext( 'help', 'IP/DNS of blacklist clients. Use coma as delimiter in case of multiple clients.' ); $help['openid_connect_base_url'] = dgettext( 'help', 'Your OpenId Connect base Url (for example http://IP:8080/auth/realms/master/protocol/openid-connect).' ); $help['openid_connect_authorization_endpoint'] = dgettext( 'help', 'Your OpenId Connect Authorization endpoint (for example /auth).' ); $help['openid_connect_token_endpoint'] = dgettext( 'help', 'Your OpenId Connect Token endpoint (for example /token).' ); $help['openid_connect_introspection_endpoint'] = dgettext( 'help', 'Your OpenId Connect Introspection Token endpoint (for example /token/introspect).' ); $help['openid_connect_userinfo_endpoint'] = dgettext( 'help', 'Your OpenId Connect User Information endpoint (for example /userinfo).' ); $help['openid_connect_end_session_endpoint'] = dgettext( 'help', 'Your OpenId Connect End Session endpoint (for example /logout).' ); $help['openid_connect_scope'] = dgettext( 'help', 'Your OpenId Connect Scope (for example openid).' ); $help['openid_connect_login_claim'] = dgettext( 'help', 'Your OpenId Connect login claim value (if empty preferred_username will be used).' ); $help['openid_connect_redirect_url'] = dgettext( 'help', 'Your OpenId Connect redirect url (this server, {scheme}, {hostname} and {port} can be used for substitions,' . ' default is {scheme}://{hostname}:{port}/your_centreon_path/index.php if left empty).' ); $help['openid_connect_client_id'] = dgettext( 'help', 'Your OpenId Connect client ID.' ); $help['openid_connect_client_secret'] = dgettext( 'help', 'Your OpenId Connect client secret.' ); $help['openid_connect_client_basic_auth'] = dgettext( 'help', 'Switch token_endpoint_auth_method from client_secret_post to client_secret_basic' ); /** * UI bahvior */ $help['strict_hostParent_poller_management'] = dgettext( 'help', 'This option enable a strict mode for the management of parent links between hosts on different pollers.' . ' Some hosts can have a parent link between them even if they are not monitored by the same poller.' . ' Select yes if you want to block the UI in order to oblige user to let host with a declared relation on the' . ' same poller. if you select No, during the generation process, relation will be broken and not generated' . ' but kept with Centreon Broker Correlation module.' ); // Support Informations $help['tip_centreon_support_email'] = dgettext( 'help', 'Centreon Support email: this email is uses in the Centreon footer in order to have a quick' . ' link in order to open an issue to your help desk.' ); // Proxy options $help['tip_proxy_url'] = dgettext( 'help', 'URL of the proxy.' ); $help['tip_proxy_port'] = dgettext( 'help', 'Port of the proxy.' ); $help['tip_proxy_user'] = dgettext( 'help', 'User of the proxy (Only if you use basic authentication).' ); $help['tip_proxy_password'] = dgettext( 'help', 'Password of the proxy (Only if you use basic authentication).' ); // Chart options $help['tip_display_downtime_chart'] = dgettext( 'help', 'If this option is enable, the downtimes and acknowledgments will be displayed on metric chart.<br>' . '<b>Warning</b> : This option can slow down the display of chart.' ); $help['tip_display_comment_chart'] = dgettext( 'help', 'If this option is enabled, the comments will be displayed on the status chart.<br>' . '<b>Warning</b> : This option can slow down the display of the chart.' ); $help['tip_resource_status_search_mode'] = dgettext( 'help', 'This option can be used to avoid search performance issues in Resource status, when dealing with large amounts of data. Limited search: Free text search will be performed only on the following fields: host name, alias and address, and service description. Use if you have a large amount of data. Full search: Free text search will also be performed on the "information" field. This is appropriate only if you have a small amount of data, as it affects performance.' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/general/form.php
centreon/www/include/Administration/parameters/general/form.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__ . '/../../../../class/centreonGMT.class.php'; const RESOURCE_STATUS_LIMITED_SEARCH = 0; const RESOURCE_STATUS_FULL_SEARCH = 1; const VERTICAL_NOTIFICATION = 1; const CLOSE_NOTIFICATION = 2; const CUMULATIVE_NOTIFICATION = 3; if (! isset($centreon)) { exit(); } // getting the garbage collector value set define('SESSION_DURATION_LIMIT', (int) (ini_get('session.gc_maxlifetime') / 60)); $transcoKey = ['enable_autologin' => 'yes', 'display_autologin_shortcut' => 'yes', 'enable_gmt' => 'yes', 'strict_hostParent_poller_management' => 'yes', 'display_downtime_chart' => 'yes', 'display_comment_chart' => 'yes', 'send_statistics' => 'yes']; $dbResult = $pearDB->query("SELECT * FROM `options` WHERE `key` <> 'proxy_password'"); while ($opt = $dbResult->fetch()) { if (isset($transcoKey[$opt['key']])) { $gopt[$opt['key']][$transcoKey[$opt['key']]] = myDecode($opt['value']); } else { $gopt[$opt['key']] = myDecode($opt['value']); } } // Style $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; $autocompleteOff = ['autocomplete' => 'new-password']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify General Options')); // information $form->addElement('header', 'oreon', _('Centreon information')); $form->addElement('text', 'oreon_path', _('Directory'), $attrsText); $form->addElement('text', 'session_expire', _('Sessions Expiration Time'), $attrsText2); $inheritanceMode = []; $inheritanceMode[] = $form->createElement( 'radio', 'inheritance_mode', null, _('Vertical Inheritance Only'), VERTICAL_NOTIFICATION ); $inheritanceMode[] = $form->createElement( 'radio', 'inheritance_mode', null, _('Closest Value'), CLOSE_NOTIFICATION ); $inheritanceMode[] = $form->createElement( 'radio', 'inheritance_mode', null, _('Cumulative inheritance'), CUMULATIVE_NOTIFICATION ); $form->addGroup($inheritanceMode, 'inheritance_mode', _('Contacts & Contact groups method calculation'), '&nbsp;'); $form->setDefaults(['inheritance_mode' => CUMULATIVE_NOTIFICATION]); $resourceStatusSearchMode = []; $resourceStatusSearchMode[] = $form->createElement( 'radio', 'resource_status_search_mode', null, _('Limited search'), RESOURCE_STATUS_LIMITED_SEARCH ); $resourceStatusSearchMode[] = $form->createElement( 'radio', 'resource_status_search_mode', null, _('Full search'), RESOURCE_STATUS_FULL_SEARCH ); $form->addGroup($resourceStatusSearchMode, 'resource_status_search_mode', _('Free text search behavior'), '&nbsp;'); $form->setDefaults(['resource_status_search_mode' => RESOURCE_STATUS_FULL_SEARCH]); $limit = [10 => 10, 20 => 20, 30 => 30, 40 => 40, 50 => 50, 60 => 60, 70 => 70, 80 => 80, 90 => 90, 100 => 100]; $form->addElement('select', 'maxViewMonitoring', _('Limit per page for Monitoring'), $limit); $form->addElement('text', 'maxGraphPerformances', _('Graph per page for Performances'), $attrsText2); $form->addElement('text', 'maxViewConfiguration', _('Limit per page (default)'), $attrsText2); $form->addElement('text', 'AjaxTimeReloadStatistic', _('Refresh Interval for statistics'), $attrsText2); $form->addElement('text', 'AjaxTimeReloadMonitoring', _('Refresh Interval for monitoring'), $attrsText2); $form->addElement('text', 'selectPaginationSize', _('Number of elements loaded in select'), $attrsText2); $CentreonGMT = new CentreonGMT(); $GMTList = $CentreonGMT->getGMTList(); $form->addElement('select', 'gmt', _('Timezone'), $GMTList); $globalSortType = ['host_name' => _('Hosts'), 'last_state_change' => _('Duration'), 'service_description' => _('Services'), 'current_state' => _('Status'), 'last_check' => _('Last check'), 'output' => _('Output'), 'criticality_id' => _('Criticality'), 'current_attempt' => _('Attempt')]; $sortType = ['last_state_change' => _('Duration'), 'host_name' => _('Hosts'), 'service_description' => _('Services'), 'current_state' => _('Status'), 'last_check' => _('Last check'), 'plugin_output' => _('Output'), 'criticality_id' => _('Criticality')]; $form->addElement('select', 'global_sort_type', _('Sort by '), $globalSortType); $global_sort_order = ['ASC' => _('Ascending'), 'DESC' => _('Descending')]; $form->addElement('select', 'global_sort_order', _('Order sort '), $global_sort_order); $form->addElement('select', 'problem_sort_type', _('Sort problems by'), $sortType); $sort_order = ['ASC' => _('Ascending'), 'DESC' => _('Descending')]; $form->addElement('select', 'problem_sort_order', _('Order sort problems'), $sort_order); $options1[] = $form->createElement( 'checkbox', 'yes', '&nbsp;', '', ['id' => 'enableAutoLogin', 'data-testid' => _('Enable Autologin')] ); $form->addGroup($options1, 'enable_autologin', _('Enable Autologin'), '&nbsp;&nbsp;'); $options2[] = $form->createElement('checkbox', 'yes', '&nbsp;', ''); $form->addGroup($options2, 'display_autologin_shortcut', _('Display Autologin shortcut'), '&nbsp;&nbsp;'); // statistics options $stat = []; $stat[] = $form->createElement('checkbox', 'yes', '&nbsp;', ''); $form->addGroup($stat, 'send_statistics', _('Send anonymous statistics'), '&nbsp;&nbsp;'); // Proxy options $form->addElement('text', 'proxy_url', _('Proxy URL'), $attrsText); $form->addElement( 'button', 'test_proxy', _('Test Internet Connection'), ['class' => 'btc bt_success', 'onClick' => 'javascript:checkProxyConf()'] ); $form->addElement('text', 'proxy_port', _('Proxy port'), $attrsText2); $form->addElement('text', 'proxy_user', _('Proxy user'), array_merge($attrsText, $autocompleteOff)); $form->addElement('password', 'proxy_password', _('Proxy password'), array_merge($attrsText, $autocompleteOff)); /** * Charts options */ $displayDowntimeOnChart[] = $form->createElement('checkbox', 'yes', '&nbsp;', ''); $form->addGroup( $displayDowntimeOnChart, 'display_downtime_chart', _('Display downtime and acknowledgment on chart'), '&nbsp;&nbsp;' ); $displayCommentOnChart[] = $form->createElement('checkbox', 'yes', '&nbsp;', ''); $form->addGroup( $displayCommentOnChart, 'display_comment_chart', _('Display comment on chart'), '&nbsp;&nbsp;' ); $options3[] = $form->createElement('checkbox', 'yes', '&nbsp;', ''); $form->addGroup($options3, 'enable_gmt', _('Enable Timezone management'), '&nbsp;&nbsp;'); // Support Email $form->addElement('text', 'centreon_support_email', _('Centreon Support Email'), $attrsText); $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('nagios_path', 'slash'); $form->applyFilter('nagios_path_plugins', 'slash'); $form->applyFilter('oreon_path', 'slash'); $form->applyFilter('debug_path', 'slash'); $form->registerRule('is_valid_path', 'callback', 'is_valid_path'); $form->registerRule('is_readable_path', 'callback', 'is_readable_path'); $form->registerRule('is_executable_binary', 'callback', 'is_executable_binary'); $form->registerRule('is_writable_path', 'callback', 'is_writable_path'); $form->registerRule('is_writable_file', 'callback', 'is_writable_file'); $form->registerRule('is_writable_file_if_exist', 'callback', 'is_writable_file_if_exist'); $form->registerRule('greaterthan', 'callback', 'is_greater_than'); $form->addRule('oreon_path', _('Mandatory field'), 'required'); $form->addRule('oreon_path', _("Can't write in directory"), 'is_valid_path'); $form->addRule('AjaxTimeReloadMonitoring', _('Mandatory field'), 'required'); $form->addRule('AjaxTimeReloadMonitoring', _('Must be a number'), 'numeric'); $form->addRule('AjaxTimeReloadMonitoring', _('The minimum allowed value is 10'), 'greaterthan', 10); $form->addRule('AjaxTimeReloadStatistic', _('Mandatory field'), 'required'); $form->addRule('AjaxTimeReloadStatistic', _('Must be a number'), 'numeric'); $form->addRule('AjaxTimeReloadStatistic', _('The minimum allowed value is 10'), 'greaterthan', 10); $form->addRule('selectPaginationSize', _('Mandatory field'), 'required'); $form->addRule('selectPaginationSize', _('Must be a number'), 'numeric'); $form->addRule('maxGraphPerformances', _('Mandatory field'), 'required'); $form->addRule('maxGraphPerformances', _('Must be a number'), 'numeric'); $form->addRule('maxViewConfiguration', _('Mandatory field'), 'required'); $form->addRule('maxViewConfiguration', _('Must be a number'), 'numeric'); $form->addRule('maxViewMonitoring', _('Mandatory field'), 'required'); $form->addRule('maxViewMonitoring', _('Must be a number'), 'numeric'); $form->addRule('session_expire', _('Mandatory field'), 'required'); $form->addRule('session_expire', _('Must be a number'), 'numeric'); $form->registerRule('isSessionDurationValid', 'callback', 'isSessionDurationValid'); $form->addRule( 'session_expire', _('This value needs to be an integer lesser than') . ' ' . SESSION_DURATION_LIMIT . ' min', 'isSessionDurationValid' ); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'general/'); $form->setDefaults($gopt); $subC = $form->addElement( 'submit', 'submitC', _('Save'), ['class' => 'btc bt_success', 'id' => 'submitGeneralOptionsForm', 'data-testid' => _('Save')] ); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $valid = false; if ($form->validate()) { try { // Update in DB updateGeneralConfigData(); // Update in Oreon Object $centreon->initOptGen($pearDB); $o = null; $valid = true; /** * Freeze the form and reload the page */ $form->freeze(); $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=general'", 'class' => 'btc bt_info'] ); $_SESSION[$sessionKeyFreeze] = true; echo '<script>parent.location.href = "main.php?p=' . $p . '&o=general";</script>'; exit; } catch (InvalidArgumentException $e) { echo "<div class='msg' align='center'>" . $e->getMessage() . '</div>'; $valid = false; } } elseif (array_key_exists($sessionKeyFreeze, $_SESSION) && $_SESSION[$sessionKeyFreeze] === true) { unset($_SESSION[$sessionKeyFreeze]); $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=general'", 'class' => 'btc bt_info'] ); $form->freeze(); $valid = true; } // Send variable to template $tpl->assign('o', $o); $tpl->assign('sorting', _('Sorting')); $tpl->assign('notification', _('Notification')); $tpl->assign('genOpt_max_page_size', _('Maximum page size')); $tpl->assign('genOpt_expiration_properties', _('Sessions Properties')); $tpl->assign('time_min', _('minutes')); $tpl->assign('genOpt_refresh_properties', _('Refresh Properties')); $tpl->assign('time_sec', _('seconds')); $tpl->assign('genOpt_global_display', _('Display properties')); $tpl->assign('genOpt_problem_display', _('Problem display properties')); $tpl->assign('genOpt_time_zone', _('Time Zone')); $tpl->assign('genOpt_auth', _('Authentication properties')); $tpl->assign('support', _('Support Information')); $tpl->assign('statistics', _('Statistics')); $tpl->assign('resource_status_performance', _('Resource status performance')); $tpl->assign('valid', $valid); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('form.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/knowledgeBase/formKnowledgeBase.php
centreon/www/include/Administration/parameters/knowledgeBase/formKnowledgeBase.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 * */ if (! isset($oreon)) { exit(); } $DBRESULT = $pearDB->query( "SELECT * FROM `options` WHERE options.key LIKE 'kb_%'" ); $originalPassword = null; while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt['key']] = myDecode($opt['value']); // store the value before occultation to be able to extract Vault Path if it is configured if ($opt['key'] === 'kb_wiki_password') { $originalPassword = $opt['value']; $gopt[$opt['key']] = CentreonAuth::PWS_OCCULTATION; } } $DBRESULT->closeCursor(); $attrsAdvSelect = null; $autocompleteOff = ['autocomplete' => 'new-password']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Knowledge base form $form->addElement('text', 'kb_wiki_url', _('Knowledge base url')); $form->addRule('kb_wiki_url', _('Mandatory field'), 'required'); $form->addElement('text', 'kb_wiki_account', _('Knowledge wiki account (with delete right)'), $autocompleteOff); $form->addRule('kb_wiki_account', _('Mandatory field'), 'required'); $form->addElement('password', 'kb_wiki_password', _('Knowledge wiki account password'), $autocompleteOff); $form->addRule('kb_wiki_password', _('Mandatory field'), 'required'); $form->addElement('checkbox', 'kb_wiki_certificate', 'ssl certificate', _('Ignore ssl certificate')); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . '/knowledgeBase'); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { // Update in DB updateKnowledgeBaseData($pearDB, $form, $oreon, $originalPassword); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=knowledgeBase'", 'class' => 'btc bt_info'] ); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('valid', $valid); $tpl->display('formKnowledgeBase.html');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/knowledgeBase/help.php
centreon/www/include/Administration/parameters/knowledgeBase/help.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 * */ $help = []; /** * knowledge Settings */ $help['tip_knowledge_wiki_url'] = dgettext( 'help', 'Knowledge wiki url. ' . 'Exemple: http://wiki/mywiki' ); $help['tip_knowledge_wiki_account'] = dgettext( 'help', 'Wiki account with delete right.' ); $help['tip_knowledge_wiki_certificate'] = dgettext( 'help', 'Ignore ssl certificate.' ); $help['tip_knowledge_wiki_account_password'] = dgettext( 'help', 'Wiki account password.' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/rrdtool/help.php
centreon/www/include/Administration/parameters/rrdtool/help.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 * */ $help = []; /** * RRDTool Configuration */ $help['tip_directory+rrdtool_binary'] = dgettext('help', 'RRDTOOL binary complete path.'); $help['tip_rrdtool_version'] = dgettext('help', 'RRDTool version.'); /** * RRDCached Properties */ $help['tip_rrdcached_enable'] = dgettext( 'help', 'Enable the rrdcached for Centreon. This option is valid only with Centreon Broker' ); $help['tip_rrdcached_port'] = dgettext('help', 'Port for communicating with rrdcached'); $help['tip_rrdcached_unix_path'] = dgettext( 'help', 'The absolute path to unix socket for communicating with rrdcached' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/rrdtool/formFunction.php
centreon/www/include/Administration/parameters/rrdtool/formFunction.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 * */ /** * Get the version of rrdtool * * @param string $rrdtoolBin The full path of rrdtool * @return string */ function getRrdtoolVersion($rrdtoolBin = null) { if (is_null($rrdtoolBin) || ! is_executable($rrdtoolBin)) { return ''; } $output = []; $retval = 0; @exec($rrdtoolBin, $output, $retval); if ($retval != 0) { return ''; } $ret = preg_match('/^RRDtool ((\d\.?)+).*$/', $output[0], $matches); if ($ret === false || $ret === 0) { return ''; } return $matches[1]; } /** * Validate if only one rrdcached options is set * * @param array $values rrdcached_port and rrdcached_unix_path * @return bool */ function rrdcached_valid($values) { return ! (trim($values[0]) != '' && trim($values[1]) != ''); } function rrdcached_has_option($values) { if (isset($values[0]['rrdcached_enable']) && $values[0]['rrdcached_enable'] == 1) { if (trim($values[1]) == '' && trim($values[2]) == '') { return false; } } 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/include/Administration/parameters/rrdtool/form.php
centreon/www/include/Administration/parameters/rrdtool/form.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 * */ if (! isset($oreon)) { exit(); } require_once __DIR__ . '/formFunction.php'; $DBRESULT = $pearDB->query('SELECT * FROM `options`'); while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt['key']] = myDecode($opt['value']); } $DBRESULT->closeCursor(); // Var information to format the element $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrSelect = ['style' => 'width: 220px;']; $attrSelect2 = ['style' => 'width: 50px;']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify General Options')); // Various information $form->addElement('text', 'rrdtool_path_bin', _('Directory + RRDTOOL Binary'), $attrsText); $form->addElement('text', 'rrdtool_version', _('RRDTool Version'), $attrsText2); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); $form->registerRule('is_executable_binary', 'callback', 'is_executable_binary'); $form->registerRule('is_writable_path', 'callback', 'is_writable_path'); $form->registerRule('rrdcached_has_option', 'callback', 'rrdcached_has_option'); $form->registerRule('rrdcached_valid', 'callback', 'rrdcached_valid'); $form->addRule('rrdtool_path_bin', _("Can't execute binary"), 'is_executable_binary'); // $form->addRule('oreon_rrdbase_path', _("Can't write in directory"), 'is_writable_path'); - Field is not added so no need for rule // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'rrdtool/'); $version = ''; if (isset($gopt['rrdtool_path_bin']) && trim($gopt['rrdtool_path_bin']) != '') { $version = getRrdtoolVersion($gopt['rrdtool_path_bin']); } $gopt['rrdtool_version'] = $version; $form->freeze('rrdtool_version'); if (! isset($gopt['rrdcached_enable'])) { $gopt['rrdcached_enable'] = '0'; } if (version_compare('1.4.0', $version, '>')) { $gopt['rrdcached_enable'] = '0'; $form->freeze('rrdcached_enable'); $form->freeze('rrdcached_port'); $form->freeze('rrdcached_unix_path'); } $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $valid = false; if ($form->validate()) { // Update in DB updateRRDToolConfigData($form->getSubmitValue('gopt_id')); // Update in Oreon Object $oreon->initOptGen($pearDB); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('Impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=rrdtool'", 'class' => 'btc bt_info'] ); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('genOpt_rrdtool_properties', _('RRDTool Properties')); $tpl->assign('genOpt_rrdtool_configurations', _('RRDTool Configuration')); $tpl->assign('valid', $valid); $tpl->display('form.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/backup/formBackup.php
centreon/www/include/Administration/parameters/backup/formBackup.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 * */ if (! isset($oreon)) { exit(); } $checkboxGroup = ['backup_database_full', 'backup_database_partial']; $DBRESULT = $pearDB->query("SELECT * FROM `options` WHERE options.key LIKE 'backup_%'"); while ($opt = $DBRESULT->fetchRow()) { if (in_array($opt['key'], $checkboxGroup)) { $values = explode(',', $opt['value']); foreach ($values as $value) { $gopt[$opt['key']][trim($value)] = 1; } } else { $gopt[$opt['key']] = myDecode($opt['value']); } } $DBRESULT->closeCursor(); $attrsText = ['size' => '40']; $attrsText2 = ['size' => '3']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // General Options $backupEnabled = []; $backupEnabled[] = $form->createElement('radio', 'backup_enabled', null, _('Yes'), '1'); $backupEnabled[] = $form->createElement('radio', 'backup_enabled', null, _('No'), '0'); $form->addGroup($backupEnabled, 'backup_enabled', _('Backup enabled'), '&nbsp;'); $form->setDefaults(['backup_enabled' => '0']); $form->addElement('text', 'backup_backup_directory', _('Backup directory'), $attrsText); $form->addRule('backup_backup_directory', _('Mandatory field'), 'required'); $form->addElement('text', 'backup_tmp_directory', _('Temporary directory'), $attrsText); $form->addRule('backup_tmp_directory', _('Mandatory field'), 'required'); // Database Options $form->addElement('checkbox', 'backup_database_centreon', _('Backup database centreon')); $form->addElement('checkbox', 'backup_database_centreon_storage', _('Backup database centreon_storage')); $backupDatabaseType = []; $backupDatabaseType[] = $form->createElement('radio', 'backup_database_type', null, _('Dump'), '0'); $backupDatabaseType[] = $form->createElement('radio', 'backup_database_type', null, _('LVM Snapshot'), '1'); $form->addGroup($backupDatabaseType, 'backup_database_type', _('Backup type'), '&nbsp;'); $form->setDefaults(['backup_database_type' => '1']); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '1', '&nbsp;', _('Monday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '2', '&nbsp;', _('Tuesday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '3', '&nbsp;', _('Wednesday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '4', '&nbsp;', _('Thursday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '5', '&nbsp;', _('Friday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '6', '&nbsp;', _('Saturday')); $backupDatabasePeriodFull[] = $form->createElement('checkbox', '0', '&nbsp;', _('Sunday')); $form->addGroup($backupDatabasePeriodFull, 'backup_database_full', _('Full backup'), '&nbsp;&nbsp;'); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '1', '&nbsp;', _('Monday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '2', '&nbsp;', _('Tuesday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '3', '&nbsp;', _('Wednesday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '4', '&nbsp;', _('Thursday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '5', '&nbsp;', _('Friday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '6', '&nbsp;', _('Saturday')); $backupDatabasePeriodPartial[] = $form->createElement('checkbox', '0', '&nbsp;', _('Sunday')); $form->addGroup($backupDatabasePeriodPartial, 'backup_database_partial', _('Partial backup'), '&nbsp;&nbsp;'); $form->addElement('text', 'backup_retention', _('Backup retention'), $attrsText2); $form->addRule('backup_retention', _('Mandatory field'), 'required'); $form->addRule('backup_retention', _('Must be a number'), 'numeric'); // Configuration Files Options $form->addElement('checkbox', 'backup_configuration_files', _('Backup configuration files')); $form->addElement('text', 'backup_mysql_conf', _('MySQL configuration file path'), $attrsText); // Export Options $scpEnabled = []; $scpEnabled[] = $form->createElement('radio', 'backup_export_scp_enabled', null, _('Yes'), '1'); $scpEnabled[] = $form->createElement('radio', 'backup_export_scp_enabled', null, _('No'), '0'); $form->addGroup($scpEnabled, 'backup_export_scp_enabled', _('SCP export enabled'), '&nbsp;'); $form->setDefaults(['backup_export_scp_enabled' => '0']); $form->addElement('text', 'backup_export_scp_user', _('Remote user'), $attrsText); $form->addElement('text', 'backup_export_scp_host', _('Remote host'), $attrsText); $form->addElement('text', 'backup_export_scp_directory', _('Remote directory'), $attrsText); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); $form->setDefaults($gopt); $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . '/backup'); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { // Update in DB updateBackupConfigData($pearDB, $form, $oreon); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=backup'", 'class' => 'btc bt_info'] ); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('valid', $valid); $tpl->display('formBackup.html');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/backup/help.php
centreon/www/include/Administration/parameters/backup/help.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 * */ $help = []; /** * Backup Settings */ $help['tip_backup_enabled'] = dgettext( 'help', 'Enable Backup process' ); $help['tip_backup_configuration_files'] = dgettext( 'help', 'Backup configuration files (MySQL, Apache, PHP, SNMP, centreon, centreon-engine, centreon-broker)' ); $help['tip_backup_database_centreon'] = dgettext( 'help', 'Backup centreon database' ); $help['tip_backup_database_centreon_storage'] = dgettext( 'help', 'Backup centreon_storage database' ); $help['tip_backup_database_type'] = dgettext( 'help', 'Backup type for centreon_storage database : mysqldump or LVM snapshot (need available space on MySQL LVM)' ); $help['tip_backup_database_full'] = dgettext( 'help', 'Full backup period' ); $help['tip_backup_database_partial'] = dgettext( 'help', 'Partial backup period (available on partitioned tables)' ); $help['tip_backup_directory'] = dgettext( 'help', 'Directory where backups will be stored' ); $help['tip_backup_tmp_directory'] = dgettext( 'help', 'Temporary directory used by backup process' ); $help['tip_backup_retention'] = dgettext( 'help', 'Backup retention (in days)' ); $help['tip_backup_mysql_conf'] = dgettext( 'help', 'MySQL configuration file path (e.g. /etc/my.cnf.d/centreon.cnf); leave empty to use the default value.' ); $help['tip_backup_export_scp_enabled'] = dgettext( 'help', 'Use SCP to copy backup on remote host' ); $help['tip_backup_export_scp_user'] = dgettext( 'help', 'Remote user used by SCP' ); $help['tip_backup_export_scp_host'] = dgettext( 'help', 'Remote host to copy by SCP' ); $help['tip_backup_export_scp_directory'] = dgettext( 'help', 'Remote directory to copy by SCP' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/gorgone/gorgone.php
centreon/www/include/Administration/parameters/gorgone/gorgone.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 * */ if (! isset($oreon)) { exit(); } $DBRESULT = $pearDB->query('SELECT * FROM `options`'); while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt['key']] = myDecode($opt['value']); } $DBRESULT->closeCursor(); $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; $autocompleteOff = ['autocomplete' => 'new-password']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify Gorgone options')); // Gorgone Options $form->addElement('checkbox', 'enable_broker_stats', _('Enable Broker statistics collection')); $form->addElement('text', 'gorgone_cmd_timeout', _('Timeout value for Gorgone commands'), $attrsText2); $form->addRule('gorgone_cmd_timeout', _('Must be a number'), 'numeric'); $form->addElement('text', 'gorgone_illegal_characters', _('Illegal characters for Gorgone commands'), $attrsText); // API $form->addElement('text', 'gorgone_api_address', _('IP address or hostname'), $attrsText); $form->addElement('text', 'gorgone_api_port', _('Port'), $attrsText2); $form->addRule('gorgone_api_port', _('Must be a number'), 'numeric'); $form->addElement('text', 'gorgone_api_username', _('Username'), array_merge($attrsText, $autocompleteOff)); $form->addElement('password', 'gorgone_api_password', _('Password'), array_merge($attrsText, $autocompleteOff)); $form->addElement( 'checkbox', 'gorgone_api_ssl', _('Use SSL/TLS'), null ); $form->setDefaults(1); $form->addElement( 'checkbox', 'gorgone_api_allow_self_signed', _('Allow self signed certificate'), null ); $form->setDefaults(1); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . '/gorgone'); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { // Update in DB updateGorgoneConfigData($pearDB, $form, $oreon); $o = null; $valid = true; $form->freeze(); } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=gorgone'", 'class' => 'btc bt_info'] ); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('valid', $valid); $tpl->display('gorgone.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/gorgone/help.php
centreon/www/include/Administration/parameters/gorgone/help.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 * */ $help = []; /** * Gorgone Settings */ $help['tip_gorgone_cmd_timeout'] = dgettext( 'help', 'Timeout value in seconds. Used to make actions calls timeout.' ); $help['tip_enable_broker_stats'] = dgettext( 'help', 'Enable Centreon Broker statistics collection into the central server.' . ' Be careful: if disabled, Broker statistics will not be' . ' available into Home > Broker statistics.' ); $help['tip_gorgone_illegal_characters'] = dgettext( 'help', 'Illegal characters in external commands. Those characters will be removed ' . 'before being processed by Centreon Gorgone.' ); $help['tip_gorgone_api_address'] = dgettext( 'help', 'IP Address or hostname to communicate with Gorgone API. Should remain default value ' . '(Default: "127.0.0.1").' ); $help['tip_gorgone_api_port'] = dgettext( 'help', 'Port on which Gorgone API is listening. It must match Gorgone httpserver module definition. ' . 'Should remain default value (Default: "8085").' ); $help['tip_gorgone_api_username'] = dgettext( 'help', 'Username used to connect to Gorgone API. It must match Gorgone httpserver module definition ' . '(Default: none).' ); $help['tip_gorgone_api_password'] = dgettext( 'help', 'Password used to connect to Gorgone API. It must match Gorgone httpserver module definition ' . '(Default: none).' ); $help['tip_gorgone_api_ssl'] = dgettext( 'help', 'Define if SSL/TLS must be used to connect to API. It must match Gorgone httpserver module definition ' . '(Default: no).' ); $help['tip_gorgone_api_allow_self_signed'] = dgettext( 'help', 'Define if connection to Gorgone API can be done even if a self signed certificat is used ' . '(Default: yes).' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/engine/help.php
centreon/www/include/Administration/parameters/engine/help.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 * */ $help = []; /** * Monitoring Engine */ $help['tip_default_engine'] = dgettext('help', 'Default monitoring engine.'); $help['tip_images_directory'] = dgettext('help', 'Directory where images are stored.'); $help['tip_plugins_directory'] = dgettext('help', 'Directory where check plugins are stored.'); $help['tip_interval_length'] = dgettext( 'help', 'This is the number of seconds per "unit interval" used for timing in the scheduling queue,' . ' re-notifications, etc. "Units intervals" are used in the object configuration file to determine how' . ' often to run a service check, how often to re-notify a contact, etc. The default value for this is set to 60,' . ' which means that a "unit value" of 1 in the object configuration file will mean 60 seconds (1 minute).' ); /** * Monitoring database layer */ $help['tip_broker_engine_used_by_centreon'] = dgettext('help', 'Broker module used by Centreon.'); /** * Correlation Engine */ $help['tip_start_script_for_correlator_engine'] = dgettext('help', 'Init script for broker daemon.'); /** * Mailer path */ $help['tip_directory+mailer_binary'] = dgettext( 'help', 'Mailer binary with complete path. This define the @MAILER@ macro used in notification commands.' ); /** * Tactical Overview */ $help['tip_maximum_number_of_hosts_to_show'] = dgettext( 'help', 'Maximum number of hosts to show in the Tactical Overview page.' ); $help['tip_maximum_number_of_services_to_show'] = dgettext( 'help', 'Maximum number of services to show in the Tactical Overview page.' ); $help['tip_page_refresh_interval'] = dgettext('help', 'Refresh interval used in the Tactical Overview page.'); /** * Default acknowledgement settings */ $help['tip_sticky'] = dgettext('help', '[Sticky] option is enabled by default.'); $help['tip_notify'] = dgettext('help', '[Notify] option is enabled by default.'); $help['tip_persistent'] = dgettext('help', '[Persistent] option is enabled by default.'); $help['tip_acknowledge_services_attached_to_hosts'] = dgettext( 'help', '[Acknowledge services attached to hosts] option is enabled by default.' ); $help['tip_force_active_checks'] = dgettext('help', '[Force Active Checks] option is enabled by default.'); /** * Default downtime settings */ $help['tip_fixed'] = dgettext('help', 'Fixed.'); $help['tip_set_downtimes_on_services_attached_to_hosts'] = dgettext( 'help', '[Set downtimes on services attached to hosts] option is enbaled by default.' ); $help['tip_duration'] = dgettext('help', 'Default duration of scheduled downtimes.'); /** * Misc */ $help['tip_console_notification'] = dgettext( 'help', 'When enabled, notification messages are displayed when new alerts arise in the monitoring consoles.' ); $help['tip_host_notification_0'] = dgettext('help', 'When enabled, "Host Up" notification messages will be displayed.'); $help['tip_host_notification_1'] = dgettext( 'help', 'When enabled, "Host Down" notification messages will be displayed.' ); $help['tip_host_notification_2'] = dgettext( 'help', 'When enabled, "Host Unreachable" notification messages will be displayed.' ); $help['tip_svc_notification_0'] = dgettext( 'help', 'When enabled, "Service OK" notification messages will be displayed.' ); $help['tip_svc_notification_1'] = dgettext( 'help', 'When enabled, "Service Warning" notification messages will be displayed.' ); $help['tip_svc_notification_2'] = dgettext( 'help', 'When enabled, "Service Critical" notification messages will be displayed.' ); $help['tip_svc_notification_3'] = dgettext( 'help', 'When enabled, "Service Unknown" notification messages will be displayed.' );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/engine/formFunction.php
centreon/www/include/Administration/parameters/engine/formFunction.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 * */ // Form Rules function isNum($value) { return is_numeric($value); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/engine/form.php
centreon/www/include/Administration/parameters/engine/form.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 * */ if (! isset($oreon)) { exit(); } require_once __DIR__ . '/formFunction.php'; $dbResult = $pearDB->query('SELECT * FROM `options`'); while ($opt = $dbResult->fetch()) { $gopt[$opt['key']] = myDecode($opt['value']); } $dbResult->closeCursor(); // Check value for interval_length if (! isset($gopt['interval_length'])) { $gopt['interval_length'] = 60; } $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify General Options')); // Nagios information $form->addElement('header', 'nagios', _('Monitoring Engine information')); $form->addElement('text', 'nagios_path_plugins', _('Plugins Directory'), $attrsText); $form->addElement('text', 'interval_length', _('Interval Length'), $attrsText2); $form->addElement('text', 'mailer_path_bin', _('Directory + Mailer Binary'), $attrsText); // Tactical Overview form $limitArray = []; for ($i = 10; $i <= 100; $i += 10) { $limitArray[$i] = $i; } $form->addElement('select', 'tactical_host_limit', _('Maximum number of hosts to show'), $limitArray); $form->addElement('select', 'tactical_service_limit', _('Maximum number of services to show'), $limitArray); $form->addElement('text', 'tactical_refresh_interval', _('Page refresh interval'), $attrsText2); // Acknowledgement form $form->addElement('checkbox', 'monitoring_ack_sticky', _('Sticky')); $form->addElement('checkbox', 'monitoring_ack_notify', _('Notify')); $form->addElement('checkbox', 'monitoring_ack_persistent', _('Persistent')); $form->addElement('checkbox', 'monitoring_ack_active_checks', _('Force Active Checks')); $form->addElement('checkbox', 'monitoring_ack_svc', _('Acknowledge services attached to hosts')); // Downtime form $form->addElement('checkbox', 'monitoring_dwt_fixed', _('Fixed')); $form->addElement('checkbox', 'monitoring_dwt_svc', _('Set downtimes on services attached to hosts')); $form->addElement('text', 'monitoring_dwt_duration', _('Duration'), $attrsText2); $scaleChoices = ['s' => _('seconds'), 'm' => _('minutes'), 'h' => _('hours'), 'd' => _('days')]; $form->addElement('select', 'monitoring_dwt_duration_scale', _('Scale of time'), $scaleChoices); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('nagios_path', 'slash'); $form->applyFilter('nagios_path_plugins', 'slash'); $form->registerRule('is_valid_path', 'callback', 'is_valid_path'); $form->registerRule('is_readable_path', 'callback', 'is_readable_path'); $form->registerRule('is_executable_binary', 'callback', 'is_executable_binary'); $form->registerRule('is_writable_path', 'callback', 'is_writable_path'); $form->registerRule('is_writable_file', 'callback', 'is_writable_file'); $form->registerRule('is_writable_file_if_exist', 'callback', 'is_writable_file_if_exist'); $form->registerRule('isNum', 'callback', 'isNum'); $form->addRule('nagios_path_plugins', _("The directory isn't valid"), 'is_valid_path'); $form->addRule('tactical_refresh_interval', _('Refresh interval must be numeric'), 'numeric'); $form->addRule('interval_length', _('This value must be a numerical value.'), 'isNum'); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . '/engine'); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $dbResult = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $valid = false; $sessionKeyFreeze = 'administration-parameters-monitoring-freeze'; if ($form->validate()) { try { // Update in DB updateNagiosConfigData($form->getSubmitValue('gopt_id')); // Update in Centreon Object $oreon->initOptGen($pearDB); $o = null; $valid = true; /** * Freeze the form and reload the page */ $form->freeze(); $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=engine'", 'class' => 'btc bt_info'] ); $_SESSION[$sessionKeyFreeze] = true; echo '<script>parent.location.href = "main.php?p=' . $p . '&o=engine";</script>'; exit; } catch (Throwable $e) { echo "<div class='msg' align='center'>" . $e->getMessage() . '</div>'; $valid = false; } } elseif (array_key_exists($sessionKeyFreeze, $_SESSION) && $_SESSION[$sessionKeyFreeze] === true) { unset($_SESSION[$sessionKeyFreeze]); $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=engine'", 'class' => 'btc bt_info'] ); $form->freeze(); $valid = true; } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('impossible to validate, one or more field is incorrect') . '</div>'; } // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('genOpt_nagios_version', _('Monitoring Engine')); $tpl->assign('genOpt_dbLayer', _('Monitoring database layer')); $tpl->assign('genOpt_nagios_direstory', _('Engine Directories')); $tpl->assign('tacticalOverviewOptions', _('Tactical Overview')); $tpl->assign('genOpt_mailer_path', _('Mailer path')); $tpl->assign('genOpt_monitoring_properties', 'Monitoring properties'); $tpl->assign('acknowledgement_default_settings', _('Default acknowledgement settings')); $tpl->assign('downtime_default_settings', _('Default downtime settings')); $tpl->assign('seconds', _('seconds')); $tpl->assign('valid', $valid); $tpl->display('form.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/debug/help.php
centreon/www/include/Administration/parameters/debug/help.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 * */ $help = []; /** * Debug */ $help['tip_logs_directory'] = dgettext('help', 'Directory of log files.'); $help['tip_authentication_debug'] = dgettext('help', 'Enables authentication debug.'); $help['tip_nagios_import_debug'] = dgettext('help', 'Enables Monitoring Engine import debug.'); $help['tip_rrdtool_debug'] = dgettext('help', 'Enables RRDTool debug.'); $help['tip_ldap_user_import_debug'] = dgettext('help', 'Enables LDAP user import debug.'); $help['tip_sql_debug'] = dgettext('help', 'Enables SQL debug.'); $help['tip_centcore_debug'] = dgettext('help', 'Enables Centcore debug.'); $help['tip_centstorage_debug'] = dgettext('help', 'Enables Centstorage debug.'); $help['tip_centreontrapd_debug'] = dgettext('help', 'Enables Centreontrapd debug.'); $help['tip_debug_level'] = dgettext('help', 'Set the lowest log level: Debug => Info => Notice => Warning => Error => Critical => Alert => Emergency');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/Administration/parameters/debug/form.php
centreon/www/include/Administration/parameters/debug/form.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 * */ if (! isset($centreon)) { exit(); } $DBRESULT = $pearDB->query('SELECT * FROM `options`'); while ($opt = $DBRESULT->fetchRow()) { $gopt[$opt['key']] = myDecode($opt['value']); } $DBRESULT->closeCursor(); $attrsText = ['size' => '40']; $attrsText2 = ['size' => '5']; $attrsAdvSelect = null; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Modify General Options')); $form->addElement('header', 'debug', _('Debug')); $form->addElement('text', 'debug_path', _('Logs Directory'), $attrsText); $form->addElement('checkbox', 'debug_auth', _('Authentication debug')); $form->addElement( 'select', 'debug_level', _('Debug level'), [ 000 => 'None', 100 => 'Debug', 200 => 'Info', 250 => 'Notice', 300 => 'Warning', 400 => 'Error', 500 => 'Critical', 550 => 'Alert', 600 => 'Emergency', ] ); $form->addElement('checkbox', 'debug_sql', _('SQL debug')); $form->addElement('checkbox', 'debug_nagios_import', _('Monitoring Engine Import debug')); $form->addElement('checkbox', 'debug_rrdtool', _('RRDTool debug')); $form->addElement('checkbox', 'debug_ldap_import', _('LDAP User Import debug')); $form->addElement('checkbox', 'debug_gorgone', _('Centreon Gorgone debug')); $form->addElement('checkbox', 'debug_centreontrapd', _('Centreontrapd debug')); $form->applyFilter('__ALL__', 'myTrim'); $form->applyFilter('debug_path', 'slash'); $form->registerRule('is_valid_path', 'callback', 'is_valid_path'); $form->registerRule('is_readable_path', 'callback', 'is_readable_path'); $form->registerRule('is_executable_binary', 'callback', 'is_executable_binary'); $form->registerRule('is_writable_path', 'callback', 'is_writable_path'); $form->registerRule('is_writable_file', 'callback', 'is_writable_file'); $form->registerRule('is_writable_file_if_exist', 'callback', 'is_writable_file_if_exist'); $form->addRule('debug_path', _("Can't write in directory"), 'is_writable_path'); $form->addElement('hidden', 'gopt_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path . 'debug/'); $form->setDefaults($gopt); $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $DBRESULT = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $valid = false; if ($form->validate()) { // Update in DB updateDebugConfigData($form->getSubmitValue('gopt_id')); // Update in Oreon Object $oreon->initOptGen($pearDB); $o = null; $valid = true; $form->freeze(); if (isset($_POST['debug_auth_clear'])) { @unlink($oreon->optGen['debug_path'] . 'auth.log'); } if (isset($_POST['debug_nagios_import_clear'])) { @unlink($oreon->optGen['debug_path'] . 'cfgimport.log'); } if (isset($_POST['debug_rrdtool_clear'])) { @unlink($oreon->optGen['debug_path'] . 'rrdtool.log'); } if (isset($_POST['debug_ldap_import_clear'])) { @unlink($oreon->optGen['debug_path'] . 'ldapsearch.log'); } if (isset($_POST['debug_inventory_clear'])) { @unlink($oreon->optGen['debug_path'] . 'inventory.log'); } } if (! $form->validate() && isset($_POST['gopt_id'])) { echo "<div class='msg' align='center'>" . _('Impossible to validate, one or more field is incorrect') . '</div>'; } $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . "&o=debug'", 'class' => 'btc bt_info'] ); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n"; } $tpl->assign('helptext', $helptext); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('genOpt_debug_options', _('Debug Properties')); $tpl->assign('valid', $valid); $tpl->display('form.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/common-Func.php
centreon/www/include/monitoring/common-Func.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 * */ $configFile = realpath(__DIR__ . '/../../../config/centreon.config.php'); require_once __DIR__ . '/../../class/config-generate/host.class.php'; require_once __DIR__ . '/../../class/config-generate/service.class.php'; if (! isset($centreon)) { exit(); } function get_user_param($user_id, $pearDB) { $list_param = ['ack_sticky', 'ack_notify', 'ack_persistent', 'ack_services', 'force_active', 'force_check']; $tab_row = []; foreach ($list_param as $param) { if (isset($_SESSION[$param])) { $tab_row[$param] = $_SESSION[$param]; } } return $tab_row; } function set_user_param($user_id, $pearDB, $key, $value) { $_SESSION[$key] = $value; } /** * Get the notified contact/contact group of host tree inheritance * * @param int $hostId * @param Pimple\Container $dependencyInjector * @return array */ function getNotifiedInfosForHost(int $hostId, Pimple\Container $dependencyInjector): array { $results = ['contacts' => [], 'contactGroups' => []]; $hostInstance = Host::getInstance($dependencyInjector); $notifications = $hostInstance->getCgAndContacts($hostId); if (isset($notifications['cg']) && count($notifications['cg']) > 0) { $results['contactGroups'] = getContactgroups($notifications['cg']); } if (isset($notifications['contact']) && count($notifications['contact']) > 0) { $results['contacts'] = getContacts($notifications['contact']); } natcasesort($results['contacts']); natcasesort($results['contactGroups']); return $results; } /** * Get the list of enable contact groups (id/name) * * @param int[] $cg list contact group id * @return array */ function getContactgroups(array $cg): array { global $pearDB; $contactGroups = []; $dbResult = $pearDB->query( 'SELECT cg_id, cg_name FROM contactgroup WHERE cg_id IN (' . implode(', ', $cg) . ')' ); while (($row = $dbResult->fetchRow())) { $contactGroups[$row['cg_id']] = $row['cg_name']; } return $contactGroups; } /** * Get the list of enable contact (id/name) * * @param int[] $contacts list contact id * @return array */ function getContacts(array $contacts): array { global $pearDB; $contactsResult = []; $dbResult = $pearDB->query( 'SELECT contact_id, contact_name FROM contact WHERE contact_id IN (' . implode(', ', $contacts) . ')' ); while (($row = $dbResult->fetchRow())) { $contactsResult[$row['contact_id']] = $row['contact_name']; } return $contactsResult; } /** * Get the notified contact/contact group of service tree inheritance * * @param int $serviceId * @param int $hostId * @param Pimple\Container $dependencyInjector * @return array */ function getNotifiedInfosForService(int $serviceId, int $hostId, Pimple\Container $dependencyInjector): array { $results = ['contacts' => [], 'contactGroups' => []]; $serviceInstance = Service::getInstance($dependencyInjector); $notifications = $serviceInstance->getCgAndContacts($serviceId); if (((! isset($notifications['cg']) || count($notifications['cg']) == 0) && (! isset($notifications['contact']) || count($notifications['contact']) == 0)) || $serviceInstance->getString($serviceId, 'service_use_only_contacts_from_host') ) { $results = getNotifiedInfosForHost($hostId, $dependencyInjector); } else { if (isset($notifications['cg']) && count($notifications['cg']) > 0) { $results['contactGroups'] = getContactgroups($notifications['cg']); } if (isset($notifications['contact']) && count($notifications['contact']) > 0) { $results['contacts'] = getContacts($notifications['contact']); } } natcasesort($results['contacts']); natcasesort($results['contactGroups']); return $results; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/downtime/common-Func.php
centreon/www/include/monitoring/downtime/common-Func.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 * */ if (! isset($centreon)) { exit(); } function deleteDowntimeInDb($downtimeInternalId = null) { if ($downtimeInternalId === null) { return; } $db = CentreonDBInstance::getDbCentreonStorageInstance(); $statement = $db->prepare('DELETE FROM downtimes WHERE internal_id = :internal_id'); $statement->bindValue(':internal_id', (int) $downtimeInternalId, PDO::PARAM_INT); $statement->execute(); } function getDowntimes($internalId) { $db = CentreonDBInstance::getDbCentreonStorageInstance(); $statement = $db->prepare( <<<'SQL' SELECT host_id, service_id FROM downtimes WHERE internal_id = :internal_id ORDER BY downtime_id DESC LIMIT 0,1 SQL ); $statement->bindValue(':internal_id', $internalId, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if (! empty($row)) { return $row; } return false; } function isDownTimeHost($internalId) { $downtime = getDowntimes($internalId); return ! (! empty($downtime['host_id']) && ! empty($downtime['service_id'])); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/downtime/AddDowntime.php
centreon/www/include/monitoring/downtime/AddDowntime.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 * */ if (! isset($centreon)) { exit(); } include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php'; const DOWNTIME_YEAR_MAX = Centreon\Domain\Downtime\Downtime::DOWNTIME_YEAR_MAX; $hostStr = $centreon->user->access->getHostsString('ID', $pearDBO); $hostAclId = preg_split('/,/', str_replace("'", '', $hostStr)); $hObj = new CentreonHost($pearDB); $serviceObj = new CentreonService($pearDB); $resourceId ??= 0; /** * @param array $fields form data * @return bool|array Returns TRUE (valid date) if the year is less than 2100, otherwise returns errors */ function checkYearMax(array $fields) { $errors = []; $tooHighDateMessage = sprintf(_('Please choose a date before %d'), DOWNTIME_YEAR_MAX); if (((int) (new DateTime($fields['alternativeDateStart']))->format('Y')) >= DOWNTIME_YEAR_MAX) { $errors['start'] = $tooHighDateMessage; } if (((int) (new DateTime($fields['alternativeDateEnd']))->format('Y')) >= DOWNTIME_YEAR_MAX) { $errors['end'] = $tooHighDateMessage; } return $errors !== [] ? $errors : true; } if ( ! $centreon->user->access->checkAction('host_schedule_downtime') && ! $centreon->user->access->checkAction('service_schedule_downtime') ) { require_once _CENTREON_PATH_ . 'www/include/core/errors/alt_error.php'; } else { // Init $debug = 0; $attrsTextI = ['size' => '3']; $attrsText = ['size' => '30']; $attrsTextarea = ['rows' => '7', 'cols' => '80']; $form = new HTML_QuickFormCustom('Form', 'POST', '?p=' . $p); // Indicator basic information $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) { $disabled = 'disabled'; $hostName = $hObj->getHostName($_GET['host_id']); } elseif (isset($_GET['host_id'], $_GET['service_id'])) { $disabled = 'disabled'; $serviceParameters = $serviceObj->getParameters($_GET['service_id'], ['service_description']); $serviceDisplayName = $serviceParameters['service_description']; $hostName = $hObj->getHostName($_GET['host_id']); } else { $disabled = ' '; } if (! isset($_GET['host_id'])) { $dtType[] = $form->createElement( 'radio', 'downtimeType', null, _('Host'), '1', [$disabled, 'id' => 'host', 'onclick' => "toggleParams('host');"] ); $dtType[] = $form->createElement( 'radio', 'downtimeType', null, _('Services'), '2', [$disabled, 'id' => 'service', 'onclick' => "toggleParams('service');"] ); $dtType[] = $form->createElement( 'radio', 'downtimeType', null, _('Hostgroup'), '0', [$disabled, 'id' => 'hostgroup', 'onclick' => "toggleParams('hostgroup');"] ); $dtType[] = $form->createElement( 'radio', 'downtimeType', null, _('Servicegroup'), '3', [$disabled, 'id' => 'servicegroup', 'onclick' => "toggleParams('servicegroup');"] ); $dtType[] = $form->createElement( 'radio', 'downtimeType', null, _('Poller'), '4', [$disabled, 'id' => 'poller', 'onclick' => "toggleParams('poller');"] ); $form->addGroup($dtType, 'downtimeType', _('Downtime type'), '&nbsp;'); // ----- Hosts ----- $attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_host&action=list', 'multiple' => true, 'linkedObject' => 'centreonHost']; $form->addElement('select2', 'host_id', _('Hosts'), [], $attrHosts); if (! isset($_GET['service_id'])) { // ----- Services ----- $attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_service&action=list&e=enable', 'multiple' => true, 'linkedObject' => 'centreonService']; $form->addElement('select2', 'service_id', _('Services'), [$disabled], $attrServices); } // ----- HostGroups ----- $attrHostgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_hostgroup&action=list', 'multiple' => true, 'linkedObject' => 'centreonHostgroups']; $form->addElement('select2', 'hostgroup_id', _('Hostgroups'), [], $attrHostgroups); // ----- Servicegroups ----- $attrServicegroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_servicegroup&action=list', 'multiple' => true, 'linkedObject' => 'centreonServicegroups']; $form->addElement('select2', 'servicegroup_id', _('Servicegroups'), [], $attrServicegroups); } // ----- Pollers ----- $attrPoller = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_poller&action=list', 'multiple' => true, 'linkedObject' => 'centreonInstance']; // Host Parents if ($resourceId !== 0) { $attrPoller1 = array_merge( $attrPoller, ['defaultDatasetRoute' => './api/internal.php?object=centreon_configuration_poller' . '&action=defaultValues&target=resources&field=instance_id&id=' . $resourceId] ); $form->addElement('select2', 'poller_id', _('Pollers'), [], $attrPoller1); } else { $form->addElement('select2', 'poller_id', _('Pollers'), [], $attrPoller); } $chbx = $form->addElement( 'checkbox', 'persistant', _('Fixed'), null, ['id' => 'fixed', 'onClick' => 'javascript:setDurationField()'] ); if (isset($centreon->optGen['monitoring_dwt_fixed']) && $centreon->optGen['monitoring_dwt_fixed']) { $chbx->setChecked(true); } $form->addElement( 'text', 'start', _('Start Time'), ['size' => 10, 'class' => 'datepicker'] ); $form->addElement( 'text', 'end', _('End Time'), ['size' => 10, 'class' => 'datepicker'] ); $form->addElement( 'text', 'start_time', '', ['size' => 5, 'class' => 'timepicker'] ); $form->addElement( 'text', 'end_time', '', ['size' => 5, 'class' => 'timepicker'] ); $form->addElement( 'text', 'duration', _('Duration'), ['size' => '15', 'id' => 'duration'] ); $form->addElement( 'text', 'timezone_warning', _(' The timezone used is configured on your user settings') ); // adding hidden fields to get the result of datepicker in an unlocalized format $form->addElement( 'hidden', 'alternativeDateStart', '', ['size' => 10, 'class' => 'alternativeDate'] ); $form->addElement( 'hidden', 'alternativeDateEnd', '', ['size' => 10, 'class' => 'alternativeDate'] ); $defaultDuration = 7200; $defaultScale = 's'; if ( isset($centreon->optGen['monitoring_dwt_duration']) && $centreon->optGen['monitoring_dwt_duration'] ) { $defaultDuration = $centreon->optGen['monitoring_dwt_duration']; if ( isset($centreon->optGen['monitoring_dwt_duration_scale']) && $centreon->optGen['monitoring_dwt_duration_scale'] ) { $defaultScale = $centreon->optGen['monitoring_dwt_duration_scale']; } } $form->setDefaults(['duration' => $defaultDuration]); $form->addElement( 'select', 'duration_scale', _('Scale of time'), ['s' => _('seconds'), 'm' => _('minutes'), 'h' => _('hours'), 'd' => _('days')], ['id' => 'duration_scale'] ); $form->setDefaults(['duration_scale' => $defaultScale]); $withServices[] = $form->createElement('radio', 'with_services', null, _('Yes'), '1'); $withServices[] = $form->createElement('radio', 'with_services', null, _('No'), '0'); $form->addGroup($withServices, 'with_services', _('Set downtime for hosts services'), '&nbsp;'); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->setDefaults( ['comment' => sprintf(_('Downtime set by %s'), $centreon->user->alias)] ); $form->addFormRule('checkYearMax'); $form->addRule('end', _('Required Field'), 'required'); $form->addRule('start', _('Required Field'), 'required'); $form->addRule('end_time', _('Required Field'), 'required'); $form->addRule('start_time', _('Required Field'), 'required'); $form->addRule('comment', _('Required Field'), 'required'); $data = []; $data['host_or_hg'] = 1; $data['with_services'] = $centreon->optGen['monitoring_dwt_svc']; if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) { $data['host_id'] = $_GET['host_id']; $data['downtimeType'] = 1; $focus = 'host'; $form->addElement('hidden', 'host_id', $_GET['host_id']); $form->addElement('hidden', 'downtimeType[downtimeType]', $data['downtimeType']); } elseif (isset($_GET['host_id'], $_GET['service_id'])) { $data['service_id'] = $_GET['host_id'] . '-' . $_GET['service_id']; $data['downtimeType'] = 2; $focus = 'service'; $form->addElement('hidden', 'service_id', $data['service_id']); $form->addElement('hidden', 'downtimeType[downtimeType]', $data['downtimeType']); } else { $data['downtimeType'] = 1; $focus = 'host'; } $form->setDefaults($data); $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Push the downtime if ((isset($_POST['submitA']) && $_POST['submitA']) && $form->validate()) { $values = $form->getSubmitValues(); if (! isset($_POST['persistant']) || ! in_array($_POST['persistant'], ['0', '1'])) { $_POST['persistant'] = '0'; } if (! isset($_POST['comment'])) { $_POST['comment'] = 0; } $_POST['comment'] = str_replace("'", ' ', $_POST['comment']); $duration = null; if (isset($_POST['duration'])) { $duration_scale = $_POST['duration_scale'] ?? 's'; switch ($duration_scale) { default: case 's': $duration = $_POST['duration']; break; case 'm': $duration = $_POST['duration'] * 60; break; case 'h': $duration = $_POST['duration'] * 60 * 60; break; case 'd': $duration = $_POST['duration'] * 60 * 60 * 24; break; } } if ( isset($_POST['host_or_centreon_time']['host_or_centreon_time']) && $_POST['host_or_centreon_time']['host_or_centreon_time'] ) { $hostOrCentreonTime = $_POST['host_or_centreon_time']['host_or_centreon_time']; } else { $hostOrCentreonTime = '0'; } $applyDtOnServices = false; if ( isset($values['with_services']) && $values['with_services']['with_services'] == 1 ) { $applyDtOnServices = true; } // concatenating the chosen dates before sending them to ext_cmd $concatenatedStart = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['alternativeDateStart'] . ' ' . $_POST['start_time'] ); $concatenatedEnd = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['alternativeDateEnd'] . ' ' . $_POST['end_time'] ); if ( isset($values['downtimeType']) && $values['downtimeType']['downtimeType'] == 1 ) { // Set a downtime for host only // catch fix input host_id if (isset($_POST['host_id'])) { if (! is_array($_POST['host_id'])) { $_POST['host_id'] = [$_POST['host_id']]; } foreach ($_POST['host_id'] as $host_id) { $ecObj->addHostDowntime( $host_id, $_POST['comment'], $concatenatedStart, $concatenatedEnd, $_POST['persistant'], $duration, $applyDtOnServices, $hostOrCentreonTime ); } } } elseif ( $values['downtimeType']['downtimeType'] == 0 && isset($_POST['hostgroup_id']) && is_array($_POST['hostgroup_id']) ) { // Set a downtime for hostgroup $hg = new CentreonHostgroups($pearDB); foreach ($_POST['hostgroup_id'] as $hg_id) { $hostlist = $hg->getHostGroupHosts($hg_id); foreach ($hostlist as $host_id) { if ($centreon->user->access->admin || in_array($host_id, $hostAclId)) { $ecObj->addHostDowntime( $host_id, $_POST['comment'], $concatenatedStart, $concatenatedEnd, $_POST['persistant'], $duration, $applyDtOnServices, $hostOrCentreonTime ); } } } } elseif ($values['downtimeType']['downtimeType'] == 2) { // Set a downtime for a service list // catch fix input service_id if (! is_array($_POST['service_id'])) { $_POST['service_id'] = [$_POST['service_id']]; } foreach ($_POST['service_id'] as $value) { $info = explode('-', $value); if ($centreon->user->access->admin || in_array($info[0], $hostAclId)) { $ecObj->addSvcDowntime( $info[0], $info[1], $_POST['comment'], $concatenatedStart, $concatenatedEnd, $_POST['persistant'], $duration, $hostOrCentreonTime ); } } } elseif ($values['downtimeType']['downtimeType'] == 3) { // Set a downtime for a service group list foreach ($_POST['servicegroup_id'] as $sgId) { $stmt = $pearDBO->prepare( 'SELECT host_id, service_id FROM services_servicegroups WHERE servicegroup_id = :sgId' ); $stmt->bindValue(':sgId', $sgId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch()) { $ecObj->addSvcDowntime( $row['host_id'], $row['service_id'], $_POST['comment'], $concatenatedStart, $concatenatedEnd, $_POST['persistant'], $duration, $hostOrCentreonTime ); } } } elseif ($values['downtimeType']['downtimeType'] == 4) { // Set a downtime for poller foreach ($_POST['poller_id'] as $pollerId) { $stmt = $pearDBO->prepare( 'SELECT host_id FROM hosts WHERE instance_id = :poller_id AND enabled = 1' ); $stmt->bindValue(':poller_id', $pollerId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch()) { if ($centreon->user->access->admin || in_array($row['host_id'], $hostAclId)) { $ecObj->addHostDowntime( $row['host_id'], $_POST['comment'], $concatenatedStart, $concatenatedEnd, $_POST['persistant'], $duration, $applyDtOnServices, $hostOrCentreonTime ); } } } } require_once 'listDowntime.php'; } else { // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, 'template/'); $tpl->assign('dataPickerMaxYear', DOWNTIME_YEAR_MAX - 1); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); if (isset($_GET['service_id'], $_GET['host_id'])) { $tpl->assign('host_name', $hostName); $tpl->assign('service_description', $serviceDisplayName); } elseif (isset($_GET['host_id'])) { $tpl->assign('host_name', $hostName); } $tpl->assign('seconds', _('seconds')); $tpl->assign('o', $o); $tpl->assign('focus', $focus); $tpl->display('AddDowntime.ihtml'); } } ?> <script type='text/javascript'> jQuery(function () { setDurationField(); <?php if (isset($data['service_id'])) { echo "toggleParams('service');"; } ?> }); function setDurationField() { var durationField = jQuery('#duration'); var durationScaleField = jQuery('#duration_scale'); var fixedCb = jQuery('#fixed'); if (fixedCb.prop("checked") == true) { durationField.attr('disabled', true); durationScaleField.attr('disabled', true); } else { durationField.removeAttr('disabled'); durationScaleField.removeAttr('disabled'); } } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/downtime/listDowntime.php
centreon/www/include/monitoring/downtime/listDowntime.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 * */ if (! isset($centreon)) { exit(); } require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; require_once _CENTREON_PATH_ . 'www/include/common/sqlCommonFunction.php'; require_once './include/common/autoNumLimit.php'; $search_service = null; $host_name = null; $search_output = null; $canViewAll = false; $canViewDowntimeCycle = false; $serviceType = 1; $hostType = 2; if (isset($_POST['SearchB'])) { $centreon->historySearch[$url] = []; $search_service = isset($_POST['search_service']) ? HtmlSanitizer::createFromString($_POST['search_service'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_service'] = $search_service; $host_name = isset($_POST['search_host']) ? HtmlSanitizer::createFromString($_POST['search_host'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_host'] = $host_name; $search_output = isset($_POST['search_output']) ? HtmlSanitizer::createFromString($_POST['search_output'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_output'] = $search_output; $search_author = isset($_POST['search_author']) ? HtmlSanitizer::createFromString($_POST['search_author'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_author'] = $search_author; $canViewAll = isset($_POST['view_all']) ? true : false; $centreon->historySearch[$url]['view_all'] = $canViewAll; $canViewDowntimeCycle = isset($_POST['view_downtime_cycle']) ? true : false; $centreon->historySearch[$url]['view_downtime_cycle'] = $canViewDowntimeCycle; } elseif (isset($_GET['SearchB'])) { $centreon->historySearch[$url] = []; $search_service = isset($_GET['search_service']) ? HtmlSanitizer::createFromString($_GET['search_service'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_service'] = $search_service; $host_name = isset($_GET['search_host']) ? HtmlSanitizer::createFromString($_GET['search_host'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_host'] = $host_name; $search_output = isset($_GET['search_output']) ? HtmlSanitizer::createFromString($_GET['search_output'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_output'] = $search_output; $search_author = isset($_GET['search_author']) ? HtmlSanitizer::createFromString($_GET['search_author'])->removeTags()->getString() : null; $centreon->historySearch[$url]['search_author'] = $search_author; $canViewAll = isset($_GET['view_all']) ? true : false; $centreon->historySearch[$url]['view_all'] = $canViewAll; $canViewDowntimeCycle = isset($_GET['view_downtime_cycle']) ? true : false; $centreon->historySearch[$url]['view_downtime_cycle'] = $canViewDowntimeCycle; } else { $search_service = $centreon->historySearch[$url]['search_service'] ?? null; $host_name = $centreon->historySearch[$url]['search_host'] ?? null; $search_output = $centreon->historySearch[$url]['search_output'] ?? null; $search_author = $centreon->historySearch[$url]['search_author'] ?? null; $canViewAll = $centreon->historySearch[$url]['view_all'] ?? false; $canViewDowntimeCycle = $centreon->historySearch[$url]['view_downtime_cycle'] ?? false; } // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); include_once './class/centreonDB.class.php'; $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate('./include/monitoring/downtime/', 'template/'); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $tab_downtime_svc = []; $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'SearchB', _('Search'), $attrBtnSuccess); // ------------------ BAM ------------------ $tab_service_bam = []; $pdoStatement = $pearDB->executeQuery("SELECT id FROM modules_informations WHERE name = 'centreon-bam-server'"); if ($pdoStatement->rowCount() > 0) { $pdoStatement = $pearDB->executeQuery("SELECT CONCAT('ba_', ba_id) AS id, ba_id, name FROM mod_bam"); while (($elem = $pearDB->fetch($pdoStatement)) !== false) { $tab_service_bam[$elem['id']] = ['name' => $elem['name'], 'id' => $elem['ba_id']]; } } // Service Downtimes $extraFields = ''; if ($canViewAll) { $extraFields = ', actual_end_time, cancelled as was_cancelled '; } $bindValues = [ ':offset' => [$num * $limit, PDO::PARAM_INT], ':limit' => [$limit, PDO::PARAM_INT], ]; $serviceAclSubRequest = ''; $hostAclSubRequest = ''; if (! $is_admin) { if ($centreon->user->access->getAccessGroups() !== []) { [$aclBindValues, $aclQuery] = createMultipleBindQuery(array_keys($centreon->user->access->getAccessGroups()), ':group_id'); foreach ($aclBindValues as $key => $value) { $bindValues[$key] = [$value, PDO::PARAM_INT]; } } else { $aclQuery = '-1'; } $serviceAclSubRequest = <<<SQL INNER JOIN centreon_acl acl ON acl.host_id = s.host_id AND acl.service_id = s.service_id AND acl.group_id IN ({$aclQuery}) SQL; $hostAclSubRequest = <<<SQL INNER JOIN centreon_acl acl ON acl.host_id = h.host_id AND acl.service_id IS NULL AND acl.group_id IN ({$aclQuery}) SQL; } $subQueryConditionCancelled = (! $canViewAll) ? ' AND d.cancelled = 0 ' : ''; $subQueryConditionSearchService = ''; if (isset($search_service) && $search_service !== '') { $subQueryConditionSearchService = 'AND s.description LIKE :service '; $bindValues[':service'] = ['%' . $search_service . '%', PDO::PARAM_STR]; } $subQueryConditionSearchOutput = ''; if (isset($search_output) && $search_output !== '') { $subQueryConditionSearchOutput = 'AND d.comment_data LIKE :output '; $bindValues[':output'] = ['%' . $search_output . '%', PDO::PARAM_STR]; } elseif ($canViewDowntimeCycle === false) { $subQueryConditionSearchOutput = " AND d.comment_data NOT LIKE '%Downtime cycle%' "; } $subQueryConditionSearchAuthor = ''; if (isset($search_author) && $search_author !== '') { $subQueryConditionSearchAuthor = 'AND d.author LIKE :author '; $bindValues[':author'] = ['%' . $search_author . '%', PDO::PARAM_STR]; } $subQueryConditionSearchHost = ''; if (isset($host_name) && $host_name !== '') { $subQueryConditionSearchHost = 'AND h.name LIKE :host '; $bindValues[':host'] = ['%' . $host_name . '%', PDO::PARAM_STR]; } $subQueryConditionSearchEndTime = ''; if ($canViewAll === false) { $subQueryConditionSearchEndTime = 'AND d.end_time > :end_time '; $bindValues[':end_time'] = [time(), PDO::PARAM_INT]; } $serviceQuery = <<<SQL SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, d.internal_id as internal_downtime_id, d.entry_time, duration, d.author as author_name, d.comment_data, d.fixed as is_fixed, d.start_time as scheduled_start_time, d.end_time as scheduled_end_time, d.started as was_started, d.host_id, d.service_id, h.name as host_name, s.description as service_description, s.display_name as display_name {$extraFields} FROM downtimes d INNER JOIN services s ON d.host_id = s.host_id AND d.service_id = s.service_id INNER JOIN hosts h ON h.host_id = s.host_id {$serviceAclSubRequest} WHERE d.type = {$serviceType} {$subQueryConditionCancelled} {$subQueryConditionSearchService} {$subQueryConditionSearchOutput} {$subQueryConditionSearchAuthor} {$subQueryConditionSearchHost} {$subQueryConditionSearchEndTime} SQL; $hostQuery = <<<SQL SELECT DISTINCT 1 AS REALTIME, d.internal_id as internal_downtime_id, d.entry_time, duration, d.author as author_name, d.comment_data, d.fixed as is_fixed, d.start_time as scheduled_start_time, d.end_time as scheduled_end_time, d.started as was_started, d.host_id, d.service_id, h.name as host_name, '' as service_description, '' as display_name {$extraFields} FROM downtimes d INNER JOIN hosts h ON d.host_id = h.host_id {$hostAclSubRequest} WHERE d.type = {$hostType} {$subQueryConditionCancelled} {$subQueryConditionSearchOutput} {$subQueryConditionSearchAuthor} {$subQueryConditionSearchHost} {$subQueryConditionSearchEndTime} SQL; $unionQuery = <<<SQL ({$serviceQuery}) UNION ({$hostQuery}) ORDER BY scheduled_start_time DESC LIMIT :offset, :limit SQL; $downtimesStatement = $pearDBO->prepareQuery($unionQuery); $pearDBO->executePreparedQuery($downtimesStatement, $bindValues, true); $rows = $pearDBO->fetchColumn($pearDBO->executeQuery('SELECT FOUND_ROWS() AS REALTIME')); for ($i = 0; ($data = $pearDBO->fetch($downtimesStatement)) !== false; $i++) { $tab_downtime_svc[$i] = $data; $tab_downtime_svc[$i]['comment_data'] = CentreonUtils::escapeAllExceptSelectedTags($data['comment_data']); $tab_downtime_svc[$i]['scheduled_start_time'] = $tab_downtime_svc[$i]['scheduled_start_time'] . ' '; $tab_downtime_svc[$i]['scheduled_end_time'] = $tab_downtime_svc[$i]['scheduled_end_time'] . ' '; if (preg_match('/_Module_BAM_\d+/', $data['host_name'])) { $tab_downtime_svc[$i]['host_name'] = 'Module BAM'; $tab_downtime_svc[$i]['h_details_uri'] = './main.php?p=207&o=d&ba_id=' . $tab_service_bam[$data['service_description']]['id']; $tab_downtime_svc[$i]['s_details_uri'] = './main.php?p=207&o=d&ba_id=' . $tab_service_bam[$data['service_description']]['id']; $tab_downtime_svc[$i]['service_description'] = $tab_service_bam[$data['service_description']]['name']; $tab_downtime_svc[$i]['downtime_type'] = 'SVC'; if ($tab_downtime_svc[$i]['author_name'] === 'Centreon Broker BAM Module') { $tab_downtime_svc[$i]['scheduled_end_time'] = 'Automatic'; $tab_downtime_svc[$i]['duration'] = 'Automatic'; } } else { $tab_downtime_svc[$i]['host_name'] = $data['host_name']; $tab_downtime_svc[$i]['h_details_uri'] = $useDeprecatedPages ? './main.php?p=20202&o=hd&host_name=' . $data['host_name'] : $resourceController->buildHostDetailsUri($data['host_id']); if ($data['service_description'] !== '') { $tab_downtime_svc[$i]['s_details_uri'] = $useDeprecatedPages ? './main.php?p=202&o=svcd&host_name=' . $data['host_name'] . '&service_description=' . $data['service_description'] : $resourceController->buildServiceDetailsUri( $data['host_id'], $data['service_id'] ); $tab_downtime_svc[$i]['service_description'] = preg_match('/_Module_Meta/', $data['host_name']) ? $data['display_name'] : $data['service_description']; $tab_downtime_svc[$i]['downtime_type'] = 'SVC'; } else { $tab_downtime_svc[$i]['service_description'] = '-'; $tab_downtime_svc[$i]['downtime_type'] = 'HOST'; } } } unset($data); include './include/common/checkPagination.php'; $en = ['0' => _('No'), '1' => _('Yes')]; foreach ($tab_downtime_svc as $key => $value) { $tab_downtime_svc[$key]['is_fixed'] = $en[$tab_downtime_svc[$key]['is_fixed']]; $tab_downtime_svc[$key]['was_started'] = $en[$tab_downtime_svc[$key]['was_started']]; if ($canViewAll) { if (! isset($tab_downtime_svc[$key]['actual_end_time']) || ! $tab_downtime_svc[$key]['actual_end_time']) { if ($tab_downtime_svc[$key]['was_cancelled'] === 0) { $tab_downtime_svc[$key]['actual_end_time'] = _('N/A'); } else { $tab_downtime_svc[$key]['actual_end_time'] = _('Never Started'); } } else { $tab_downtime_svc[$key]['actual_end_time'] = $tab_downtime_svc[$key]['actual_end_time'] . ' '; } $tab_downtime_svc[$key]['was_cancelled'] = $en[$tab_downtime_svc[$key]['was_cancelled']]; } } // Element we need when we reload the page $form->addElement('hidden', 'p'); $tab = ['p' => $p]; $form->setDefaults($tab); if ($centreon->user->access->checkAction('host_schedule_downtime')) { $tpl->assign('msgs2', ['addL2' => '?p=' . $p . '&o=a', 'addT2' => _('Add a downtime'), 'delConfirm' => addslashes(_('Do you confirm the cancellation ?'))]); } $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('tab_downtime_svc', $tab_downtime_svc); $tpl->assign('nb_downtime_svc', count($tab_downtime_svc)); $tpl->assign('dtm_service_downtime', _('Services Downtimes')); $tpl->assign('secondes', _('s')); $tpl->assign('view_host_dtm', _('View downtimes of hosts')); $tpl->assign('host_dtm_link', './main.php?p=' . $p . '&o=vh'); $tpl->assign('cancel', _('Cancel')); $tpl->assign('limit', $limit); $tpl->assign('Host', _('Host Name')); $tpl->assign('Service', _('Service')); $tpl->assign('Output', _('Output')); $tpl->assign('user', _('Users')); $tpl->assign('Hostgroup', _('Hostgroup')); $tpl->assign('Search', _('Search')); $tpl->assign('ViewAll', _('Display Finished Downtimes')); $tpl->assign('ViewDowntimeCycle', _('Display Recurring Downtimes')); $tpl->assign('Author', _('Author')); $tpl->assign('search_output', $search_output); $tpl->assign('search_host', $host_name); $tpl->assign('search_service', $search_service); $tpl->assign('view_all', (int) $canViewAll); $tpl->assign('view_downtime_cycle', (int) $canViewDowntimeCycle); $tpl->assign('search_author', $search_author ?? ''); // Send Form $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); // Display Page $tpl->display('listDowntime.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/downtime/downtime.php
centreon/www/include/monitoring/downtime/downtime.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 * */ if (! isset($centreon)) { exit(); } // External Command Object $ecObj = new CentreonExternalCommand($centreon); $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Path to the configuration dir $path = './include/monitoring/downtime/'; // PHP functions require_once './include/common/common-Func.php'; require_once $path . 'common-Func.php'; require_once './include/monitoring/external_cmd/functions.php'; switch ($o) { case 'a': require_once $path . 'AddDowntime.php'; break; case 'ds': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (isset($_POST['select'])) { foreach ($_POST['select'] as $key => $value) { $res = explode(';', urldecode($key)); $ishost = isDownTimeHost($res[2]); if ( $oreon->user->access->admin || ($ishost && $oreon->user->access->checkAction('host_schedule_downtime')) || (! $ishost && $oreon->user->access->checkAction('service_schedule_downtime')) ) { $ecObj->deleteDowntime($res[0], [$res[1] . ';' . $res[2] => 'on']); deleteDowntimeInDb($res[2]); } } } } else { unvalidFormMessage(); } try { require_once $path . 'listDowntime.php'; } catch (Throwable $ex) { CentreonLog::create()->error( logTypeId: CentreonLog::TYPE_BUSINESS_LOG, message: 'Error while listing downtime: ' . $ex->getMessage(), exception: $ex ); throw $ex; } break; case 'cs': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (isset($_POST['select'])) { foreach ($_POST['select'] as $key => $value) { $res = explode(';', urldecode($key)); $ishost = isDownTimeHost($res[2]); if ( $oreon->user->access->admin || ($ishost && $oreon->user->access->checkAction('host_schedule_downtime')) || (! $ishost && $oreon->user->access->checkAction('service_schedule_downtime')) ) { $ecObj->deleteDowntime($res[0], [$res[1] . ';' . $res[2] => 'on']); } } } } else { unvalidFormMessage(); } // then, as all the next cases, requiring the listDowntime.php // no break case 'vs': case 'vh': default: try { require_once $path . 'listDowntime.php'; } catch (Throwable $ex) { CentreonLog::create()->error( logTypeId: CentreonLog::TYPE_BUSINESS_LOG, message: 'Error while listing downtime: ' . $ex->getMessage(), exception: $ex ); throw $ex; } break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/downtime/xml/broker/makeXMLForDowntime.php
centreon/www/include/monitoring/downtime/xml/broker/makeXMLForDowntime.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 realpath(__DIR__ . '/../../../../../../config/centreon.config.php'); include_once _CENTREON_PATH_ . 'www/class/centreonDuration.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; session_start(); session_write_close(); $oreon = $_SESSION['centreon']; $db = new CentreonDB(); $dbb = new CentreonDB('centstorage'); $centreonLang = new CentreonLang(_CENTREON_PATH_, $oreon); $centreonLang->bindLang(); $sid = session_id(); if (isset($sid)) { $res = $db->prepare('SELECT * FROM session WHERE session_id = :id'); $res->bindValue(':id', $sid, PDO::PARAM_STR); $res->execute(); if (! $session = $res->fetch()) { get_error('bad session id'); } } else { get_error('need session id !'); } // sanitize host and service id from request; $hostId = filter_var($_GET['hid'] ?? false, FILTER_VALIDATE_INT); $svcId = filter_var($_GET['svc_id'] ?? false, FILTER_VALIDATE_INT); // check if a mandatory valid hostId is given if ($hostId === false) { get_error('bad host Id'); } // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession($sid); // Start Buffer $xml = new CentreonXML(); $xml->startElement('response'); $xml->startElement('label'); $xml->writeElement('author', _('Author')); $xml->writeElement('fixed', _('Fixed')); $xml->writeElement('start', _('Start Time')); $xml->writeElement('end', _('End Time')); $xml->writeElement('comment', _('Comment')); $xml->endElement(); // Retrieve info if ($svcId === false) { $res = $dbb->prepare( 'SELECT author, actual_start_time , end_time, comment_data, duration, fixed FROM downtimes WHERE host_id = :hostId AND type = 2 AND cancelled = 0 AND UNIX_TIMESTAMP(NOW()) >= actual_start_time AND end_time > UNIX_TIMESTAMP(NOW()) ORDER BY actual_start_time' ); $res->bindValue(':hostId', $hostId, PDO::PARAM_INT); $res->execute(); } else { $res = $dbb->prepare( 'SELECT author, actual_start_time, end_time, comment_data, duration, fixed FROM downtimes WHERE host_id = :hostId AND service_id = :svcId AND type = 1 AND cancelled = 0 AND UNIX_TIMESTAMP(NOW()) >= actual_start_time AND end_time > UNIX_TIMESTAMP(NOW()) ORDER BY actual_start_time' ); $res->bindValue(':hostId', $hostId, PDO::PARAM_INT); $res->bindValue(':svcId', $svcId, PDO::PARAM_INT); $res->execute(); } $rowClass = 'list_one'; while ($row = $res->fetch()) { $row['comment_data'] = strip_tags($row['comment_data']); $xml->startElement('dwt'); $xml->writeAttribute('class', $rowClass); $xml->writeElement('author', $row['author']); $xml->writeElement('start', $row['actual_start_time']); if (! $row['fixed']) { $row['end_time'] = (int) $row['actual_start_time'] + (int) $row['duration']; } $xml->writeElement('end', $row['end_time']); $xml->writeElement('comment', $row['comment_data']); $xml->writeElement('duration', CentreonDuration::toString($row['duration'])); $xml->writeElement('fixed', $row['fixed'] ? _('Yes') : _('No')); $xml->endElement(); $rowClass = $rowClass == 'list_one' ? 'list_two' : 'list_one'; } // End buffer $xml->endElement(); header('Content-type: text/xml; charset=utf-8'); header('Cache-Control: no-cache, must-revalidate'); // Print Buffer $xml->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/submitPassivResults/hostPassiveCheck.php
centreon/www/include/monitoring/submitPassivResults/hostPassiveCheck.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 * */ $o = 'hd'; if (! isset($centreon)) { exit(); } require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php'; $host_name = $_GET['host_name'] ?? null; $cmd = $_GET['cmd'] ?? null; $hObj = new CentreonHost($pearDB); $path = './include/monitoring/submitPassivResults/'; $pearDBndo = new CentreonDB('centstorage'); $aclObj = new CentreonACL($centreon->user->get_id()); if (! $is_admin) { $hostTab = explode(',', $centreon->user->access->getHostsString('NAME', $pearDBndo)); foreach ($hostTab as $value) { if ($value == "'" . $host_name . "'") { $flag_acl = 1; } } } $hostTab = []; if ($is_admin || ($flag_acl && ! $is_admin)) { $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $form->addElement('header', 'title', _('Command Options')); $hosts = [$host_name => $host_name]; $form->addElement('select', 'host_name', _('Host Name'), $hosts, ['onChange' => 'this.form.submit();']); $form->addRule('host_name', _('Required Field'), 'required'); $return_code = ['0' => 'UP', '1' => 'DOWN', '2' => 'UNREACHABLE']; $form->addElement('select', 'return_code', _('Check result'), $return_code); $form->addElement('text', 'output', _('Check output'), ['size' => '100']); $form->addElement('text', 'dataPerform', _('Performance data'), ['size' => '100']); $form->addElement('hidden', 'author', $centreon->user->get_alias()); $form->addElement('hidden', 'cmd', $cmd); $form->addElement('hidden', 'p', $p); $form->addElement('submit', 'submit', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('hostPassiveCheck.ihtml'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/submitPassivResults/servicePassiveCheck.php
centreon/www/include/monitoring/submitPassivResults/servicePassiveCheck.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 * */ $o = 'svcd'; if (! isset($centreon)) { exit(); } require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonMeta.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; $host_name = $_GET['host_name'] ?? null; $service_description = $_GET['service_description'] ?? null; $cmd = $_GET['cmd'] ?? null; $is_meta = isset($_GET['is_meta']) && $_GET['is_meta'] == 'true' ? $_GET['is_meta'] : 'false'; $hObj = new CentreonHost($pearDB); $serviceObj = new CentreonService($pearDB); $metaObj = new CentreonMeta($pearDB); $path = './include/monitoring/submitPassivResults/'; $pearDBndo = new CentreonDB('centstorage'); $host_id = $hObj->getHostId($host_name); $hostDisplayName = $host_name; $serviceDisplayName = $service_description; if ($is_meta == 'true') { $metaId = null; if (preg_match('/meta_(\d+)/', $service_description, $matches)) { $metaId = $matches[1]; } $hostDisplayName = 'Meta'; $serviceId = $metaObj->getRealServiceId($metaId); $serviceParameters = $serviceObj->getParameters($serviceId, ['display_name']); $serviceDisplayName = $serviceParameters['display_name']; } if (! $is_admin && $host_id) { $flag_acl = 0; if ($is_meta == 'true') { $aclMetaServices = $centreon->user->access->getMetaServices(); $aclMetaIds = array_keys($aclMetaServices); if (in_array($metaId, $aclMetaIds)) { $flag_acl = 1; } } else { $serviceTab = $centreon->user->access->getHostServices($pearDBndo, $host_id); if (in_array($service_description, $serviceTab)) { $flag_acl = 1; } } } if (($is_admin || $flag_acl) && $host_id) { $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $form->addElement('header', 'title', _('Command Options')); $return_code = ['0' => 'OK', '1' => 'WARNING', '3' => 'UNKNOWN', '2' => 'CRITICAL']; $form->addElement('select', 'return_code', _('Check result'), $return_code); $form->addElement('text', 'output', _('Check output'), ['size' => '100']); $form->addElement('text', 'dataPerform', _('Performance data'), ['size' => '100']); $form->addElement('hidden', 'host_name', $host_name); $form->addElement('hidden', 'service_description', $service_description); $form->addElement('hidden', 'author', $centreon->user->get_alias()); $form->addElement('hidden', 'cmd', $cmd); $form->addElement('hidden', 'p', $p); $form->addElement('submit', 'submit', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('host_name', $hostDisplayName); $tpl->assign('service_description', $serviceDisplayName); $tpl->assign('form', $renderer->toArray()); $tpl->display('servicePassiveCheck.ihtml'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/functionsPopup.php
centreon/www/include/monitoring/external_cmd/functionsPopup.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 * */ if (! isset($centreon)) { exit(); } function sanitizeShellString($string) { $string = str_replace('\'', ' ', trim(urldecode($string))); $string = str_replace('`', ' ', $string); return str_replace('$(', '(', $string); } /** * Ack hosts massively * @param $key * @return string */ function massiveHostAck($key) { global $pearDB, $is_admin, $centreon; static $processedHosts = []; $actions = $centreon->user->access->checkAction('host_acknowledgement'); $key = urldecode($key); $tmp = preg_split("/\;/", $key); $hostName = $tmp[0]; if (isset($processedHosts[$hostName])) { return null; } $processedHosts[$hostName] = true; $persistent = isset($_POST['persistent']) && $_POST['persistent'] == 'true' ? '1' : '0'; $notify = isset($_POST['notify']) && $_POST['notify'] == 'true' ? '1' : '0'; $sticky = isset($_POST['sticky']) && $_POST['sticky'] == 'true' ? '2' : '1'; $force_check = isset($_POST['force_check']) && $_POST['force_check'] == 'true' ? '1' : '0'; $_POST['comment'] = sanitizeShellString($_POST['comment']); $extCmdObj = new CentreonExternalCommand($centreon); if ($actions == true || $is_admin) { $extCmdObj->acknowledgeHost( $hostName, $sticky, $notify, $persistent, $_POST['author'], $_POST['comment'] ); if ($force_check == 1) { $extCmdObj->scheduleForcedCheckHost( $hostName ); } } $actions = $centreon->user->access->checkAction('service_acknowledgement'); if ( ($actions == true || $is_admin) && isset($_POST['ackhostservice']) && $_POST['ackhostservice'] == 'true' ) { $statement = $pearDB->prepare('SELECT host_id FROM `host` WHERE host_name = :hostName LIMIT 1'); $statement->bindValue(':hostName', $hostName, PDO::PARAM_STR); $statement->execute(); $row = $statement->fetchRow(); $svc_tab = getMyHostServices($row['host_id']); if (count($svc_tab)) { foreach ($svc_tab as $key2 => $value) { $extCmdObj->acknowledgeService( $hostName, $value, $sticky, $notify, $persistent, $_POST['author'], $_POST['comment'] ); if ( $force_check == 1 && $centreon->user->access->checkAction('service_schedule_forced_check') == true ) { $extCmdObj->scheduleForcedCheckService( $hostName, $value ); } } } } // Set param in memory set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $sticky); set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $notify); set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $persistent); set_user_param($centreon->user->user_id, $pearDB, 'force_check', $force_check); return _('Your command has been sent'); } /** * Ack services massively * @param $key * @throws Exception * @return null|string */ function massiveServiceAck($key) { global $pearDB, $is_admin, $centreon; $actions = $centreon->user->access->checkAction('service_acknowledgement'); $key = urldecode($key); $tmp = preg_split("/\;/", $key); if (! isset($tmp[0])) { throw new Exception('No host found'); } $hostName = $tmp[0]; if (! isset($tmp[1])) { throw new Exception('No service found'); } $serviceDescription = $tmp[1]; $persistent = isset($_POST['persistent']) && $_POST['persistent'] == 'true' ? '1' : '0'; $notify = isset($_POST['notify']) && $_POST['notify'] == 'true' ? '1' : '0'; $sticky = isset($_POST['sticky']) && $_POST['sticky'] == 'true' ? '2' : '1'; $force_check = isset($_POST['force_check']) && $_POST['force_check'] == 'true' ? '1' : '0'; if ($actions == true || $is_admin) { $_POST['comment'] = sanitizeShellString($_POST['comment']); $extCmdObj = new CentreonExternalCommand($centreon); $extCmdObj->acknowledgeService( $hostName, $serviceDescription, $sticky, $notify, $persistent, $_POST['author'], $_POST['comment'] ); if ($force_check == 1 && $centreon->user->access->checkAction('service_schedule_forced_check') == true) { $extCmdObj->scheduleForcedCheckService( $hostName, $serviceDescription ); } set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $sticky); set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $notify); set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $persistent); set_user_param($centreon->user->user_id, $pearDB, 'force_check', $force_check); return _('Your command has been sent'); } return null; } /** * Sets host downtime massively * @param $key * @throws Exception * @return null */ function massiveHostDowntime($key) { global $is_admin, $centreon; static $processedHosts = []; $actions = $centreon->user->access->checkAction('host_schedule_downtime'); if ($actions == true || $is_admin) { $key = urldecode($key); $tmp = preg_split("/\;/", $key); if (! isset($tmp[0])) { throw new Exception('No host found'); } $host_name = $tmp[0]; if (isset($processedHosts[$host_name])) { return null; } $processedHosts[$host_name] = true; $start = isset($_POST['start']) && $_POST['start'] ? $_POST['start'] : time(); $end = isset($_POST['end']) && $_POST['end'] ? $_POST['end'] : time(); $comment = isset($_POST['comment']) && $_POST['comment'] ? sanitizeShellString($_POST['comment']) : ''; $fixed = isset($_POST['fixed']) && $_POST['fixed'] == 'true' ? $fixed = 1 : $fixed = 0; $duration = isset($_POST['duration']) && $_POST['duration'] && is_numeric($_POST['duration']) ? $duration = $_POST['duration'] : $duration = 0; $duration_scale = isset($_POST['duration_scale']) && $_POST['duration_scale'] ? $duration_scale = $_POST['duration_scale'] : $duration_scale = 's'; $hostTime = isset($_POST['host_or_centreon_time']) && $_POST['host_or_centreon_time'] == 'true' ? '1' : '0'; if ($duration > 0) { switch ($duration_scale) { default: case 's': $duration = $duration; break; case 'm': $duration = $duration * 60; break; case 'h': $duration = $duration * 60 * 60; break; case 'd': $duration = $duration * 60 * 60 * 24; break; } } $host = getMyHostID($host_name); $with_services = false; if ( ($centreon->user->access->checkAction('service_schedule_downtime') == true) && isset($_POST['downtimehostservice']) && $_POST['downtimehostservice'] == 'true' ) { $with_services = true; } $extCmdObj = new CentreonExternalCommand($centreon); $extCmdObj->addHostDowntime($host, $comment, $start, $end, $fixed, $duration, $with_services, $hostTime); } return null; } // Sets service downtime massively function massiveServiceDowntime($key) { global $is_admin, $centreon; $actions = $centreon->user->access->checkAction('service_schedule_downtime'); if ($actions == true || $is_admin) { $key = urldecode($key); $tmp = preg_split("/\;/", $key); if (! isset($tmp[0])) { throw new Exception('No host found'); } $host_name = $tmp[0]; if (! isset($tmp[1])) { throw new Exception('No service found'); } $svc_description = $tmp[1]; $start = isset($_POST['start']) && $_POST['start'] ? $_POST['start'] : time(); $end = isset($_POST['end']) && $_POST['end'] ? $_POST['end'] : time(); $comment = isset($_POST['comment']) && $_POST['comment'] ? sanitizeShellString($_POST['comment']) : ''; $fixed = isset($_POST['fixed']) && $_POST['fixed'] == 'true' ? 1 : 0; $duration = isset($_POST['duration']) && $_POST['duration'] && is_numeric($_POST['duration']) ? $_POST['duration'] : 0; $duration_scale = isset($_POST['duration_scale']) && $_POST['duration_scale'] ? $_POST['duration_scale'] : 's'; $hostTime = isset($_POST['host_or_centreon_time']) && $_POST['host_or_centreon_time'] == 'true' ? '1' : '0'; if ($duration > 0) { switch ($duration_scale) { default: case 's': $duration = $duration; break; case 'm': $duration = $duration * 60; break; case 'h': $duration = $duration * 60 * 60; break; case 'd': $duration = $duration * 60 * 60 * 24; break; } } $host = getMyHostID($host_name); $service = getMyServiceID($svc_description, $host); $extCmdObj = new CentreonExternalCommand($centreon); $extCmdObj->addSvcDowntime($host, $service, $comment, $start, $end, $fixed, $duration, $hostTime); } 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/include/monitoring/external_cmd/cmdPopup.php
centreon/www/include/monitoring/external_cmd/cmdPopup.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 realpath(__DIR__ . '/../../../../bootstrap.php'); require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; session_start(); session_write_close(); $centreon = $_SESSION['centreon']; global $centreon, $pearDB; // Connect to DB $pearDB = $dependencyInjector['configuration_db']; session_start(); session_write_close(); if (! CentreonSession::checkSession(session_id(), $pearDB)) { exit(); } $centreon = $_SESSION['centreon']; // GMT management $centreonGMT = new CentreonGMT(); $sid = session_id(); $centreonGMT->getMyGMTFromSession($sid); require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; require_once _CENTREON_PATH_ . 'www/include/monitoring/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/monitoring/external_cmd/functionsPopup.php'; const ACKNOWLEDGEMENT_ON_SERVICE = 70; const ACKNOWLEDGEMENT_ON_HOST = 72; const DOWNTIME_ON_SERVICE = 74; const DOWNTIME_ON_HOST = 75; if ( isset($_POST['resources'], $sid, $_POST['cmd']) ) { $is_admin = isUserAdmin($sid); $resources = json_decode($_POST['resources'], true); foreach ($resources as $resource) { switch ((int) $_POST['cmd']) { case ACKNOWLEDGEMENT_ON_SERVICE: massiveServiceAck($resource); break; case ACKNOWLEDGEMENT_ON_HOST: massiveHostAck($resource); break; case DOWNTIME_ON_SERVICE: massiveServiceDowntime($resource); break; case DOWNTIME_ON_HOST: massiveHostDowntime($resource); break; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/functions.php
centreon/www/include/monitoring/external_cmd/functions.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 * */ if (! isset($centreon)) { exit(); } $tab = ['1' => 'ENABLE', '0' => 'DISABLE']; function write_command($cmd, $poller) { global $centreon, $key, $pearDB; $str = null; // Destination is centcore pipe path $destination = defined('_CENTREON_VARLIB_') ? _CENTREON_VARLIB_ . '/centcore.cmd' : '/var/lib/centreon/centcore.cmd'; $cmd = str_replace('`', '&#96;', $cmd); $cmd = str_replace("\n", '<br>', $cmd); $informations = preg_split("/\;/", $key); if (! mb_detect_encoding($cmd, 'UTF-8', true)) { $cmd = mb_convert_encoding($cmd, 'UTF-8', 'ISO-8859-1'); } setlocale(LC_CTYPE, 'en_US.UTF-8'); $str = 'echo ' . escapeshellarg("EXTERNALCMD:{$poller}:[" . time() . ']' . $cmd) . ' >> ' . $destination; return passthru($str); } function send_cmd($cmd, $poller = null) { if (isset($cmd)) { $flg = write_command($cmd, $poller); } return isset($flg) && $flg ? $flg : _('Command execution problem'); } // Re-Schedule for all services of an host function schedule_host_svc_checks($arg, $forced) { global $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_checks_for_services'); if ($actions == true || $is_admin) { $tab_forced = ['0' => '', '1' => '_FORCED']; $flg = send_cmd( ' SCHEDULE' . $tab_forced[$forced] . '_HOST_SVC_CHECKS;' . $arg . ';' . time(), GetMyHostPoller($pearDB, $arg) ); return $flg; } return null; } // SCHEDULE_SVC_CHECK function schedule_svc_checks($arg, $forced) { global $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_schedule_check'); if ($forced == '1') { $actions = $centreon->user->access->checkAction('service_schedule_forced_check'); } if ($actions == true || $is_admin) { $tab_forced = ['0' => '', '1' => '_FORCED']; $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' SCHEDULE' . $tab_forced[$forced] . '_SVC_CHECK;' . urldecode($tab_data[0]) . ';' . urldecode($tab_data[1]) . ';' . time(), GetMyHostPoller($pearDB, urldecode($tab_data[0])) ); return $flg; } return null; } // SCHEDULE_HOST_CHECK function schedule_host_checks($arg, $forced) { global $pearDB, $is_admin, $oreon; $actions = false; $actions = $oreon->user->access->checkAction('host_schedule_check'); if ($forced == '1') { $actions = $oreon->user->access->checkAction('host_schedule_forced_check'); } if ($actions == true || $is_admin) { $tab_forced = ['0' => '', '1' => '_FORCED']; $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' SCHEDULE' . $tab_forced[$forced] . '_HOST_CHECK;' . urldecode($tab_data[0]) . ';' . time(), GetMyHostPoller($pearDB, urldecode($tab_data[0])) ); return $flg; } return null; } // host check function host_check($arg, $type) { global $tab, $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_checks'); if ($actions == true || $is_admin) { $flg = send_cmd( ' ' . $tab[$type] . '_HOST_CHECK;' . urldecode($arg), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // host notification function host_notification($arg, $type) { global $tab, $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_notifications'); if ($actions == true || $is_admin) { $flg = send_cmd( ' ' . $tab[$type] . '_HOST_NOTIFICATIONS;' . urldecode($arg), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // ENABLE_HOST_SVC_NOTIFICATIONS function host_svc_notifications($arg, $type) { global $tab, $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_notifications_for_services'); if ($actions == true || $is_admin) { $flg = send_cmd( ' ' . $tab[$type] . '_HOST_SVC_NOTIFICATIONS;' . urldecode($arg), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // ENABLE_HOST_SVC_CHECKS function host_svc_checks($arg, $type) { global $tab, $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_checks_for_services'); if ($actions == true || $is_admin) { $flg = send_cmd( ' ' . $tab[$type] . '_HOST_SVC_CHECKS;' . urldecode($arg) . ';' . time(), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // ENABLE_HOST_SVC_CHECKS function svc_check($arg, $type) { global $tab, $pearDB, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_checks'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_SVC_CHECK;' . urldecode($tab_data['0']) . ';' . urldecode($tab_data['1']), GetMyHostPoller($pearDB, urldecode($tab_data['0'])) ); return $flg; } return null; } // PASSIVE_SVC_CHECKS function passive_svc_check($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_passive_checks'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_PASSIVE_SVC_CHECKS;' . urldecode($tab_data[0]) . ';' . urldecode($tab_data[1]), GetMyHostPoller($pearDB, urldecode($tab_data['0'])) ); return $flg; } return null; } // SVC_NOTIFICATIONS function svc_notifications($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_notifications'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_SVC_NOTIFICATIONS;' . urldecode($tab_data[0]) . ';' . urldecode($tab_data[1]), GetMyHostPoller($pearDB, urldecode($tab_data['0'])) ); return $flg; } return null; } // SVC_EVENT_HANDLER function svc_event_handler($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_event_handler'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_SVC_EVENT_HANDLER;' . urldecode($tab_data[0]) . ';' . urldecode($tab_data[1]), GetMyHostPoller($pearDB, urldecode($tab_data['0'])) ); return $flg; } return null; } // HOST_EVENT_HANDLER function host_event_handler($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_event_handler'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_HOST_EVENT_HANDLER;' . urldecode($arg), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // Enable or disable Flap detection function svc_flapping_enable($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_flap_detection'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_SVC_FLAP_DETECTION;' . urldecode($tab_data[0]) . ';' . urldecode($tab_data[1]), GetMyHostPoller($pearDB, urldecode($tab_data[0])) ); return $flg; } return null; } // HOST_FLAP_DETECTION function host_flapping_enable($arg, $type) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_flap_detection'); if ($actions == true || $is_admin) { $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_HOST_FLAP_DETECTION;' . urldecode($arg), GetMyHostPoller($pearDB, urldecode($arg)) ); return $flg; } return null; } // enable or disable notification for a hostgroup function notify_host_hostgroup($arg, $type) { global $pearDB, $tab, $is_admin; $tab_data = preg_split("/\;/", $arg); $flg = send_cmd( ' ' . $tab[$type] . '_HOST_NOTIFICATIONS;' . urldecode($tab_data[0]), GetMyHostPoller($pearDB, urldecode($tab_data[0])) ); return $flg; } // Ack a host function acknowledgeHost($param) { global $pearDB, $tab, $key, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_acknowledgement'); if ($actions == true || $is_admin) { $key = $param['host_name']; $sticky = isset($param['sticky']) && $param['sticky'] == '1' ? '2' : '1'; $host_poller = GetMyHostPoller($pearDB, htmlentities($param['host_name'], ENT_QUOTES, 'UTF-8')); $flg = write_command( ' ACKNOWLEDGE_HOST_PROBLEM;' . urldecode($param['host_name']) . ";{$sticky};" . htmlentities($param['notify'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['persistent'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['author'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['comment'], ENT_QUOTES, 'UTF-8'), urldecode($host_poller) ); if (isset($param['ackhostservice']) && $param['ackhostservice'] == 1) { $svc_tab = getMyHostServices(getMyHostID(htmlentities($param['host_name'], ENT_QUOTES, 'UTF-8'))); if (count($svc_tab)) { foreach ($svc_tab as $key2 => $value) { write_command( ' ACKNOWLEDGE_SVC_PROBLEM;' . htmlentities(urldecode($param['host_name']), ENT_QUOTES, 'UTF-8') . ';' . $value . ';' . $sticky . ';' . htmlentities($param['notify'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['persistent'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['author'], ENT_QUOTES, 'UTF-8') . ';' . htmlentities($param['comment'], ENT_QUOTES, 'UTF-8'), urldecode($host_poller) ); } } } set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $param['sticky']); set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $param['notify']); set_user_param($centreon->user->user_id, $pearDB, 'ack_services', $param['ackhostservice']); set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $param['persistent']); return _('Your command has been sent'); } return null; } // Remove ack for a host function acknowledgeHostDisable() { global $pearDB, $tab, $_GET, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_disacknowledgement'); if ($actions == true || $is_admin) { $flg = send_cmd( ' REMOVE_HOST_ACKNOWLEDGEMENT;' . urldecode($_GET['host_name']), GetMyHostPoller($pearDB, urldecode($_GET['host_name'])) ); return $flg; } return null; } // Remove ack for a service function acknowledgeServiceDisable() { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_disacknowledgement'); if ($actions == true || $is_admin) { $flg = send_cmd( ' REMOVE_SVC_ACKNOWLEDGEMENT;' . urldecode($_GET['host_name']) . ';' . urldecode($_GET['service_description']), GetMyHostPoller($pearDB, urldecode($_GET['host_name'])) ); return $flg; } return null; } // Ack a service function acknowledgeService($param) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_acknowledgement'); if ($actions == true || $is_admin) { $param['comment'] = $param['comment']; $param['comment'] = str_replace('\'', ' ', $param['comment']); $sticky = isset($param['sticky']) && $param['sticky'] == '1' ? '2' : '1'; $flg = send_cmd( ' ACKNOWLEDGE_SVC_PROBLEM;' . urldecode($param['host_name']) . ';' . urldecode($param['service_description']) . ';' . $sticky . ';' . $param['notify'] . ';' . $param['persistent'] . ';' . $param['author'] . ';' . $param['comment'], GetMyHostPoller($pearDB, urldecode($param['host_name'])) ); $force_check = isset($param['force_check']) && $param['force_check'] ? 1 : 0; if ($force_check == 1 && $centreon->user->access->checkAction('service_schedule_forced_check') == true) { send_cmd( ' SCHEDULE_FORCED_SVC_CHECK;' . urldecode($param['host_name']) . ';' . urldecode($param['service_description']) . ';' . time(), GetMyHostPoller($pearDB, urldecode($param['host_name'])) ); } set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $param['sticky']); set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $param['notify']); set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $param['persistent']); set_user_param($centreon->user->user_id, $pearDB, 'force_check', $force_check); return $flg; } return null; } function submitPassiveCheck() { global $pearDB, $key, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_submit_result'); if ($actions == true || $is_admin) { $key = $_GET['host_name']; $flg = send_cmd( ' PROCESS_SERVICE_CHECK_RESULT;' . urldecode($_GET['host_name']) . ';' . urldecode($_GET['service_description']) . ';' . $_GET['return_code'] . ';' . $_GET['output'] . '|' . $_GET['dataPerform'], GetMyHostPoller($pearDB, urldecode($_GET['host_name'])) ); return $flg; } return null; } function submitHostPassiveCheck() { global $pearDB, $key, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_submit_result'); if ($actions == true || $is_admin) { $key = $_GET['host_name']; $flg = send_cmd( ' PROCESS_HOST_CHECK_RESULT;' . urldecode($_GET['host_name']) . ';' . $_GET['return_code'] . ';' . $_GET['output'] . '|' . $_GET['dataPerform'], GetMyHostPoller($pearDB, urldecode($_GET['host_name'])) ); return $flg; } return null; } function notify_svc_host_hostgroup($arg, $type) { global $tab, $pearDB, $is_admin; /* $res = $pearDB->query("SELECT host_host_id FROM hostgroup_relation WHERE hostgroup_hg_id = '".$arg."'"); while ($r = $res->fetchRow()){ $resH = $pearDB->query("SELECT host_name FROM host WHERE host_id = '".$r["host_host_id"]."'"); $rH = $resH->fetchRow(); $flg = send_cmd(" " . $tab[$type] . "_HOST_NOTIFICATIONS;". $rH["host_name"]); } */ return $flg; } function checks_svc_host_hostgroup($arg, $type) { global $tab, $pearDB, $is_admin; /* $res = $pearDB->query("SELECT host_host_id FROM hostgroup_relation WHERE hostgroup_hg_id = '".$arg."'"); $r = $res->fetchRow(); $flg = send_cmd(" " . $tab[$type] . "_HOST_SVC_CHECKS;". $rH["host_name"]); */ return $flg; } // ############################################################################ // Monitoring Quick Actions // ############################################################################ // Quick Action -> service ack : Stop and start function autoAcknowledgeServiceStart($key) { global $pearDB, $tab, $centreon, $is_admin; $actions = false; $actions = $centreon->user->access->checkAction('service_acknowledgement'); if ($actions == true || $is_admin) { $comment = 'Service Auto Acknowledge by ' . $centreon->user->alias . "\n"; $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ACKNOWLEDGE_SVC_PROBLEM;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]) . ';1;1;1;' . $centreon->user->alias . ';' . $comment, GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoAcknowledgeServiceStop($key) { global $pearDB, $tab, $centreon, $is_admin; $actions = false; $actions = $centreon->user->access->checkAction('service_disacknowledgement'); if ($actions == true || $is_admin) { $comment = 'Service Auto Acknowledge by ' . $centreon->user->alias . "\n"; $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' REMOVE_SVC_ACKNOWLEDGEMENT;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } // Quick Action -> host ack : Stop and start function autoAcknowledgeHostStart($key) { global $pearDB, $tab, $centreon, $is_admin; $actions = false; $actions = $centreon->user->access->checkAction('host_acknowledgement'); if ($actions == true || $is_admin) { $comment = 'Host Auto Acknowledge by ' . $centreon->user->alias . "\n"; $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ACKNOWLEDGE_HOST_PROBLEM;' . urldecode($ressource[0]) . ';1;1;1;' . $centreon->user->alias . ';' . $comment, GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoAcknowledgeHostStop($key) { global $pearDB, $tab, $centreon, $is_admin; $actions = false; $actions = $centreon->user->access->checkAction('host_disacknowledgement'); if ($actions == true || $is_admin) { $comment = 'Host Auto Acknowledge by ' . $centreon->user->alias . "\n"; $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' REMOVE_HOST_ACKNOWLEDGEMENT;' . urldecode($ressource[0]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } // Quick Action -> service notification : Stop and start function autoNotificationServiceStart($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_notifications'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ENABLE_SVC_NOTIFICATIONS;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoNotificationServiceStop($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_notifications'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' DISABLE_SVC_NOTIFICATIONS;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } // Quick Action -> host notification : Stop and start function autoNotificationHostStart($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_notifications'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ENABLE_HOST_NOTIFICATIONS;' . urldecode($ressource[0]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoNotificationHostStop($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_notifications'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' DISABLE_HOST_NOTIFICATIONS;' . urldecode($ressource[0]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } // Quick Action -> service check : Stop and start function autoCheckServiceStart($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_checks'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ENABLE_SVC_CHECK;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoCheckServiceStop($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('service_checks'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' DISABLE_SVC_CHECK;' . urldecode($ressource[0]) . ';' . urldecode($ressource[1]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } // Quick Action -> host check : Stop and start function autoCheckHostStart($key) { global $pearDB, $tab, $is_admin, $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_checks'); if ($actions == true || $is_admin) { $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' ENABLE_HOST_CHECK;' . urldecode($ressource[0]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } } function autoCheckHostStop($key) { global $centreon; $actions = false; $actions = $centreon->user->access->checkAction('host_checks'); if ($actions == true || $is_admin) { global $pearDB, $tab, $is_admin; $ressource = preg_split("/\;/", $key); $flg = send_cmd( ' DISABLE_HOST_CHECK;' . urldecode($ressource[0]), GetMyHostPoller($pearDB, urldecode($ressource[0])) ); return $flg; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/cmd.php
centreon/www/include/monitoring/external_cmd/cmd.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 * */ if (! isset($centreon)) { exit(); } include_once './include/monitoring/external_cmd/functions.php'; // Get Parameters $param = ! isset($_GET['cmd']) && isset($_POST['cmd']) ? $_POST : $_GET; if (isset($param['en'])) { $en = $param['en']; } if (! isset($param['select']) || ! isset($param['cmd'])) { return; } $informationsService = $dependencyInjector['centreon_remote.informations_service']; $serverIsRemote = $informationsService->serverIsRemote(); $disabledCommandsForRemote = [80, 81, 82, 83, 90, 91, 92, 93]; if ($serverIsRemote && in_array($param['cmd'], $disabledCommandsForRemote)) { return; } foreach ($param['select'] as $key => $value) { switch ($param['cmd']) { // Re-Schedule SVC Checks case 1: schedule_host_svc_checks($key, 0); break; case 2: schedule_host_svc_checks($key, 1); break; case 3: schedule_svc_checks($key, 0); break; case 4: schedule_svc_checks($key, 1); break; // Scheduling svc case 5: host_svc_checks($key, $en); break; case 6: host_check($key, $en); break; case 7: svc_check($key, $en); break; // Notifications case 8: host_svc_notifications($key, $en); break; case 9: host_notification($key, $en); break; case 10: svc_notifications($key, $en); break; // Auto Notification case 80: autoNotificationServiceStart($key); break; case 81: autoNotificationServiceStop($key); break; case 82: autoNotificationHostStart($key); break; case 83: autoNotificationHostStop($key); break; // Auto Check case 90: autoCheckServiceStart($key); break; case 91: autoCheckServiceStop($key); break; case 92: autoCheckHostStart($key); break; case 93: autoCheckHostStop($key); break; // Scheduling host case 94: schedule_host_checks($key, 0); break; case 95: schedule_host_checks($key, 1); break; // Acknowledge status case 14: acknowledgeHost($param); break; case 15: acknowledgeService($param); break; // Configure nagios Core case 20: send_cmd('ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST', ''); break; case 21: send_cmd('DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST', ''); break; case 22: send_cmd('ENABLE_NOTIFICATIONS', ''); break; case 23: send_cmd('DISABLE_NOTIFICATIONS', ''); break; case 24: send_cmd('SHUTDOWN_PROGRAM', time()); break; case 25: send_cmd(' RESTART_PROGRAM', time()); break; case 26: send_cmd('PROCESS_SERVICE_CHECK_RESULT', ''); break; case 27: send_cmd('SAVE_STATE_INFORMATION', ''); break; case 28: send_cmd('READ_STATE_INFORMATION', ''); break; case 29: send_cmd('START_EXECUTING_SVC_CHECKS', ''); break; case 30: send_cmd('STOP_EXECUTING_SVC_CHECKS', ''); break; case 31: send_cmd('START_ACCEPTING_PASSIVE_SVC_CHECKS', ''); break; case 32: send_cmd('STOP_ACCEPTING_PASSIVE_SVC_CHECKS', ''); break; case 33: send_cmd('ENABLE_PASSIVE_SVC_CHECKS', ''); break; case 34: send_cmd('DISABLE_PASSIVE_SVC_CHECKS', ''); break; case 35: send_cmd('ENABLE_EVENT_HANDLERS', ''); break; case 36: send_cmd('DISABLE_EVENT_HANDLERS', ''); break; case 37: send_cmd('START_OBSESSING_OVER_SVC_CHECKS', ''); break; case 38: send_cmd('STOP_OBSESSING_OVER_SVC_CHECKS', ''); break; case 39: send_cmd('ENABLE_FLAP_DETECTION', ''); break; case 40: send_cmd('DISABLE_FLAP_DETECTION', ''); break; case 41: send_cmd('ENABLE_PERFORMANCE_DATA', ''); break; case 42: send_cmd('DISABLE_PERFORMANCE_DATA', ''); break; // End Configuration Nagios Core case 43: host_flapping_enable($key, $en); break; case 44: svc_flapping_enable($key, $en); break; case 45: host_event_handler($key, $en); break; case 46: svc_event_handler($key, $en); break; case 49: // @TODO : seems like dead code - to check in other repo host_flap_detection($key, 1); break; case 50: // @TODO : seems like dead code - to check in other repo host_flap_detection($key, 0); break; case 51: host_event_handler($key, 1); break; case 52: host_event_handler($key, 0); break; case 59: // @TODO : seems like dead code - to check in other repo add_hostgroup_downtime($param['dtm']); break; case 60: // @TODO : seems like dead code - to check in other repo add_svc_hostgroup_downtime($param['dtm']); break; case 61: // @TODO : seems like dead code - to check in other repo notifi_host_hostgroup($key, 1); break; case 62: // @TODO : seems like dead code - to check in other repo notifi_host_hostgroup($key, 0); break; case 63: // @TODO : seems like dead code - to check in other repo notifi_svc_host_hostgroup($key, 1); break; case 64: // @TODO : seems like dead code - to check in other repo notifi_svc_host_hostgroup($key, 0); break; case 65: checks_svc_host_hostgroup($key, 1); break; case 66: checks_svc_host_hostgroup($key, 0); break; case 67: schedule_svc_check($key, 1, 1); break; // Auto Aknowledge case 70: autoAcknowledgeServiceStart($key); break; case 71: autoAcknowledgeServiceStop($key); break; case 72: autoAcknowledgeHostStart($key); break; case 73: autoAcknowledgeHostStop($key); break; // Auto Notification case 80: autoNotificationServiceStart($key); break; case 81: autoNotificationServiceStop($key); break; case 82: autoNotificationHostStart($key); break; case 83: autoNotificationHostStop($key); break; // Auto Check case 90: autoCheckServiceStart($key); break; case 91: autoCheckServiceStop($key); break; case 92: autoCheckHostStart($key); break; case 93: autoCheckHostStop($key); break; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/popup/massive_downtime.php
centreon/www/include/monitoring/external_cmd/popup/massive_downtime.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 * */ if (! isset($centreon)) { exit(); } const DOWNTIME_ON_HOST = 75; $select = []; if (isset($_GET['select'])) { foreach ($_GET['select'] as $key => $value) { if ((int) $cmd == DOWNTIME_ON_HOST) { $tmp = preg_split("/\;/", urlencode($key)); $select[] = $tmp[0]; } else { $select[] = urlencode($key); } } } // Smarty template initialization $path = _CENTREON_PATH_ . '/www/include/monitoring/external_cmd/popup/'; $tpl = SmartyBC::createSmartyTemplate($path, './templates/'); $form = new HTML_QuickFormCustom('select_form', 'GET', 'main.php'); $form->addElement( 'header', 'title', _('Set downtimes') ); $tpl->assign('authorlabel', _('Alias')); $tpl->assign('authoralias', $centreon->user->get_alias()); $form->addElement( 'textarea', 'comment', _('Comment'), ['rows' => '5', 'cols' => '70', 'id' => 'popupComment'] ); $form->setDefaults(['comment' => sprintf(_('Downtime set by %s'), $centreon->user->alias)]); $form->addElement( 'text', 'start', _('Start Time'), ['id' => 'start', 'size' => 10, 'class' => 'datepicker'] ); $form->addElement( 'text', 'end', _('End Time'), ['id' => 'end', 'size' => 10, 'class' => 'datepicker'] ); $form->addElement( 'text', 'start_time', '', ['id' => 'start_time', 'size' => 5, 'class' => 'timepicker'] ); $form->addElement( 'text', 'end_time', '', ['id' => 'end_time', 'size' => 5, 'class' => 'timepicker'] ); $form->addElement( 'text', 'timezone_warning', _('*The timezone used is configured on your user settings') ); $form->addElement( 'text', 'duration', _('Duration'), ['id' => 'duration', 'width' => '30', 'disabled' => 'true'] ); // setting default values $defaultDuration = 7200; $defaultScale = 's'; // overriding the default duration and scale by the user's value from the administration fields if ( isset($centreon->optGen['monitoring_dwt_duration']) && $centreon->optGen['monitoring_dwt_duration'] ) { $defaultDuration = $centreon->optGen['monitoring_dwt_duration']; if ( isset($centreon->optGen['monitoring_dwt_duration_scale']) && $centreon->optGen['monitoring_dwt_duration_scale'] ) { $defaultScale = $centreon->optGen['monitoring_dwt_duration_scale']; } } $form->setDefaults(['duration' => $defaultDuration]); $scaleChoices = ['s' => _('Seconds'), 'm' => _('Minutes'), 'h' => _('Hours'), 'd' => _('Days')]; $form->addElement( 'select', 'duration_scale', _('Scale of time'), $scaleChoices, ['id' => 'duration_scale', 'disabled' => 'true'] ); $form->setDefaults(['duration_scale' => $defaultScale]); $chckbox[] = $form->addElement( 'checkbox', 'fixed', _('Fixed'), '', ['id' => 'fixed'] ); $chckbox[0]->setChecked(true); $chckbox2[] = $form->addElement( 'checkbox', 'downtimehostservice', _('Set downtimes on services attached to hosts'), '', ['id' => 'downtimehostservice'] ); $chckbox2[0]->setChecked(true); $form->addElement( 'hidden', 'author', $centreon->user->get_alias(), ['id' => 'author'] ); $form->addRule( 'comment', _('Comment is required'), 'required', '', 'client' ); $form->setJsWarnings(_('Invalid information entered'), _('Please correct these fields')); $form->addElement( 'button', 'submit', _('Set downtime'), ['onClick' => 'send_the_command();', 'class' => 'btc bt_info'] ); $form->addElement( 'reset', 'reset', _('Reset'), ['class' => 'btc bt_default'] ); // adding hidden fields to get the result of datepicker in an unlocalized format // required for the external command to be send to centreon-engine $form->addElement( 'hidden', 'alternativeDateStart', '', ['size' => 10, 'class' => 'alternativeDate'] ); $form->addElement( 'hidden', 'alternativeDateEnd', '', ['size' => 10, 'class' => 'alternativeDate'] ); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $defaultFixed = ''; if (isset($centreon->optGen['monitoring_dwt_fixed']) && $centreon->optGen['monitoring_dwt_fixed'] ) { $defaultFixed = 'checked'; } $tpl->assign('defaultFixed', $defaultFixed); $defaultSetDwtOnSvc = ''; if (isset($centreon->optGen['monitoring_dwt_svc']) && $centreon->optGen['monitoring_dwt_svc'] ) { $defaultSetDwtOnSvc = 'checked'; } $tpl->assign('defaultSetDwtOnSvc', $defaultSetDwtOnSvc); $tpl->assign('o', $o); $tpl->assign('p', $p); $tpl->assign('cmd', $cmd); $tpl->assign('select', $select); $tpl->display('massive_downtime.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/popup/massive_ack.php
centreon/www/include/monitoring/external_cmd/popup/massive_ack.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 * */ if (! isset($centreon)) { exit(); } $select = []; if (isset($_GET['select'])) { foreach ($_GET['select'] as $key => $value) { if ($cmd == '72') { $tmp = preg_split("/\;/", urlencode($key)); $select[] = $tmp[0]; } else { $select[] = urlencode($key); } } } // Smarty template initialization $path = _CENTREON_PATH_ . '/www/include/monitoring/external_cmd/popup/'; $tpl = SmartyBC::createSmartyTemplate($path, './templates/'); require_once _CENTREON_PATH_ . 'www/include/monitoring/common-Func.php'; // Fetch default values for form $user_params = get_user_param($centreon->user->user_id, $pearDB); if (! isset($user_params['ack_sticky'])) { $user_params['ack_sticky'] = 1; } if (! isset($user_params['ack_notify'])) { $user_params['ack_notify'] = 0; } if (! isset($user_params['ack_persistent'])) { $user_params['ack_persistent'] = 1; } if (! isset($user_params['ack_services'])) { $user_params['ack_services'] = 1; } if (! isset($user_params['force_check'])) { $user_params['force_check'] = 1; } /* $sticky = $user_params["ack_sticky"]; $notify = $user_params["ack_notify"]; $persistent = $user_params["ack_persistent"]; $force_check = $user_params["force_check"]; $ack_services = $user_params["ack_services"]; */ $form = new HTML_QuickFormCustom('select_form', 'GET', 'main.php'); $form->addElement('header', 'title', _('Acknowledge problems')); $tpl->assign('authorlabel', _('Alias')); $tpl->assign('authoralias', $centreon->user->get_alias()); $form->addElement('textarea', 'comment', _('Comment'), ['rows' => '5', 'cols' => '85', 'id' => 'popupComment']); $form->setDefaults(['comment' => sprintf(_('Acknowledged by %s'), $centreon->user->alias)]); $chckbox[] = $form->addElement('checkbox', 'persistent', _('Persistent'), '', ['id' => 'persistent']); if (isset($centreon->optGen['monitoring_ack_persistent']) && $centreon->optGen['monitoring_ack_persistent']) { $chckbox[0]->setChecked(true); } $chckbox2[] = $form->addElement( 'checkbox', 'ackhostservice', _('Acknowledge services attached to hosts'), '', ['id' => 'ackhostservice'] ); if (isset($centreon->optGen['monitoring_ack_svc']) && $centreon->optGen['monitoring_ack_svc']) { $chckbox2[0]->setChecked(true); } $chckbox3[] = $form->addElement('checkbox', 'sticky', _('Sticky'), '', ['id' => 'sticky']); if (isset($centreon->optGen['monitoring_ack_sticky']) && $centreon->optGen['monitoring_ack_sticky']) { $chckbox3[0]->setChecked(true); } $chckbox4[] = $form->addElement('checkbox', 'force_check', _('Force active checks'), '', ['id' => 'force_check']); if (isset($centreon->optGen['monitoring_ack_active_checks']) && $centreon->optGen['monitoring_ack_active_checks']) { $chckbox4[0]->setChecked(true); } $chckbox5[] = $form->addElement('checkbox', 'notify', _('Notify'), '', ['id' => 'notify']); if (isset($centreon->optGen['monitoring_ack_notify']) && $centreon->optGen['monitoring_ack_notify']) { $chckbox5[0]->setChecked(true); } $form->addElement('hidden', 'author', $centreon->user->get_alias(), ['id' => 'author']); $form->addRule('comment', _('Comment is required'), 'required', '', 'client'); $form->setJsWarnings(_('Invalid information entered'), _('Please correct these fields')); $form->addElement( 'button', 'submit', _('Acknowledge selected problems'), ['onClick' => 'send_the_command();', 'class' => 'btc bt_info'] ); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('p', $p); $tpl->assign('cmd', $cmd); $tpl->assign('select', $select); $tpl->display('massive_ack.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/external_cmd/popup/popup.php
centreon/www/include/monitoring/external_cmd/popup/popup.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 * */ // using bootstrap.php to load the paths and the DB configurations require_once __DIR__ . '/../../../../../bootstrap.php'; require_once _CENTREON_PATH_ . 'vendor/autoload.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php'; require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; const ACKNOWLEDGEMENT_ON_SERVICE = 70; const ACKNOWLEDGEMENT_ON_HOST = 72; const DOWNTIME_ON_SERVICE = 74; const DOWNTIME_ON_HOST = 75; $pearDB = $dependencyInjector['configuration_db']; session_start(); session_write_close(); $centreon = $_SESSION['centreon']; $centreonLang = new CentreonLang(_CENTREON_PATH_, $centreon); $centreonLang->bindLang(); if ( ! isset($centreon) || ! isset($_GET['o']) || ! isset($_GET['cmd']) || ! isset($_GET['p']) ) { exit(); } if (session_id()) { $res = $pearDB->prepare('SELECT * FROM `session` WHERE `session_id` = :sid'); $res->bindValue(':sid', session_id(), PDO::PARAM_STR); $res->execute(); if (! $session = $res->fetch()) { exit(); } } else { exit; } $o = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']); $p = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['p']); $cmd = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['cmd']); if ( (int) $cmd === ACKNOWLEDGEMENT_ON_SERVICE || (int) $cmd === ACKNOWLEDGEMENT_ON_HOST ) { require_once _CENTREON_PATH_ . 'www/include/monitoring/external_cmd/popup/massive_ack.php'; } elseif ( (int) $cmd === DOWNTIME_ON_HOST || (int) $cmd === DOWNTIME_ON_SERVICE ) { require_once _CENTREON_PATH_ . 'www/include/monitoring/external_cmd/popup/massive_downtime.php'; } exit();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/common-Func.php
centreon/www/include/monitoring/comments/common-Func.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 * */ if (! isset($centreon)) { exit(); } function DeleteComment($type = null, $hosts = []) { if (! isset($type) || ! is_array($hosts)) { return; } global $pearDB; $type = HtmlAnalyzer::sanitizeAndRemoveTags($type ?? ''); foreach ($hosts as $key => $value) { $res = preg_split("/\;/", $key); $res[1] = filter_var($res[1] ?? 0, FILTER_VALIDATE_INT); write_command(' DEL_' . $type . '_COMMENT;' . $res[1], GetMyHostPoller($pearDB, $res[0])); } } function AddHostComment($host, $comment, $persistant) { global $centreon, $pearDB; if (! isset($persistant) || ! in_array($persistant, ['0', '1'])) { $persistant = '0'; } write_command(' ADD_HOST_COMMENT;' . getMyHostName($host) . ';' . $persistant . ';' . $centreon->user->get_alias() . ';' . trim($comment), GetMyHostPoller($pearDB, getMyHostName($host))); } function AddSvcComment($host, $service, $comment, $persistant) { global $centreon, $pearDB; if (! isset($persistant) || ! in_array($persistant, ['0', '1'])) { $persistant = '0'; } write_command(' ADD_SVC_COMMENT;' . getMyHostName($host) . ';' . getMyServiceName($service) . ';' . $persistant . ';' . $centreon->user->get_alias() . ';' . trim($comment), GetMyHostPoller($pearDB, getMyHostName($host))); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/listComment.php
centreon/www/include/monitoring/comments/listComment.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 * */ if (! isset($centreon)) { exit(); } include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include './include/common/autoNumLimit.php'; // initializing filters values $searchService = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchService'] ?? $_GET['searchService'] ?? '' ); $searchHost = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchHost'] ?? $_GET['searchHost'] ?? '' ); $searchOutput = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchOutput'] ?? $_GET['searchOutput'] ?? '' ); if (isset($_POST['search']) || isset($_GET['search'])) { // saving chosen filters values $centreon->historySearch[$url] = []; $centreon->historySearch[$url]['searchService'] = $searchService; $centreon->historySearch[$url]['searchHost'] = $searchHost; $centreon->historySearch[$url]['searchOutput'] = $searchOutput; } else { // restoring saved values $searchService = $centreon->historySearch[$url]['searchService'] ?? ''; $searchHost = $centreon->historySearch[$url]['searchHost'] ?? ''; $searchOutput = $centreon->historySearch[$url]['searchOutput'] ?? ''; } $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, 'template/'); include_once './class/centreonDB.class.php'; $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); $tab_comments_svc = []; $en = ['0' => _('No'), '1' => _('Yes')]; // Service Comments $rq2 = 'SELECT SQL_CALC_FOUND_ROWS 1 AS REALTIME, c.internal_id, c.entry_time, c.author, c.data, c.persistent, c.host_id, c.service_id, h.name AS host_name, s.description AS service_description ' . 'FROM comments c, hosts h, services s '; if (! $is_admin) { $rq2 .= ', centreon_acl acl '; } $rq2 .= 'WHERE c.type = 2 AND c.host_id = h.host_id AND c.service_id = s.service_id AND h.host_id = s.host_id '; $rq2 .= " AND c.expires = '0' AND h.enabled = 1 AND s.enabled = 1 "; $rq2 .= ' AND (c.deletion_time IS NULL OR c.deletion_time = 0) '; if (! $is_admin) { $rq2 .= ' AND s.host_id = acl.host_id AND s.service_id = acl.service_id AND group_id IN (' . $centreon->user->access->getAccessGroupsString() . ') '; } $rq2 .= (isset($searchService) && $searchService != '' ? " AND s.description LIKE '%{$searchService}%'" : ''); $rq2 .= (isset($searchHost) && $searchHost != '' ? " AND h.name LIKE '%{$searchHost}%'" : ''); $rq2 .= (isset($searchOutput) && $searchOutput != '' ? " AND c.data LIKE '%{$searchOutput}%'" : ''); $rq2 .= ' UNION '; // Host Comments $rq2 .= "SELECT 1 AS REALTIME, c.internal_id, c.entry_time, c.author, c.data, c.persistent, c.host_id, '' as service_id, h.name AS host_name, '' AS service_description " . 'FROM comments c, hosts h '; if (! $is_admin) { $rq2 .= ', centreon_acl acl '; } $rq2 .= 'WHERE c.host_id = h.host_id AND c.type = 1'; $rq2 .= " AND c.expires = '0' AND h.enabled = 1 "; $rq2 .= ' AND (c.deletion_time IS NULL OR c.deletion_time = 0) '; if (! $is_admin) { $rq2 .= ' AND h.host_id = acl.host_id AND acl.service_id IS NULL AND group_id IN (' . $centreon->user->access->getAccessGroupsString() . ') '; } $rq2 .= (isset($searchService) && $searchService != '' ? ' AND 1 = 0' : ''); $rq2 .= (isset($searchHost) && $searchHost != '' ? " AND h.name LIKE '%{$searchHost}%'" : ''); $rq2 .= (isset($searchOutput) && $searchOutput != '' ? " AND c.data LIKE '%{$searchOutput}%'" : ''); $rq2 .= ' ORDER BY entry_time DESC LIMIT ' . $num * $limit . ', ' . $limit; $DBRESULT = $pearDBO->query($rq2); $rows = $pearDBO->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn(); for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) { $tab_comments_svc[$i] = $data; $tab_comments_svc[$i]['persistent'] = $en[$tab_comments_svc[$i]['persistent']]; $tab_comments_svc[$i]['data'] = CentreonUtils::escapeAllExceptSelectedTags( $tab_comments_svc[$i]['data'], ['a', 'br', 'hr'] ); $tab_comments_svc[$i]['h_details_uri'] = $useDeprecatedPages ? 'main.php?p=20202&o=hd&host_name=' . $data['host_name'] : $resourceController->buildHostDetailsUri($data['host_id']); if ($data['service_description'] != '') { $tab_comments_svc[$i]['s_details_uri'] = $useDeprecatedPages ? 'main.php?p=202&o=svcd&host_name=' . $data['host_name'] . '&service_description=' . $data['service_description'] : $resourceController->buildServiceDetailsUri( $data['host_id'], $data['service_id'] ); $tab_comments_svc[$i]['service_description'] = htmlentities($data['service_description'], ENT_QUOTES, 'UTF-8'); $tab_comments_svc[$i]['comment_type'] = 'SVC'; } else { $tab_comments_svc[$i]['service_description'] = '-'; $tab_comments_svc[$i]['comment_type'] = 'HOST'; } } unset($data); $DBRESULT->closeCursor(); include './include/common/checkPagination.php'; // Element we need when we reload the page $form->addElement('hidden', 'p'); $tab = ['p' => $p]; $form->setDefaults($tab); if ($oreon->user->access->checkAction('service_comment')) { $tpl->assign('msgs', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add a comment'), 'delConfirm' => _('Do you confirm the deletion ?')]); } $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('tab_comments_svc', $tab_comments_svc); $tpl->assign('nb_comments_svc', count($tab_comments_svc)); $tpl->assign('no_svc_comments', _('No Comment for services.')); $tpl->assign('cmt_service_comment', _('Services Comments')); $tpl->assign('host_comment_link', './main.php?p=' . $p . '&o=vh'); $tpl->assign('view_host_comments', _('View comments of hosts')); $tpl->assign('delete', _('Delete')); $tpl->assign('Host', _('Host Name')); $tpl->assign('Service', _('Service')); $tpl->assign('Output', _('Output')); $tpl->assign('user', _('Users')); $tpl->assign('Hostgroup', _('Hostgroup')); $tpl->assign('searchOutput', $searchOutput); $tpl->assign('searchHost', $searchHost); $tpl->assign('searchService', $searchService); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('limit', $limit); $tpl->assign('form', $renderer->toArray()); $tpl->display('comments.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/commentHost.php
centreon/www/include/monitoring/comments/commentHost.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 * */ if (! isset($oreon)) { exit(); } $contactId = filter_var( $_GET['contact_id'] ?? $_POST['contact_id'] ?? 0, FILTER_VALIDATE_INT ); $select = $_GET['select'] ?? $_POST['select'] ?? []; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Path to the configuration folder $path = './include/monitoring/comments/'; // PHP functions require_once './include/common/common-Func.php'; require_once './include/monitoring/comments/common-Func.php'; require_once './include/monitoring/external_cmd/functions.php'; switch ($o) { case 'ah': require_once $path . 'AddHostComment.php'; break; case 'dh': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); DeleteComment('HOST', $select); } else { unvalidFormMessage(); } require_once $path . 'viewHostComment.php'; break; case 'vh': require_once $path . 'viewHostComment.php'; break; default: require_once $path . 'viewHostComment.php'; break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/AddComment.php
centreon/www/include/monitoring/comments/AddComment.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 * */ if (! isset($centreon)) { exit(); } include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php'; // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); $hostStr = $centreon->user->access->getHostsString('ID', $pearDBO); $hObj = new CentreonHost($pearDB); $serviceObj = new CentreonService($pearDB); if (! $centreon->user->access->checkAction('service_comment')) { require_once '../errors/alt_error.php'; } else { // Init $debug = 0; $attrsTextI = ['size' => '3']; $attrsText = ['size' => '30']; $attrsTextarea = ['rows' => '7', 'cols' => '80']; // Form begin $form = new HTML_QuickFormCustom('Form', 'POST', '?p=' . $p); // Indicator basic information $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) { $host_name = $hObj->getHostName($_GET['host_id']); } elseif (isset($_GET['host_id'], $_GET['service_id'])) { $serviceParameters = $serviceObj->getParameters($_GET['service_id'], ['service_description']); $serviceDisplayName = $serviceParameters['service_description']; $host_name = $hObj->getHostName($_GET['host_id']); } if (! isset($_GET['host_id'])) { $dtType[] = $form->createElement( 'radio', 'commentType', null, _('Host'), '1', ['id' => 'host', 'onclick' => "toggleParams('host');"] ); $dtType[] = $form->createElement( 'radio', 'commentType', null, _('Services'), '2', ['id' => 'service', 'onclick' => "toggleParams('service');"] ); $form->addGroup($dtType, 'commentType', _('Comment type'), '&nbsp;'); // ----- Hosts ----- $attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_host&action=list', 'multiple' => true, 'linkedObject' => 'centreonHost']; $form->addElement('select2', 'host_id', _('Hosts'), [], $attrHosts); if (! isset($_GET['service_id'])) { // ----- Services ----- $attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_service&action=list&e=enable', 'multiple' => true, 'linkedObject' => 'centreonService']; $form->addElement('select2', 'service_id', _('Services'), [], $attrServices); } } $persistant = $form->addElement('checkbox', 'persistant', _('Persistent')); $persistant->setValue('1'); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->addRule('comment', _('Required Field'), 'required'); $data = []; if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) { $data['host_id'] = $_GET['host_id']; $data['commentType'] = 1; $focus = 'host'; $form->addElement('hidden', 'host_id', $_GET['host_id']); $form->addElement('hidden', 'commentType[commentType]', $data['commentType']); } elseif (isset($_GET['host_id'], $_GET['service_id'])) { $data['service_id'] = $_GET['host_id'] . '-' . $_GET['service_id']; $data['commentType'] = 2; $focus = 'service'; $form->addElement('hidden', 'service_id', $data['service_id']); $form->addElement('hidden', 'commentType[commentType]', $data['commentType']); } else { $data['commentType'] = 1; $focus = 'host'; } $form->setDefaults($data); $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); // Push the comment if ((isset($_POST['submitA']) && $_POST['submitA']) && $form->validate()) { $values = $form->getSubmitValues(); if (! isset($_POST['persistant']) || ! in_array($_POST['persistant'], ['0', '1'])) { $_POST['persistant'] = '0'; } $_POST['comment'] = str_replace("'", ' ', $_POST['comment']); if ($values['commentType']['commentType'] == 1) { // Set a comment for only host // catch fix input host_id if (isset($_POST['host_id'])) { if (! is_array($_POST['host_id'])) { $_POST['host_id'] = [$_POST['host_id']]; } foreach ($_POST['host_id'] as $host_id) { AddHostComment($host_id, $_POST['comment'], $_POST['persistant']); } } $valid = true; require_once $path . 'listComment.php'; } elseif ($values['commentType']['commentType'] == 2) { // Set a comment for a service list // catch fix input service_id if (! is_array($_POST['service_id'])) { $_POST['service_id'] = [$_POST['service_id']]; } // global services comment if (! isset($_POST['host_id'])) { foreach ($_POST['service_id'] as $value) { $info = explode('-', $value); AddSvcComment( $info[0], $info[1], $_POST['comment'], $_POST['persistant'] ); } } else { // specific service comment AddSvcComment($_POST['host_id'], $_POST['service_id'], $_POST['comment'], $_POST['persistant']); } $valid = true; require_once $path . 'listComment.php'; } } else { // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, 'template/'); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); if (isset($service_id, $host_id)) { $tpl->assign('host_name', $host_name); $tpl->assign('service_description', $svc_description); } elseif (isset($host_id)) { $tpl->assign('host_name', $host_name); } $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('focus', $focus); $tpl->display('AddComment.html'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/comments.php
centreon/www/include/monitoring/comments/comments.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 * */ if (! isset($centreon)) { exit(); } $contactId = filter_var( $_GET['contact_id'] ?? $_POST['contact_id'] ?? 0, FILTER_VALIDATE_INT ); $select = $_GET['select'] ?? $_POST['select'] ?? []; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Path to the configuration dir $path = './include/monitoring/comments/'; // PHP functions require_once './include/common/common-Func.php'; require_once './include/monitoring/comments/common-Func.php'; require_once './include/monitoring/external_cmd/functions.php'; switch ($o) { case 'ah': require_once $path . 'AddHostComment.php'; break; case 'vh': require_once $path . 'listComment.php'; break; case 'a': require_once $path . 'AddComment.php'; break; case 'as': require_once $path . 'AddSvcComment.php'; break; case 'ds': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (! empty($select)) { foreach ($select as $key => $value) { $res = explode(';', urldecode($key)); DeleteComment($res[0], [$res[1] . ';' . (int) $res[2] => 'on']); } } } else { unvalidFormMessage(); } require_once $path . 'listComment.php'; break; case 'vs': require_once $path . 'listComment.php'; break; default: require_once $path . 'listComment.php'; break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/AddSvcComment.php
centreon/www/include/monitoring/comments/AddSvcComment.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 * */ if (! isset($centreon)) { exit(); } include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php'; // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); $hostStr = $centreon->user->access->getHostsString('ID', $pearDBO); if ($centreon->user->access->checkAction('service_comment')) { $LCA_error = 0; $cG = $_GET['host_id'] ?? null; $cP = $_POST['host_id'] ?? null; $host_id = $cG ?: $cP; $host_name = null; $svc_description = null; if (isset($_GET['host_name'], $_GET['service_description'])) { $host_id = getMyHostID($_GET['host_name']); $service_id = getMyServiceID($_GET['service_description'], $host_id); $host_name = $_GET['host_name']; $svc_description = $_GET['service_description']; if ($host_name == '_Module_Meta' && preg_match('/^meta_(\d+)/', $svc_description, $matches)) { $host_name = 'Meta'; $serviceObj = new CentreonService($pearDB); $serviceParameters = $serviceObj->getParameters($service_id, ['display_name']); $svc_description = $serviceParameters['display_name']; } } /* * Database retrieve information for differents * elements list we need on the page */ $query = "SELECT host_id, host_name FROM `host` WHERE (host_register = '1' OR host_register = '2' )" . $centreon->user->access->queryBuilder('AND', 'host_id', $hostStr) . 'ORDER BY host_name'; $DBRESULT = $pearDB->query($query); $hosts = [null => null]; while ($row = $DBRESULT->fetchRow()) { $hosts[$row['host_id']] = $row['host_name']; } $DBRESULT->closeCursor(); $services = []; if (isset($host_id)) { $services = $centreon->user->access->getHostServices($pearDBO, $host_id); } $debug = 0; $attrsTextI = ['size' => '3']; $attrsText = ['size' => '30']; $attrsTextarea = ['rows' => '7', 'cols' => '100']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); $form->addElement('header', 'title', _('Add a comment for Service')); // Indicator basic information $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); if (isset($host_id, $service_id)) { $form->addElement('hidden', 'host_id', $host_id); $form->addElement('hidden', 'service_id', $service_id); } else { $disabled = ' '; $attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_service&action=list&e=enable', 'multiple' => true, 'linkedObject' => 'centreonService']; $form->addElement('select2', 'service_id', _('Services'), [$disabled], $attrServices); } $persistant = $form->addElement('checkbox', 'persistant', _('Persistent')); $persistant->setValue('1'); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->addRule('comment', _('Required Field'), 'required'); $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $valid = false; if ((isset($_POST['submitA']) && $_POST['submitA']) && $form->validate()) { if (! isset($_POST['persistant']) || ! in_array($_POST['persistant'], ['0', '1'])) { $_POST['persistant'] = '0'; } if (! isset($_POST['comment'])) { $_POST['comment'] = 0; } // global services comment if (! isset($_POST['host_id'])) { foreach ($_POST['service_id'] as $value) { $info = explode('-', $value); AddSvcComment( $info[0], $info[1], $_POST['comment'], $_POST['persistant'] ); } } else { // specific service comment AddSvcComment($_POST['host_id'], $_POST['service_id'], $_POST['comment'], $_POST['persistant']); } $valid = true; require_once $path . 'listComment.php'; } else { // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, 'template/'); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); if (isset($host_id, $service_id)) { $tpl->assign('host_name', $host_name); $tpl->assign('service_description', $svc_description); } $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->display('AddSvcComment.ihtml'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/comments/AddHostComment.php
centreon/www/include/monitoring/comments/AddHostComment.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 * */ if (! isset($centreon)) { exit(); } include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; // Init GMT class $hostStr = $oreon->user->access->getHostsString('ID', $pearDBO); $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession(session_id()); if ($centreon->user->access->checkAction('host_comment')) { // ACL if (isset($_GET['host_name'])) { $host_id = getMyHostID($_GET['host_name']); $host_name = $_GET['host_name']; } else { $host_name = ''; } $data = []; if (isset($host_id)) { $data = ['host_id' => $host_id]; } if (isset($_GET['host_name'])) { $host_id = getMyHostID($_GET['host_name']); $host_name = $_GET['host_name']; if ($host_name == '_Module_Meta') { $host_name = 'Meta'; } } // Database retrieve information for differents elements list we need on the page $hosts = ['' => '']; $query = 'SELECT host_id, host_name ' . 'FROM `host` ' . "WHERE host_register = '1' " . "AND host_activate = '1'" . $oreon->user->access->queryBuilder('AND', 'host_id', $hostStr) . 'ORDER BY host_name'; $DBRESULT = $pearDB->query($query); while ($host = $DBRESULT->fetchRow()) { $hosts[$host['host_id']] = $host['host_name']; } $DBRESULT->closeCursor(); $debug = 0; $attrsTextI = ['size' => '3']; $attrsText = ['size' => '30']; $attrsTextarea = ['rows' => '7', 'cols' => '100']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o == 'ah') { $form->addElement('header', 'title', _('Add a comment for Host')); } // Indicator basic information $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); if (isset($host_id)) { $form->addElement('hidden', 'host_id', $host_id); } else { $selHost = $form->addElement('select', 'host_id', _('Host Name'), $hosts); $form->addRule('host_id', _('Required Field'), 'required'); } $persistant = $form->addElement('checkbox', 'persistant', _('Persistent')); $persistant->setValue('1'); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->addRule('comment', _('Required Field'), 'required'); $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $form->setDefaults($data); $valid = false; if ((isset($_POST['submitA']) && $_POST['submitA']) && $form->validate()) { if (! isset($_POST['persistant']) || ! in_array($_POST['persistant'], ['0', '1'])) { $_POST['persistant'] = '0'; } if (! isset($_POST['comment'])) { $_POST['comment'] = 0; } AddHostComment($_POST['host_id'], $_POST['comment'], $_POST['persistant']); $valid = true; require_once $path . 'listComment.php'; } else { // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, 'template/'); if (isset($host_id)) { $tpl->assign('host_name', $host_name); } // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->display('AddHostComment.ihtml'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/monitoringHost.php
centreon/www/include/monitoring/status/monitoringHost.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 * */ if (! isset($centreon)) { exit(); } require_once './class/centreonDuration.class.php'; include_once './include/monitoring/common-Func.php'; include_once './include/monitoring/external_cmd/cmd.php'; // Init Continue Value $continue = true; $path = './include/monitoring/status/Hosts/'; $path_hg = './include/monitoring/status/HostGroups/'; $pathRoot = './include/monitoring/'; $pathDetails = './include/monitoring/objectDetails/'; $pathTools = './include/tools/'; $param = ! isset($_GET['cmd']) && isset($_POST['cmd']) ? $_POST : $_GET; if (isset($param['cmd']) && $param['cmd'] == 14 && isset($param['author'], $param['en']) && $param['en'] == 1 ) { if (! isset($param['sticky'])) { $param['sticky'] = 0; } if (! isset($param['notify'])) { $param['notify'] = 0; } if (! isset($param['persistent'])) { $param['persistent'] = 0; } if (! isset($param['ackhostservice'])) { $param['ackhostservice'] = 0; } acknowledgeHost($param); } elseif (isset($param['cmd']) && $param['cmd'] == 14 && isset($param['author'], $param['en']) && $param['en'] == 0 ) { acknowledgeHostDisable(); } if (isset($param['cmd']) && $param['cmd'] == 16 && isset($param['output'])) { submitHostPassiveCheck(); } if ($min) { switch ($o) { default: require_once $pathTools . 'tools.php'; break; } } elseif ($continue) { // Now route to pages or Actions switch ($o) { case 'h': require_once $path . 'host.php'; break; case 'hpb': require_once $path . 'host.php'; break; case 'h_unhandled': require_once $path . 'host.php'; break; case 'hd': require_once $pathDetails . 'hostDetails.php'; break; case 'hpc': require_once './include/monitoring/submitPassivResults/hostPassiveCheck.php'; break; case 'hak': require_once $pathRoot . 'acknowlegement/hostAcknowledge.php'; break; default: require_once $path . 'host.php'; break; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/monitoringService.php
centreon/www/include/monitoring/status/monitoringService.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 * */ if (! isset($centreon)) { exit(); } require_once './class/centreonDuration.class.php'; include_once './include/monitoring/common-Func.php'; include_once './include/monitoring/external_cmd/cmd.php'; // Init Continue Value $continue = true; // DB Connect include_once './class/centreonDB.class.php'; $param = ! isset($_GET['cmd']) && isset($_POST['cmd']) ? $_POST : $_GET; if ( isset($param['cmd']) && $param['cmd'] == 15 && isset($param['author'], $param['en']) && $param['en'] == 1 ) { if ( ! isset($param['sticky']) || ! in_array($param['sticky'], ['0', '1']) ) { $param['sticky'] = '0'; } if ( ! isset($param['notify']) || ! in_array($param['notify'], ['0', '1']) ) { $param['notify'] = '0'; } if ( ! isset($param['persistent']) || ! in_array($param['persistent'], ['0', '1']) ) { $param['persistent'] = '0'; } acknowledgeService($param); } elseif ( isset($param['cmd']) && $param['cmd'] == 15 && isset($param['author'], $param['en']) && $param['en'] == 0 ) { acknowledgeServiceDisable(); } if ( isset($param['cmd']) && $param['cmd'] == 16 && isset($param['output']) ) { submitPassiveCheck(); } if ($o == 'svcSch') { $param['sort_types'] = 'next_check'; $param['order'] = 'sort_asc'; } $path = './include/monitoring/status/'; $metaservicepath = $path . 'service.php'; $pathRoot = './include/monitoring/'; $pathExternal = './include/monitoring/external_cmd/'; $pathDetails = './include/monitoring/objectDetails/'; // Special Paths $svc_path = $path . 'Services/'; $hg_path = $path . 'ServicesHostGroups/'; $sg_path = $path . 'ServicesServiceGroups/'; if ($continue) { switch ($o) { // View of Service case 'svc': case 'svcpb': case 'svc_warning': case 'svc_critical': case 'svc_unknown': case 'svc_ok': case 'svc_pending': case 'svc_unhandled': require_once $svc_path . 'service.php'; break; // Special Views case 'svcd': require_once $pathDetails . 'serviceDetails.php'; break; case 'svcak': require_once './include/monitoring/acknowlegement/serviceAcknowledge.php'; break; case 'svcpc': require_once './include/monitoring/submitPassivResults/servicePassiveCheck.php'; break; case 'svcgrid': case 'svcOV': case 'svcOV_pb': require_once $svc_path . 'serviceGrid.php'; break; case 'svcSum': require_once $svc_path . 'serviceSummary.php'; break; // View by Service Groups case 'svcgridSG': case 'svcOVSG': case 'svcOVSG_pb': require_once $sg_path . 'serviceGridBySG.php'; break; case 'svcSumSG': require_once $sg_path . 'serviceSummaryBySG.php'; break; // View By hosts groups case 'svcgridHG': case 'svcOVHG': case 'svcOVHG_pb': require_once $hg_path . 'serviceGridByHG.php'; break; case 'svcSumHG': require_once $hg_path . 'serviceSummaryByHG.php'; break; default: require_once $svc_path . 'service.php'; break; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/monitoringHostGroup.php
centreon/www/include/monitoring/status/monitoringHostGroup.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 * */ if (! isset($centreon)) { exit(); } require_once './class/centreonDuration.class.php'; include_once './include/monitoring/common-Func.php'; include_once './include/monitoring/external_cmd/cmd.php'; $continue = true; $path_hg = './include/monitoring/status/HostGroups/'; $pathDetails = './include/monitoring/objectDetails/'; include_once './class/centreonDB.class.php'; switch ($o) { case 'hg': require_once $path_hg . 'hostGroup.php'; break; case 'hgpb': require_once $path_hg . 'hostGroup.php'; break; case 'hgd': require_once $pathDetails . 'hostgroupDetails.php'; break; default: require_once $path_hg . 'hostGroup.php'; break; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/common-Func.php
centreon/www/include/monitoring/status/Common/common-Func.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 * */ function getMyIndexGraph4Service($host_id = null, $service_id = null, $pearDBO) { if ((! isset($service_id) || ! $service_id) || (! isset($host_id) || ! $host_id)) { return null; } $DBRESULT = $pearDBO->query("SELECT id FROM index_data i, metrics m WHERE i.host_id = '" . $host_id . "' " . "AND m.hidden = '0' " . "AND i.service_id = '" . $service_id . "' " . 'AND i.id = m.index_id'); if ($DBRESULT->rowCount()) { $row = $DBRESULT->fetchRow(); return $row['id']; } 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/include/monitoring/status/Common/default_poller.php
centreon/www/include/monitoring/status/Common/default_poller.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 * */ $default_poller = $_SESSION['monitoring_default_poller'] ?? -1;
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/default_servicegroups.php
centreon/www/include/monitoring/status/Common/default_servicegroups.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 * */ $default_sg = $_SESSION['monitoring_default_servicegroups'] ?? '0';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/setHistory.php
centreon/www/include/monitoring/status/Common/setHistory.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 realpath(__DIR__ . '/../../../../../config/centreon.config.php'); $path = _CENTREON_PATH_ . '/www'; require_once "{$path}/class/centreon.class.php"; require_once "{$path}/class/centreonSession.class.php"; require_once "{$path}/class/centreonDB.class.php"; $DB = new CentreonDB(); CentreonSession::start(); if (! CentreonSession::checkSession(session_id(), $DB)) { echo 'Bad Session ID'; exit(); } $centreon = $_SESSION['centreon']; if (isset($_POST['url'])) { $url = filter_input(INPUT_POST, 'url', FILTER_SANITIZE_URL); if (! empty($url)) { if (isset($_POST['search'])) { $search = isset($_POST['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['search']) : null; $centreon->historySearchService[$url] = $search; } if (isset($_POST['search_host'])) { $searchHost = isset($_POST['seach_host']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['seach_host']) : null; $centreon->historySearch[$url] = $searchHost; } if (isset($_POST['search_output'])) { $searchOutput = isset($_POST['search_output']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['search_output']) : null; $centreon->historySearchOutput[$url] = $searchOutput; } $defaultLimit = $centreon->optGen['maxViewConfiguration'] >= 1 ? (int) $centreon->optGen['maxViewConfiguration'] : 30; if (isset($_POST['limit'])) { $limit = filter_input( INPUT_POST, 'limit', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'default' => $defaultLimit]] ); $centreon->historyLimit[$url] = $limit; } if (isset($_POST['page'])) { $page = filter_input( INPUT_POST, 'page', FILTER_VALIDATE_INT ); if ($page !== false) { $centreon->historyPage[$url] = $page; } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/updateContactParamServiceGroups.php
centreon/www/include/monitoring/status/Common/updateContactParamServiceGroups.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 * */ if (! isset($_GET['uid']) || ! isset($_GET['servicegroups'])) { exit(0); } // sanitize parameter $serviceGroup = filter_var($_GET['servicegroups'], FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php'; $pearDB = new CentreonDB(); CentreonSession::start(); $_SESSION['monitoring_default_servicegroups'] = $serviceGroup;
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/default_hostgroups.php
centreon/www/include/monitoring/status/Common/default_hostgroups.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 * */ $default_hg = $_SESSION['monitoring_default_hostgroups'] ?? '0';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/updateContactParamHostGroups.php
centreon/www/include/monitoring/status/Common/updateContactParamHostGroups.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 * */ if (! isset($_GET['uid']) || ! isset($_GET['hostgroups'])) { exit(0); } // sanitize parameter $hostGroup = filter_var($_GET['hostgroups'], FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php'; $pearDB = new CentreonDB(); CentreonSession::start(); $_SESSION['monitoring_default_hostgroups'] = $hostGroup;
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/updateContactParam.php
centreon/www/include/monitoring/status/Common/updateContactParam.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 * */ if (! isset($_GET['uid']) || ! isset($_GET['instance_id'])) { exit(0); } // sanitize parameter $instanceId = filter_var($_GET['instance_id'], FILTER_VALIDATE_INT, ['options' => ['default' => -1]]); require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php'; $pearDB = new CentreonDB(); CentreonSession::start(); $_SESSION['monitoring_default_poller'] = $instanceId;
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Common/commonJS.php
centreon/www/include/monitoring/status/Common/commonJS.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 * */ if (! isset($centreon)) { exit(); } if (! isset($default_poller)) { include_once './include/monitoring/status/Common/default_poller.php'; } $searchHistory = CentreonUtils::escapeSecure( ($centreon->historySearch[$url] ?? '') ); $historySearchService = CentreonUtils::escapeSecure( ($centreon->historySearchService[$url] ?? '') ); if (! isset($search_host) || empty($search_host)) { $search_host = $searchHistory; } if (! isset($search_sg) || empty($search_sg)) { $search_sg = $searchHistory; } if (! isset($search_output) || empty($search_output)) { $search_output = CentreonUtils::escapeSecure( ($centreon->historySearchOutput[$url] ?? '') ); } ?> // Dynamique <?php if (isset($search_type_host)) { ?> var _search_type_host='<?php echo $search_type_host; ?>'; <?php } ?> <?php if (isset($search_type_service)) { ?> var _search_type_service='<?php echo $search_type_service; ?>'; <?php } ?> var _search = '<?= $search ?? $historySearchService; ?>'; var _host_search = '<?= $search_host; ?>'; var _sg_search = '<?= $search_sg; ?>'; var _output_search = '<?= $search_output; ?>'; var _num='<?php echo $num; ?>'; var _limit='<?php echo $limit; ?>'; var _sort_type='<?php echo $sort_type ?? ''; ?>'; var _order='<?php echo $order ?? ''; ?>'; var _date_time_format_status='<?php echo addslashes(_('Y/m/d H:i:s')); ?>'; var _o='<?php echo (isset($obis) && $obis) ? $obis : $o; ?>'; var _p='<?php echo $p; ?>'; // Parameters var _timeoutID = 0; var _counter = 0; var _hostgroup_enable = 1; var _servicegroup_enable = 1; var _on = 1; var _time_reload = <?php echo $tM; ?>; var _time_live = <?php echo $tFM; ?>; var _nb = 0; var _oldInputFieldValue = ''; var _oldInputHostFieldValue = ''; var _oldInputOutputFieldValue = ''; var _oldInputHGFieldValue = ''; var _currentInputFieldValue=""; // valeur actuelle du champ texte var _resultCache=new Object(); var _first = 1; var _lock = 0; var _instance = "-1"; var _default_hg = "<?php if (isset($default_hg)) { echo htmlentities($default_hg, ENT_QUOTES, 'UTF-8'); } ?>"; var _default_sg = "<?php if (isset($default_sg)) { echo htmlentities($default_sg, ENT_QUOTES, 'UTF-8'); } ?>"; var _default_instance = "<?php echo $default_poller; ?>"; var _nc = 0; var _poppup = (navigator.appName.substring(0,3) == "Net") ? 1 : 0; var _popup_no_comment_msg = '<?php echo addslashes(_('Please enter a comment')); ?>'; // Hosts WS For Poppin var _addrXMLSpanHost = "./include/monitoring/status/Services/xml/makeXMLForOneHost.php"; var _addrXSLSpanhost = "./include/monitoring/status/Services/xsl/popupForHost.xsl"; // Services WS For Poppin var _addrXMLSpanSvc = "./include/monitoring/status/Services/xml/makeXMLForOneService.php"; var _addrXSLSpanSvc = "./include/monitoring/status/Services/xsl/popupForService.xsl"; // Position var tempX = 0; var tempY = 0; if (navigator.appName.substring(0, 3) == "Net") { document.captureEvents(Event.MOUSEMOVE); } document.onmousemove = position; /* Reset trim function in order to be compatible with IE */ if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } /* Global event */ /* Graph */ jQuery('body').delegate( '#forAjax a .graph-volant', 'mouseenter', function(e) { func_displayIMG(e, function() { }); } ); jQuery('body').delegate( '#forAjax a .graph-volant', 'mouseleave', function() { func_hideIMG(); } ); /* Popup */ jQuery('body').delegate( '#forAjax .link_popup_volante', 'mouseenter', function(e) { func_displayPOPUP(e); } ); jQuery('body').delegate( '#forAjax .link_popup_volante', 'mouseleave', function(e) { func_hidePOPUP(e); } ); /* Generic info */ jQuery('body').delegate( '#forAjax .link_generic_info_volante', 'mouseenter', function(e) { func_displayGenericInfo(e); } ); jQuery('body').delegate( '#forAjax .link_generic_info_volante', 'mouseleave', function(e) { func_hidePOPUP(e); } ); function monitoringCallBack(t) { resetSelectedCheckboxes(); mk_pagination(t.getXmlDocument()); set_header_title(); } function resetSelectedCheckboxes() { $('.ListColPicker,.ListColHeaderPicker input').each(function(index) { var id = $(this).attr('id'); if (typeof(savedChecked) != "undefined" && typeof(savedChecked[id]) != 'undefined') { if (savedChecked[id] == 1) { $(this).prop('checked', true); } } }); $('input[type="checkbox"]').each(function(index) { var id = $(this).attr('id'); if (typeof(_selectedElem) != "undefined" && _selectedElem[encodeURIComponent(id)]) { $(this).prop('checked', true); } }); } function getXhrC() { if (window.XMLHttpRequest) { // Firefox et autres var xhrC = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer try { var xhrC = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { var xhrC = new ActiveXObject("Microsoft.XMLHTTP"); } } else { // XMLHttpRequest non support2 par le navigateur alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); var xhrC = false; } return xhrC; } function addORdelTab(_name) { var d = document.getElementsByName('next_check_case'); if (d[0].checked == true) { _nc = 1; } else { _nc = 0; } monitoring_refresh(); } function advanced_options(id) { var d = document.getElementById(id); if (d) { if (d.style.display == 'block') { d.style.display='none'; } else { d.style.display='block'; } } } function construct_selecteList_ndo_instance(id){ var displayPoller = <?php echo $centreon->user->access->checkAction('poller_listing'); ?> if (!displayPoller) { return null; } if (!document.getElementById("select_instance")){ var select_index = new Array(); var _select_instance = document.getElementById(id); if (_select_instance == null) { return; } var _select = document.createElement("select"); _select.name = "select_instance"; _select.id = "select_instance"; _select.onchange = function() { _instance = this.value; _default_instance = this.value; xhr = new XMLHttpRequest(); xhr.open('GET','./include/monitoring/status/Common/updateContactParam.php?uid=<?php echo $centreon->user->user_id; ?>&instance_id='+this.value, true); xhr.send(null); xhr.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE) { monitoring_refresh(); } }; }; var k = document.createElement('option'); k.value= -1; var l = document.createTextNode(""); k.appendChild(l); _select.appendChild(k); var i = 1; <?php $pollerArray = $centreon->user->access->getPollers(); /** ************************************* * Get instance listing */ if ($centreon->user->admin || ! count($pollerArray)) { $instanceQuery = 'SELECT 1 AS REALTIME, instance_id, name FROM `instances` WHERE running = 1 AND deleted = 0 ORDER BY name'; } else { $instanceQuery = 'SELECT 1 AS REALTIME, instance_id, name FROM `instances` WHERE running = 1 AND deleted = 0 AND name IN (' . $centreon->user->access->getPollerString('NAME') . ') ORDER BY name'; } $DBRESULT = $pearDBO->query($instanceQuery); while ($nagios_server = $DBRESULT->fetchRow()) { ?> var m = document.createElement('option'); m.value= "<?php echo $nagios_server['instance_id']; ?>"; _select.appendChild(m); var n = document.createTextNode("<?php echo $nagios_server['name'] . ' '; ?> "); m.appendChild(n); _select.appendChild(m); select_index["<?php echo $nagios_server['instance_id']; ?>"] = i; i++; <?php } ?> _select.selectedIndex = select_index[_default_instance]; _select_instance.appendChild(_select); } } function construct_HostGroupSelectList(id) { if (!document.getElementById("hostgroups")) { var select_index = new Array(); var _select_hostgroups = document.getElementById(id); if (_select_hostgroups == null) { return; } var _select = document.createElement("select"); _select.name = "hostgroups"; _select.id = "hostgroups"; _select.onchange = function() { _default_hg = this.value; xhr = new XMLHttpRequest(); xhr.open('GET','./include/monitoring/status/Common/updateContactParamHostGroups.php?uid=<?php echo $centreon->user->user_id; ?>&hostgroups='+this.value, true); xhr.send(null); xhr.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE) { monitoring_refresh(); } }; }; var k = document.createElement('option'); k.value= "0"; _select.appendChild(k); var i = 1; <?php $hgNdo = []; $hgBrk = []; $acldb = $pearDBO; if (! $centreon->user->access->admin) { $query = 'SELECT DISTINCT hg.hg_alias, hg.hg_name AS name FROM hostgroup hg, acl_resources_hg_relations arhr WHERE hg.hg_id = arhr.hg_hg_id AND arhr.acl_res_id IN (' . $centreon->user->access->getResourceGroupsString() . ") AND hg.hg_activate = '1' AND hg.hg_id in (SELECT hostgroup_hg_id FROM hostgroup_relation WHERE host_host_id IN (" . $centreon->user->access->getHostsString('ID', $acldb) . '))'; $DBRESULT = $pearDB->query($query); while ($data = $DBRESULT->fetchRow()) { $hgNdo[$data['name']] = 1; $hgBrk[$data['name']] = 1; } $DBRESULT->closeCursor(); unset($data); } $DBRESULT = $pearDBO->query( 'SELECT DISTINCT 1 AS REALTIME, hg.name, hg.hostgroup_id ' . 'FROM hostgroups hg, hosts_hostgroups hhg ' . 'WHERE hg.hostgroup_id = hhg.hostgroup_id ' . "AND hg.name NOT LIKE 'meta\_%' " . 'ORDER BY hg.name' ); while ($hostgroups = $DBRESULT->fetchRow()) { if ($centreon->user->access->admin || ($centreon->user->access->admin == 0 && isset($hgBrk[$hostgroups['name']]))) { if (! isset($tabHG)) { $tabHG = []; } if (! isset($tabHG[$hostgroups['name']])) { $tabHG[$hostgroups['name']] = ''; } else { $tabHG[$hostgroups['name']] .= ','; } $tabHG[$hostgroups['name']] .= $hostgroups['hostgroup_id']; } } if (isset($tabHG)) { foreach ($tabHG as $name => $id) { ?> var m = document.createElement('option'); m.value= "<?php echo $id; ?>"; _select.appendChild(m); var n = document.createTextNode("<?php echo $name; ?> "); m.appendChild(n); _select.appendChild(m); select_index["<?php echo $id; ?>"] = i; i++; <?php } } ?> if (typeof(_default_hg) != "undefined") { _select.selectedIndex = select_index[_default_hg]; } _select_hostgroups.appendChild(_select); } } function construct_ServiceGroupSelectList(id) { if (!document.getElementById("servicegroups")) { var select_index = new Array(); var _select_servicegroups = document.getElementById(id); if (_select_servicegroups == null) { return; } var _select = document.createElement("select"); _select.name = "servicegroups"; _select.id = "servicegroups"; _select.onchange = function() { _default_sg = this.value; xhr = new XMLHttpRequest(); xhr.open('GET','./include/monitoring/status/Common/updateContactParamServiceGroups.php?uid=<?php echo $centreon->user->user_id; ?>&servicegroups='+this.value, true); xhr.send(null); xhr.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE) { monitoring_refresh(); } }; }; var k = document.createElement('option'); k.value= "0"; _select.appendChild(k); var i = 1; <?php $sgBrk = []; $acldb = $pearDBO; if (! $centreon->user->access->admin) { $query = 'SELECT DISTINCT sg.sg_alias, sg.sg_name AS name FROM servicegroup sg, acl_resources_sg_relations arsr WHERE sg.sg_id = arsr.sg_id AND arsr.acl_res_id IN (' . $centreon->user->access->getResourceGroupsString() . ") AND sg.sg_activate = '1'"; $DBRESULT = $pearDB->query($query); while ($data = $DBRESULT->fetchRow()) { $sgBrk[$data['name']] = 1; } $DBRESULT->closeCursor(); unset($data); } $DBRESULT = $pearDBO->query("SELECT DISTINCT 1 AS REALTIME, sg.name, sg.servicegroup_id FROM servicegroups sg, services_servicegroups ssg WHERE sg.servicegroup_id = ssg.servicegroup_id AND sg.name NOT LIKE 'meta\_%' ORDER BY sg.name"); while ($servicegroups = $DBRESULT->fetchRow()) { if ($centreon->user->access->admin || ($centreon->user->access->admin == 0 && isset($sgBrk[$servicegroups['name']]))) { if (! isset($tabSG)) { $tabSG = []; } if (! isset($tabSG[$servicegroups['name']])) { $tabSG[$servicegroups['name']] = ''; } else { $tabSG[$servicegroups['name']] .= ','; } $tabSG[$servicegroups['name']] .= $servicegroups['servicegroup_id']; } } if (isset($tabSG)) { foreach ($tabSG as $name => $id) { ?> var m = document.createElement('option'); m.value= "<?php echo $id; ?>"; _select.appendChild(m); var n = document.createTextNode("<?php echo $name; ?> "); m.appendChild(n); _select.appendChild(m); select_index["<?php echo $id; ?>"] = i; i++; <?php } } ?> if (typeof(_default_sg) != "undefined") { _select.selectedIndex = select_index[_default_sg]; } _select_servicegroups.appendChild(_select); } } function viewDebugInfo(_str) { if (_debug) { _nb = _nb + 1; var mytable=document.getElementById("debugtable") var newrow=mytable.insertRow(0) //add new row to end of table var newcell=newrow.insertCell(0) //insert new cell to row newcell.innerHTML='<td>line:' + _nb + ' ' + _str + '</td>'; } } function change_page(page_number) { _selectedElem = new Array(); viewDebugInfo('change page'); _num = page_number; monitoring_refresh(); pagination_changed(); set_page(page_number); } function change_type_order(_type) { if (_sort_type != _type){ _sort_type = _type; } monitoring_refresh(); } function change_order(_odr) { if (_order == 'ASC'){ _order = 'DESC'; } else { _order = 'ASC'; } monitoring_refresh(); } function change_limit(l) { _limit= l; pagination_changed(); monitoring_refresh(); var _sel1 = document.getElementById('l1'); for(i=0 ; _sel1[i] && _sel1[i].value != l ; i++) ; _sel1.selectedIndex = i; set_limit(l); } var _numRows = 0; function getVar (nomVariable) { var infos = location.href.substring(location.href.indexOf("?")+1, location.href.length)+"&"; if (infos.indexOf("#")!=-1) infos = infos.substring(0,infos.indexOf("#"))+"&"; var variable='' { nomVariable = nomVariable + "="; var taille = nomVariable.length; if (infos.indexOf(nomVariable)!=-1) variable = infos.substring(infos.indexOf(nomVariable)+taille,infos.length) .substring(0,infos.substring(infos.indexOf(nomVariable)+taille,infos.length).indexOf("&")) } return variable; } function mk_img(_src, _alt) { var _img = document.createElement("img"); _img.src = _src; _img.alt = _alt; _img.title = _alt; //_img.className = 'ico-10'; if (_img.complete){ _img.alt = _alt; } else { _img.alt = ""; } return _img; } function mk_imgOrder(_src, _alt) { var _img = document.createElement("img"); _img.src = _src; _img.alt = _alt; _img.title = _alt; _img.style.paddingLeft = '10px'; _img.style.marginBottom = '0.5px'; if (_img.complete){ _img.alt = _alt; } else { _img.alt = ""; } return _img; } function mk_pagination(resXML){ viewDebugInfo('mk pagination'); var flag = 0; var infos = resXML.getElementsByTagName('i'); var _nr = infos[0].getElementsByTagName('numrows')[0].firstChild.data; var _nl = infos[0].getElementsByTagName("limit")[0].firstChild.data; var _nn = infos[0].getElementsByTagName("num")[0].firstChild.data; if (_numRows != _nr) { _numRows = _nr; flag = 1; } if (_num != _nn) { _num = _nn; flag = 1; } if (_limit != _nl) { _limit = _nl; flag = 1; } if (flag == 1) { pagination_changed(); } } function mk_paginationFF(resXML){ viewDebugInfo('mk pagination'); var flag = 0; var infos = resXML.getElementsByTagName('i'); if (infos[0]) { var _nr = infos[0].getElementsByTagName('numrows')[0].firstChild.data; var _nl = infos[0].getElementsByTagName("limit")[0].firstChild.data; var _nn = infos[0].getElementsByTagName("num")[0].firstChild.data; if (_numRows != _nr){ _numRows = _nr; flag = 1; } if (_num != _nn){ _num = _nn; flag = 1; } if (_limit != _nl){ _limit = _nl; flag = 1; } if (flag == 1){ pagination_changed(); } } } function pagination_changed(){ viewDebugInfo('pagination_changed'); // compute Max Page var page_max = 0; if ((_numRows % _limit) == 0) { page_max = Math.round( (_numRows / _limit)); } else{ page_max = Math.round( (_numRows / _limit) + 0.5); } if (_num >= page_max && _numRows && _num > 0){ viewDebugInfo('!!num!!'+_num); viewDebugInfo('!!max!!'+page_max); _num = Number(page_max) - 1; viewDebugInfo('new:'+_num); monitoring_refresh(); } var p = getVar('p'); var o = getVar('o'); var search = '' + getVar('search'); var _numnext = Number(_num) + 1; var _numprev = Number(_num) - 1; <?php for ($i = 1; $i <= 2; $i++) { ?> var _img_previous<?php echo $i; ?> = mk_img("./img/icons/rewind.png", "previous"); var _img_next<?php echo $i; ?> = mk_img("./img/icons/fast_forward.png", "next"); var _img_first<?php echo $i; ?> = mk_img("./img/icons/first_rewind.png", "first"); var _img_last<?php echo $i; ?> = mk_img("./img/icons/end_forward.png", "last"); var _linkaction_right<?php echo $i; ?> = document.createElement("a"); _linkaction_right<?php echo $i; ?>.href = '#' ; _linkaction_right<?php echo $i; ?>.indice = _numnext; _linkaction_right<?php echo $i; ?>.onclick=function(){change_page(Number(this.indice))} _linkaction_right<?php echo $i; ?>.appendChild(_img_next<?php echo $i; ?>); var _linkaction_last<?php echo $i; ?> = document.createElement("a"); _linkaction_last<?php echo $i; ?>.href = '#' ; _linkaction_last<?php echo $i; ?>.indice = page_max - 1; _linkaction_last<?php echo $i; ?>.onclick=function(){change_page(Number(this.indice))} _linkaction_last<?php echo $i; ?>.appendChild(_img_last<?php echo $i; ?>); var _linkaction_first<?php echo $i; ?> = document.createElement("a"); _linkaction_first<?php echo $i; ?>.href = '#' ; _linkaction_first<?php echo $i; ?>.indice = 0; _linkaction_first<?php echo $i; ?>.onclick=function(){change_page(Number(this.indice))} _linkaction_first<?php echo $i; ?>.appendChild(_img_first<?php echo $i; ?>); var _linkaction_left<?php echo $i; ?> = document.createElement("a"); _linkaction_left<?php echo $i; ?>.href = '#' ; _linkaction_left<?php echo $i; ?>.indice = _numprev; _linkaction_left<?php echo $i; ?>.onclick=function(){change_page(Number(this.indice))} _linkaction_left<?php echo $i; ?>.appendChild(_img_previous<?php echo $i; ?>); var _pagination<?php echo $i; ?> = document.getElementById('pagination<?php echo $i; ?>'); _pagination<?php echo $i; ?>.innerHTML =''; if (_num > 0){ _pagination<?php echo $i; ?>.appendChild(_linkaction_first<?php echo $i; ?>); _pagination<?php echo $i; ?>.appendChild(_linkaction_left<?php echo $i; ?>); } <?php } // Page Number for ($i = 1; $i <= 2; $i++) { ?> var istart = 0; for (i = 5, istart = _num; istart && i > 0 && istart > 0; i--) { istart--; } for (i2 = 0, iend = _num; ( iend < (_numRows / _limit -1)) && ( i2 < (5 + i)); i2++) { iend++; } for (i = istart; i <= iend && page_max > 1; i++) { var span_space = document.createElement("span"); span_space.innerHTML = '&nbsp;'; _pagination<?php echo $i; ?>.appendChild(span_space); var _linkaction_num = document.createElement("a"); _linkaction_num.href = '#' ; _linkaction_num.indice = i; _linkaction_num.onclick=function(){change_page(this.indice)}; _linkaction_num.innerHTML = parseInt(i + 1); _linkaction_num.className = "otherPageNumber"; if (i == _num) _linkaction_num.className = "currentPageNumber"; _pagination<?php echo $i; ?>.appendChild(_linkaction_num); var span_space = document.createElement("span"); span_space.innerHTML = '&nbsp;'; _pagination<?php echo $i; ?>.appendChild(span_space); } if (_num < page_max - 1){ _pagination<?php echo $i; ?>.appendChild(_linkaction_right<?php echo $i; ?>); _pagination<?php echo $i; ?>.appendChild(_linkaction_last<?php echo $i; ?>); } <?php } ?> var _sel1 = document.getElementById('sel1'); _sel1.innerHTML =''; var _sel2 = document.getElementById('sel2'); _sel2.innerHTML =''; var sel1 = document.createElement('select'); sel1.name = 'l'; sel1.id = 'l1'; sel1.onchange = function() { change_limit(this.value) }; var sel2 = document.createElement('select'); sel2.name = 'l'; sel2.id = 'l2'; sel2.onchange = function() { change_limit(this.value) }; var _max = 100; if (_limit > 100) { _max = 1000; } var _index; for (i = 10, j = 0 ; i <= 100 ; i += 10, j++) { var k = document.createElement('option'); k.value = i; sel1.appendChild(k); if (_limit == i) { _index = j; } var l = document.createTextNode(i); k.appendChild(l); } for (i = 10, j = 0; i <= 100 ; i += 10, j++) { var k = document.createElement('option'); k.value = i; sel2.appendChild(k); if (_limit == i) { _index = j; } var l = document.createTextNode(i); k.appendChild(l); } sel1.selectedIndex = _index; _sel1.appendChild(sel1); sel2.selectedIndex = _index; _sel2.appendChild(sel2); } function escapeURI(La) { if (encodeURIComponent) { return encodeURIComponent(La); } if (escape) { return escape(La) } } function mainLoop() { _currentInputField = document.getElementById('input_search'); if (document.getElementById('input_search') && document.getElementById('input_search').value) { _currentInputFieldValue = document.getElementById('input_search').value; } else { _currentInputFieldValue = ""; } _currentInputHostField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputHostFieldValue = document.getElementById('host_search').value; } else { _currentInputHostFieldValue = ""; } _currentInputOutputField = document.getElementById('output_search'); if (document.getElementById('output_search') && document.getElementById('output_search').value) { _currentInputOutputFieldValue = document.getElementById('output_search').value; } else { _currentInputOutputFieldValue = ""; } // Add HostGroups search field monitoring _currentInputHGField = jQuery('input[name="searchHG"]')[0]; if (_currentInputHGField && _currentInputHGField.value) { _currentInputHGFieldValue = _currentInputHGField.value; } else { _currentInputHGFieldValue = ""; } if (((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue) || ((_currentInputHostFieldValue.length >= 3 || _currentInputHostFieldValue.length == 0) && _oldInputHostFieldValue != _currentInputHostFieldValue) || ((_currentInputOutputFieldValue.length >= 3 || _currentInputOutputFieldValue.length == 0) && _oldInputOutputFieldValue != _currentInputOutputFieldValue) || ((_currentInputHGFieldValue.length >= 3 || _currentInputHGFieldValue.length == 0) && _oldInputHGFieldValue != _currentInputHGFieldValue)){ if (!_lock) { set_search(escapeURI(_currentInputFieldValue)); _search = _currentInputFieldValue; set_search_host(escapeURI(_currentInputHostFieldValue)); _host_search = _currentInputHostFieldValue; set_search_output(escapeURI(_currentInputOutputFieldValue)); _output_search = _currentInputOutputFieldValue; set_search_hg(escapeURI(_currentInputHGFieldValue)); _searchHG = _currentInputHGFieldValue; monitoring_refresh(); if (isset(_currentInputFieldValue.className) && _currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else if (isset(_currentInputFieldValue.className)) { _currentInputField.className = "search_input"; } if (isset(_currentInputHostFieldValue.className) && _currentInputHostFieldValue.length >= 3) { _currentInputHostField.className = "search_input_active"; } else if (isset(_currentInputHostFieldValue.className)) { _currentInputHostField.className = "search_input"; } if (isset(_currentInputOutputFieldValue.className) && _currentInputOutputFieldValue.length >= 3) { _currentInputOutputField.className = "search_input_active"; } else if (isset(_currentInputOutputFieldValue.className)) { _currentInputOutputField.className = "search_input"; } if (_currentInputHGField && _currentInputHGFieldValue.length >= 3) { _currentInputHGField.className = "search_input_active"; } else if (_currentInputHGField) { _currentInputHGField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; _oldInputHostFieldValue = _currentInputHostFieldValue; _oldInputOutputFieldValue = _currentInputOutputFieldValue; _oldInputHGFieldValue = _currentInputHGFieldValue; setTimeout("mainLoop()",250); } // History Functions function set_limit(limit) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "limit="+limit+"&url=<?php echo $url; ?>"; xhrM.send(_var); jQuery('input[name=limit]').val(limit); } function set_search(search) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "search="+search+"&url=<?php echo $url; ?>"; xhrM.send(_var); } function set_search_host(search_host) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "search_host="+search_host+"&url=<?php echo $url; ?>"; xhrM.send(_var); } function set_search_output(search_output) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "search_output="+search_output+"&url=<?php echo $url; ?>"; xhrM.send(_var); } function set_search_hg(search_hg) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "searchHG="+search_hg+"&url=<?php echo $url; ?>"; xhrM.send(_var); } function set_page(page) { var xhrM = getXhrC(); xhrM.open("POST","./include/monitoring/status/Common/setHistory.php",true); xhrM.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); _var = "page="+page+"&url=<?php echo $url; ?>"; xhrM.send(_var); } // Popin images var func_displayIMG = function(event, callback) { var self = event.currentTarget; var windowHeight = jQuery(window).height(); //getting the absolute cursor position, when scrolling in the iFrame var positionY = self .getBoundingClientRect() .top; jQuery('.img_volante').css('top', positionY); jQuery('.img_volante').css('left', event.pageX + 15); jQuery('.img_volante').show(); var chartElem = jQuery('<div></div>') .addClass('chart') .data('graphType', 'service') .data('graphId', jQuery(self).attr('id').replace('-', '_')) .appendTo(jQuery('.img_volante')); // Add event resize, as we can't get the popin size until it is loaded var oldHeight = 0; var interval = setInterval(function () { if (oldHeight == chartElem.height()) { clearInterval(interval); callback(); } else { oldHeight = chartElem.height(); //is the popup out the displayed screen ? if ((positionY + oldHeight) >= windowHeight) { positionY = windowHeight - oldHeight; //setting the new popin position jQuery('.img_volante').css('top', positionY); jQuery('.img_volante').show(); } } }, 500); jQuery(chartElem).centreonGraph({height: 200, interval: '24h'}); }; var func_hideIMG = function(event) { jQuery('.img_volante').hide(); jQuery('.img_volante').empty(); }; // Poppin Function var popup_counter = {}; var func_popupXsltCallback = function(trans_obj) { var target_element = trans_obj.getTargetElement(); if (popup_counter[target_element] == 0) { return ; } jQuery('.popup_volante .container-load').empty(); jQuery('.popup_volante').css('left', jQuery('#' + target_element).attr('left')); //item's Id from where the popin was called var eventCalledFrom = target_element.substr(24); //removing "popup-container-display-" var windowHeight = jQuery(window).height(); var popupHeight = jQuery('#' + target_element).height(); //getting the absolute cursor position, when scrolling in the iFrame var positionY = document .querySelector('#' + eventCalledFrom) .getBoundingClientRect() .top; //is the popup out the displayed screen ? if ((positionY + popupHeight) >= windowHeight) {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/serviceJS.php
centreon/www/include/monitoring/status/Services/serviceJS.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 * */ if (! isset($centreon)) { exit(); } $tFS = 10; $tFM = 10; $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/Services/xml/serviceXML.php"; var _addrXSL = "./include/monitoring/status/Services/xsl/service.xsl"; var _criticality_id = 0; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> var _selectedElem = new Array(); function getCheckedList(_input_name) { var mesinputs = document.getElementsByTagName("input"); var tab = new Array(); var nb = 0; for (var i = 0; i < mesinputs.length; i++) { if (mesinputs[i].type.toLowerCase() == 'checkbox' && mesinputs[i].checked && mesinputs[i].name.substr(0, 6) == _input_name ) { var name = mesinputs[i].name; var l = name.length; tab[nb] = name.substr(7, l - 8); nb++; } } return tab; } function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "<?php echo _('Sort results (ascendant)'); ?>"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "<?php echo _('Sort results (descendant)'); ?>"); if (document.getElementById('host_name')) { var h = document.getElementById('host_name'); h.innerHTML = '<?php echo addslashes(_('Hosts')); ?>'; h.indice = 'host_name'; h.title = "<?php echo _('Sort by host name'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('service_description'); h.innerHTML = '<?php echo addslashes(_('Services')); ?>'; h.indice = 'service_description'; h.title = "<?php echo _('Sort by service description'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('current_state'); h.innerHTML = '<?php echo addslashes(_('Status')); ?>'; h.indice = 'current_state'; h.title = "<?php echo _('Sort by status'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('last_state_change'); h.innerHTML = '<?php echo addslashes(_('Duration')); ?>'; h.indice = 'last_state_change'; h.title = '<?php echo addslashes(_('Sort by last change date')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('last_hard_state_change'); if (h) { h.innerHTML = '<?php echo addslashes(_('Hard State Duration')); ?>'; h.indice = 'last_hard_state_change'; h.title = '<?php echo addslashes(_('Sort by last hard state change date')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById('last_check'); h.innerHTML = '<?php echo addslashes(_('Last Check')); ?>'; h.indice = 'last_check'; h.title = '<?php echo addslashes(_('Sort by last check')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('current_attempt'); h.innerHTML = '<?php echo addslashes(_('Tries')); ?>'; h.indice = 'current_attempt'; h.title = '<?php echo addslashes(_('Sort by retries number')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('criticality_id'); if (h) { h.innerHTML = '<?php echo addslashes('S'); ?>'; h.indice = 'criticality_id'; h.title = "<?php echo _('Sort by severity'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById('plugin_output'); h.innerHTML = '<?php echo addslashes(_('Status information')); ?>'; h.indice = 'plugin_output'; h.title = '<?php echo addslashes(_('Sort by plugin output')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; if (h) { h.appendChild(_linkaction_asc); } } } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); construct_HostGroupSelectList('hostgroups_selected'); construct_ServiceGroupSelectList('servicegroups_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('host search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } if (document.getElementById("output_search") && document.getElementById("output_search").value) { _output_search = document.getElementById("output_search").value; viewDebugInfo('Output search: ' + document.getElementById("output_search").value); } else if (document.getElementById("output_search").length == 0) { _output_search = ""; } if (document.getElementById("input_search") && document.getElementById("input_search").value) { _search = document.getElementById("input_search").value; viewDebugInfo('service search: ' + document.getElementById("input_search").value); } else if (document.getElementById("input_search").length == 0) { _search = ""; } if (document.getElementById("critFilter") && document.getElementById("critFilter").value) { _criticality_id = document.getElementById("critFilter").value; viewDebugInfo('service criticality: ' + document.getElementById("critFilter").value); } if (_first) { mainLoop(); _first = 0; } _time =<?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { if (_on == 0) { return; } _lock = 1; var proc = new Transformation(); // INIT search informations if (_counter == 0) { document.getElementById("input_search").value = _search; document.getElementById("host_search").value = _host_search; document.getElementById("output_search").value = _output_search; _counter += 1; } var statusService = jQuery.trim(jQuery('#statusService').val()); var statusFilter = jQuery.trim(jQuery('#statusFilter').val()); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml( _addrXML + "?" + '&search=' + _search + '&search_host=' + _host_search + '&search_output=' + _output_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&host_name=<?php echo $host_name; ?>' + '&nc=' + _nc + '&criticality=' + _criticality_id + '&statusService=' + statusService + '&statusFilter=' + statusFilter + "&sSetOrderInMemory=" + sSetOrderInMemory ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } _lock = 0; if (_timeoutID) { // Kill next execution if in queue clearTimeout(_timeoutID); } _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } function unsetCheckboxes() { for (keyz in _selectedElem) { if (keyz == _selectedElem[keyz]) { removeFromSelectedElem(decodeURIComponent(keyz)); if (document.getElementById(decodeURIComponent(keyz))) { document.getElementById(decodeURIComponent(keyz)).checked = false; } } } } function cmdCallback(cmd) { jQuery('.centreon-popin').remove(); var keyz; _cmd = cmd; var resources = []; _getVar = ""; if (cmd != '70' && cmd != '72' && cmd != '74' && cmd != '75') { return 1; } else { for (keyz in _selectedElem) { if ((keyz == _selectedElem[keyz]) && typeof(document.getElementById(decodeURIComponent(keyz)) != 'undefined') && document.getElementById(decodeURIComponent(keyz)) ) { if (document.getElementById(decodeURIComponent(keyz)).checked) { resources.push(keyz); } } } _getVar = JSON.stringify(resources) var url = './include/monitoring/external_cmd/popup/popup.php?o=' + _o + '&p=' + _p + '&cmd=' + cmd; var popin = jQuery('<div>'); popin.centreonPopin({open: true, url: url}); window.currentPopin = popin; return 0; } } function send_the_command() { if (window.XMLHttpRequest) { xhr_cmd = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr_cmd = new ActiveXObject("Microsoft.XMLHTTP"); } var searchElement = jQuery(document); if (_cmd == '70' || _cmd == '72') { searchElement = jQuery(':visible #popupAcknowledgement'); } else if (_cmd == '74' || _cmd == '75') { searchElement = jQuery(':visible #popupDowntime'); } var comment = encodeURIComponent(searchElement.find('#popupComment').val().trim()); if (comment == "") { alert(_popup_no_comment_msg); return 0; } if (_cmd == '70' || _cmd == '72') { var sticky = 0; if (searchElement.find('#sticky').length && searchElement.find('#sticky').is(':checked')) { sticky = true; } var persistent = 0; if (searchElement.find('#persistent').length && searchElement.find('#persistent').is(':checked')) { persistent = true; } var notify = 0; if (searchElement.find('#notify').length && searchElement.find('#notify').is(':checked')) { notify = true; } var force_check = 0; if (searchElement.find('#force_check').length && searchElement.find('#force_check').is(':checked')) { force_check = true; } var ackhostservice = 0; if (searchElement.find('#ackhostservice').length && searchElement.find('#ackhostservice').is(':checked')) { ackhostservice = true; } var author = jQuery('#author').val(); xhr_cmd.open( "POST", "./include/monitoring/external_cmd/cmdPopup.php", true ); var data = new FormData(); data.append('cmd', _cmd); data.append('comment', comment); data.append('sticky', sticky); data.append('persistent', persistent); data.append('notify', notify); data.append('ackhostservice', ackhostservice); data.append('force_check', force_check); data.append('author', author); data.append('resources', _getVar); } else if (_cmd == '74' || _cmd == '75') { var downtimehostservice = 0; if (searchElement.find('#downtimehostservice').length && searchElement.find('#downtimehostservice').is(':checked') ) { downtimehostservice = true; } var fixed = 0; if (searchElement.find('#fixed').length && searchElement.find('#fixed').is(':checked')) { fixed = true; } var start = searchElement.find('[name="alternativeDateStart"]').val() + ' ' + searchElement.find('#start_time').val(); var end = searchElement.find('[name="alternativeDateEnd"]').val() + ' ' + searchElement.find('#end_time').val(); var author = jQuery('#author').val(); var duration = searchElement.find('#duration').val(); var duration_scale = searchElement.find('#duration_scale').val(); var host_or_centreon_time = "0"; if (searchElement.find('[name="host_or_centreon_time"]').length && searchElement.find('[name="host_or_centreon_time"]').is(':checked') ) { host_or_centreon_time = "1"; } xhr_cmd.open( "POST", "./include/monitoring/external_cmd/cmdPopup.php", true ); var data = new FormData(); data.append('cmd', _cmd); data.append('duration', duration); data.append('duration_scale', duration_scale); data.append('comment', comment); data.append('start', start); data.append('end', end); data.append('host_or_centreon_time', host_or_centreon_time); data.append('fixed', fixed); data.append('downtimehostservice', downtimehostservice); data.append('author', author); data.append('resources', _getVar); } xhr_cmd.send(data); window.currentPopin.centreonPopin("close"); unsetCheckboxes(); } function toggleFields(fixed) { var durationField = jQuery('#duration'); var durationScaleField = jQuery('#duration_scale'); if (fixed.checked) { durationField.attr('disabled', true); durationScaleField.attr('disabled', true); } else { durationField.removeAttr('disabled'); durationScaleField.removeAttr('disabled'); } } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/serviceSummaryJS.php
centreon/www/include/monitoring/status/Services/serviceSummaryJS.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 * */ if (! isset($centreon)) { exit(); } $tFS = 10; $tFM = 10; $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/Services/xml/serviceSummaryXML.php"; var _addrXSL = "./include/monitoring/status/Services/xsl/serviceSummary.xsl"; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc"); if (document.getElementById('host_name')) { var h = document.getElementById('host_name'); h.innerHTML = '<?php echo addslashes(_('Hosts')); ?>'; h.indice = 'host_name'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('services'); h.innerHTML = '<?php echo addslashes(_('Services information')); ?>'; h.indice = 'services'; if (document.getElementById('current_state')) { var h = document.getElementById('current_state'); h.innerHTML = '<?php echo addslashes(_('Status')); ?>'; h.indice = 'current_state'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; h.appendChild(_linkaction_asc); } } function mainLoopLocal() { _currentInputField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputFieldValue = document.getElementById('host_search').value; } else { _currentInputFieldValue = ""; } if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue ) { if (!_lock) { set_search_host(escapeURI(_currentInputFieldValue)); _host_search = _currentInputFieldValue; monitoring_refresh(); if (_currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else { _currentInputField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; setTimeout(mainLoopLocal, 250); } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); construct_HostGroupSelectList('hostgroups_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } if (_first) { mainLoopLocal(); _first = 0; } _time =<?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { _lock = 1; var proc = new Transformation(); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml(_addrXML + "?" + '&search=' + _host_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&time=<?php echo time(); ?>' ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } if (_counter == 0) { document.getElementById("host_search").value = _host_search; _counter += 1; } _lock = 0; _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/service.php
centreon/www/include/monitoring/status/Services/service.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 * */ if (! isset($centreon)) { exit(); } $myinputsGet = [ 'host_search' => isset($_GET['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_search']) : null, 'search' => isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : null, 'output_search' => isset($_GET['output_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['output_search']) : null, 'hg' => isset($_GET['hg']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hg']) : null, 'sg' => isset($_GET['sg']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sg']) : null, 'monitoring_default_hostgroups' => isset($_GET['monitoring_default_hostgroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['monitoring_default_hostgroups']) : null, 'monitoring_default_servicegroups' => isset($_GET['monitoring_default_servicegroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['monitoring_default_servicegroups']) : null, 'hostgroup' => isset($_GET['hostgroup']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hostgroup']) : null, 'sort_type' => filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT), 'host_name' => isset($_GET['host_name']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_name']) : null, 'global_sort_type' => isset($_GET['global_sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['global_sort_type']) : null, 'global_sort_order' => isset($_GET['global_sort_order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['global_sort_order']) : null, 'order' => isset($_GET['order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['order']) : null, 'monitoring_service_status_filter' => isset($_GET['monitoring_service_status_filter']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['lang']) : null, 'monitoring_service_status' => isset($_GET['monitoring_service_status']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['monitoring_service_status']) : null, 'criticality_id' => filter_input(INPUT_GET, 'criticality_id', FILTER_VALIDATE_INT), 'reset_filter' => filter_input(INPUT_GET, 'reset_filter', FILTER_VALIDATE_INT), ]; $myinputsPost = [ 'host_search' => isset($_POST['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['host_search']) : null, 'search' => isset($_POST['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['search']) : null, 'output_search' => isset($_POST['output_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['output_search']) : null, 'hg' => isset($_POST['hg']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['hg']) : null, 'sg' => isset($_POST['sg']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['sg']) : null, 'monitoring_default_hostgroups' => isset($_POST['monitoring_default_hostgroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['monitoring_default_hostgroups']) : null, 'monitoring_default_servicegroups' => isset($_POST['monitoring_default_servicegroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['monitoring_default_servicegroups']) : null, 'hostgroup' => isset($_POST['hostgroup']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['hostgroup']) : null, 'sort_type' => filter_input(INPUT_POST, 'num', FILTER_VALIDATE_INT), 'host_name' => isset($_POST['host_name']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['host_name']) : null, 'global_sort_type' => isset($_POST['global_sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['global_sort_type']) : null, 'global_sort_order' => isset($_POST['global_sort_order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['global_sort_order']) : null, 'order' => isset($_POST['order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['order']) : null, 'monitoring_service_status_filter' => isset($_POST['monitoring_service_status_filter']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['lang']) : null, 'monitoring_service_status' => isset($_POST['monitoring_service_status']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['monitoring_service_status']) : null, 'criticality_id' => filter_input(INPUT_POST, 'criticality_id', FILTER_VALIDATE_INT), 'reset_filter' => filter_input(INPUT_POST, 'reset_filter', FILTER_VALIDATE_INT), ]; $resetFilter = (isset($myinputsGet['reset_filter']) && $myinputsGet['reset_filter'] == 1) ? true : false; if ($resetFilter) { $centreon->historySearch[$url] = ''; $centreon->historySearchService[$url] = ''; $centreon->historySearchOutput[$url] = ''; $_SESSION['filters'][$url] = []; $_SESSION['monitoring_default_hostgroups'] = ''; $_SESSION['monitoring_default_servicegroups'] = ''; $_SESSION['monitoring_default_poller'] = ''; $_SESSION['monitoring_service_status_filter'] = ''; $_SESSION['criticality_id'] = ''; } if (! isset($o) || empty($o)) { $o = $_SESSION['monitoring_service_status'] ?? null; } foreach ($myinputsGet as $key => $value) { if (! empty($value)) { $filters[$key] = $value; } elseif (! empty($myinputsPost[$key])) { $filters[$key] = $myinputsPost[$key]; } elseif ($resetFilter && isset($_SESSION['filters'][$url][$key]) && ! empty($_SESSION['filters'][$url][$key])) { $filters[$key] = $_SESSION['filters'][$url][$key]; } else { $filters[$key] = ''; } } if (empty($filters['host_search']) && isset($centreon->historySearch[$url])) { $filters['host_search'] = $centreon->historySearch[$url]; } else { $centreon->historySearch[$url] = $filters['host_search']; } if (empty($filters['search']) && isset($centreon->historySearchService[$url])) { $filters['search'] = $centreon->historySearchService[$url]; } else { $centreon->historySearchService[$url] = $filters['search']; } if (empty($filters['output_search']) && isset($centreon->historySearchOutput[$url])) { $filters['output_search'] = $centreon->historySearchOutput[$url]; } else { $centreon->historySearchOutput[$url] = $filters['output_search']; } $_SESSION['filters'][$url] = $filters; if (! empty($filters['hg'])) { $_SESSION['monitoring_default_hostgroups'] = $filters['hg']; } if (! empty($filters['sg'])) { $_SESSION['monitoring_default_servicegroups'] = $filters['sg']; } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; // ACL Actions $GroupListofUser = []; $GroupListofUser = $centreon->user->access->getAccessGroups(); $allActions = false; // Get list of actions allowed for user if (count($GroupListofUser) > 0 && $is_admin == 0) { $authorized_actions = []; $authorized_actions = $centreon->user->access->getActions(); } else { // if user is admin, or without ACL, he cans perform all actions $allActions = true; } include './include/common/autoNumLimit.php'; // set limit & num $DBRESULT = $pearDB->query("SELECT * FROM options WHERE `key` = 'maxViewMonitoring' LIMIT 1"); $data = $DBRESULT->fetchRow(); $gopt[$data['key']] = myDecode($data['key']); $sort_type = empty($filters['sort_type']) ? 0 : $filters['sort_type']; $host_name = empty($filters['host_name']) ? '' : $filters['host_name']; $problem_sort_type = 'host_name'; if (! empty($centreon->optGen['problem_sort_type'])) { $problem_sort_type = $centreon->optGen['problem_sort_type']; } $problem_sort_order = 'asc'; if (! empty($centreon->optGen['problem_sort_type'])) { $problem_sort_order = $centreon->optGen['problem_sort_order']; } $global_sort_type = 'host_name'; if (! empty($centreon->optGen['global_sort_type'])) { $global_sort_type = $centreon->optGen['global_sort_type']; } $global_sort_order = 'asc'; if (! empty($centreon->optGen['global_sort_order'])) { $global_sort_order = $centreon->optGen['global_sort_order']; } if ($o == 'svcpb' || $o == 'svc_unhandled') { $sort_type = ! empty($filters['sort_type']) ? $filters['sort_type'] : $centreon->optGen['problem_sort_type']; $order = ! empty($filters['order']) ? $filters['order'] : $centreon->optGen['problem_sort_order']; } else { if (! empty($filters['sort_type'])) { $sort_type = $filters['sort_type']; } elseif (isset($centreon->optGen['global_sort_type'])) { $sort_type = CentreonDB::escape($centreon->optGen['global_sort_type']); } else { $sort_type = 'host_name'; } if (! empty($filters['order'])) { $order = $filters['order']; } elseif (isset($centreon->optGen['global_sort_order']) && $centreon->optGen['global_sort_order'] != '' ) { $order = $centreon->optGen['global_sort_order']; } else { $order = 'ASC'; } } include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once './include/monitoring/status/Common/default_servicegroups.php'; include_once $svc_path . '/serviceJS.php'; /** * Build the resource status listing URI that will be used in the * deprecated banner */ $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); $deprecationMessage = _('[Page deprecated] This page will be removed in the next major version. Please use the new page: '); $resourcesStatusLabel = _('Resources Status'); $filter = [ 'criterias' => [ [ 'name' => 'resource_types', 'value' => [ [ 'id' => 'service', 'name' => 'Service', ], ], ], [ 'name' => 'states', 'value' => [ [ 'id' => 'unhandled_problems', 'name' => 'Unhandled', ], ], ], [ 'name' => 'search', 'value' => '', ], ], ]; $redirectionUrl = $resourceController->buildListingUri(['filter' => json_encode($filter)]); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($svc_path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_type', $sort_type); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; $sSetOrderInMemory = ! isset($_GET['o']) ? '1' : '0'; $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } </script> <?php $action_list = []; $action_list[] = _('More actions...'); $informationsService = $dependencyInjector['centreon_remote.informations_service']; $serverIsMaster = $informationsService->serverIsMaster(); // Showing actions allowed for current user if (isset($authorized_actions) && $allActions == false) { if (isset($authorized_actions['service_schedule_check'])) { $action_list[3] = _('Services : Schedule immediate check'); } if (isset($authorized_actions['service_schedule_forced_check'])) { $action_list[4] = _('Services : Schedule immediate check (Forced)'); } if (isset($authorized_actions['service_acknowledgement'])) { $action_list[70] = _('Services : Acknowledge'); } if (isset($authorized_actions['service_disacknowledgement'])) { $action_list[71] = _('Services : Disacknowledge'); } if ($serverIsMaster && isset($authorized_actions['service_notifications'])) { $action_list[80] = _('Services : Enable Notification'); } if ($serverIsMaster && isset($authorized_actions['service_notifications'])) { $action_list[81] = _('Services : Disable Notification'); } if ($serverIsMaster && isset($authorized_actions['service_checks'])) { $action_list[90] = _('Services : Enable Check'); } if ($serverIsMaster && isset($authorized_actions['service_checks'])) { $action_list[91] = _('Services : Disable Check'); } if (isset($authorized_actions['service_schedule_downtime'])) { $action_list[74] = _('Services : Set Downtime'); } if (isset($authorized_actions['host_schedule_check'])) { $action_list[94] = _('Hosts : Schedule immediate check'); } if (isset($authorized_actions['host_schedule_forced_check'])) { $action_list[95] = _('Hosts : Schedule immediate check (Forced)'); } if (isset($authorized_actions['host_acknowledgement'])) { $action_list[72] = _('Hosts : Acknowledge'); } if (isset($authorized_actions['host_disacknowledgement'])) { $action_list[73] = _('Hosts : Disacknowledge'); } if ($serverIsMaster && isset($authorized_actions['host_notifications'])) { $action_list[82] = _('Hosts : Enable Notification'); } if ($serverIsMaster && isset($authorized_actions['host_notifications'])) { $action_list[83] = _('Hosts : Disable Notification'); } if ($serverIsMaster && isset($authorized_actions['host_checks'])) { $action_list[92] = _('Hosts : Enable Check'); } if ($serverIsMaster && isset($authorized_actions['host_checks'])) { $action_list[93] = _('Hosts : Disable Check'); } if (isset($authorized_actions['host_schedule_downtime'])) { $action_list[75] = _('Hosts : Set Downtime'); } } else { $action_list[3] = _('Services : Schedule immediate check'); $action_list[4] = _('Services : Schedule immediate check (Forced)'); $action_list[70] = _('Services : Acknowledge'); $action_list[71] = _('Services : Disacknowledge'); if ($serverIsMaster) { $action_list[80] = _('Services : Enable Notification'); $action_list[81] = _('Services : Disable Notification'); $action_list[90] = _('Services : Enable Check'); $action_list[91] = _('Services : Disable Check'); } $action_list[74] = _('Services : Set Downtime'); $action_list[94] = _('Hosts : Schedule immediate check'); $action_list[95] = _('Hosts : Schedule immediate check (Forced)'); $action_list[72] = _('Hosts : Acknowledge'); $action_list[73] = _('Hosts : Disacknowledge'); if ($serverIsMaster) { $action_list[82] = _('Hosts : Enable Notification'); $action_list[83] = _('Hosts : Disable Notification'); $action_list[92] = _('Hosts : Enable Check'); $action_list[93] = _('Hosts : Disable Check'); } $action_list[75] = _('Hosts : Set Downtime'); } $attrs = ['onchange' => 'javascript: ' . ' var bChecked = isChecked(); ' . " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {" . " alert('" . _('Please select one or more items') . "'); return false;} " . " if (this.form.elements['o1'].selectedIndex == 0) {" . ' return false;} ' . ' if (cmdCallback(this.value)) { setO(this.value); submit();} else { setO(this.value); }']; $form->addElement('select', 'o1', null, $action_list, $attrs); $form->setDefaults(['o1' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $attrs = ['onchange' => 'javascript: ' . ' var bChecked = isChecked(); ' . " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {" . " alert('" . _('Please select one or more items') . "'); return false;} " . " if (this.form.elements['o2'].selectedIndex == 0) {" . ' return false;} ' . ' if (cmdCallback(this.value)) { setO(this.value); submit();} else { setO(this.value); }']; $form->addElement('select', 'o2', null, $action_list, $attrs); $form->setDefaults(['o2' => null]); $o2 = $form->getElement('o2'); $o2->setValue(null); $o2->setSelected(null); $tpl->assign('limit', $limit); $keyPrefix = ''; $statusList = ['' => '', 'ok' => _('OK'), 'warning' => _('Warning'), 'critical' => _('Critical'), 'unknown' => _('Unknown'), 'pending' => _('Pending')]; $statusService = ['svc_unhandled' => _('Unhandled Problems'), 'svcpb' => _('Service Problems'), 'svc' => _('All')]; if ($o == 'svc') { $keyPrefix = 'svc'; } elseif ($o == 'svcpb') { $keyPrefix = 'svc'; unset($statusList['ok']); } elseif ($o == 'svc_unhandled') { $keyPrefix = 'svc_unhandled'; unset($statusList['ok'], $statusList['pending']); } elseif (preg_match('/svc_([a-z]+)/', $o, $matches)) { if (isset($matches[1])) { $keyPrefix = 'svc'; $defaultStatus = $matches[1]; } } $serviceStatusFromO = isset($_GET['o']) && in_array($_GET['o'], array_keys($statusService)) ? $_GET['o'] : null; $defaultStatusService = $_GET['statusService'] ?? $_POST['statusService'] ?? $serviceStatusFromO ?: $_SESSION['monitoring_service_status'] ?? 'svc_unhandled'; $o = $defaultStatusService; $form->setDefaults(['statusFilter' => $defaultStatusService]); $defaultStatusFilter = $_GET['statusFilter'] ?? $_POST['statusFilter'] ?? $_SESSION['monitoring_service_status_filter'] ?? ''; $form->addElement( 'select', 'statusFilter', _('Status'), $statusList, ['id' => 'statusFilter', 'onChange' => 'filterStatus(this.value);'] ); $form->setDefaults(['statusFilter' => $defaultStatusFilter]); $form->addElement( 'select', 'statusService', _('Service Status'), $statusService, ['id' => 'statusService', 'onChange' => 'statusServices(this.value);'] ); $form->setDefaults(['statusService' => $defaultStatusService]); $criticality = new CentreonCriticality($pearDB); $crits = $criticality->getList(null, 'level', 'ASC', null, null, true); $critArray = [0 => '']; foreach ($crits as $critId => $crit) { $critArray[$critId] = $crit['sc_name'] . " ({$crit['level']})"; } $form->addElement( 'select', 'criticality', _('Severity'), $critArray, ['id' => 'critFilter', 'onChange' => 'filterCrit(this.value);'] ); $form->setDefaults(['criticality' => $_SESSION['criticality_id'] ?? '0']); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('hostStr', _('Host')); $tpl->assign('serviceStr', _('Service')); $tpl->assign('statusService', _('Service Status')); $tpl->assign('filters', _('Filters')); $tpl->assign('outputStr', _('Output')); $tpl->assign('poller_listing', $centreon->user->access->checkAction('poller_listing')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('hgStr', _('Hostgroup')); $tpl->assign('sgStr', _('Servicegroup')); $criticality = new CentreonCriticality($pearDB); $tpl->assign('criticalityUsed', count($criticality->getList())); $tpl->assign('form', $renderer->toArray()); $tpl->display('service.ihtml'); ?> <script type='text/javascript'> var tabSortPb = []; tabSortPb['champ'] = '<?php echo $problem_sort_type; ?>'; tabSortPb['ordre'] = '<?php echo $problem_sort_order; ?>'; var tabSortAll = []; tabSortAll['champ'] = '<?php echo $global_sort_type; ?>'; tabSortAll['ordre'] = '<?php echo $global_sort_order; ?>'; var ok = '<?php echo _('OK'); ?>'; var warning = '<?php echo _('Warning'); ?>'; var critical = '<?php echo _('Critical'); ?>'; var unknown = '<?php echo _('Unknown'); ?>'; var pending = '<?php echo _('Pending'); ?>'; display_deprecated_banner(); function display_deprecated_banner() { const url = "<?php echo $redirectionUrl; ?>"; const message = "<?php echo $deprecationMessage; ?>"; const label = "<?php echo $resourcesStatusLabel; ?>"; jQuery('.pathway').append( '<span style="color:#FF4500;padding-left:10px;font-weight:bold">' + message + '<a style="position:relative" href="' + url + '" isreact="isreact">' + label + '</a></span>' ); } jQuery('#statusService').change(function () { updateSelect(); }); function updateSelect() { var oldStatus = jQuery('#statusFilter').val(); var opts = document.getElementById('statusFilter').options; var newTypeOrder = null; if (jQuery('#statusService').val() == 'svcpb' || jQuery('#statusService').val() == 'svc_unhandled') { opts.length = 0; opts[opts.length] = new Option("", ""); opts[opts.length] = new Option(warning, "warning"); opts[opts.length] = new Option(critical, "critical"); opts[opts.length] = new Option(unknown, "unknown"); newTypeOrder = tabSortPb['champ']; } else { opts.length = 0; opts[opts.length] = new Option("", ""); opts[opts.length] = new Option(ok, "ok"); opts[opts.length] = new Option(warning, "warning"); opts[opts.length] = new Option(critical, "critical"); opts[opts.length] = new Option(unknown, "unknown"); opts[opts.length] = new Option(pending, "pending"); newTypeOrder = tabSortAll['champ']; } // We define the statusFilter before calling ajax if (jQuery("#statusFilter option[value='" + oldStatus + "']").length > 0) { jQuery("#statusFilter option[value='" + oldStatus + "']").prop('selected', true); } else { jQuery("#statusFilter option[value='']").prop('selected', true); } change_type_order(newTypeOrder); } var _keyPrefix; jQuery(function () { preInit(); }); function preInit() { _keyPrefix = '<?= $keyPrefix; ?>'; _tm = <?= $tM; ?>; _o = '<?= $o; ?>'; _defaultStatusFilter = '<?= htmlspecialchars($defaultStatusFilter, ENT_QUOTES, 'UTF-8'); ?>'; _defaultStatusService = '<?= $defaultStatusService; ?>'; sSetOrderInMemory = '<?= $sSetOrderInMemory; ?>'; if (_defaultStatusService !== '') { jQuery("#statusService option[value='" + _defaultStatusService + "']").prop('selected', true); } if (_defaultStatusFilter !== '') { jQuery("#statusFilter option[value='" + _defaultStatusFilter + "']").prop('selected', true); } filterStatus(document.getElementById('statusFilter').value, 1); } function filterStatus(value, isInit) { _o = jQuery('#statusService').val(); if (value) { _o = _keyPrefix + '_' + value; } else if (!isInit && _o != 'svcpb') { _o = _keyPrefix; } window.clearTimeout(_timeoutID); initM(_tm, _o); } function filterCrit(value) { window.clearTimeout(_timeoutID); initM(_tm, _o); } function statusServices(value, isInit) { _o = value; } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/serviceGridJS.php
centreon/www/include/monitoring/status/Services/serviceGridJS.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 * */ if (! isset($centreon)) { exit(); } $tFM = 10; $tFS = 10; $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/Services/xml/serviceGridXML.php"; var _addrXSL = "./include/monitoring/status/Services/xsl/serviceGrid.xsl"; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "<?php echo _('Sort results (ascendant)'); ?>"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "<?php echo _('Sort results (descendant)'); ?>"); if (document.getElementById('host_name')) { var h = document.getElementById('host_name'); h.innerHTML = '<?php echo addslashes(_('Hosts')); ?>'; h.indice = 'host_name'; h.title = "<?php echo _('Sort by Host Name'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('current_state'); h.innerHTML = "<?php echo _('Status'); ?>"; h.indice = 'current_state'; h.title = '<?php echo addslashes(_('Sort by Status')); ?>'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('services'); h.innerHTML = '<?php echo addslashes(_('Services information')); ?>'; h.indice = 'services'; var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; h.appendChild(_linkaction_asc); } } function mainLoopLocal() { _currentInputField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputFieldValue = document.getElementById('host_search').value; } else { _currentInputFieldValue = ""; } if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue ) { if (!_lock) { set_search_host(escapeURI(_currentInputFieldValue)); _host_search = _currentInputFieldValue; monitoring_refresh(); if (_currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else { _currentInputField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; setTimeout(mainLoopLocal, 250); } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); construct_HostGroupSelectList('hostgroups_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } if (_first) { mainLoopLocal(); _first = 0; } _time = <?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { _lock = 1; var proc = new Transformation(); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml(_addrXML + "?" + '&search=' + _host_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&time=<?php echo time(); ?>' ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } if (_counter == 0) { document.getElementById("host_search").value = _host_search; _counter += 1; } _lock = 0; _timeoutID = cycleVisibilityChange(function(){goM( _time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } </SCRIPT>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/serviceGrid.php
centreon/www/include/monitoring/status/Services/serviceGrid.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 * */ if (! isset($centreon)) { exit(); } include './include/common/autoNumLimit.php'; $sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types']; $order = ! isset($_GET['order']) ? 'ASC' : $_GET['order']; $num = ! isset($_GET['num']) ? 0 : $_GET['num']; $host_search = ! isset($_GET['host_search']) ? 0 : $_GET['host_search']; $search_type_host = ! isset($_GET['search_type_host']) ? 1 : $_GET['search_type_host']; $search_type_service = ! isset($_GET['search_type_service']) ? 1 : $_GET['search_type_service']; $sort_type = ! isset($_GET['sort_type']) ? 'host_name' : $_GET['sort_type']; // Check search value in Host search field if (isset($_GET['host_search'])) { $centreon->historySearch[$url] = $_GET['host_search']; } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once $svc_path . '/serviceGridJS.php'; $aTypeAffichageLevel1 = ['svcOV' => _('Details'), 'svcSum' => _('Summary')]; $aTypeAffichageLevel2 = ['' => _('All'), 'pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')]; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($svc_path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_types', $sort_types); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('typeDisplay', _('Display')); $tpl->assign('typeDisplay2', _('Display details')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); ?> <script type="text/javascript"> _tm = <?php echo $tM; ?>; p = <?php echo $p; ?>; function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } function displayingLevel1(val) { var sel2 = document.getElementById("typeDisplay2").value; _o = val; if (sel2 != '') { _o += "_" + sel2; } if (val == 'svcOV') { _addrXML = "./include/monitoring/status/Services/xml/serviceGridXML.php"; _addrXSL = "./include/monitoring/status/Services/xsl/serviceGrid.xsl"; } else { _addrXML = "./include/monitoring/status/Services/xml/serviceSummaryXML.php"; _addrXSL = "./include/monitoring/status/Services/xsl/serviceSummary.xsl"; } monitoring_refresh(); } function displayingLevel2(val) { var sel1 = document.getElementById("typeDisplay").value; _o = sel1; if (val != '') { _o = _o + "_" + val; } monitoring_refresh(); } </script> <?php $form->addElement( 'select', 'typeDisplay', _('Display'), $aTypeAffichageLevel1, ['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);'] ); $form->addElement( 'select', 'typeDisplay2', _('Display '), $aTypeAffichageLevel2, ['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);'] ); $form->setDefaults(['typeDisplay2' => 'pb']); foreach (['o1', 'o2'] as $option) { $attrs = ['onchange' => "javascript: setO(this.form.elements['{$option}'].value); submit();"]; $form->addElement('select', $option, null, [null => _('More actions...'), '3' => _('Verification Check'), '4' => _('Verification Check (Forced)'), '70' => _('Services : Acknowledge'), '71' => _('Services : Disacknowledge'), '80' => _('Services : Enable Notification'), '81' => _('Services : Disable Notification'), '90' => _('Services : Enable Check'), '91' => _('Services : Disable Check'), '72' => _('Hosts : Acknowledge'), '73' => _('Hosts : Disacknowledge'), '82' => _('Hosts : Enable Notification'), '83' => _('Hosts : Disable Notification'), '92' => _('Hosts : Enable Check'), '93' => _('Hosts : Disable Check')], $attrs); $form->setDefaults([$option => null]); $o1 = $form->getElement($option); $o1->setValue(null); $o1->setSelected(null); } $tpl->assign('limit', $limit); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('search', _('Search')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('poller_listing', $centreon->user->access->checkAction('poller_listing')); $tpl->assign('hgStr', _('Hostgroup')); $tpl->assign('form', $renderer->toArray()); $tpl->display('serviceGrid.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/serviceSummary.php
centreon/www/include/monitoring/status/Services/serviceSummary.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 * */ if (! isset($oreon)) { exit(); } include './include/common/autoNumLimit.php'; $sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types']; $order = ! isset($_GET['order']) ? 'ASC' : $_GET['order']; $num = ! isset($_GET['num']) ? 0 : $_GET['num']; $host_search = ! isset($_GET['host_search']) ? 0 : $_GET['host_search']; $search_type_host = ! isset($_GET['search_type_host']) ? 1 : $_GET['search_type_host']; $search_type_service = ! isset($_GET['search_type_service']) ? 1 : $_GET['search_type_service']; $sort_type = ! isset($_GET['sort_type']) ? 'host_name' : $_GET['sort_type']; // Check search value in Host search field if (isset($_GET['host_search'])) { $centreon->historySearch[$url] = $_GET['host_search']; } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once $svc_path . '/serviceSummaryJS.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($svc_path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_types', $sort_types); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('typeDisplay', _('Display')); $tpl->assign('typeDisplay2', _('Display details')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); $aTypeAffichageLevel1 = ['svcOV' => _('Details'), 'svcSum' => _('Summary')]; $aTypeAffichageLevel2 = ['pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')]; // #Toolbar select $lang["lgd_more_actions"] ?> <script type="text/javascript"> p = <?php echo $p; ?>; function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } function displayingLevel1(val) { var sel2 = document.getElementById("typeDisplay2").value; _o = val; if (sel2 != '') { _o += "_" + sel2; } if (val == 'svcOV') { _addrXML = "./include/monitoring/status/Services/xml/serviceGridXML.php"; _addrXSL = "./include/monitoring/status/Services/xsl/serviceGrid.xsl"; } else { _addrXML = "./include/monitoring/status/Services/xml/serviceSummaryXML.php"; _addrXSL = "./include/monitoring/status/Services/xsl/serviceSummary.xsl"; } monitoring_refresh(); } function displayingLevel2(val) { var sel1 = document.getElementById("typeDisplay").value; _o = sel1; if (val != '') { _o += "_" + val; } monitoring_refresh(); } </script> <?php $form->addElement( 'select', 'typeDisplay', _('Display'), $aTypeAffichageLevel1, ['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);'] ); $form->addElement( 'select', 'typeDisplay2', _('Display '), $aTypeAffichageLevel2, ['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);'] ); foreach (['o1', 'o2'] as $option) { $attrs = ['onchange' => "javascript: setO(this.form.elements['{$option}'].value); submit();"]; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), '3' => _('Verification Check'), '4' => _('Verification Check (Forced)'), '70' => _('Services : Acknowledge'), '71' => _('Services : Disacknowledge'), '80' => _('Services : Enable Notification'), '81' => _('Services : Disable Notification'), '90' => _('Services : Enable Check'), '91' => _('Services : Disable Check'), '72' => _('Hosts : Acknowledge'), '73' => _('Hosts : Disacknowledge'), '82' => _('Hosts : Enable Notification'), '83' => _('Hosts : Disable Notification'), '92' => _('Hosts : Enable Check'), '93' => _('Hosts : Disable Check')], $attrs ); $form->setDefaults([$option => null]); $o1 = $form->getElement($option); $o1->setValue(null); } $tpl->assign('limit', $limit); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('search', _('Search')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('poller_listing', $oreon->user->access->checkAction('poller_listing')); $tpl->assign('hgStr', _('Hostgroup')); $tpl->assign('form', $renderer->toArray()); $tpl->display('serviceGrid.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/xml/serviceXML.php
centreon/www/include/monitoring/status/Services/xml/serviceXML.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 configuration. require_once realpath(__DIR__ . '/../../../../../../bootstrap.php'); require_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php'; // Require Specific XML / Ajax Class require_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonInstance.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonCriticality.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonMedia.class.php'; // Require common Files. require_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php'; require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; // Create XML Request Objects CentreonSession::start(); $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); // Get session if (isset($_SESSION['centreon'])) { $centreon = $_SESSION['centreon']; } else { exit; } // Get language $locale = $centreon->user->get_lang(); putenv("LANG={$locale}"); setlocale(LC_ALL, $locale); bindtextdomain('messages', _CENTREON_PATH_ . 'www/locale/'); bind_textdomain_codeset('messages', 'UTF-8'); textdomain('messages'); $criticality = new CentreonCriticality($obj->DB); $instanceObj = new CentreonInstance($obj->DB); $media = new CentreonMedia($obj->DB); if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo 'Bad Session ID'; exit(); } // Set Default Poller $obj->getDefaultFilters(); // Check Arguments From GET tab $o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h'; $p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]); $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); $nc = filter_input(INPUT_GET, 'nc', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $criticalityId = filter_input(INPUT_GET, 'criticality', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $serviceToSearch = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $hostToSearch = isset($_GET['search_host']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search_host']) : ''; $outputToSearch = isset($_GET['search_output']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search_output']) : ''; $sortType = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name'; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; $statusService = isset($_GET['statusService']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['statusService']) : ''; $statusFilter = isset($_GET['statusFilter']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['statusFilter']) : ''; $dateFormat = 'Y/m/d H:i:s'; // if instance, hostgroup or servicegroup values are not set, displaying each active linked resources $instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT); $hostgroups = filter_var($obj->defaultHostgroups ?? 0, FILTER_VALIDATE_INT); $servicegroups = filter_var($obj->defaultServicegroups ?? 0, FILTER_VALIDATE_INT); // Store in session the last type of call $_SESSION['monitoring_service_status'] = $statusService; $_SESSION['monitoring_service_status_filter'] = $statusFilter; // Backup poller selection $obj->setInstanceHistory($instance); // Backup criticality id $obj->setCriticality($criticalityId); // Saving bound values $queryValues = []; // Graphs Tables $graphs = []; $tabOrder = []; $tabOrder['criticality_id'] = ' ORDER BY isnull ' . $order . ', criticality ' . $order . ', h.name, s.description '; $tabOrder['host_name'] = ' ORDER BY h.name ' . $order . ', s.description '; $tabOrder['service_description'] = ' ORDER BY s.description ' . $order . ', h.name'; $tabOrder['current_state'] = ' ORDER BY s.state ' . $order . ', h.name, s.description'; $tabOrder['last_state_change'] = ' ORDER BY s.last_state_change ' . $order . ', h.name, s.description'; $tabOrder['last_hard_state_change'] = ' ORDER by s.last_hard_state_change ' . $order . ', h.name, s.description'; $tabOrder['last_check'] = ' ORDER BY s.last_check ' . $order . ', h.name, s.description'; $tabOrder['current_attempt'] = ' ORDER BY s.check_attempt ' . $order . ', h.name, s.description'; $tabOrder['output'] = ' ORDER BY s.output ' . $order . ', h.name, s.description'; $tabOrder['default'] = $tabOrder['criticality_id']; /** * Analyse if services have graphs by performing a single query. * * @param array $hostServiceIds */ function analyseGraphs(array $hostServiceIds): void { if ($hostServiceIds === []) { return; } global $obj, $graphs; $request = <<<'SQL' SELECT DISTINCT index_data.host_id, index_data.service_id FROM index_data INNER JOIN metrics ON metrics.index_id = index_data.id AND index_data.hidden = '0' WHERE SQL; $whereConditions = null; $index = 0; $valuesToBind = []; foreach ($hostServiceIds as $hostServiceId) { [$hostId, $serviceId] = explode('_', $hostServiceId); if (! empty($whereConditions)) { $whereConditions .= ' OR '; } $whereConditions .= sprintf(' (host_id = :host_id_%d AND service_id = :service_id_%d)', $index, $index); $valuesToBind[$index] = ['host_id' => $hostId, 'service_id' => $serviceId]; $index++; } $request .= $whereConditions; $statement = $obj->DBC->prepare($request); foreach ($valuesToBind as $index => $hostServiceId) { $statement->bindValue(':host_id_' . $index, $hostServiceId['host_id'], PDO::PARAM_INT); $statement->bindValue(':service_id_' . $index, $hostServiceId['service_id'], PDO::PARAM_INT); } $statement->execute(); while ($result = $statement->fetch(PDO::FETCH_ASSOC)) { $hostServiceId = $result['host_id'] . '_' . $result['service_id']; $graphs[$hostServiceId] = true; } } $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, h.name, h.alias, h.address, h.host_id, s.description, s.service_id, s.notes, s.notes_url, s.action_url, s.max_check_attempts, s.icon_image, s.display_name, s.state, s.output as plugin_output, s.state_type, s.check_attempt as current_attempt, s.last_update as status_update_time, s.last_state_change, s.last_hard_state_change, s.last_check, s.next_check, s.notify, s.acknowledged, s.passive_checks, s.active_checks, s.event_handler_enabled, s.flapping, s.scheduled_downtime_depth, s.flap_detection, h.state as host_state, h.acknowledged AS h_acknowledged, h.scheduled_downtime_depth AS h_scheduled_downtime_depth, h.icon_image AS h_icon_images, h.display_name AS h_display_name, h.action_url AS h_action_url, h.notes_url AS h_notes_url, h.notes AS h_notes, h.address, h.passive_checks AS h_passive_checks, h.active_checks AS h_active_checks, i.name as instance_name, cv.value as criticality, cv.value IS NULL as isnull FROM hosts h INNER JOIN instances i ON h.instance_id = i.instance_id INNER JOIN services s ON s.host_id = h.host_id SQL_WRAP; if (! $obj->is_admin) { $request .= <<<SQL INNER JOIN centreon_acl ON centreon_acl.host_id = h.host_id AND centreon_acl.service_id = s.service_id AND group_id IN ({$obj->grouplistStr}) SQL; } if (isset($hostgroups) && $hostgroups != 0) { $request .= <<<'SQL' INNER JOIN hosts_hostgroups hg ON hg.host_id = h.host_id AND hg.hostgroup_id = :hostGroupId INNER JOIN hostgroups hg2 ON hg2.hostgroup_id = hg.hostgroup_id SQL; $queryValues['hostGroupId'] = [PDO::PARAM_INT => $hostgroups]; } if (isset($servicegroups) && $servicegroups != 0) { $request .= <<<'SQL' INNER JOIN services_servicegroups ssg ON ssg.service_id = s.service_id AND ssg.servicegroup_id = :serviceGroupId INNER JOIN servicegroups sg ON sg.servicegroup_id = ssg.servicegroup_id SQL; $queryValues['serviceGroupId'] = [PDO::PARAM_INT => $servicegroups]; } if ($criticalityId) { $request .= <<<'SQL' INNER JOIN customvariables cvs ON cvs.service_id = s.service_id AND cvs.host_id = h.host_id AND cvs.name = 'CRITICALITY_ID' AND cvs.value = :criticalityValue SQL; // the variable bounded to criticalityValue must be an integer. But is inserted in a DB's varchar column $queryValues['criticalityValue'] = [PDO::PARAM_STR => $criticalityId]; } $request .= <<<SQL LEFT JOIN customvariables cv ON ( s.service_id = cv.service_id AND cv.host_id = s.host_id AND cv.name = 'CRITICALITY_LEVEL' ) WHERE s.enabled = 1 AND h.enabled = 1 AND h.name NOT LIKE '\_Module\_BAM%' SQL; if ($hostToSearch) { $request .= <<<'SQL' AND (h.name LIKE :hostToSearch OR h.alias LIKE :hostToSearch OR h.address LIKE :hostToSearch) SQL; $queryValues['hostToSearch'] = [PDO::PARAM_STR => '%' . $hostToSearch . '%']; } if ($serviceToSearch) { $request .= ' AND (s.description LIKE :serviceToSearch OR s.display_name LIKE :serviceToSearch) '; $queryValues['serviceToSearch'] = [PDO::PARAM_STR => '%' . $serviceToSearch . '%']; } if ($outputToSearch) { $request .= ' AND s.output LIKE :outputToSearch '; $queryValues['outputToSearch'] = [PDO::PARAM_STR => '%' . $outputToSearch . '%']; } if (! empty($instance) && $instance != -1) { $request .= ' AND h.instance_id = :instanceId'; $queryValues['instanceId'] = [PDO::PARAM_INT => $instance]; } if ($statusService == 'svc_unhandled') { $request .= <<<'SQL' AND s.state_type = 1 AND s.acknowledged = 0 AND s.scheduled_downtime_depth = 0 AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 SQL; } if ($statusService === 'svc_unhandled' || $statusService === 'svcpb') { switch ($statusFilter) { case 'warning': $request .= ' AND s.state = 1 '; break; case 'critical': $request .= ' AND s.state = 2 '; break; case 'unknown': $request .= ' AND s.state = 3 '; break; default: $request .= ' AND s.state != 0 AND s.state != 4 '; } } elseif ($statusService === 'svc') { switch ($statusFilter) { case 'ok': $request .= ' AND s.state = 0'; break; case 'warning': $request .= ' AND s.state = 1 '; break; case 'critical': $request .= ' AND s.state = 2 '; break; case 'unknown': $request .= ' AND s.state = 3 '; break; case 'pending': $request .= ' AND s.state = 4 '; break; } } // Sort order by $request .= $tabOrder[$sortType] ?? $tabOrder['default']; $request .= ' LIMIT :numLimit, :limit'; $queryValues['numLimit'] = [PDO::PARAM_INT => ($num * $limit)]; $queryValues['limit'] = [PDO::PARAM_INT => $limit]; // Get Pagination Rows $sqlError = false; try { $dbResult = $obj->DBC->prepare($request); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); $numRows = (int) $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn(); } catch (PDOException $e) { $sqlError = true; $numRows = 0; } // Get criticality ids $critRes = $obj->DBC->query( "SELECT value, service_id FROM customvariables WHERE name = 'CRITICALITY_ID' AND service_id IS NOT NULL" ); $criticalityUsed = 0; $critCache = []; if ($critRes->rowCount()) { $criticalityUsed = 1; while ($critRow = $critRes->fetch()) { $critCache[$critRow['service_id']] = $critRow['value']; } } $isHardStateDurationVisible = ! ( $statusService === 'svc' && ($statusFilter === 'ok' || $statusFilter === 'pending') ); /** * Create Buffer */ $obj->XML->startElement('reponse'); $obj->XML->startElement('i'); $obj->XML->writeElement('numrows', $numRows); $obj->XML->writeElement('num', $num); $obj->XML->writeElement('limit', $limit); $obj->XML->writeElement('p', $p); $obj->XML->writeElement('nc', $nc); $obj->XML->writeElement('o', $o); $obj->XML->writeElement('hard_state_label', _('Hard State Duration')); $obj->XML->writeElement('http_link', _('HTTP Link')); $obj->XML->writeElement('http_action_link', _('HTTP Action Link')); $obj->XML->writeElement('host_currently_downtime', _('Host is currently on downtime')); $obj->XML->writeElement('problem_ack', _('Problem has been acknowledged')); $obj->XML->writeElement('host_passive_mode', _('This host is only checked in passive mode')); $obj->XML->writeElement('host_never_checked', _('This host is never checked')); $obj->XML->writeElement('service_currently_downtime', _('Service is currently on Downtime')); $obj->XML->writeElement('service_passive_mode', _('This service is only checked in passive mode')); $obj->XML->writeElement('service_not_active_not_passive', _('This service is neither active nor passive')); $obj->XML->writeElement('service_flapping', _('This Service is flapping')); $obj->XML->writeElement('notif_disabled', _('Notification is disabled')); $obj->XML->writeElement('use_criticality', $criticalityUsed); $obj->XML->writeElement('use_hard_state_duration', $isHardStateDurationVisible ? 1 : 0); $obj->XML->endElement(); $host_prev = ''; $ct = 0; $flag = 0; if (! $sqlError) { $allResults = []; $hostServiceIdsToAnalyse = []; // We get the host and service IDs to see if they have graphs or not while ($result = $dbResult->fetch()) { $hostId = (int) $result['host_id']; $serviceId = (int) $result['service_id']; $graphs[$hostId . '_' . $serviceId] = false; $hostServiceIdsToAnalyse[] = $hostId . '_' . $serviceId; $allResults[] = $result; } analyseGraphs($hostServiceIdsToAnalyse); foreach ($allResults as $data) { $hostId = (int) $data['host_id']; $serviceId = (int) $data['service_id']; $passive = 0; $active = 1; $last_check = ' '; $duration = ' '; // Split the plugin_output $outputLines = explode("\n", $data['plugin_output']); $pluginShortOuput = $outputLines[0]; if ($data['last_state_change'] > 0 && time() > $data['last_state_change']) { $duration = CentreonDuration::toString(time() - $data['last_state_change']); } elseif ($data['last_state_change'] > 0) { $duration = ' - '; } $hard_duration = ' N/S '; if (($data['last_hard_state_change'] > 0) && ($data['last_hard_state_change'] >= $data['last_state_change'])) { $hard_duration = CentreonDuration::toString(time() - $data['last_hard_state_change']); } $class = null; if ($data['scheduled_downtime_depth'] > 0) { $class = 'line_downtime'; } elseif ($data['state'] == 2) { $class = $data['acknowledged'] == 1 ? 'line_ack' : 'list_down'; } elseif ($data['acknowledged'] == 1) { $class = 'line_ack'; } $obj->XML->startElement('l'); $trClass = $obj->getNextLineClass(); if (isset($class)) { $trClass = $class; } $obj->XML->writeAttribute('class', $trClass); $obj->XML->writeElement('o', $ct++); $isMeta = 0; $data['host_display_name'] = $data['name']; if (! strncmp($data['name'], '_Module_Meta', strlen('_Module_Meta'))) { $isMeta = 1; $data['host_display_name'] = 'Meta'; $data['host_state'] = '0'; } if ($host_prev == $data['name']) { $obj->XML->writeElement('hc', 'transparent'); $obj->XML->writeElement('isMeta', $isMeta); $obj->XML->writeElement('hdn', $data['host_display_name']); $obj->XML->startElement('hn'); $obj->XML->writeAttribute('none', '1'); $obj->XML->text(CentreonUtils::escapeSecure(urlencode($data['name']))); $obj->XML->endElement(); $obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($data['name']))); $obj->XML->writeElement('hid', $data['host_id']); } else { $host_prev = $data['name']; if ($data['h_scheduled_downtime_depth'] == 0) { $obj->XML->writeElement('hc', $obj->colorHostInService[$data['host_state']]); } else { $obj->XML->writeElement('hc', $obj->general_opt['color_downtime']); } $obj->XML->writeElement('isMeta', $isMeta); $obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($data['name']))); $obj->XML->writeElement('hdn', $data['host_display_name']); $obj->XML->startElement('hn'); $obj->XML->writeAttribute('none', '0'); $obj->XML->text(CentreonUtils::escapeSecure(urlencode($data['name'])), true, false); $obj->XML->endElement(); $hostNotesUrl = 'none'; if ($data['h_notes_url']) { $hostNotesUrl = str_replace('$HOSTNAME$', $data['name'], $data['h_notes_url']); $hostNotesUrl = str_replace('$HOSTALIAS$', $data['alias'], $hostNotesUrl); $hostNotesUrl = str_replace('$HOSTADDRESS$', $data['address'], $hostNotesUrl); $hostNotesUrl = str_replace('$INSTANCENAME$', $data['instance_name'], $hostNotesUrl); $hostNotesUrl = str_replace('$HOSTSTATE$', $obj->statusHost[$data['host_state']], $hostNotesUrl); $hostNotesUrl = str_replace('$HOSTSTATEID$', $data['host_state'], $hostNotesUrl); $hostNotesUrl = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $hostNotesUrl ); } $obj->XML->writeElement( 'hnu', CentreonUtils::escapeSecure($obj->hostObj->replaceMacroInString($data['name'], $hostNotesUrl)) ); $hostActionUrl = 'none'; if ($data['h_action_url']) { $hostActionUrl = str_replace('$HOSTNAME$', $data['name'], $data['h_action_url']); $hostActionUrl = str_replace('$HOSTALIAS$', $data['alias'], $hostActionUrl); $hostActionUrl = str_replace('$HOSTADDRESS$', $data['address'], $hostActionUrl); $hostActionUrl = str_replace('$INSTANCENAME$', $data['instance_name'], $hostActionUrl); $hostActionUrl = str_replace('$HOSTSTATE$', $obj->statusHost[$data['host_state']], $hostActionUrl); $hostActionUrl = str_replace('$HOSTSTATEID$', $data['host_state'], $hostActionUrl); $hostActionUrl = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $hostActionUrl ); } $obj->XML->writeElement( 'hau', CentreonUtils::escapeSecure($obj->hostObj->replaceMacroInString($data['host_id'], $hostActionUrl)) ); $obj->XML->writeElement('hnn', CentreonUtils::escapeSecure($data['h_notes'])); $obj->XML->writeElement('hico', $data['h_icon_images']); $obj->XML->writeElement('hip', CentreonUtils::escapeSecure($data['address'])); $obj->XML->writeElement('hdtm', $data['h_scheduled_downtime_depth']); $obj->XML->writeElement( 'hdtmXml', './include/monitoring/downtime/xml/broker/makeXMLForDowntime.php?hid=' . $data['host_id'] ); $obj->XML->writeElement('hdtmXsl', './include/monitoring/downtime/xsl/popupForDowntime.xsl'); $obj->XML->writeElement( 'hackXml', './include/monitoring/acknowlegement/xml/broker/makeXMLForAck.php?hid=' . $data['host_id'] ); $obj->XML->writeElement('hackXsl', './include/monitoring/acknowlegement/xsl/popupForAck.xsl'); $obj->XML->writeElement('hid', $data['host_id']); } $obj->XML->writeElement('hs', $data['host_state']); // Add possibility to use display name if ($isMeta) { $obj->XML->writeElement('sdn', CentreonUtils::escapeSecure($data['display_name']), false); } else { $obj->XML->writeElement('sdn', CentreonUtils::escapeSecure($data['description']), false); } $obj->XML->writeElement('sd', CentreonUtils::escapeSecure($data['description']), false); $obj->XML->writeElement('sico', $data['icon_image']); $obj->XML->writeElement('sdl', CentreonUtils::escapeSecure(urlencode($data['description']))); $obj->XML->writeElement('svc_id', $data['service_id']); $obj->XML->writeElement('sc', $obj->colorService[$data['state']]); $obj->XML->writeElement('cs', _($obj->statusService[$data['state']]), false); $obj->XML->writeElement('ssc', $data['state']); $obj->XML->writeElement('po', CentreonUtils::escapeSecure($pluginShortOuput)); $obj->XML->writeElement( 'ca', $data['current_attempt'] . '/' . $data['max_check_attempts'] . ' (' . $obj->stateType[$data['state_type']] . ')' ); if (isset($data['criticality']) && $data['criticality'] != '' && isset($critCache[$data['service_id']])) { $obj->XML->writeElement('hci', 1); // has criticality $critData = $criticality->getData($critCache[$data['service_id']], true); $obj->XML->writeElement('ci', $media->getFilename($critData['icon_id'])); $obj->XML->writeElement('cih', CentreonUtils::escapeSecure($critData['name'])); } else { $obj->XML->writeElement('hci', 0); // has no criticality } $obj->XML->writeElement('ne', $data['notify']); $obj->XML->writeElement('pa', $data['acknowledged']); $obj->XML->writeElement('pc', $data['passive_checks']); $obj->XML->writeElement('ac', $data['active_checks']); $obj->XML->writeElement('eh', $data['event_handler_enabled']); $obj->XML->writeElement('is', $data['flapping']); $obj->XML->writeElement('dtm', $data['scheduled_downtime_depth']); $obj->XML->writeElement( 'dtmXml', './include/monitoring/downtime/xml/broker/makeXMLForDowntime.php?hid=' . $data['host_id'] . '&svc_id=' . $data['service_id'] ); $obj->XML->writeElement('dtmXsl', './include/monitoring/downtime/xsl/popupForDowntime.xsl'); $obj->XML->writeElement( 'ackXml', './include/monitoring/acknowlegement/xml/broker/makeXMLForAck.php?hid=' . $data['host_id'] . '&svc_id=' . $data['service_id'] ); $obj->XML->writeElement('ackXsl', './include/monitoring/acknowlegement/xsl/popupForAck.xsl'); if ($data['notes'] != '') { $data['notes'] = str_replace('$SERVICEDESC$', $data['description'], $data['notes']); $data['notes'] = str_replace('$HOSTNAME$', $data['name'], $data['notes']); if (isset($data['alias']) && $data['alias']) { $data['notes'] = str_replace('$HOSTALIAS$', $data['alias'], $data['notes']); } if (isset($data['address']) && $data['address']) { $data['notes'] = str_replace('$HOSTADDRESS$', $data['address'], $data['notes']); } if (isset($data['instance_name']) && $data['instance_name']) { $data['notes'] = str_replace('$INSTANCENAME$', $data['instance_name'], $data['notes']); $data['notes'] = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $data['notes'] ); } $obj->XML->writeElement('snn', CentreonUtils::escapeSecure($data['notes'])); } else { $obj->XML->writeElement('snn', 'none'); } if ($data['notes_url'] != '') { $data['notes_url'] = str_replace('$SERVICEDESC$', $data['description'], $data['notes_url']); $data['notes_url'] = str_replace('$SERVICESTATEID$', $data['state'], $data['notes_url']); $data['notes_url'] = str_replace( '$SERVICESTATE$', $obj->statusService[$data['state']], $data['notes_url'] ); $data['notes_url'] = str_replace('$HOSTNAME$', $data['name'], $data['notes_url']); if (isset($data['alias']) && $data['alias']) { $data['notes_url'] = str_replace('$HOSTALIAS$', $data['alias'], $data['notes_url']); } if (isset($data['address']) && $data['address']) { $data['notes_url'] = str_replace('$HOSTADDRESS$', $data['address'], $data['notes_url']); } if (isset($data['instance_name']) && $data['instance_name']) { $data['notes_url'] = str_replace('$INSTANCENAME$', $data['instance_name'], $data['notes_url']); $data['notes_url'] = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $data['notes_url'] ); } $obj->XML->writeElement( 'snu', CentreonUtils::escapeSecure( $obj->serviceObj->replaceMacroInString($data['service_id'], $data['notes_url']) ) ); } else { $obj->XML->writeElement('snu', 'none'); } if ($data['action_url'] != '') { $data['action_url'] = str_replace('$SERVICEDESC$', $data['description'], $data['action_url']); $data['action_url'] = str_replace('$SERVICESTATEID$', $data['state'], $data['action_url']); $data['action_url'] = str_replace( '$SERVICESTATE$', $obj->statusService[$data['state']], $data['action_url'] ); $data['action_url'] = str_replace('$HOSTNAME$', $data['name'], $data['action_url']); if (isset($data['alias']) && $data['alias']) { $data['action_url'] = str_replace('$HOSTALIAS$', $data['alias'], $data['action_url']); } if (isset($data['address']) && $data['address']) { $data['action_url'] = str_replace('$HOSTADDRESS$', $data['address'], $data['action_url']); } if (isset($data['instance_name']) && $data['instance_name']) { $data['action_url'] = str_replace('$INSTANCENAME$', $data['instance_name'], $data['action_url']); $data['action_url'] = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $data['action_url'] ); } $obj->XML->writeElement( 'sau', CentreonUtils::escapeSecure( $obj->serviceObj->replaceMacroInString($data['service_id'], $data['action_url']) ) ); } else { $obj->XML->writeElement('sau', 'none'); } if ($data['notes'] != '') { $data['notes'] = str_replace('$SERVICEDESC$', $data['description'], $data['notes']); $data['notes'] = str_replace('$HOSTNAME$', $data['name'], $data['notes']); if (isset($data['alias']) && $data['alias']) { $data['notes'] = str_replace('$HOSTALIAS$', $data['alias'], $data['notes']); } if (isset($data['address']) && $data['address']) { $data['notes'] = str_replace('$HOSTADDRESS$', $data['address'], $data['notes']); } $obj->XML->writeElement('sn', CentreonUtils::escapeSecure($data['notes'])); } else { $obj->XML->writeElement('sn', 'none'); } $obj->XML->writeElement('fd', $data['flap_detection']); $obj->XML->writeElement('ha', $data['h_acknowledged']); $obj->XML->writeElement('hae', $data['h_active_checks']); $obj->XML->writeElement('hpe', $data['h_passive_checks']); $obj->XML->writeElement('nc', $obj->GMT->getDate($dateFormat, $data['next_check'])); if ($data['last_check'] != 0) { $obj->XML->writeElement('lc', CentreonDuration::toString(time() - $data['last_check'])); } else { $obj->XML->writeElement('lc', 'N/A'); } $obj->XML->writeElement('d', $duration); $obj->XML->writeElement('rd', (time() - $data['last_state_change'])); $obj->XML->writeElement('last_hard_state_change', $hard_duration); // Get Service Graph index $obj->XML->writeElement('hasGraph', $graphs[$hostId . '_' . $serviceId] ? '1' : '0'); $obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18)); $obj->XML->endElement(); } $dbResult->closeCursor(); } unset($data, $host_status); if (! $ct) { $obj->XML->writeElement('infos', 'none'); } $obj->XML->writeElement('sid', $obj->session_id); $obj->XML->endElement(); // Send Header $obj->header(); // Send XML $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/xml/serviceSummaryXML.php
centreon/www/include/monitoring/status/Services/xml/serviceSummaryXML.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 * */ ini_set('display_errors', 'Off'); require_once realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; // Create XML Request Objects CentreonSession::start(1); $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo 'Bad Session ID'; exit(); } // Set Default Poller $obj->getDefaultFilters(); $centreon = $_SESSION['centreon']; /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); // Check Arguments From GET tab $o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h'; $p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]); $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); // if instance value is not set, displaying all active pollers linked resources $instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT); $hostgroups = filter_var($obj->defaultHostgroups ?? 0, FILTER_VALIDATE_INT); $search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $sortType = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name'; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; // Backup poller selection $obj->setInstanceHistory($instance); $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); $service = []; $host_status = []; $service_status = []; $host_services = []; $metaService_status = []; $tab_host_service = []; $tabIcone = []; // saving bound values $queryValues = []; /** * Get status */ $rq1 = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, hosts.name, hosts.state, hosts.icon_image, hosts.host_id FROM hosts '; if ($hostgroups) { $rq1 .= ', hosts_hostgroups hg, hostgroups hg2 '; } if (! $obj->is_admin) { $rq1 .= ', centreon_acl '; } $rq1 .= "WHERE hosts.name NOT LIKE '\_Module\_%' AND hosts.enabled = 1 " . $obj->access->queryBuilder('AND', 'hosts.host_id', 'centreon_acl.host_id') . ' ' . $obj->access->queryBuilder('AND', 'group_id', $obj->grouplistStr) . ' '; if (str_ends_with($o, '_pb') || str_ends_with($o, '_ack_0')) { $rq1 .= 'AND hosts.host_id IN ( ' . 'SELECT s.host_id FROM services s ' . 'WHERE s.state != 0 ' . 'AND s.state != 4 ' . 'AND s.enabled = 1) '; } elseif (str_ends_with($o, '_ack_1')) { $rq1 .= 'AND hosts.host_id IN ( ' . 'SELECT s.host_id FROM services s ' . "WHERE s.acknowledged = '1' " . 'AND s.enabled = 1) '; } if ($search != '') { $rq1 .= 'AND hosts.name like :search '; $queryValues['search'] = [PDO::PARAM_STR => '%' . $search . '%']; } if ($instance != -1) { $rq1 .= 'AND hosts.instance_id = :instance '; $queryValues['instance'] = [PDO::PARAM_INT => $instance]; } if ($hostgroups) { $rq1 .= ' AND hosts.host_id = hg.host_id AND hg.hostgroup_id = :hostGroup AND hg.hostgroup_id = hg2.hostgroup_id '; $queryValues['hostGroup'] = [PDO::PARAM_INT => $hostgroups]; } // Sort order switch ($sortType) { case 'current_state': $rq1 .= 'ORDER BY hosts.state ' . $order . ',hosts.name '; break; default: $rq1 .= 'ORDER BY hosts.name ' . $order . ' '; break; } // Limit $rq1 .= ' LIMIT :numLimit, :limit'; $queryValues['numLimit'] = [PDO::PARAM_INT => ($num * $limit)]; $queryValues['limit'] = [PDO::PARAM_INT => $limit]; $dbResult = $obj->DBC->prepare($rq1); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); $numRows = (int) $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn(); // Info / Pagination $obj->XML->startElement('reponse'); $obj->XML->startElement('i'); $obj->XML->writeElement('numrows', $numRows); $obj->XML->writeElement('num', $num); $obj->XML->writeElement('limit', $limit); $obj->XML->writeElement('p', $p); $obj->XML->endElement(); $buildParameter = function (string $id, string $name) { return [ 'id' => $id, 'name' => $name, ]; }; $buildServicesUri = function (string $hostname, array $statuses) use ($resourceController, $buildParameter) { return $resourceController->buildListingUri([ 'filter' => json_encode([ 'criterias' => [ 'search' => 'h.name:^' . $hostname . '$', 'resourceTypes' => [$buildParameter('service', 'Service')], 'statuses' => $statuses, ], ]), ]); }; $okStatus = $buildParameter('OK', 'Ok'); $warningStatus = $buildParameter('WARNING', 'Warning'); $criticalStatus = $buildParameter('CRITICAL', 'Critical'); $unknownStatus = $buildParameter('UNKNOWN', 'Unknown'); $pendingStatus = $buildParameter('PENDING', 'Pending'); $ct = 0; $tabFinal = []; while ($ndo = $dbResult->fetch()) { $tabFinal[$ndo['name']]['nb_service_k'] = 0; $tabFinal[$ndo['name']]['host_id'] = $ndo['host_id']; if (! str_starts_with($o, 'svcSum')) { $tabFinal[$ndo['name']]['nb_service_k'] = $obj->monObj->getServiceStatusCount( $ndo['name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_OK ); } $tabFinal[$ndo['name']]['nb_service_w'] = 0 + $obj->monObj->getServiceStatusCount( $ndo['name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_WARNING ); $tabFinal[$ndo['name']]['nb_service_c'] = 0 + $obj->monObj->getServiceStatusCount( $ndo['name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_CRITICAL ); $tabFinal[$ndo['name']]['nb_service_u'] = 0 + $obj->monObj->getServiceStatusCount( $ndo['name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_UNKNOWN ); $tabFinal[$ndo['name']]['nb_service_p'] = 0 + $obj->monObj->getServiceStatusCount( $ndo['name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_PENDING ); $tabFinal[$ndo['name']]['cs'] = $ndo['state']; $tabIcone[$ndo['name']] = isset($ndo['icon_image']) && $ndo['icon_image'] != '' ? $ndo['icon_image'] : 'none'; } foreach ($tabFinal as $host_name => $tab) { $obj->XML->startElement('l'); $obj->XML->writeAttribute('class', $obj->getNextLineClass()); $obj->XML->writeElement('o', $ct++); $obj->XML->writeElement('hn', CentreonUtils::escapeSecure($host_name), false); $obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($host_name))); $obj->XML->writeElement('hid', $tab['host_id'], false); $obj->XML->writeElement( 'h_details_uri', $useDeprecatedPages ? 'main.php?p=20202&o=hd&host_name=' . $host_name : $resourceController->buildHostDetailsUri($tab['host_id']) ); $serviceListingDeprecatedUri = 'main.php?p=20201&o=svc&host_search=' . $host_name; $obj->XML->writeElement( 's_listing_uri', $useDeprecatedPages ? 'main.php?o=svc&p=20201&statusFilter=&host_search=' . $host_name : $resourceController->buildListingUri([ 'filter' => json_encode([ 'criterias' => [ 'search' => 'h.name:^' . $host_name . '$', ], ]), ]) ); $obj->XML->writeElement('ico', $tabIcone[$host_name]); $obj->XML->writeElement('hs', _($obj->statusHost[$tab['cs']]), false); $obj->XML->writeElement('hc', $obj->colorHost[$tab['cs']]); $obj->XML->writeElement('sc', $tab['nb_service_c']); $obj->XML->writeElement('scc', $obj->colorService[2]); $obj->XML->writeElement('sw', $tab['nb_service_w']); $obj->XML->writeElement('swc', $obj->colorService[1]); $obj->XML->writeElement('su', $tab['nb_service_u']); $obj->XML->writeElement('suc', $obj->colorService[3]); $obj->XML->writeElement('sk', $tab['nb_service_k']); $obj->XML->writeElement('skc', $obj->colorService[0]); $obj->XML->writeElement('sp', $tab['nb_service_p']); $obj->XML->writeElement('spc', $obj->colorService[4]); $obj->XML->writeElement( 's_listing_ok', $useDeprecatedPages ? $serviceListingDeprecatedUri . '&statusFilter=ok' : $buildServicesUri($host_name, [$okStatus]) ); $obj->XML->writeElement( 's_listing_warning', $useDeprecatedPages ? $serviceListingDeprecatedUri . '&statusFilter=warning' : $buildServicesUri($host_name, [$warningStatus]) ); $obj->XML->writeElement( 's_listing_critical', $useDeprecatedPages ? $serviceListingDeprecatedUri . '&statusFilter=critical' : $buildServicesUri($host_name, [$criticalStatus]) ); $obj->XML->writeElement( 's_listing_unknown', $useDeprecatedPages ? $serviceListingDeprecatedUri . '&statusFilter=unknown' : $buildServicesUri($host_name, [$unknownStatus]) ); $obj->XML->writeElement( 's_listing_pending', $useDeprecatedPages ? $serviceListingDeprecatedUri . '&statusFilter=pending' : $buildServicesUri($host_name, [$pendingStatus]) ); $obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18)); $obj->XML->writeElement('viewIcon', returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18)); $obj->XML->endElement(); } if (! $ct) { $obj->XML->writeElement('infos', 'none'); } $obj->XML->endElement(); // Send Header $obj->header(); // Send XML $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/xml/makeXMLForOneHost.php
centreon/www/include/monitoring/status/Services/xml/makeXMLForOneHost.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 Centreon Config file */ require_once realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once $centreon_path . 'www/class/centreonUtils.class.php'; include_once $centreon_path . 'www/class/centreonACL.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php'; // Create XML Request Objects CentreonSession::start(1); $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); // Manage Session $centreon = $_SESSION['centreon']; // Check Security if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo _('Bad Session ID'); exit(); } // Enable Lang Object $centreonlang = new CentreonLang(_CENTREON_PATH_, $centreon); $centreonlang->bindLang(); // Check Arguments From GET tab $hostId = filter_input(INPUT_GET, 'host_id', FILTER_VALIDATE_INT, ['options' => ['default' => false]]); if ($hostId === false) { echo _('Bad host ID'); exit(); } // Check ACL if user is not admin $isAdmin = $centreon->user->admin; if (! $isAdmin) { $userId = $centreon->user->user_id; $acl = new CentreonACL($userId, $isAdmin); if (! $acl->checkHost($hostId)) { echo _("You don't have access to this resource"); exit(); } } /** * Get Host status */ $rq1 = 'SELECT 1 AS REALTIME, h.state, h.address, h.name, h.alias, i.name AS poller, h.perfdata, h.check_attempt, h.state_type, h.last_check, h.next_check, h.latency, h.execution_time, h.last_state_change, h.last_notification, h.next_host_notification, h.last_hard_state_change, h.last_hard_state, h.last_time_up, h.last_time_down, h.last_time_unreachable, h.notification_number, h.scheduled_downtime_depth, h.output, h.notes, h.notify, h.event_handler_enabled, h.icon_image, h.timezone FROM hosts h, instances i WHERE h.host_id = :hostId AND h.instance_id = i.instance_id LIMIT 1'; $dbResult = $obj->DBC->prepare($rq1); $dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT); $dbResult->execute(); // Start Buffer $obj->XML->startElement('reponse'); if ($data = $dbResult->fetch()) { // Split the plugin_output $outputLines = explode("\n", $data['output']); $pluginShortOuput = $outputLines[0]; $duration = ''; if ($data['last_state_change'] > 0) { $duration = CentreonDuration::toString(time() - $data['last_state_change']); } $data['icon_image'] = $data['icon_image'] == '' ? './img/icons/host.png' : './img/media/' . $data['icon_image']; $last_notification = 'N/A'; if ($data['last_notification'] > 0) { $last_notification = $data['last_notification']; } $next_notification = 'N/A'; if ($data['next_host_notification'] > 0) { $next_notification = $data['next_host_notification']; } $obj->XML->writeElement('hostname', CentreonUtils::escapeSecure($data['name']), false); $obj->XML->writeElement('hostalias', CentreonUtils::escapeSecure($data['alias']), false); $obj->XML->writeElement('address', CentreonUtils::escapeSecure($data['address'])); $obj->XML->writeElement('poller_name', _('Polling instance'), 0); $obj->XML->writeElement('poller', $data['poller']); $obj->XML->writeElement('color', $obj->backgroundHost[$data['state']]); $obj->XML->startElement('current_state'); $obj->XML->writeAttribute('color', $obj->colorHost[$data['state']]); $obj->XML->text(_($obj->statusHost[$data['state']]), false); $obj->XML->endElement(); $obj->XML->writeElement('current_state_name', _('Host Status'), 0); $obj->XML->startElement('plugin_output'); $obj->XML->writeAttribute('name', _('Status Information')); $obj->XML->text(CentreonUtils::escapeSecure($pluginShortOuput), 0); $obj->XML->endElement(); $obj->XML->startElement('current_attempt'); $obj->XML->writeAttribute('name', _('Current Attempt')); $obj->XML->text($data['check_attempt']); $obj->XML->endElement(); $obj->XML->writeElement('state_type', $obj->stateTypeFull[$data['state_type']]); $obj->XML->writeElement('state_type_name', _('State Type'), 0); $obj->XML->writeElement('last_check', $data['last_check']); $obj->XML->writeElement('last_check_name', _('Last Check'), 0); $obj->XML->writeElement('last_state_change', $data['last_state_change']); $obj->XML->writeElement('last_state_change_name', _('Last State Change'), 0); $obj->XML->writeElement('duration', $duration); $obj->XML->writeElement('duration_name', _('Current State Duration'), 0); $obj->XML->writeElement('last_notification', $last_notification); $obj->XML->writeElement('last_notification_name', _('Last Notification'), 0); $obj->XML->writeElement('current_notification_number', $data['notification_number']); $obj->XML->writeElement('current_notification_number_name', _('Current Notification Number'), 0); $obj->XML->writeElement('is_downtime', ($data['scheduled_downtime_depth'] > 0 ? $obj->en[1] : $obj->en[0])); $obj->XML->writeElement('is_downtime_name', _('In Scheduled Downtime?'), 0); $obj->XML->writeElement('last_update', time()); $obj->XML->writeElement('last_update_name', _('Last Update'), 0); $obj->XML->writeElement('ico', $data['icon_image']); $obj->XML->writeElement('timezone_name', _('Timezone')); $obj->XML->writeElement('timezone', str_replace(':', '', $data['timezone'])); // Last State Info if ($data['state'] == 0) { $status = _('DOWN'); $status_date = 0; if (isset($data['last_time_down']) && $status_date < $data['last_time_down']) { $status_date = $data['last_time_down']; $status = _('DOWN'); } if (isset($data['last_time_unreachable']) && $status_date < $data['last_time_unreachable']) { $status_date = $data['last_time_unreachable']; $status = _('UNREACHABLE'); } } else { $status = _('OK'); $status_date = 0; if ($data['last_time_up']) { $status_date = $data['last_time_up']; } } if ($status_date == 0) { $status_date = '-'; } $obj->XML->writeElement('last_time_name', _('Last time in '), 0); $obj->XML->writeElement('last_time', $status_date, 0); $obj->XML->writeElement('last_time_status', $status, 0); $obj->XML->startElement('notes'); $obj->XML->writeAttribute('name', _('Notes')); $obj->XML->text(CentreonUtils::escapeSecure($data['notes'])); $obj->XML->endElement(); } else { $obj->XML->writeElement('infos', 'none'); } $dbResult->closeCursor(); // Translations $obj->XML->writeElement('tr1', _('Check information'), 0); $obj->XML->writeElement('tr2', _('Notification information'), 0); $obj->XML->writeElement('tr3', _('Last Status Change'), 0); $obj->XML->writeElement('tr4', _('Extended information'), 0); $obj->XML->writeElement('tr5', _('Status Information'), 0); // End buffer $obj->XML->endElement(); // Send Header $obj->header(); // Send XML $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/xml/makeXMLForOneService.php
centreon/www/include/monitoring/status/Services/xml/makeXMLForOneService.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 Centreon Config file */ require_once realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once $centreon_path . 'www/class/centreonUtils.class.php'; include_once $centreon_path . 'www/class/centreonACL.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php'; // Create XML Request Objects CentreonSession::start(1); $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); // Manage Session $centreon = $_SESSION['centreon']; // Check Security if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo _('Bad Session ID'); exit(); } // Enable Lang Object $centreonlang = new CentreonLang(_CENTREON_PATH_, $centreon); $centreonlang->bindLang(); // Check Arguments From GET tab $svcId = isset($_GET['svc_id']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['svc_id']) : 0; // splitting the host/service combination if (! empty($svcId)) { $tab = preg_split('/\_/', $svcId); } // checking splitted values consistency $hostId = filter_var($tab[0] ?? null, FILTER_VALIDATE_INT); $serviceId = filter_var($tab[1] ?? null, FILTER_VALIDATE_INT); if ($hostId === false || $serviceId === false) { echo _('Bad service ID'); exit(); } // Check if the user is admin or not $isAdmin = $centreon->user->admin; if (! $isAdmin) { $userId = $centreon->user->user_id; $acl = new CentreonACL($userId, $isAdmin); if (! $acl->checkService($serviceId)) { echo _("You don't have access to this resource"); exit(); } } // Get Service status $rq1 = 'SELECT s.state, h.name, s.description, s.last_check, s.next_check, s.last_state_change, s.last_notification, s.last_hard_state_change, s.last_hard_state, s.latency, s.last_time_ok, s.last_time_critical, s.last_time_unknown, s.last_time_warning, s.notification_number, s.scheduled_downtime_depth, s.output, s.notes, ROUND(s.percent_state_change) as percent_state_change, s.notify, s.perfdata, s.state_type, s.execution_time, s.event_handler_enabled, s.icon_image, s.display_name FROM hosts h, services s WHERE s.host_id = h.host_id AND s.host_id = :hostId AND service_id = :serviceId LIMIT 1'; $dbResult = $obj->DBC->prepare($rq1); $dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT); $dbResult->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $dbResult->execute(); // Init Buffer $obj->XML->startElement('reponse'); if ($data = $dbResult->fetch()) { // Split the plugin_output $outputLines = preg_split('/<br \/>|<br>|\\\n|\x0A|\x0D\x0A|\n/', $data['output']); $pluginShortOuput = strlen($outputLines[0]) > 100 ? sprintf('%.100s', $outputLines[0]) . '...' : $outputLines[0]; $longOutput = []; if (isset($outputLines[1])) { for ($x = 1; isset($outputLines[$x]) && $x < 5; $x++) { $longOutput[] = $outputLines[$x]; } if (isset($outputLines[5])) { $longOutput[] = '...'; } } $obj->XML->writeElement('svc_name', CentreonUtils::escapeSecure($data['description']), false); $data['icon_image'] = $data['icon_image'] == '' ? './img/icons/service.png' : './img/media/' . $data['icon_image']; $duration = ''; if ($data['last_state_change'] > 0) { $duration = CentreonDuration::toString(time() - $data['last_state_change']); } $last_notification = 'N/A'; if ($data['last_notification'] > 0) { $last_notification = $data['last_notification']; } if ($data['last_check'] == 0) { $data['last_check'] = _('N/A'); } if ($data['name'] == '_Module_Meta') { $hostname = _('Meta service'); $service_desc = $data['display_name']; } else { $hostname = $data['name']; $service_desc = $data['description']; } $obj->XML->writeElement('service_description', CentreonUtils::escapeSecure($service_desc), false); $obj->XML->writeElement('hostname', CentreonUtils::escapeSecure($hostname), false); $obj->XML->writeElement('color', $obj->backgroundService[$data['state']]); $obj->XML->startElement('current_state'); $obj->XML->writeAttribute('color', $obj->colorService[$data['state']]); $obj->XML->text(_($obj->statusService[$data['state']]), false); $obj->XML->endElement(); $obj->XML->writeElement('current_state_name', _('Host Status'), 0); $obj->XML->startElement('plugin_output'); $obj->XML->writeAttribute('name', _('Status Information')); $obj->XML->text(CentreonUtils::escapeSecure($pluginShortOuput), 0); $obj->XML->endElement(); // Long Output $obj->XML->writeElement('long_name', _('Extended Status Information'), 0); foreach ($longOutput as $val) { if ($val != '') { if (strlen($val) > 100) { $val = sprintf('%.100s', $val) . '...'; } $obj->XML->startElement('long_output_data'); $obj->XML->writeElement('lo_data', $val); $obj->XML->endElement(); } } $tab_perf = preg_split("/\ /", $data['perfdata']); $perf_data = array_slice($tab_perf, 0, 4); if (count($tab_perf) > 5) { $perf_data[5] = '...'; } foreach ($perf_data as $val) { $obj->XML->startElement('performance_data'); $obj->XML->writeElement('perf_data', CentreonUtils::escapeSecure($val)); $obj->XML->endElement(); } $obj->XML->writeElement('performance_data_name', _('Performance Data'), 0); $obj->XML->writeElement('state_type', $obj->stateTypeFull[$data['state_type']]); $obj->XML->writeElement('state_type_name', _('State Type'), 0); $obj->XML->writeElement('last_check', $data['last_check']); $obj->XML->writeElement('last_check_name', _('Last Check'), 0); $obj->XML->writeElement('next_check', $data['next_check']); $obj->XML->writeElement('next_check_name', _('Next Check'), 0); $obj->XML->writeElement('check_latency', $data['latency']); $obj->XML->writeElement('check_latency_name', _('Latency'), 0); $obj->XML->writeElement('check_execution_time', $data['execution_time']); $obj->XML->writeElement('check_execution_time_name', _('Execution Time'), 0); $obj->XML->writeElement('last_state_change', $data['last_state_change']); $obj->XML->writeElement('last_state_change_name', _('Last State Change'), 0); $obj->XML->writeElement('duration', $duration); $obj->XML->writeElement('duration_name', _('Current State Duration'), 0); $obj->XML->writeElement('last_notification', $last_notification); $obj->XML->writeElement('last_notification_name', _('Last Notification'), 0); $obj->XML->writeElement('current_notification_number', $data['notification_number']); $obj->XML->writeElement('current_notification_number_name', _('Current Notification Number'), 0); $obj->XML->writeElement('is_downtime', ($data['scheduled_downtime_depth'] ? $obj->en['1'] : $obj->en['0'])); $obj->XML->writeElement('is_downtime_name', _('In Scheduled Downtime?'), 0); $obj->XML->writeElement('ico', $data['icon_image']); // Last State Info if ($data['state'] == 0) { $status = ''; $status_date = 0; if (isset($data['last_time_critical']) && $status_date < $data['last_time_critical']) { $status_date = $data['last_time_critical']; $status = _('CRITICAL'); } if (isset($data['last_time_warning']) && $status_date < $data['last_time_warning']) { $status_date = $data['last_time_warning']; $status = _('WARNING'); } if (isset($data['last_time_unknown']) && $status_date < $data['last_time_unknown']) { $status_date = $data['last_time_unknown']; $status = _('UNKNOWN'); } } else { $status = _('OK'); $status_date = 0; if ($data['last_time_ok']) { $status_date = $data['last_time_ok']; } } if ($status_date == 0) { $status_date = '-'; } $obj->XML->writeElement('last_time_name', _('Last time in '), 0); $obj->XML->writeElement('last_time', $status_date, 0); $obj->XML->writeElement('last_time_status', $status, 0); $obj->XML->startElement('notes'); $obj->XML->writeAttribute('name', _('Notes')); $obj->XML->text(CentreonUtils::escapeSecure($data['notes'])); $obj->XML->endElement(); } else { $obj->XML->writeElement('infos', 'none'); } unset($data); // Translations $obj->XML->writeElement('tr1', _('Check information'), 0); $obj->XML->writeElement('tr2', _('Notification Information'), 0); $obj->XML->writeElement('tr3', _('Last Status Change'), 0); $obj->XML->writeElement('tr4', _('Extended information'), 0); $obj->XML->writeElement('tr5', _('Status Information'), 0); $obj->XML->writeElement('tr6', _('Output'), 0); // End Buffer $obj->XML->endElement(); // Send Header $obj->header(); // Send XML $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Services/xml/serviceGridXML.php
centreon/www/include/monitoring/status/Services/xml/serviceGridXML.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 * */ ini_set('display_errors', 'Off'); require_once realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php'; // Create XML Request Objects CentreonSession::start(1); $centreonXMLBGRequest = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); if ( ! isset($centreonXMLBGRequest->session_id) || ! CentreonSession::checkSession($centreonXMLBGRequest->session_id, $centreonXMLBGRequest->DB) ) { echo 'Bad Session ID'; exit(); } $centreon = $_SESSION['centreon']; /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); // Set Default Poller $centreonXMLBGRequest->getDefaultFilters(); // Check Arguments From GET tab $o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h'; $p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]); $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); // if instance value is not set, displaying all active pollers linked resources $instance = filter_var($centreonXMLBGRequest->defaultPoller ?? -1, FILTER_VALIDATE_INT); $hostgroups = filter_var($centreonXMLBGRequest->defaultHostgroups ?? 0, FILTER_VALIDATE_INT); $search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $sortType = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name'; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; // Backup poller selection $centreonXMLBGRequest->setInstanceHistory($instance); $kernel = App\Kernel::createForWeb(); /** * @var Centreon\Application\Controller\MonitoringResourceController $resourceController */ $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); // saving bound values $queryValues = []; /** * Get Host status */ $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, hosts.name, hosts.state, hosts.icon_image, hosts.host_id FROM hosts SQL_WRAP; if ($hostgroups) { $request .= <<<'SQL' INNER JOIN hosts_hostgroups hhg ON hhg.host_id = hosts.host_id AND hhg.hostgroup_id = :hostgroup INNER JOIN hostgroups hg ON hg.hostgroup_id = hhg.hostgroup_id SQL; // only one value is returned from the current "select" filter $queryValues['hostgroup'] = [PDO::PARAM_INT => $hostgroups]; } if (! $centreonXMLBGRequest->is_admin) { $request .= <<<SQL INNER JOIN centreon_acl ON centreon_acl.host_id = hosts.host_id AND centreon_acl.group_id IN ({$centreonXMLBGRequest->grouplistStr}) SQL; } $request .= " WHERE hosts.name NOT LIKE '\_Module\_%' "; if ($o == 'svcgrid_pb' || $o == 'svcOV_pb' || $o == 'svcgrid_ack_0' || $o == 'svcOV_ack_0') { $request .= <<<'SQL' AND hosts.host_id IN ( SELECT s.host_id FROM services s WHERE s.state != 0 AND s.state != 4 AND s.enabled = 1 ) SQL; } if ($o == 'svcgrid_ack_1' || $o == 'svcOV_ack_1') { $request .= <<<'SQL' AND hosts.host_id IN ( SELECT s.host_id FROM services s WHERE s.acknowledged = '1' AND s.enabled = 1 ) SQL; } if ($search != '') { $request .= ' AND hosts.name like :search '; $queryValues['search'] = [PDO::PARAM_STR => '%' . $search . '%']; } if ($instance != -1) { $request .= ' AND hosts.instance_id = :instance '; $queryValues['instance'] = [PDO::PARAM_INT => $instance]; } $request .= ' AND hosts.enabled = 1 '; switch ($sortType) { case 'current_state': $request .= ' ORDER BY hosts.state ' . $order . ',hosts.name '; break; default: $request .= ' ORDER BY hosts.name ' . $order; break; } $request .= ' LIMIT :numLimit, :limit'; $queryValues['numLimit'] = [PDO::PARAM_INT => ($num * $limit)]; $queryValues['limit'] = [PDO::PARAM_INT => $limit]; // Execute request $dbResult = $centreonXMLBGRequest->DBC->prepare($request); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); $numRows = (int) $centreonXMLBGRequest->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn(); $centreonXMLBGRequest->XML->startElement('reponse'); $centreonXMLBGRequest->XML->startElement('i'); $centreonXMLBGRequest->XML->writeElement('numrows', $numRows); $centreonXMLBGRequest->XML->writeElement('num', $num); $centreonXMLBGRequest->XML->writeElement('limit', $limit); $centreonXMLBGRequest->XML->writeElement('p', $p); preg_match('/svcOV/', $_GET['o'], $matches) ? $centreonXMLBGRequest->XML->writeElement('s', '1') : $centreonXMLBGRequest->XML->writeElement('s', '0'); $centreonXMLBGRequest->XML->endElement(); $tab_final = []; $hostIds = []; while ($ndo = $dbResult->fetch()) { $hostIds[] = $ndo['host_id']; $tab_final[$ndo['name']] = ['cs' => $ndo['state'], 'hid' => $ndo['host_id']]; $tabIcone[$ndo['name']] = $ndo['icon_image'] != '' ? $ndo['icon_image'] : 'none'; } $dbResult->closeCursor(); // Get Service status $tab_svc = $centreonXMLBGRequest->monObj->getServiceStatus($hostIds, $centreonXMLBGRequest, $o, $instance); if (isset($tab_svc)) { foreach ($tab_svc as $host_name => $tab) { if (count($tab)) { $tab_final[$host_name]['tab_svc'] = $tab; } } } $ct = 0; if (isset($tab_svc)) { foreach ($tab_final as $host_name => $tab) { $centreonXMLBGRequest->XML->startElement('l'); $centreonXMLBGRequest->XML->writeAttribute('class', $centreonXMLBGRequest->getNextLineClass()); if (isset($tab['tab_svc'])) { foreach ($tab['tab_svc'] as $svc => $details) { $state = $details['state']; $serviceId = $details['service_id']; $centreonXMLBGRequest->XML->startElement('svc'); $centreonXMLBGRequest->XML->writeElement('sn', CentreonUtils::escapeSecure($svc), false); $centreonXMLBGRequest->XML->writeElement('snl', CentreonUtils::escapeSecure(urlencode($svc))); $centreonXMLBGRequest->XML->writeElement('sc', $centreonXMLBGRequest->colorService[$state]); $centreonXMLBGRequest->XML->writeElement('svc_id', $serviceId); $centreonXMLBGRequest->XML->writeElement( 's_details_uri', $useDeprecatedPages ? 'main.php?o=svcd&p=202&host_name=' . $host_name . '&service_description=' . $svc : $resourceController->buildServiceDetailsUri($tab['hid'], $serviceId) ); $centreonXMLBGRequest->XML->endElement(); } } $centreonXMLBGRequest->XML->writeElement('o', $ct++); $centreonXMLBGRequest->XML->writeElement('ico', $tabIcone[$host_name]); $centreonXMLBGRequest->XML->writeElement('hn', $host_name, false); $centreonXMLBGRequest->XML->writeElement('hid', $tab['hid'], false); $centreonXMLBGRequest->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($host_name))); $centreonXMLBGRequest->XML->writeElement('hs', _($centreonXMLBGRequest->statusHost[$tab['cs']]), false); $centreonXMLBGRequest->XML->writeElement('hc', $centreonXMLBGRequest->colorHost[$tab['cs']]); $centreonXMLBGRequest->XML->writeElement( 'h_details_uri', $useDeprecatedPages ? 'main.php?p=20202&o=hd&host_name=' . $host_name : $resourceController->buildHostDetailsUri($tab['hid']) ); $centreonXMLBGRequest->XML->writeElement( 's_listing_uri', $useDeprecatedPages ? 'main.php?o=svc&p=20201&statusFilter=;host_search=' . $host_name : $resourceController->buildListingUri([ 'filter' => json_encode([ 'criterias' => [ 'search' => 'h.name:^' . $host_name . '$', ], ]), ]) ); $centreonXMLBGRequest->XML->writeElement( 'chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18) ); $centreonXMLBGRequest->XML->writeElement( 'viewIcon', returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18) ); $centreonXMLBGRequest->XML->endElement(); } } if (! $ct) { $centreonXMLBGRequest->XML->writeElement('infos', 'none'); } $centreonXMLBGRequest->XML->endElement(); // Send Header $centreonXMLBGRequest->header(); // Send XML $centreonXMLBGRequest->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/HostGroups/hostGroupJS.php
centreon/www/include/monitoring/status/HostGroups/hostGroupJS.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 * */ if (! isset($centreon)) { exit(); } $tS = $centreon->optGen['AjaxTimeReloadStatistic'] * 1000; $tM = $centreon->optGen['AjaxTimeReloadMonitoring'] * 1000; if (! isset($centreon->optGen['AjaxFirstTimeReloadMonitoring']) || $centreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0 ) { $tFM = 10; } else { $tFM = $centreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000; } $sid = session_id(); $time = time(); ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/HostGroups/xml/hostGroupXML.php?"; var _addrXSL = "./include/monitoring/status/HostGroups/xsl/hostGroup.xsl"; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc"); if (document.getElementById('hostGroup_name')) { var h = document.getElementById('hostGroup_name'); h.innerHTML = "<?php echo _('Host Group'); ?>"; h.indice = 'hostGroup_name'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('host_status'); h.innerHTML = '<?php echo addslashes(_('Hosts Status')); ?>'; h.indice = 'host_status'; var h = document.getElementById('service_status'); h.innerHTML = '<?php echo addslashes(_('Services Status')); ?>'; h.indice = 'service_status'; var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; h.appendChild(_linkaction_asc); } } function goM(_time_reload, _o) { _lock = 1; var proc = new Transformation(); var _search = jQuery('input[name="searchHG"]').val(); proc.setXml(_addrXML + 'search=' + _search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&instance=' + _instance + '&time=<?php echo time(); ?>') proc.setXslt(_addrXSL); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); if (handleVisibilityChange()) { proc.transform("forAjax"); } _lock = 0; _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } </SCRIPT>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/HostGroups/hostGroup.php
centreon/www/include/monitoring/status/HostGroups/hostGroup.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 * */ if (! isset($centreon)) { exit(); } include './include/common/autoNumLimit.php'; $sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types']; $order = ! isset($_GET['order']) ? 'ASC' : $_GET['order']; $num = ! isset($_GET['num']) ? 0 : $_GET['num']; $sort_type = ! isset($_GET['sort_type']) ? 'hostGroup_name' : $_GET['sort_type']; $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; include_once './include/monitoring/status/Common/default_poller.php'; include_once $path_hg . 'hostGroupJS.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path_hg, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_types', $sort_types); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $tpl->assign('poller_listing', $centreon->user->access->checkAction('poller_listing')); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); $tpl->assign('limit', $limit); if (isset($_GET['searchHG'])) { $tpl->assign('searchHG', $_GET['searchHG']); } else { $tpl->assign('searchHG', ''); } $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('hostGroup.ihtml');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/HostGroups/xml/hostGroupXML.php
centreon/www/include/monitoring/status/HostGroups/xml/hostGroupXML.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 realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; // Create XML Request Objects CentreonSession::start(); $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo 'Bad Session ID'; exit(); } $centreon = $_SESSION['centreon']; /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); // Set Default Poller $obj->getDefaultFilters(); $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); // Alias / Name conversion table $convertTable = []; $convertID = []; $dbResult = $obj->DBC->query('SELECT 1 AS REALTIME, hostgroup_id, name FROM hostgroups'); while ($hg = $dbResult->fetch()) { $convertTable[$hg['name']] = $hg['name']; $convertID[$hg['name']] = $hg['hostgroup_id']; } $dbResult->closeCursor(); // Check Arguments From GET tab $o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h'; $p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]); $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); // if instance value is not set, displaying all active pollers linked resources $instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT); $search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; // saving bound values $queryValues = []; $groupStr = $obj->access->getAccessGroupsString(); // Backup poller selection $obj->setInstanceHistory($instance); // Search string $searchStr = ' '; if ($search != '') { $searchStr = ' AND hg.name LIKE :search '; $queryValues['search'] = [ PDO::PARAM_STR => '%' . $search . '%', ]; } // Host state if ($obj->is_admin) { $rq1 = 'SELECT 1 AS REALTIME, hg.name as alias, h.state, COUNT(h.host_id) AS nb FROM hosts_hostgroups hhg, hosts h, hostgroups hg WHERE hg.hostgroup_id = hhg.hostgroup_id AND hhg.host_id = h.host_id AND h.enabled = 1 '; if (isset($instance) && $instance > 0) { $rq1 .= 'AND h.instance_id = :instance'; $queryValues['instance'] = [ PDO::PARAM_INT => $instance, ]; } $rq1 .= $searchStr . 'GROUP BY hg.name, h.state ORDER BY hg.name ' . $order; } else { $rq1 = 'SELECT 1 AS REALTIME, hg.name as alias, h.state, COUNT(DISTINCT h.host_id) AS nb FROM centreon_acl acl, hosts_hostgroups hhg, hosts h, hostgroups hg WHERE hg.hostgroup_id = hhg.hostgroup_id AND hhg.host_id = h.host_id AND h.enabled = 1 '; if (isset($instance) && $instance > 0) { $rq1 .= 'AND h.instance_id = :instance'; $queryValues['instance'] = [ PDO::PARAM_INT => $instance, ]; } $rq1 .= $searchStr . $obj->access->queryBuilder('AND', 'hg.name', $obj->access->getHostGroupsString('NAME')) . 'AND h.host_id = acl.host_id AND acl.group_id in (' . $groupStr . ') GROUP BY hg.name, h.state ORDER BY hg.name ' . $order; } $dbResult = $obj->DBC->prepare($rq1); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); while ($data = $dbResult->fetch()) { if (! isset($stats[$data['alias']])) { $stats[$data['alias']] = ['h' => [0 => 0, 1 => 0, 2 => 0, 3 => 0], 's' => [0 => 0, 1 => 0, 2 => 0, 3 => 0, 3 => 0, 4 => 0]]; } $stats[$data['alias']]['h'][$data['state']] = $data['nb']; } $dbResult->closeCursor(); // Get Services request if ($obj->is_admin) { $rq2 = 'SELECT 1 AS REALTIME, hg.name AS alias, s.state, COUNT( s.service_id ) AS nb, (CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri FROM hosts_hostgroups hhg, hosts h, hostgroups hg, services s WHERE hg.hostgroup_id = hhg.hostgroup_id AND hhg.host_id = h.host_id AND h.enabled = 1 AND h.host_id = s.host_id AND s.enabled = 1 '; if (isset($instance) && $instance > 0) { $rq2 .= 'AND h.instance_id = :instance'; } $rq2 .= $searchStr . 'GROUP BY hg.name, s.state ORDER BY tri ASC'; } else { $rq2 = 'SELECT 1 AS REALTIME, hg.name as alias, s.state, COUNT( s.service_id ) AS nb, (CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri FROM centreon_acl acl, hosts_hostgroups hhg, hosts h, hostgroups hg, services s WHERE hg.hostgroup_id = hhg.hostgroup_id AND hhg.host_id = h.host_id AND h.enabled = 1 AND h.host_id = s.host_id AND s.enabled = 1 '; if (isset($instance) && $instance > 0) { $rq2 .= 'AND h.instance_id = :instance'; } $rq2 .= $searchStr . $obj->access->queryBuilder('AND', 'hg.name', $obj->access->getHostGroupsString('NAME')) . 'AND h.host_id = acl.host_id AND s.service_id = acl.service_id AND acl.group_id IN (' . $groupStr . ') GROUP BY hg.name, s.state ORDER BY tri ASC'; } $dbResult = $obj->DBC->prepare($rq2); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); while ($data = $dbResult->fetch()) { if (! isset($stats[$data['alias']])) { $stats[$data['alias']] = ['h' => [0 => 0, 1 => 0, 2 => 0, 3 => 0], 's' => [0 => 0, 1 => 0, 2 => 0, 3 => 0, 3 => 0, 4 => 0]]; } if ($stats[$data['alias']]) { $stats[$data['alias']]['s'][$data['state']] = $data['nb']; } } // Get Pagination Rows $stats ??= []; $numRows = count($stats); $obj->XML->startElement('reponse'); $obj->XML->startElement('i'); $obj->XML->writeElement('numrows', $numRows); $obj->XML->writeElement('num', $num); $obj->XML->writeElement('limit', $limit); $obj->XML->writeElement('p', $p); $obj->XML->endElement(); $buildParameter = function ($id, string $name) { return [ 'id' => $id, 'name' => $name, ]; }; $buildHostgroupUri = function (array $hostgroups, array $types, array $statuses) use ($resourceController) { return $resourceController->buildListingUri([ 'filter' => json_encode([ 'criterias' => [ 'hostGroups' => $hostgroups, 'resourceTypes' => $types, 'statuses' => $statuses, ], ]), ]); }; $hostType = $buildParameter('host', 'Host'); $serviceType = $buildParameter('service', 'Service'); $okStatus = $buildParameter('OK', 'Ok'); $warningStatus = $buildParameter('WARNING', 'Warning'); $criticalStatus = $buildParameter('CRITICAL', 'Critical'); $unknownStatus = $buildParameter('UNKNOWN', 'Unknown'); $pendingStatus = $buildParameter('PENDING', 'Pending'); $upStatus = $buildParameter('UP', 'Up'); $downStatus = $buildParameter('DOWN', 'Down'); $unreachableStatus = $buildParameter('UNREACHABLE', 'Unreachable'); $i = 0; $ct = 0; if (isset($stats)) { foreach ($stats as $name => $stat) { if ( ($i < (($num + 1) * $limit) && $i >= (($num) * $limit)) && ((isset($converTable[$name], $acl[$convertTable[$name]])) || (! isset($acl))) && $name != 'meta_hostgroup' ) { $class = $obj->getNextLineClass(); if (isset($stat['h']) && count($stat['h'])) { $hostgroup = $buildParameter( (int) $convertID[$convertTable[$name]], $convertTable[$name] ); $obj->XML->startElement('l'); $obj->XML->writeAttribute('class', $class); $obj->XML->writeElement('o', $ct++); $obj->XML->writeElement( 'hn', CentreonUtils::escapeSecure($convertTable[$name] . ' (' . $name . ')'), false ); $obj->XML->writeElement('hu', $stat['h'][0]); $obj->XML->writeElement('huc', $obj->colorHost[0]); $obj->XML->writeElement('hd', $stat['h'][1]); $obj->XML->writeElement('hdc', $obj->colorHost[1]); $obj->XML->writeElement('hur', $stat['h'][2]); $obj->XML->writeElement('hurc', $obj->colorHost[2]); $obj->XML->writeElement('sc', $stat['s'][2]); $obj->XML->writeElement('scc', $obj->colorService[2]); $obj->XML->writeElement('sw', $stat['s'][1]); $obj->XML->writeElement('swc', $obj->colorService[1]); $obj->XML->writeElement('su', $stat['s'][3]); $obj->XML->writeElement('suc', $obj->colorService[3]); $obj->XML->writeElement('sk', $stat['s'][0]); $obj->XML->writeElement('skc', $obj->colorService[0]); $obj->XML->writeElement('sp', $stat['s'][4]); $obj->XML->writeElement('spc', $obj->colorService[4]); $hostgroupDeprecatedUri = CentreonUtils::escapeSecure('main.php?p=20201&o=svc&hg=' . $hostgroup['id']); $obj->XML->writeElement( 'hg_listing_uri', $useDeprecatedPages ? $hostgroupDeprecatedUri : $buildHostgroupUri([$hostgroup], [], []) ); $obj->XML->writeElement( 'hg_listing_h_up', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=h_up' : $buildHostgroupUri([$hostgroup], [$hostType], [$upStatus]) ); $obj->XML->writeElement( 'hg_listing_h_down', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=h_down' : $buildHostgroupUri([$hostgroup], [$hostType], [$downStatus]) ); $obj->XML->writeElement( 'hg_listing_h_unreachable', $buildHostgroupUri([$hostgroup], [$hostType], [$unreachableStatus]) ); $obj->XML->writeElement( 'hg_listing_h_pending', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=h_pending' : $buildHostgroupUri([$hostgroup], [$hostType], [$pendingStatus]) ); $obj->XML->writeElement( 'hg_listing_s_ok', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=svc&amp;statusFilter=ok' : $buildHostgroupUri([$hostgroup], [$serviceType], [$okStatus]) ); $obj->XML->writeElement( 'hg_listing_s_warning', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=svc&amp;statusFilter=warning' : $buildHostgroupUri([$hostgroup], [$serviceType], [$warningStatus]) ); $obj->XML->writeElement( 'hg_listing_s_critical', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=svc&amp;statusFilter=critical' : $buildHostgroupUri([$hostgroup], [$serviceType], [$criticalStatus]) ); $obj->XML->writeElement( 'hg_listing_s_unknown', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=svc&amp;statusFilter=unknown' : $buildHostgroupUri([$hostgroup], [$serviceType], [$unknownStatus]) ); $obj->XML->writeElement( 'hg_listing_s_pending', $useDeprecatedPages ? $hostgroupDeprecatedUri . '&amp;o=svc&amp;statusFilter=pending' : $buildHostgroupUri([$hostgroup], [$serviceType], [$pendingStatus]) ); $obj->XML->endElement(); } } $i++; } } if (! $ct) { $obj->XML->writeElement('infos', 'none'); } $obj->XML->endElement(); $obj->header(); $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Hosts/host.php
centreon/www/include/monitoring/status/Hosts/host.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 * */ if (! isset($centreon)) { exit(); } $myinputsGet = [ 'sort_types' => isset($_GET['sort_types']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_types']) : null, 'order' => isset($_GET['order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['order']) : null, 'num' => isset($_GET['num']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['num']) : null, 'host_search' => isset($_GET['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_search']) : null, 'sort_type' => isset($_GET['sort_types']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : null, 'hostgroups' => isset($_GET['hostgroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hostgroups']) : null, 'criticality_id' => filter_input(INPUT_GET, 'criticality_id', FILTER_SANITIZE_NUMBER_INT), 'reset_filter' => filter_input(INPUT_GET, 'reset_filter', FILTER_SANITIZE_NUMBER_INT), ]; $myinputsPost = [ 'sort_types' => isset($_POST['sort_types']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['sort_types']) : null, 'order' => isset($_POST['order']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['order']) : null, 'num' => isset($_POST['num']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['num']) : null, 'host_search' => isset($_POST['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['host_search']) : null, 'sort_type' => isset($_POST['sort_types']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['sort_type']) : null, 'hostgroups' => isset($_POST['hostgroups']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['hostgroups']) : null, 'criticality_id' => filter_input(INPUT_GET, 'criticality_id', FILTER_SANITIZE_NUMBER_INT), 'reset_filter' => filter_input(INPUT_GET, 'reset_filter', FILTER_SANITIZE_NUMBER_INT), ]; $resetFilter = (isset($myinputsGet['reset_filter']) && $myinputsGet['reset_filter'] == 1) ? true : false; if ($resetFilter) { $centreon->historySearch[$url] = ''; $centreon->historySearchService[$url] = ''; $centreon->historySearchOutput[$url] = ''; $_SESSION['filters'][$url] = []; $_SESSION['monitoring_default_hostgroups'] = ''; $_SESSION['monitoring_default_poller'] = ''; $_SESSION['monitoring_host_status'] = ''; $_SESSION['monitoring_host_status_filter'] = ''; $_SESSION['criticality_id'] = ''; } foreach ($myinputsGet as $key => $value) { if (! empty($value)) { $filters[$key] = $value; } elseif (! empty($myinputsPost[$key])) { $filters[$key] = $myinputsPost[$key]; } elseif ($resetFilter && isset($_SESSION['filters'][$url][$key]) && ! empty($_SESSION['filters'][$url][$key])) { $filters[$key] = $_SESSION['filters'][$url][$key]; } else { $filters[$key] = ''; } } if (empty($filters['host_search']) && isset($centreon->historySearch[$url])) { $filters['host_search'] = $centreon->historySearch[$url]; } else { $centreon->historySearch[$url] = $filters['host_search']; } // ACL Actions $GroupListofUser = []; $GroupListofUser = $centreon->user->access->getAccessGroups(); $allActions = false; // Get list of actions allowed for user if (count($GroupListofUser) > 0 && $is_admin == 0) { $authorized_actions = []; $authorized_actions = $centreon->user->access->getActions(); } else { // if user is admin, or without ACL, he cans perform all actions $allActions = true; } include './include/common/autoNumLimit.php'; $sort_types = empty($filters['sort_types']) ? 0 : $filters['sort_types']; $order = empty($filters['order']) ? 'ASC' : $filters['order']; $num = empty($filters['num']) ? 0 : $filters['num']; $search_host = empty($filters['host_search']) ? '' : $filters['host_search']; $sort_type = empty($filters['sort_type']) ? '' : $filters['sort_type']; if (! empty($filters['hostgroups'])) { $_SESSION['monitoring_default_hostgroups'] = $filters['hostgroups']; } if (! empty($filters['criticality_id'])) { $_SESSION['criticality_id'] = $filters['criticality_id']; } $problem_sort_type = 'host_name'; if (! empty($centreon->optGen['problem_sort_type'])) { $problem_sort_type = $centreon->optGen['problem_sort_type']; } $problem_sort_order = 'asc'; if (! empty($centreon->optGen['problem_sort_type'])) { $problem_sort_order = $centreon->optGen['problem_sort_order']; } $global_sort_type = 'host_name'; if (! empty($centreon->optGen['global_sort_type'])) { $global_sort_type = $centreon->optGen['global_sort_type']; } $global_sort_order = 'asc'; if (! empty($centreon->optGen['global_sort_order'])) { $global_sort_order = $centreon->optGen['global_sort_order']; } if ($o == 'hpb' || $o == 'h_unhandled' || empty($o)) { $sort_type = ! isset($filters['sort_type']) ? $centreon->optGen['problem_sort_type'] : $filters['sort_type']; $order = ! isset($filters['order']) ? $centreon->optGen['problem_sort_order'] : $filters['order']; } else { if (! isset($filters['sort_type'])) { if (isset($centreon->optGen['global_sort_type']) && $centreon->optGen['global_sort_type'] != 'host_name') { $sort_type = CentreonDB::escape($centreon->optGen['global_sort_type']); } else { $sort_type = 'host_name'; } } else { $sort_type = $filters['sort_type']; } if (! isset($filters['order'])) { if (isset($centreon->optGen['global_sort_order']) && $centreon->optGen['global_sort_order'] == '') { $order = 'ASC'; } else { $order = $centreon->optGen['global_sort_order']; } } else { $order = $filters['order']; } } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; $aStatusHost = ['h_unhandled' => _('Unhandled Problems'), 'hpb' => _('Host Problems'), 'h' => _('All')]; include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once 'hostJS.php'; /** * Build the resource status listing URI that will be used in the * deprecated banner */ $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); $deprecationMessage = _('[Page deprecated] This page will be removed in the next major version. Please use the new page: '); $resourcesStatusLabel = _('Resources Status'); $filter = [ 'criterias' => [ [ 'name' => 'resource_types', 'value' => [ [ 'id' => 'host', 'name' => 'Host', ], ], ], [ 'name' => 'states', 'value' => [ [ 'id' => 'unhandled_problems', 'name' => 'Unhandled', ], ], ], [ 'name' => 'search', 'value' => '', ], ], ]; $redirectionUrl = $resourceController->buildListingUri(['filter' => json_encode($filter)]); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_type', $sort_type); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('statusHost', _('Host Status')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_tries', _('Tries')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $sSetOrderInMemory = ! isset($_GET['o']) ? '1' : '0'; $sDefaultOrder = '0'; $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $form->addElement( 'select', 'statusHost', _('Host Status'), $aStatusHost, ['id' => 'statusHost', 'onChange' => 'statusHosts(this.value);'] ); // Get default host status by GET if (isset($_GET['o']) && in_array($_GET['o'], array_keys($aStatusHost))) { $form->setDefaults(['statusHost' => $_GET['o']]); // Get default host status in SESSION } elseif ((! isset($_GET['o']) || empty($_GET['o'])) && isset($_SESSION['monitoring_host_status'])) { $form->setDefaults(['statusHost' => $_SESSION['monitoring_host_status']]); $sDefaultOrder = '1'; } $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } </script> <?php $action_list = []; $action_list[] = _('More actions...'); $informationsService = $dependencyInjector['centreon_remote.informations_service']; $serverIsMaster = $informationsService->serverIsMaster(); // Showing actions allowed for current user if (isset($authorized_actions) && $allActions == false) { if (isset($authorized_actions) && $allActions == false) { $action_list[94] = _('Hosts : Schedule immediate check'); } if (isset($authorized_actions['host_schedule_forced_check'])) { $action_list[95] = _('Hosts : Schedule immediate check (Forced)'); } if (isset($authorized_actions['host_acknowledgement'])) { $action_list[72] = _('Hosts : Acknowledge'); } if (isset($authorized_actions['host_disacknowledgement'])) { $action_list[73] = _('Hosts : Disacknowledge'); } if ($serverIsMaster && isset($authorized_actions['host_notifications'])) { $action_list[82] = _('Hosts : Enable Notification'); } if ($serverIsMaster && isset($authorized_actions['host_notifications'])) { $action_list[83] = _('Hosts : Disable Notification'); } if ($serverIsMaster && isset($authorized_actions['host_checks'])) { $action_list[92] = _('Hosts : Enable Check'); } if ($serverIsMaster && isset($authorized_actions['host_checks'])) { $action_list[93] = _('Hosts : Disable Check'); } if (isset($authorized_actions['host_schedule_downtime'])) { $action_list[75] = _('Hosts : Set Downtime'); } } else { $action_list[94] = _('Hosts : Schedule immediate check'); $action_list[95] = _('Hosts : Schedule immediate check (Forced)'); $action_list[72] = _('Hosts : Acknowledge'); $action_list[73] = _('Hosts : Disacknowledge'); if ($serverIsMaster) { $action_list[82] = _('Hosts : Enable Notification'); $action_list[83] = _('Hosts : Disable Notification'); $action_list[92] = _('Hosts : Enable Check'); $action_list[93] = _('Hosts : Disable Check'); } $action_list[75] = _('Hosts : Set Downtime'); } $attrs = ['onchange' => 'javascript: ' . ' var bChecked = isChecked(); ' . " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {" . " alert('" . _('Please select one or more items') . "'); return false;} " . " if (this.form.elements['o1'].selectedIndex == 0) {" . ' return false;} ' . 'if (cmdCallback(this.value)) { setO(this.value); submit();} else { setO(this.value); }']; $form->addElement('select', 'o1', null, $action_list, $attrs); $form->setDefaults(['o1' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $attrs = ['onchange' => 'javascript: ' . ' var bChecked = isChecked(); ' . " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {" . " alert('" . _('Please select one or more items') . "'); return false;} " . " if (this.form.elements['o2'].selectedIndex == 0) {" . ' return false;} ' . 'if (cmdCallback(this.value)) { setO(this.value); submit();} else { setO(this.value); }']; $form->addElement('select', 'o2', null, $action_list, $attrs); $form->setDefaults(['o2' => null]); $o2 = $form->getElement('o2'); $o2->setValue(null); $o2->setSelected(null); $keyPrefix = ''; $statusList = ['' => '', 'up' => _('Up'), 'down' => _('Down'), 'unreachable' => _('Unreachable'), 'pending' => _('Pending')]; if ($o == 'h') { $keyPrefix = 'h'; } elseif ($o == 'hpb') { $keyPrefix = 'h'; unset($statusList['up']); } elseif ($o == 'h_unhandled') { $keyPrefix = 'h_unhandled'; unset($statusList['up'], $statusList['pending']); } elseif (preg_match('/h_([a-z]+)/', $o, $matches)) { if (isset($matches[1])) { $keyPrefix = 'h'; $defaultStatus = $matches[1]; } } $form->addElement( 'select', 'statusFilter', _('Status'), $statusList, ['id' => 'statusFilter', 'onChange' => 'filterStatus(this.value);'] ); if (! isset($_GET['o']) && isset($_SESSION['monitoring_host_status_filter'])) { $form->setDefaults(['statusFilter' => $_SESSION['monitoring_host_status_filter']]); $sDefaultOrder = '1'; } $criticality = new CentreonCriticality($pearDB); $crits = $criticality->getList(); $critArray = [0 => '']; foreach ($crits as $critId => $crit) { $critArray[$critId] = $crit['hc_name'] . " ({$crit['level']})"; } $form->addElement( 'select', 'criticality', _('Severity'), $critArray, ['id' => 'critFilter', 'onChange' => 'filterCrit(this.value);'] ); $form->setDefaults(['criticality' => $_SESSION['criticality_id'] ?? '0']); $tpl->assign('limit', $limit); $tpl->assign('hostStr', _('Host')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('poller_listing', $centreon->user->access->checkAction('poller_listing')); $tpl->assign('hgStr', _('Hostgroup')); $criticality = new CentreonCriticality($pearDB); $tpl->assign('criticalityUsed', count($criticality->getList())); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('host.ihtml'); ?> <script type='text/javascript'> var tabSortPb = []; tabSortPb['champ'] = '<?php echo $problem_sort_type; ?>'; tabSortPb['ordre'] = '<?php echo $problem_sort_order; ?>'; var tabSortAll = []; tabSortAll['champ'] = '<?php echo $global_sort_type; ?>'; tabSortAll['ordre'] = '<?php echo $global_sort_order; ?>'; var up = '<?php echo _('Up'); ?>'; var down = '<?php echo _('Down'); ?>'; var unreachable = '<?php echo _('Unreachable'); ?>'; var pending = '<?php echo _('Pending'); ?>'; var _keyPrefix; display_deprecated_banner(); function display_deprecated_banner() { const url = "<?php echo $redirectionUrl; ?>"; const message = "<?php echo $deprecationMessage; ?>"; const label = "<?php echo $resourcesStatusLabel; ?>"; jQuery('.pathway').append( '<span style="color:#FF4500;padding-left:10px;font-weight:bold">' + message + '<a style="position:relative" href="' + url + '" isreact="isreact">' + label + '</a>' ); } jQuery('#statusHost').change(function () { updateSelect(); }); function updateSelect() { var oldStatus = jQuery('#statusFilter').val(); var opts = document.getElementById('statusFilter').options; var newTypeOrder = null; if (jQuery('#statusHost').val() == 'hpb' || jQuery('#statusHost').val() == 'h_unhandled') { opts.length = 0; opts[opts.length] = new Option("", ""); opts[opts.length] = new Option(down, "down"); opts[opts.length] = new Option(unreachable, "unreachable"); newTypeOrder = tabSortPb['champ']; } else { opts.length = 0; opts[opts.length] = new Option("", ""); opts[opts.length] = new Option(up, "up"); opts[opts.length] = new Option(down, "down"); opts[opts.length] = new Option(unreachable, "unreachable"); opts[opts.length] = new Option(pending, "pending"); newTypeOrder = tabSortAll['champ']; } // We define the statusFilter before calling ajax if (jQuery("#statusFilter option[value='" + oldStatus + "']").length > 0) { jQuery("#statusFilter option[value='" + oldStatus + "']").prop('selected', true); } else { jQuery("#statusFilter option[value='']").prop('selected', true); } change_type_order(newTypeOrder); } jQuery(function () { preInit(); }); function preInit() { _keyPrefix = '<?= $keyPrefix; ?>'; _tm = <?= $tM; ?>; _o = '<?= $o; ?>'; _sDefaultOrder = '<?= $sDefaultOrder; ?>'; sSetOrderInMemory = '<?= $sSetOrderInMemory; ?>'; if (_sDefaultOrder == "0") { if (_o == 'h') { jQuery("#statusHost option[value='h']").prop('selected', true); jQuery("#statusFilter option[value='']").prop('selected', true); } else if (_o == 'h_up') { jQuery("#statusHost option[value='h']").prop('selected', true); jQuery("#statusFilter option[value='up']").prop('selected', true); } else if (_o == 'h_down') { jQuery("#statusHost option[value='h']").prop('selected', true); jQuery("#statusFilter option[value='down']").prop('selected', true); } else if (_o == 'h_unreachable') { jQuery("#statusHost option[value='h']").prop('selected', true); jQuery("#statusFilter option[value='unreachable']").prop('selected', true); } else if (_o == 'h_pending') { jQuery("#statusHost option[value='h']").prop('selected', true); jQuery("#statusFilter option[value='pending']").prop('selected', true); } else { jQuery("#statusHost option[value='h_unhandled']").prop('selected', true); jQuery("#statusFilter option[value='']").prop('selected', true); } } filterStatus(document.getElementById('statusFilter').value, 1); } function filterStatus(value, isInit) { _o = jQuery('#statusHost').val(); if (value) { _o = _keyPrefix + '_' + value; } else if (!isInit && _o != 'hpb') { _o = _keyPrefix; } window.clearTimeout(_timeoutID); initM(_tm, _o); } function filterCrit(value) { window.clearTimeout(_timeoutID); initM(_tm, _o); } function statusHosts(value, isInit) { _o = value; } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Hosts/hostJS.php
centreon/www/include/monitoring/status/Hosts/hostJS.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 * */ if (! isset($centreon)) { exit(); } if (! isset($centreon->optGen['AjaxFirstTimeReloadMonitoring']) || $centreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0 ) { $tFM = 10; } else { $tFM = $centreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000; } if (! isset($centreon->optGen['AjaxFirstTimeReloadStatistic']) || $centreon->optGen['AjaxFirstTimeReloadStatistic'] == 0 ) { $tFS = 10; } else { $tFS = $centreon->optGen['AjaxFirstTimeReloadStatistic'] * 1000; } $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/Hosts/xml/hostXML.php"; var _addrXSL = "./include/monitoring/status/Hosts/xsl/host.xsl"; var _criticality_id = 0; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> var _selectedElem = new Array(); function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc"); if (document.getElementById('host_name')) { var h = document.getElementById('host_name'); h.innerHTML = '<?php echo addslashes(_('Hosts')); ?>'; h.indice = 'host_name'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('current_state'); h.innerHTML = '<?php echo addslashes(_('Status')); ?>'; h.indice = 'current_state'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('ip'); h.innerHTML = '<?php echo addslashes(_('IP Address')); ?>'; h.indice = 'ip'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('last_state_change'); h.innerHTML = '<?php echo addslashes(_('Duration')); ?>'; h.indice = 'last_state_change'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('last_hard_state_change'); if (h) { h.innerHTML = '<?php echo addslashes(_('Hard State Duration')); ?>'; h.indice = 'last_hard_state_change'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById('last_check'); h.innerHTML = '<?php echo addslashes(_('Last Check')); ?>'; h.indice = 'last_check'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('current_check_attempt'); h.innerHTML = '<?php echo addslashes(_('Tries')); ?>'; h.indice = 'current_check_attempt'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('criticality_id'); if (h) { h.innerHTML = '<?php echo addslashes('S'); ?>'; h.indice = 'criticality_id'; h.title = "<?php echo _('Sort by severity'); ?>"; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById('plugin_output'); h.innerHTML = '<?php echo addslashes(_('Status information')); ?>'; h.indice = 'plugin_output'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; if (_sort_type) { var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; if (h) { h.appendChild(_linkaction_asc); } } } } function mainLoopHost() { _currentInputField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputFieldValue = document.getElementById('host_search').value; } else { _currentInputFieldValue = ""; } if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue ) { if (!_lock) { set_search_host(escapeURI(_currentInputFieldValue)); _host_search = _currentInputFieldValue; monitoring_refresh(); if (_currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else { _currentInputField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; setTimeout(mainLoopHost, 250); } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); construct_HostGroupSelectList('hostgroups_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('service search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } if (document.getElementById("critFilter") && document.getElementById("critFilter").value) { _criticality_id = document.getElementById("critFilter").value; viewDebugInfo('Host criticality: ' + document.getElementById("critFilter").value); } if (_first) { mainLoopHost(); _first = 0; } _time =<?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { if (_on == 0) { return; } _lock = 1; var proc = new Transformation(); // INIT search informations if (_counter == 0) { document.getElementById("host_search").value = _host_search; _counter += 1; } var statusHost = jQuery.trim(jQuery('#statusHost').val()); var statusFilter = jQuery.trim(jQuery('#statusFilter').val()); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml(_addrXML + "?" + 'search=' + _host_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&time=<?php echo time(); ?>&criticality=' + _criticality_id + '&statusHost=' + statusHost + '&statusFilter=' + statusFilter + "&sSetOrderInMemory=" + sSetOrderInMemory ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } _lock = 0; if (_timeoutID) { // Kill next execution if in queue clearTimeout(_timeoutID); } _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } function unsetCheckboxes() { for (keyz in _selectedElem) { if (keyz == _selectedElem[keyz]) { removeFromSelectedElem(decodeURIComponent(keyz)); if (document.getElementById(decodeURIComponent(keyz))) { document.getElementById(decodeURIComponent(keyz)).checked = false; } } } } function cmdCallback(cmd) { jQuery('.centreon-popin').remove(); var keyz; _cmd = cmd; var resources = []; _getVar = ""; if (cmd != '72' && cmd != '75') { return 1; } else { for (keyz in _selectedElem) { if ((keyz == _selectedElem[keyz]) && typeof(document.getElementById(decodeURIComponent(keyz)) != 'undefined') && document.getElementById(decodeURIComponent(keyz)) ) { if (document.getElementById(decodeURIComponent(keyz)).checked) { resources.push(encodeURIComponent(keyz)); } } } _getVar = JSON.stringify(resources) var url = './include/monitoring/external_cmd/popup/popup.php?o=' + _o + '&p=' + _p + '&cmd=' + cmd; var popin = jQuery('<div>'); popin.centreonPopin({open: true, url: url}); window.currentPopin = popin; return 0; } } function send_the_command() { if (window.XMLHttpRequest) { xhr_cmd = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr_cmd = new ActiveXObject("Microsoft.XMLHTTP"); } var comment = encodeURIComponent(document.getElementById('popupComment').value.trim()); if (comment == "") { alert(_popup_no_comment_msg); return 0; } if (_cmd == '70' || _cmd == '72') { if (document.getElementById('sticky')) { var sticky = document.getElementById('sticky').checked; } else var sticky = 1; if (document.getElementById('persistent')) { var persistent = document.getElementById('persistent').checked; } else { var persistent = 1; } if (document.getElementById('notify')) { var notify = document.getElementById('notify').checked; } else { var notify = 0; } if (document.getElementById('force_check')) { var force_check = document.getElementById('force_check').checked; } else { var force_check = 0; } var ackhostservice = 0; if (document.getElementById('ackhostservice')) { ackhostservice = document.getElementById('ackhostservice').checked; } var author = document.getElementById('author').value; xhr_cmd.open( "POST", "./include/monitoring/external_cmd/cmdPopup.php", true ); var data = new FormData(); data.append('cmd', _cmd); data.append('comment', comment); data.append('sticky', sticky); data.append('persistent', persistent); data.append('notify', notify); data.append('ackhostservice', ackhostservice); data.append('force_check', force_check); data.append('author', author); data.append('resources', _getVar); } else if (_cmd == '74' || _cmd == '75') { var downtimehostservice = 0; if (document.getElementById('downtimehostservice')) { downtimehostservice = document.getElementById('downtimehostservice').checked; } if (document.getElementById('fixed')) { var fixed = document.getElementById('fixed').checked; } else { var fixed = 0; } var start = jQuery(document).find('[name="alternativeDateStart"]').val() + ' ' + document.getElementById('start_time').value; var end = jQuery(document).find('[name="alternativeDateEnd"]').val() + ' ' + document.getElementById('end_time').value; var author = document.getElementById('author').value; var duration = document.getElementById('duration').value; var duration_scale = document.getElementById('duration_scale').value; var tmp = document.querySelector('input[name="host_or_centreon_time[host_or_centreon_time]"]:checked'); var host_or_centreon_time = "0"; if (tmp !== null && typeof tmp !== "undefined") { host_or_centreon_time = tmp.value; } xhr_cmd.open( "POST", "./include/monitoring/external_cmd/cmdPopup.php", true ); var data = new FormData(); data.append('cmd', _cmd); data.append('duration', duration); data.append('duration_scale', duration_scale); data.append('comment', comment); data.append('start', start); data.append('end', end); data.append('host_or_centreon_time', host_or_centreon_time); data.append('fixed', fixed); data.append('downtimehostservice', downtimehostservice); data.append('author', author); data.append('resources', _getVar); } xhr_cmd.send(data); window.currentPopin.centreonPopin("close"); unsetCheckboxes(); } function toggleFields(fixed) { var durationField = jQuery('#duration'); var durationScaleField = jQuery('#duration_scale'); if (fixed.checked) { durationField.attr('disabled', true); durationScaleField.attr('disabled', true); } else { durationField.removeAttr('disabled'); durationScaleField.removeAttr('disabled'); } } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Hosts/xml/hostXML.php
centreon/www/include/monitoring/status/Hosts/xml/hostXML.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 realpath(__DIR__ . '/../../../../../../bootstrap.php'); include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonInstance.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonCriticality.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonMedia.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php'; // Create XML Request Objects CentreonSession::start(); if (! isset($_SESSION['centreon'])) { exit; } $centreon = $_SESSION['centreon']; $obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1); if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) { echo 'Bad Session ID'; exit(); } $criticality = new CentreonCriticality($obj->DB); $instanceObj = CentreonInstance::getInstance($obj->DB, $obj->DBC); $media = new CentreonMedia($obj->DB); $hostObj = new CentreonHost($obj->DB); // Set Default Poller $obj->getDefaultFilters(); // Check Arguments From GET tab $o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h'; $p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]); $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); $criticalityId = filter_input( INPUT_GET, 'criticality', FILTER_VALIDATE_INT, ['options' => ['default' => $obj->defaultCriticality]] ); // if instance value is not set, displaying all active pollers linked resources $instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT); $hostgroups = filter_var($obj->defaultHostgroups ?? 0, FILTER_VALIDATE_INT); $search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $statusHost = isset($_GET['statusHost']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['statusHost']) : ''; $statusFilter = isset($_GET['statusFilter']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['statusFilter']) : ''; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; if (isset($_GET['sort_type']) && $_GET['sort_type'] === 'host_name') { $sort_type = 'name'; } elseif ($o === 'hpb' || $o === 'h_unhandled') { $sort_type = $obj->checkArgument('sort_type', $_GET, ''); } else { $sort_type = $obj->checkArgument('sort_type', $_GET, 'host_name'); } // Store in session the last type of call $_SESSION['monitoring_host_status'] = $statusHost; $_SESSION['monitoring_host_status_filter'] = $statusFilter; // Backup poller selection $obj->setInstanceHistory($instance); $obj->setHostGroupsHistory($hostgroups); $obj->setCriticality($criticalityId); // saving bound values $queryValues = []; // Get Host status $rq1 = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, h.state, h.acknowledged, h.passive_checks, h.active_checks, h.notify, h.last_state_change, h.last_hard_state_change, h.output, h.last_check, h.address, h.name, h.alias, h.action_url, h.notes_url, h.notes, h.icon_image, h.icon_image_alt, h.max_check_attempts, h.state_type, h.check_attempt, h.scheduled_downtime_depth, h.host_id, h.flapping, hph.parent_id AS is_parent, i.name AS instance_name, cv.value AS criticality, cv.value IS NULL AS isnull FROM instances i INNER JOIN hosts h ON h.instance_id = i.instance_id SQL_WRAP; if (! $obj->is_admin) { $rq1 .= <<<SQL INNER JOIN centreon_acl ON centreon_acl.host_id = h.host_id AND centreon_acl.group_id IN ({$obj->grouplistStr}) SQL; } if ($hostgroups) { $rq1 .= <<<'SQL' INNER JOIN hosts_hostgroups hhg ON hhg.host_id = h.host_id INNER JOIN hostgroups hg ON hg.hostgroup_id = :hostgroup AND hg.hostgroup_id = hhg.hostgroup_id SQL; $queryValues['hostgroup'] = [PDO::PARAM_INT => $hostgroups]; } if ($criticalityId) { $rq1 .= <<<'SQL' INNER JOIN customvariables cvs ON cvs.host_id = h.host_id AND cvs.name = 'CRITICALITY_ID' AND cvs.service_id = 0 AND cvs.value = :criticalityId SQL; $queryValues['criticalityId'] = [PDO::PARAM_STR => $criticalityId]; } $rq1 .= <<<SQL LEFT JOIN hosts_hosts_parents hph ON hph.parent_id = h.host_id LEFT JOIN `customvariables` cv ON (cv.host_id = h.host_id AND cv.service_id = 0 AND cv.name = 'CRITICALITY_LEVEL') WHERE h.name NOT LIKE '\_Module\_%' AND h.instance_id = i.instance_id SQL; if ($search != '') { $rq1 .= ' AND (h.name LIKE :search OR h.alias LIKE :search OR h.address LIKE :search) '; $queryValues['search'] = [PDO::PARAM_STR => '%' . $search . '%']; } if ($statusHost == 'h_unhandled') { $rq1 .= " AND h.state = 1 AND h.state_type = '1' AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0"; } elseif ($statusHost == 'hpb') { $rq1 .= ' AND (h.state != 0 AND h.state != 4) '; } if ($statusFilter == 'up') { $rq1 .= ' AND h.state = 0 '; } elseif ($statusFilter == 'down') { $rq1 .= ' AND h.state = 1 '; } elseif ($statusFilter == 'unreachable') { $rq1 .= ' AND h.state = 2 '; } elseif ($statusFilter == 'pending') { $rq1 .= ' AND h.state = 4 '; } if ($instance != -1 && ! empty($instance)) { $rq1 .= ' AND h.instance_id = :instance '; $queryValues['instance'] = [ PDO::PARAM_INT => $instance, ]; } $rq1 .= ' AND h.enabled = 1'; switch ($sort_type) { case 'name': $rq1 .= ' ORDER BY h.name ' . $order; break; case 'current_state': $rq1 .= ' ORDER BY h.state ' . $order . ',h.name'; break; case 'last_state_change': $rq1 .= ' ORDER BY h.last_state_change ' . $order . ',h.name'; break; case 'last_hard_state_change': $rq1 .= ' ORDER BY h.last_hard_state_change ' . $order . ',h.name'; break; case 'last_check': $rq1 .= ' ORDER BY h.last_check ' . $order . ',h.name'; break; case 'current_check_attempt': $rq1 .= ' ORDER BY h.check_attempt ' . $order . ',h.name'; break; case 'ip': // Not SQL portable $rq1 .= ' ORDER BY IFNULL(inet_aton(h.address), h.address) ' . $order . ',h.name'; break; case 'plugin_output': $rq1 .= ' ORDER BY h.output ' . $order . ',h.name'; break; case 'criticality_id': default: $rq1 .= ' ORDER BY isnull ' . $order . ', criticality ' . $order . ', h.name'; break; } $rq1 .= ' LIMIT :numLimit, :limit'; $queryValues['numLimit'] = [ PDO::PARAM_INT => (int) ($num * $limit), ]; $queryValues['limit'] = [ PDO::PARAM_INT => (int) $limit, ]; $dbResult = $obj->DBC->prepare($rq1); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $dbResult->bindValue($bindId, $bindValue, $bindType); } } $dbResult->execute(); $ct = 0; $flag = 0; $numRows = (int) $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn(); /** * Get criticality ids */ $critRes = $obj->DBC->query( "SELECT value, host_id FROM customvariables WHERE name = 'CRITICALITY_ID' AND service_id = 0" ); $criticalityUsed = 0; $critCache = []; if ($obj->DBC->numberRows()) { $criticalityUsed = 1; while ($critRow = $critRes->fetch()) { $critCache[$critRow['host_id']] = $critRow['value']; } } $obj->XML->startElement('reponse'); $obj->XML->startElement('i'); $obj->XML->writeElement('numrows', $numRows); $obj->XML->writeElement('num', $num); $obj->XML->writeElement('limit', $limit); $obj->XML->writeElement('p', $p); $obj->XML->writeElement('o', $o); $obj->XML->writeElement('sort_type', $sort_type); $obj->XML->writeElement('hard_state_label', _('Hard State Duration')); $obj->XML->writeElement('parent_host_label', _('Top Priority Hosts')); $obj->XML->writeElement('regular_host_label', _('Secondary Priority Hosts')); $obj->XML->writeElement('http_action_link', _('HTTP Action Link')); $obj->XML->writeElement('notif_disabled', _('Notification is disabled')); $obj->XML->writeElement('use_criticality', $criticalityUsed); $obj->XML->endElement(); $delimInit = 0; while ($data = $dbResult->fetch()) { if ($data['last_state_change'] > 0 && time() > $data['last_state_change']) { $duration = CentreonDuration::toString(time() - $data['last_state_change']); } else { $duration = 'N/A'; } if (($data['last_hard_state_change'] > 0) && ($data['last_hard_state_change'] >= $data['last_state_change'])) { $hard_duration = CentreonDuration::toString(time() - $data['last_hard_state_change']); } elseif ($data['last_hard_state_change'] > 0) { $hard_duration = ' N/A '; } else { $hard_duration = 'N/A'; } if ($data['is_parent']) { $delimInit = 1; } $class = null; if ($data['scheduled_downtime_depth'] > 0) { $class = 'line_downtime'; } elseif ($data['state'] == 1) { $class = $data['acknowledged'] == 1 ? 'line_ack' : 'list_down'; } elseif ($data['acknowledged'] == 1) { $class = 'line_ack'; } $obj->XML->startElement('l'); $trClass = $obj->getNextLineClass(); if (isset($class)) { $trClass = $class; } $obj->XML->writeAttribute('class', $trClass); $obj->XML->writeElement('o', $ct++); $obj->XML->writeElement('hc', $obj->colorHost[$data['state']]); $obj->XML->writeElement('f', $flag); $obj->XML->writeElement('hid', $data['host_id']); $obj->XML->writeElement('hn', CentreonUtils::escapeSecure($data['name']), false); $obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($data['name']))); $obj->XML->writeElement('a', ($data['address'] ? CentreonUtils::escapeSecure($data['address']) : 'N/A')); $obj->XML->writeElement('ou', ($data['output'] ? CentreonUtils::escapeSecure($data['output']) : 'N/A')); $obj->XML->writeElement( 'lc', ($data['last_check'] != 0 ? CentreonDuration::toString(time() - $data['last_check']) : 'N/A') ); $obj->XML->writeElement('cs', _($obj->statusHost[$data['state']]), false); $obj->XML->writeElement('pha', $data['acknowledged']); $obj->XML->writeElement('pce', $data['passive_checks']); $obj->XML->writeElement('ace', $data['active_checks']); $obj->XML->writeElement('lsc', ($duration ?: 'N/A')); $obj->XML->writeElement('lhs', ($hard_duration ?: 'N/A')); $obj->XML->writeElement('ha', $data['acknowledged']); $obj->XML->writeElement('hdtm', $data['scheduled_downtime_depth']); $obj->XML->writeElement( 'hdtmXml', './include/monitoring/downtime/xml/broker/makeXMLForDowntime.php?hid=' . $data['host_id'] ); $obj->XML->writeElement('hdtmXsl', './include/monitoring/downtime/xsl/popupForDowntime.xsl'); $obj->XML->writeElement( 'hackXml', './include/monitoring/acknowlegement/xml/broker/makeXMLForAck.php?hid=' . $data['host_id'] ); $obj->XML->writeElement('hackXsl', './include/monitoring/acknowlegement/xsl/popupForAck.xsl'); $obj->XML->writeElement('hae', $data['active_checks']); $obj->XML->writeElement('hpe', $data['passive_checks']); $obj->XML->writeElement('ne', $data['notify']); $obj->XML->writeElement( 'tr', $data['check_attempt'] . '/' . $data['max_check_attempts'] . ' (' . $obj->stateType[$data['state_type']] . ')' ); if (isset($data['criticality']) && $data['criticality'] != '' && isset($critCache[$data['host_id']])) { $obj->XML->writeElement('hci', 1); // has criticality $critData = $criticality->getData($critCache[$data['host_id']]); $obj->XML->writeElement('ci', $media->getFilename($critData['icon_id'])); $obj->XML->writeElement('cih', CentreonUtils::escapeSecure($critData['name'])); } else { $obj->XML->writeElement('hci', 0); // has no criticality } $obj->XML->writeElement('ico', $data['icon_image']); $obj->XML->writeElement('isp', $data['is_parent'] ? 1 : 0); $obj->XML->writeElement('isf', $data['flapping']); $parenth = 0; if ($ct === 1 && $data['is_parent']) { $parenth = 1; } if (! $sort_type && $delimInit && ! $data['is_parent']) { $delim = 1; $delimInit = 0; } else { $delim = 0; } $obj->XML->writeElement('parenth', $parenth); $obj->XML->writeElement('delim', $delim); if ($data['notes'] != '') { $obj->XML->writeElement( 'hnn', CentreonUtils::escapeSecure( $hostObj->replaceMacroInString( $data['host_id'], str_replace( 'HOSTNAME$', $data['name'], str_replace('$HOSTADDRESS$', $data['address'], $data['notes']) ) ) ) ); } else { $obj->XML->writeElement('hnn', 'none'); } if ($data['notes_url'] != '') { $str = str_replace('$HOSTNAME$', $data['name'], $data['notes_url']); $str = str_replace('$HOSTALIAS$', $data['alias'], $str); $str = str_replace('$HOSTADDRESS$', $data['address'], $str); $str = str_replace('$HOSTNOTES$', $data['notes'], $str); $str = str_replace('$INSTANCENAME$', $data['instance_name'], $str); $str = str_replace('$HOSTSTATEID$', $data['state'], $str); $str = str_replace('$HOSTSTATE$', $obj->statusHost[$data['state']], $str); $str = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $str ); $obj->XML->writeElement( 'hnu', CentreonUtils::escapeSecure($hostObj->replaceMacroInString($data['host_id'], $str)) ); } else { $obj->XML->writeElement('hnu', 'none'); } if ($data['action_url'] != '') { $str = $data['action_url']; $str = str_replace('$HOSTNAME$', $data['name'], $str); $str = str_replace('$HOSTALIAS$', $data['alias'], $str); $str = str_replace('$HOSTADDRESS$', $data['address'], $str); $str = str_replace('$HOSTNOTES$', $data['notes'], $str); $str = str_replace('$INSTANCENAME$', $data['instance_name'], $str); $str = str_replace('$HOSTSTATEID$', $data['state'], $str); $str = str_replace('$HOSTSTATE$', $obj->statusHost[$data['state']], $str); $str = str_replace( '$INSTANCEADDRESS$', $instanceObj->getParam($data['instance_name'], 'ns_ip_address'), $str ); $obj->XML->writeElement( 'hau', CentreonUtils::escapeSecure($hostObj->replaceMacroInString($data['host_id'], $str)) ); } else { $obj->XML->writeElement('hau', 'none'); } $obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18)); $obj->XML->endElement(); } $dbResult->closeCursor(); if (! $ct) { $obj->XML->writeElement('infos', 'none'); } $obj->XML->endElement(); $obj->header(); $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Notifications/notifications.php
centreon/www/include/monitoring/status/Notifications/notifications.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 realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once realpath(__DIR__ . '/../../../../../bootstrap.php'); require_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php'; CentreonSession::start(); $sid = session_id(); if (! isset($sid) || ! isset($_GET['refresh_rate'])) { exit; } $refreshRate = (int) $_GET['refresh_rate'] / 1000; $refreshRate += ($refreshRate / 2); $obj = new CentreonXMLBGRequest($dependencyInjector, $sid, 1, 1, 0, 1); $centreon = $_SESSION['centreon'] ?? null; if (! isset($_SESSION['centreon'])) { exit; } if (! isset($obj->session_id) || ! CentreonSession::checkSession($sid, $obj->DB)) { exit; } if (! isset($_SESSION['centreon_notification_preferences'])) { $userId = $centreon->user->get_id(); $resPref = $obj->DB->prepare("SELECT cp_key, cp_value FROM contact_param WHERE cp_key LIKE 'monitoring%notification%' AND cp_contact_id = :cp_contact_id"); $resPref->bindValue(':cp_contact_id', (int) $userId, PDO::PARAM_INT); $resPref->execute(); $notificationPreferences = []; while ($rowPref = $resPref->fetch()) { $notificationPreferences[$rowPref['cp_key']] = $rowPref['cp_value']; } $_SESSION['centreon_notification_preferences'] = $notificationPreferences; } else { $notificationPreferences = $_SESSION['centreon_notification_preferences']; } $notificationEnabled = false; foreach ($notificationPreferences as $key => $value) { if (preg_match('/monitoring_(host|svc)_notification_/', $key) && ! is_null($value) && $value == 1) { $notificationEnabled = true; break; } } if ($notificationEnabled === false) { $obj->XML->startElement('data'); $obj->XML->endElement(); $obj->header(); $obj->XML->output(); return; } $serviceStateLabel = [0 => 'OK', 1 => 'Warning', 2 => 'Critical', 3 => 'Unknown']; $serviceClassLabel = [0 => 'success', 1 => 'warning', 2 => 'error', 3 => 'alert']; $hostStateLabel = [0 => 'Up', 1 => 'Down', 2 => 'Unreachable']; $hostClassLabel = [0 => 'success', 1 => 'error', 2 => 'alert']; $sql = "SELECT name, description, s.state FROM services s, hosts h %s WHERE h.host_id = s.host_id AND h.name NOT LIKE '\_Module\_%%' AND (description NOT LIKE 'meta\_%%' AND description NOT LIKE 'ba\_%%') AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ") AND s.scheduled_downtime_depth=0 AND s.acknowledged=0 %s UNION SELECT 'Meta Service', s.display_name, s.state FROM services s, hosts h %s WHERE h.host_id = s.host_id AND h.name LIKE '\_Module\_Meta%%' AND description LIKE 'meta\_%%' AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ") AND s.scheduled_downtime_depth=0 AND s.acknowledged=0 %s UNION SELECT 'Business Activity', s.display_name, s.state FROM services s, hosts h %s WHERE h.host_id = s.host_id AND h.name LIKE '\_Module\_BAM%%' AND description LIKE 'ba\_%%' AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ") AND s.scheduled_downtime_depth=0 AND s.acknowledged=0 %s UNION SELECT name, NULL, h.state FROM hosts h %s WHERE name NOT LIKE '\_Module\_%%' AND h.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ') AND h.scheduled_downtime_depth=0 AND h.acknowledged=0 %s'; if ($obj->is_admin) { $sql = sprintf($sql, '', '', '', '', '', '', '', ''); } else { $sql = sprintf( $sql, ', centreon_acl acl', 'AND acl.service_id = s.service_id AND acl.host_id = h.host_id ' . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr), ', centreon_acl acl', 'AND acl.service_id = s.service_id AND acl.host_id = h.host_id ' . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr), ', centreon_acl acl', 'AND acl.service_id = s.service_id AND acl.host_id = h.host_id ' . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr), ', centreon_acl acl', 'AND acl.host_id = h.host_id' . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr) ); } $res = $obj->DBC->query($sql); $obj->XML->startElement('data'); while ($row = $res->fetch()) { $obj->XML->startElement('message'); if ($row['description']) { if (isset($notificationPreferences['monitoring_svc_notification_' . $row['state']])) { $obj->XML->writeAttribute( 'output', sprintf( '%s / %s is %s', $row['name'], $row['description'], $serviceStateLabel[$row['state']] ) ); $obj->XML->writeAttribute( 'class', $serviceClassLabel[$row['state']] ); } if ( ! isset($_SESSION['disable_sound']) && isset($notificationPreferences['monitoring_sound_svc_notification_' . $row['state']]) && $notificationPreferences['monitoring_sound_svc_notification_' . $row['state']] ) { $obj->XML->writeAttribute( 'sound', $notificationPreferences['monitoring_sound_svc_notification_' . $row['state']] ); } } else { if (isset($notificationPreferences['monitoring_host_notification_' . $row['state']])) { $obj->XML->writeAttribute( 'output', sprintf( '%s is %s', $row['name'], $hostStateLabel[$row['state']] ) ); $obj->XML->writeAttribute( 'class', $hostClassLabel[$row['state']] ); } if ( ! isset($_SESSION['disable_sound']) && isset($notificationPreferences['monitoring_sound_host_notification_' . $row['state']]) && $notificationPreferences['monitoring_sound_host_notification_' . $row['state']] ) { $obj->XML->writeAttribute( 'sound', $notificationPreferences['monitoring_sound_host_notification_' . $row['state']] ); } } $obj->XML->endElement(); } $obj->XML->endElement(); $obj->header(); $obj->XML->output();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/Notifications/notifications_action.php
centreon/www/include/monitoring/status/Notifications/notifications_action.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 * */ session_start(); $action = 'start'; if (isset($_GET['action'])) { $action = $_GET['action']; } if ($action == 'start' && isset($_SESSION['disable_sound'])) { unset($_SESSION['disable_sound']); } if ($action == 'stop') { $_SESSION['disable_sound'] = true; } session_write_close();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/serviceGridByHGJS.php
centreon/www/include/monitoring/status/ServicesHostGroups/serviceGridByHGJS.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 * */ if (! isset($centreon)) { exit(); } if (! isset($oreon->optGen['AjaxFirstTimeReloadStatistic']) || $oreon->optGen['AjaxFirstTimeReloadStatistic'] == 0) { $tFS = 10; } else { $tFS = $oreon->optGen['AjaxFirstTimeReloadStatistic'] * 1000; } if (! isset($oreon->optGen['AjaxFirstTimeReloadMonitoring']) || $oreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0) { $tFM = 10; } else { $tFM = $oreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000; } $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceGridByHGXML.php"; var _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl"; // hostgroup select2 value var hg_search = ""; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc"); if (document.getElementById('alias')) { var h = document.getElementById('alias'); h.innerHTML = '<?php echo addslashes(_('Hostgroups / Hosts')); ?>'; h.indice = 'alias'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; if (document.getElementById('current_state')) { var h = document.getElementById('current_state'); h.innerHTML = '<?php echo addslashes(_('Status')); ?>'; h.indice = 'current_state'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; } var h = document.getElementById('services'); h.innerHTML = '<?php echo addslashes(_('Services information')); ?>'; h.indice = 'services'; var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') { _linkaction_asc.appendChild(_img_asc); } else { _linkaction_asc.appendChild(_img_desc); } _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; h.appendChild(_linkaction_asc); } } function mainLoopLocal() { _currentInputField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputFieldValue = document.getElementById('host_search').value; } else { _currentInputFieldValue = ""; } if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue ) { if (!_lock) { set_search_host(escapeURI(_currentInputFieldValue)); _host_search = _currentInputFieldValue; monitoring_refresh(); if (_currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else { _currentInputField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; setTimeout(mainLoopLocal, 250); } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } // checking if a hostgroup was selected if (document.getElementById("select2-hg_search-container") && document.getElementById("select2-hg_search-container").title ) { this.hg_search = jQuery("#select2-hg_search-container .select2-content").attr("title"); viewDebugInfo('hostgroup search: ' + this.hg_search); } if (_first) { mainLoopLocal(); _first = 0; } _time =<?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { _lock = 1; var proc = new Transformation(); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml( _addrXML + "?" + '&search=' + _host_search + '&hg_search=' + this.hg_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&time=<?php echo time(); ?>' ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } if (_counter == 0) { document.getElementById("host_search").value = _host_search; _counter += 1; } _lock = 0; _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } </script>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/serviceSummaryByHG.php
centreon/www/include/monitoring/status/ServicesHostGroups/serviceSummaryByHG.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 * */ if (! isset($oreon)) { exit(); } include './include/common/autoNumLimit.php'; $sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types']; $order = ! isset($_GET['order']) ? 'ASC' : $_GET['order']; $num = ! isset($_GET['num']) ? 0 : $_GET['num']; $search_type_host = ! isset($_GET['search_type_host']) ? 1 : $_GET['search_type_host']; $search_type_service = ! isset($_GET['search_type_service']) ? 1 : $_GET['search_type_service']; $sort_type = ! isset($_GET['sort_type']) ? 'alias' : $_GET['sort_type']; $host_search = ! isset($_GET['host_search']) ? 0 : $_GET['host_search']; // Check search value in Host search field if (isset($_GET['host_search'])) { $centreon->historySearch[$url] = $_GET['host_search']; } $aTypeAffichageLevel1 = ['svcOVHG' => _('Details'), 'svcSumHG' => _('Summary')]; $aTypeAffichageLevel2 = ['' => _('All'), 'pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')]; $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once $hg_path . 'serviceSummaryByHGJS.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($hg_path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_types', $sort_types); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('typeDisplay', _('Display')); $tpl->assign('typeDisplay2', _('Display details')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $tpl->assign('search', _('Search')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('poller_listing', $oreon->user->access->checkAction('poller_listing')); $tpl->assign('hgStr', _('Hostgroup')); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); $form->addElement( 'select', 'typeDisplay', _('Display'), $aTypeAffichageLevel1, ['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);'] ); $form->addElement( 'select', 'typeDisplay2', _('Display '), $aTypeAffichageLevel2, ['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);'] ); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); ?> <script type="text/javascript"> _tm = <?php echo $tM; ?>; function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } function displayingLevel1(val) { _o = val; if (_o == 'svcOVHG') { _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceGridByHGXML.php"; _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl"; } else { _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceSummaryByHGXML.php"; _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl"; } monitoring_refresh(); } function displayingLevel2(val) { var sel1 = document.getElementById("typeDisplay").value; _o = sel1 + "_" + val; monitoring_refresh(); } </script> <?php $tpl->assign('limit', $limit); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('serviceGrid.ihtml'); ?>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/serviceGridByHG.php
centreon/www/include/monitoring/status/ServicesHostGroups/serviceGridByHG.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 * */ if (! isset($oreon)) { exit(); } include './include/common/autoNumLimit.php'; $sort_type = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'alias'; $hgSearch = isset($_GET['hg_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hg_search']) : ''; $search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : ''; $order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC'; $num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 30]]); // Check search value in Host search field $centreon->historySearch[$url] = $search; if (isset($hostgroup)) { $centreon->historySearch[$hostgroup] = $hgSearch; } $tab_class = ['0' => 'list_one', '1' => 'list_two']; $rows = 10; include_once './include/monitoring/status/Common/default_poller.php'; include_once './include/monitoring/status/Common/default_hostgroups.php'; include_once $hg_path . 'serviceGridByHGJS.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($hg_path, '/templates/'); $tpl->assign('p', $p); $tpl->assign('o', $o); $tpl->assign('sort_types', $sort_type); $tpl->assign('num', $num); $tpl->assign('limit', $limit); $tpl->assign('mon_host', _('Hosts')); $tpl->assign('mon_status', _('Status')); $tpl->assign('typeDisplay', _('Display')); $tpl->assign('typeDisplay2', _('Display details')); $tpl->assign('mon_ip', _('IP')); $tpl->assign('mon_last_check', _('Last Check')); $tpl->assign('mon_duration', _('Duration')); $tpl->assign('mon_status_information', _('Status information')); $tpl->assign('search', _('Search')); $tpl->assign('pollerStr', _('Poller')); $tpl->assign('poller_listing', $oreon->user->access->checkAction('poller_listing')); $tpl->assign('hgStr', _('Hostgroup')); $form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p); // adding hostgroup's select2 list $hostgroupsRoute = './api/internal.php?object=centreon_configuration_hostgroup&action=list'; $attrHostGroup = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostgroupsRoute, 'defaultDatasetRoute' => '', 'multiple' => false, 'linkedObject' => 'centreonHostgroups']; $form->addElement( 'select2', 'hg_search', '', ['id' => 'hg_search'], $attrHostGroup ); // display type $aTypeAffichageLevel1 = ['svcOVHG' => _('Details'), 'svcSumHG' => _('Summary')]; $form->addElement( 'select', 'typeDisplay', _('Display'), $aTypeAffichageLevel1, ['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);'] ); // status filters $aTypeAffichageLevel2 = ['' => _('All'), 'pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')]; $form->addElement( 'select', 'typeDisplay2', _('Display '), $aTypeAffichageLevel2, ['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);'] ); $form->setDefaults(['typeDisplay2' => 'pb']); $tpl->assign('order', strtolower($order)); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; $tpl->assign('tab_order', $tab_order); ?> <script type="text/javascript"> _tm = <?php echo $tM; ?>; function setO(_i) { document.forms['form'].elements['cmd'].value = _i; document.forms['form'].elements['o1'].selectedIndex = 0; document.forms['form'].elements['o2'].selectedIndex = 0; } function displayingLevel1(val) { var filterDetails = document.getElementById("typeDisplay2").value; _o = val; if (filterDetails !== '') { _o += '_' + filterDetails; } if (val == 'svcOVHG') { _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceGridByHGXML.php"; _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl"; } else { _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceSummaryByHGXML.php"; _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl"; } monitoring_refresh(); } function displayingLevel2(val) { var sel1 = document.getElementById("typeDisplay").value; _o = sel1; if (val !== '') { _o += '_' + val; } monitoring_refresh(); } </script> <?php $tpl->assign('limit', $limit); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('serviceGrid.ihtml'); ?>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/serviceSummaryByHGJS.php
centreon/www/include/monitoring/status/ServicesHostGroups/serviceSummaryByHGJS.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 * */ if (! isset($centreon)) { exit(); } if (! isset($oreon->optGen['AjaxFirstTimeReloadStatistic']) || $oreon->optGen['AjaxFirstTimeReloadStatistic'] == 0) { $tFS = 10; } else { $tFS = $oreon->optGen['AjaxFirstTimeReloadStatistic'] * 1000; } if (! isset($oreon->optGen['AjaxFirstTimeReloadMonitoring']) || $oreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0) { $tFM = 10; } else { $tFM = $oreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000; } $sid = session_id(); $time = time(); $obis = $o; if (isset($_GET['problem'])) { $obis .= '_pb'; } if (isset($_GET['acknowledge'])) { $obis .= '_ack_' . $_GET['acknowledge']; } ?> <script type="text/javascript"> var _debug = 0; var _addrXML = "./include/monitoring/status/ServicesHostGroups/xml/serviceSummaryByHGXML.php"; var _addrXSL = "./include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl"; <?php include_once './include/monitoring/status/Common/commonJS.php'; ?> function set_header_title() { var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc"); var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc"); if (document.getElementById('alias')) { var h = document.getElementById('alias'); h.innerHTML = '<?php echo addslashes(_('Hostgroups / Hosts')); ?>'; h.indice = 'alias'; h.onclick = function () { change_type_order(this.indice) }; h.style.cursor = "pointer"; var h = document.getElementById('services'); h.innerHTML = '<?php echo addslashes(_('Services information')); ?>'; h.indice = 'services'; var h = document.getElementById(_sort_type); var _linkaction_asc = document.createElement("a"); if (_order == 'ASC') _linkaction_asc.appendChild(_img_asc); else _linkaction_asc.appendChild(_img_desc); _linkaction_asc.href = '#'; _linkaction_asc.onclick = function () { change_order() }; h.appendChild(_linkaction_asc); } } function mainLoopLocal() { _currentInputField = document.getElementById('host_search'); if (document.getElementById('host_search') && document.getElementById('host_search').value) { _currentInputFieldValue = document.getElementById('host_search').value; } else { _currentInputFieldValue = ""; } if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) && _oldInputFieldValue != _currentInputFieldValue ) { if (!_lock) { set_search_host(escapeURI(_currentInputFieldValue)); _host_search = _currentInputFieldValue; monitoring_refresh(); if (_currentInputFieldValue.length >= 3) { _currentInputField.className = "search_input_active"; } else { _currentInputField.className = "search_input"; } } } _oldInputFieldValue = _currentInputFieldValue; setTimeout(mainLoopLocal, 250); } function initM(_time_reload, _o) { // INIT Select objects construct_selecteList_ndo_instance('instance_selected'); construct_HostGroupSelectList('hostgroups_selected'); if (document.getElementById("host_search") && document.getElementById("host_search").value) { _host_search = document.getElementById("host_search").value; viewDebugInfo('search: ' + document.getElementById("host_search").value); } else if (document.getElementById("host_search").length == 0) { _host_search = ""; } if (_first) { mainLoopLocal(); _first = 0; } _time =<?php echo $time; ?>; if (_on) { goM(_time_reload, _o); } } function goM(_time_reload, _o) { _lock = 1; var proc = new Transformation(); proc.setCallback(function(t){monitoringCallBack(t); proc = null;}); proc.setXml( _addrXML + "?" + '&search=' + _host_search + '&num=' + _num + '&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order + '&date_time_format_status=' + _date_time_format_status + '&o=' + _o + '&p=' + _p + '&time=<?php echo time(); ?>' ); proc.setXslt(_addrXSL); if (handleVisibilityChange()) { proc.transform("forAjax"); } if (_counter == 0) { document.getElementById("host_search").value = _host_search; _counter += 1; } _lock = 0; _timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload); _time_live = _time_reload; _on = 1; set_header_title(); } </SCRIPT>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false