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/configuration/configObject/contact/ldapsearch.php
centreon/www/include/configuration/configObject/contact/ldapsearch.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 _CENTREON_PATH_ . 'www/include/common/common-Func.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/centreonXML.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php'; CentreonSession::start(1); if (! isset($_SESSION['centreon'])) { exit(); } $oreon = $_SESSION['centreon']; if (! isset($_POST['confList']) || ! strlen($_POST['confList'])) { exit(); } $confList = $_POST['confList']; $ldap_search_filters = []; if (isset($_POST['ldap_search_filter'])) { $ldap_search_filters = $_POST['ldap_search_filter']; } global $buffer; $pearDB = new CentreonDB(); // Debug options $debug_ldap_import = false; $dbresult = $pearDB->query("SELECT `key`, `value` FROM `options` WHERE `key` IN ('debug_ldap_import', 'debug_path')"); while ($row = $dbresult->fetchRow()) { if ($row['key'] == 'debug_ldap_import') { if ($row['value'] == 1) { $debug_ldap_import = true; } } elseif ($row['key'] == 'debug_path') { $debug_path = trim($row['value']); } } $dbresult->closeCursor(); if ($debug_path == '') { $debug_ldap_import = false; } // Get ldap users in database $queryGetLdap = 'SELECT contact_alias FROM contact WHERE contact_register = 1'; $listLdapUsers = []; try { $res = $pearDB->query($queryGetLdap); while ($row = $res->fetchRow()) { $listLdapUsers[] = $row['contact_alias']; } } catch (PDOException $e) { // Nothing to do } $buffer = new CentreonXML(); $buffer->startElement('reponse'); $ids = explode(',', $confList); foreach ($ids as $arId) { $ldap = new CentreonLDAP($pearDB, null, $arId); $connect = false; if ($ldap->connect()) { $connect = true; } if ($connect) { $ldap_search_filter = ''; $ldap_base_dn = ''; $ldap_search_limit = 0; $ldap_search_timeout = 0; $query = 'SELECT ari_name, ari_value FROM auth_ressource_info WHERE ar_id = ?'; $res = $pearDB->prepare($query); $res->execute([$arId]); while ($row = $res->fetch()) { switch ($row['ari_name']) { case 'user_filter': $ldap_search_filter = sprintf($row['ari_value'], '*'); break; case 'user_base_search': $ldap_base_dn = $row['ari_value']; break; case 'ldap_search_timeout': $ldap_search_timeout = $row['ari_value']; break; case 'ldap_search_limit': $ldap_search_limit = $row['ari_value']; break; default: break; } } if (isset($ldap_search_filters[$arId]) && $ldap_search_filters[$arId]) { $ldap_search_filter = $ldap_search_filters[$arId]; } $searchResult = $ldap->search($ldap_search_filter, $ldap_base_dn, $ldap_search_limit, $ldap_search_timeout); $number_returned = count($searchResult); if ($number_returned) { $buffer->writeElement('entries', $number_returned); for ($i = 0; $i < $number_returned; $i++) { if (isset($searchResult[$i]['dn'])) { $isvalid = '0'; if ($searchResult[$i]['alias'] != '') { $isvalid = '1'; } $in_database = '0'; if (in_array($searchResult[$i]['alias'], $listLdapUsers)) { $in_database = '1'; } $searchResult[$i]['firstname'] = str_replace("'", '', $searchResult[$i]['firstname']); $searchResult[$i]['firstname'] = str_replace('"', '', $searchResult[$i]['firstname']); $searchResult[$i]['firstname'] = str_replace("\'", "\\\'", $searchResult[$i]['firstname']); $searchResult[$i]['lastname'] = str_replace("'", '', $searchResult[$i]['lastname']); $searchResult[$i]['lastname'] = str_replace('"', '', $searchResult[$i]['lastname']); $searchResult[$i]['lastname'] = str_replace("\'", "\\\'", $searchResult[$i]['lastname']); $searchResult[$i]['name'] = str_replace("'", '', $searchResult[$i]['name']); $searchResult[$i]['name'] = str_replace('"', '', $searchResult[$i]['name']); $searchResult[$i]['name'] = str_replace("\'", "\\\'", $searchResult[$i]['name']); $buffer->startElement('user'); $query = 'SELECT `ar_id`, `ar_name` FROM auth_ressource WHERE ar_id = ' . $pearDB->escape($arId); $resServer = $pearDB->query($query); $row = $resServer->fetchRow(); $buffer->writeAttribute('server', $row['ar_name']); $buffer->writeAttribute('ar_id', $row['ar_id']); $buffer->writeAttribute('isvalid', $isvalid); $buffer->startElement('dn'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['dn'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['dn'], 1, 0); $buffer->endElement(); $buffer->startElement('sn'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['lastname'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['lastname'], 1, 0); $buffer->endElement(); $buffer->startElement('givenname'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['firstname'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['firstname'], 1, 0); $buffer->endElement(); $buffer->startElement('mail'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['email'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['email'], 1, 0); $buffer->endElement(); $buffer->startElement('pager'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['pager'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['pager'], 1, 0); $buffer->endElement(); $buffer->startElement('cn'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['name'] != '') ? '1' : '0')); $buffer->text($searchResult[$i]['name'], 1, 0); $buffer->endElement(); $buffer->startElement('uid'); $buffer->writeAttribute('isvalid', (($searchResult[$i]['alias'] != '') ? '1' : '0'), 1); $buffer->text($searchResult[$i]['alias'], 1, 0); $buffer->endElement(); $buffer->startElement('in_database'); $buffer->text($in_database, 1, 0); $buffer->endElement(); $buffer->endElement(); } } } else { $buffer->writeElement('entries', '0'); $buffer->writeElement('error', ldap_err2str($ldap->getDs())); } } } if (isset($error)) { $buffer->writeElement('error', $error); } $buffer->endElement(); header('Content-Type: text/xml'); $buffer->output(); if (isset($debug_ldap_import) && $debug_ldap_import) { error_log( '[' . date('d/m/Y H:s') . '] LDAP Search : XML Output : ' . $buffer->output() . "\n", 3, $debug_path . 'ldapsearch.log' ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/contact.php
centreon/www/include/configuration/configObject/contact/contact.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 Centreon\Infrastructure\Event\EventDispatcher; use Centreon\Infrastructure\Event\EventHandler; use Centreon\ServiceProvider; if (! isset($centreon)) { exit(); } // LDAP import form const LDAP_IMPORT_FORM = 'li'; // Massive Change const MASSIVE_CHANGE = 'mc'; // Add a contact const ADD_CONTACT = 'a'; // Watch a contact const WATCH_CONTACT = 'w'; // Modify a contact const MODIFY_CONTACT = 'c'; // Activate a contact const ACTIVATE_CONTACT = 's'; // Massive activate on selected contacts const MASSIVE_ACTIVATE_CONTACT = 'ms'; // Deactivate a contact const DEACTIVATE_CONTACT = 'u'; // Massive deactivate on selected contacts const MASSIVE_DEACTIVATE_CONTACT = 'mu'; // Massive Unblock on selected contacts const MASSIVE_UNBLOCK_CONTACT = 'mun'; // Duplicate n contacts and notify it const DUPLICATE_CONTACTS = 'm'; // Delete n contacts and notify it const DELETE_CONTACTS = 'd'; // display notification const DISPLAY_NOTIFICATION = 'dn'; // Synchronize selected contacts with the LDAP const SYNC_LDAP_CONTACTS = 'sync'; // Unblock contact const UNBLOCK_CONTACT = 'un'; $cG = $_GET['contact_id'] ?? null; $cP = $_POST['contact_id'] ?? null; $contactId = $cG ?: $cP; $cG = $_GET['select'] ?? null; $cP = $_POST['select'] ?? null; $select = $cG ?: $cP; $cG = $_GET['dupNbr'] ?? null; $cP = $_POST['dupNbr'] ?? null; $dupNbr = $cG ?: $cP; // Path to the configuration dir $path = './include/configuration/configObject/contact/'; require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; // Set the real page if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) { $p = $ret['topology_page']; } $acl = $oreon->user->access; $allowedAclGroups = $acl->getAccessGroups(); /** * @var EventDispatcher $eventDispatcher */ $eventDispatcher = $dependencyInjector[ServiceProvider::CENTREON_EVENT_DISPATCHER]; if (! is_null($eventDispatcher->getDispatcherLoader())) { $eventDispatcher->getDispatcherLoader()->load(); } $duplicateEventHandler = new EventHandler(); $duplicateEventHandler->setProcessing( function (array $arguments) { if (isset($arguments['contact_ids'], $arguments['numbers'])) { $newContactIds = multipleContactInDB( $arguments['contact_ids'], $arguments['numbers'] ); // We store the result for possible future use return ['new_contact_ids' => $newContactIds]; } } ); $eventDispatcher->addEventHandler( 'contact.form', EventDispatcher::EVENT_DUPLICATE, $duplicateEventHandler ); // We define a event to delete a list of contacts $deleteEventHandler = new EventHandler(); $deleteEventHandler->setProcessing( function ($arguments): void { if (isset($arguments['contact_ids'])) { deleteContactInDB($arguments['contact_ids']); } } ); /* * We add the delete event in the context named 'contact.form' for and event type * EventDispatcher::EVENT_DELETE */ $eventDispatcher->addEventHandler( 'contact.form', EventDispatcher::EVENT_DELETE, $deleteEventHandler ); // Defining an event to manually request a LDAP synchronization of an array of contacts $synchronizeEventHandler = new EventHandler(); $synchronizeEventHandler->setProcessing( function ($arguments): void { if (isset($arguments['contact_ids'])) { synchronizeContactWithLdap($arguments['contact_ids']); } } ); $eventDispatcher->addEventHandler( 'contact.form', EventDispatcher::EVENT_SYNCHRONIZE, $synchronizeEventHandler ); switch ($o) { case LDAP_IMPORT_FORM: require_once $path . 'ldapImportContact.php'; break; case MASSIVE_CHANGE: case ADD_CONTACT: case WATCH_CONTACT: case MODIFY_CONTACT: require_once $path . 'formContact.php'; break; case ACTIVATE_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); enableContactInDB($contactId); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case MASSIVE_ACTIVATE_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); enableContactInDB(null, $select ?? []); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case DEACTIVATE_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); disableContactInDB($contactId); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case MASSIVE_DEACTIVATE_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); disableContactInDB(null, $select ?? []); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case MASSIVE_UNBLOCK_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); unblockContactInDB($select ?? []); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case DUPLICATE_CONTACTS: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $eventDispatcher->notify( 'contact.form', EventDispatcher::EVENT_DUPLICATE, [ 'contact_ids' => $select, 'numbers' => $dupNbr, ] ); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case DELETE_CONTACTS: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $eventDispatcher->notify( 'contact.form', EventDispatcher::EVENT_DELETE, ['contact_ids' => $select] ); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case DISPLAY_NOTIFICATION: require_once $path . 'displayNotification.php'; break; case SYNC_LDAP_CONTACTS: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); $eventDispatcher->notify( 'contact.form', EventDispatcher::EVENT_SYNCHRONIZE, ['contact_ids' => $select] ); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; case UNBLOCK_CONTACT: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); unblockContactInDB($contactId); } else { unvalidFormMessage(); } require_once $path . 'listContact.php'; break; default: require_once $path . 'listContact.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/configuration/configObject/servicegroup_dependency/formServiceGroupDependency.php
centreon/www/include/configuration/configObject/servicegroup_dependency/formServiceGroupDependency.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 * */ // // # Database retrieve information for Dependency // $dep = []; $initialValues = []; if (($o == MODIFY_DEPENDENCY || $o == WATCH_DEPENDENCY) && $dep_id) { $DBRESULT = $pearDB->prepare('SELECT * FROM dependency WHERE dep_id = :dep_id LIMIT 1'); $DBRESULT->bindValue(':dep_id', $dep_id, PDO::PARAM_INT); $DBRESULT->execute(); // Set base value $dep = array_map('myDecode', $DBRESULT->fetchRow()); // Set Notification Failure Criteria $dep['notification_failure_criteria'] = explode(',', $dep['notification_failure_criteria']); foreach ($dep['notification_failure_criteria'] as $key => $value) { $dep['notification_failure_criteria'][trim($value)] = 1; } // Set Execution Failure Criteria $dep['execution_failure_criteria'] = explode(',', $dep['execution_failure_criteria']); foreach ($dep['execution_failure_criteria'] as $key => $value) { $dep['execution_failure_criteria'][trim($value)] = 1; } $DBRESULT->closeCursor(); } // Database retrieve information for differents elements list we need on the page // Var information to format the element $attrsText = ['size' => '30']; $attrsText2 = ['size' => '10']; $attrsAdvSelect = ['style' => 'width: 300px; height: 150px;']; $attrsTextarea = ['rows' => '3', 'cols' => '30']; $eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />' . '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>'; $route = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup&action=list'; $attrServicegroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonServicegroups']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o == ADD_DEPENDENCY) { $form->addElement('header', 'title', _('Add a Dependency')); } elseif ($o == MODIFY_DEPENDENCY) { $form->addElement('header', 'title', _('Modify a Dependency')); } elseif ($o == WATCH_DEPENDENCY) { $form->addElement('header', 'title', _('View a Dependency')); } // Dependency basic information $form->addElement('header', 'information', _('Information')); $form->addElement('text', 'dep_name', _('Name'), $attrsText); $form->addElement('text', 'dep_description', _('Description'), $attrsText); $tab = []; $tab[] = $form->createElement('radio', 'inherits_parent', null, _('Yes'), '1'); $tab[] = $form->createElement('radio', 'inherits_parent', null, _('No'), '0'); $form->addGroup($tab, 'inherits_parent', _('Parent relationship'), '&nbsp;'); $form->setDefaults(['inherits_parent' => '1']); $tab = []; $tab[] = $form->createElement( 'checkbox', 'o', '&nbsp;', _('Ok'), ['id' => 'nOk', 'onClick' => 'applyNotificationRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'w', '&nbsp;', _('Warning'), ['id' => 'nWarning', 'onClick' => 'applyNotificationRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'u', '&nbsp;', _('Unknown'), ['id' => 'nUnknown', 'onClick' => 'applyNotificationRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'c', '&nbsp;', _('Critical'), ['id' => 'nCritical', 'onClick' => 'applyNotificationRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'p', '&nbsp;', _('Pending'), ['id' => 'nPending', 'onClick' => 'applyNotificationRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'n', '&nbsp;', _('None'), ['id' => 'nNone', 'onClick' => 'applyNotificationRules(this);'] ); $form->addGroup($tab, 'notification_failure_criteria', _('Notification Failure Criteria'), '&nbsp;&nbsp;'); $tab = []; $tab[] = $form->createElement( 'checkbox', 'o', '&nbsp;', _('Ok'), ['id' => 'eOk', 'onClick' => 'applyExecutionRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'w', '&nbsp;', _('Warning'), ['id' => 'eWarning', 'onClick' => 'applyExecutionRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'u', '&nbsp;', _('Unknown'), ['id' => 'eUnknown', 'onClick' => 'applyExecutionRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'c', '&nbsp;', _('Critical'), ['id' => 'eCritical', 'onClick' => 'applyExecutionRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'p', '&nbsp;', _('Pending'), ['id' => 'ePending', 'onClick' => 'applyExecutionRules(this);'] ); $tab[] = $form->createElement( 'checkbox', 'n', '&nbsp;', _('None'), ['id' => 'eNone', 'onClick' => 'applyExecutionRules(this);'] ); $form->addGroup($tab, 'execution_failure_criteria', _('Execution Failure Criteria'), '&nbsp;&nbsp;'); $query = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup' . '&action=defaultValues&target=dependency&field=dep_sgParents&id=' . $dep_id; $attrServicegroup1 = array_merge( $attrServicegroups, ['defaultDatasetRoute' => $query] ); $form->addElement('select2', 'dep_sgParents', _('Servicegroups'), [], $attrServicegroup1); $route = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup' . '&action=defaultValues&target=dependency&field=dep_sgChilds&id=' . $dep_id; $attrServicegroup2 = array_merge( $attrServicegroups, ['defaultDatasetRoute' => $route] ); $form->addElement('select2', 'dep_sgChilds', _('Dependent Servicegroups'), [], $attrServicegroup2); $form->addElement('textarea', 'dep_comment', _('Comments'), $attrsTextarea); $form->addElement('hidden', 'dep_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $init = $form->addElement('hidden', 'initialValues'); $init->setValue(serialize($initialValues)); // Form Rules $form->applyFilter('__ALL__', 'myTrim'); $form->registerRule('sanitize', 'callback', 'isNotEmptyAfterStringSanitize'); $form->addRule('dep_name', _('Compulsory Name'), 'required'); $form->addRule('dep_name', _('Unauthorized value'), 'sanitize'); $form->addRule('dep_description', _('Required Field'), 'required'); $form->addRule('dep_description', _('Unauthorized value'), 'sanitize'); $form->addRule('dep_sgParents', _('Required Field'), 'required'); $form->addRule('dep_sgChilds', _('Required Field'), 'required'); $form->addRule('execution_failure_criteria', _('Required Field'), 'required'); $form->addRule('notification_failure_criteria', _('Required Field'), 'required'); $form->registerRule('cycle', 'callback', 'testServiceGroupDependencyCycle'); $form->addRule('dep_sgChilds', _('Circular Definition'), 'cycle'); $form->registerRule('exist', 'callback', 'testServiceGroupDependencyExistence'); $form->addRule('dep_name', _('Name is already in use'), 'exist'); $form->setRequiredNote("<font style='color: red;'>*</font>&nbsp;" . _('Required fields')); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // Just watch a Dependency information if ($o == WATCH_DEPENDENCY) { if ($centreon->user->access->page($p) != 2) { $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dep_id=' . $dep_id . "'"] ); } $form->setDefaults($dep); $form->freeze(); } elseif ($o == MODIFY_DEPENDENCY) { // Modify a Dependency information $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $form->setDefaults($dep); } elseif ($o == ADD_DEPENDENCY) { // Add a Dependency information $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $form->setDefaults(['inherits_parent', '0']); } $tpl->assign( 'helpattr', 'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, ' . '"orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], ' . 'WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"' ); // prepare help texts $helptext = ''; include_once 'include/configuration/configObject/service_dependency/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()) { $depObj = $form->getElement('dep_id'); if ($form->getSubmitValue('submitA')) { $depObj->setValue(insertServiceGroupDependencyInDB()); } elseif ($form->getSubmitValue('submitC')) { updateServiceGroupDependencyInDB($depObj->getValue('dep_id')); } $o = null; $valid = true; } if ($valid) { require_once 'listServiceGroupDependency.php'; } else { // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true); $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('formServiceGroupDependency.ihtml'); } ?> <script type="text/javascript"> function applyNotificationRules(object) { console.log(object.id); if (object.id === "nNone" && object.checked) { document.getElementById('nOk').checked = false; document.getElementById('nWarning').checked = false; document.getElementById('nUnknown').checked = false; document.getElementById('nCritical').checked = false; document.getElementById('nPending').checked = false; } else { document.getElementById('nNone').checked = false; } } function applyExecutionRules(object) { if (object.id === "eNone" && object.checked) { document.getElementById('eOk').checked = false; document.getElementById('eWarning').checked = false; document.getElementById('eUnknown').checked = false; document.getElementById('eCritical').checked = false; document.getElementById('ePending').checked = false; } else { document.getElementById('eNone').checked = false; } } </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/configuration/configObject/servicegroup_dependency/DB-Func.php
centreon/www/include/configuration/configObject/servicegroup_dependency/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(); } function testServiceGroupDependencyExistence($name = null) { global $pearDB; global $form; CentreonDependency::purgeObsoleteDependencies($pearDB); $id = null; if (isset($form)) { $id = $form->getSubmitValue('dep_id'); } $query = "SELECT dep_name, dep_id FROM dependency WHERE dep_name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'"; $dbResult = $pearDB->query($query); $dep = $dbResult->fetch(); // Modif case if ($dbResult->rowCount() >= 1 && $dep['dep_id'] == $id) { return true; } // Duplicate entry return ! ($dbResult->rowCount() >= 1 && $dep['dep_id'] != $id); } function testServiceGroupDependencyCycle($childs = null) { global $pearDB; global $form; $parents = []; $childs = []; if (isset($form)) { $parents = $form->getSubmitValue('dep_sgParents'); $childs = $form->getSubmitValue('dep_sgChilds'); $childs = array_flip($childs); } foreach ($parents as $parent) { if (array_key_exists($parent, $childs)) { return false; } } return true; } function deleteServiceGroupDependencyInDB($dependencies = []) { global $pearDB, $oreon; foreach ($dependencies as $key => $value) { $dbResult2 = $pearDB->query("SELECT dep_name FROM `dependency` WHERE `dep_id` = '" . $key . "' LIMIT 1"); $row = $dbResult2->fetch(); $pearDB->query("DELETE FROM dependency WHERE dep_id = '" . $key . "'"); $oreon->CentreonLogAction->insertLog('servicegroup dependency', $key, $row['dep_name'], 'd'); } } function multipleServiceGroupDependencyInDB($dependencies = [], $nbrDup = []) { foreach ($dependencies as $key => $value) { global $pearDB, $oreon; $dbResult = $pearDB->query("SELECT * FROM dependency WHERE dep_id = '" . $key . "' LIMIT 1"); $row = $dbResult->fetch(); $row['dep_id'] = null; for ($i = 1; $i <= $nbrDup[$key]; $i++) { $val = null; foreach ($row as $key2 => $value2) { $value2 = is_int($value2) ? (string) $value2 : $value2; if ($key2 == 'dep_name') { $dep_name = $value2 . '_' . $i; $value2 = $value2 . '_' . $i; } $val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL') : $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL'); if ($key2 != 'dep_id') { $fields[$key2] = $value2; } if (isset($dep_name)) { $fields['dep_name'] = $dep_name; } } if (isset($dep_name) && testServiceGroupDependencyExistence($dep_name)) { $rq = $val ? 'INSERT INTO dependency VALUES (' . $val . ')' : null; $pearDB->query($rq); $dbResult = $pearDB->query('SELECT MAX(dep_id) FROM dependency'); $maxId = $dbResult->fetch(); if (isset($maxId['MAX(dep_id)'])) { $query = 'SELECT DISTINCT servicegroup_sg_id FROM dependency_servicegroupParent_relation ' . "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields['dep_sgParents'] = ''; $query = 'INSERT INTO dependency_servicegroupParent_relation ' . 'VALUES (:dep_id, :servicegroup_sg_id)'; $statement = $pearDB->prepare($query); while ($sg = $dbResult->fetch()) { $statement->bindValue(':dep_id', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT); $statement->bindValue(':servicegroup_sg_id', (int) $sg['servicegroup_sg_id'], PDO::PARAM_INT); $statement->execute(); $fields['dep_sgParents'] .= $sg['servicegroup_sg_id'] . ','; } $fields['dep_sgParents'] = trim($fields['dep_sgParents'], ','); $dbResult->closeCursor(); $query = 'SELECT DISTINCT servicegroup_sg_id FROM dependency_servicegroupChild_relation ' . "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields['dep_sgChilds'] = ''; $query = 'INSERT INTO dependency_servicegroupChild_relation ' . 'VALUES (:dep_id, :servicegroup_sg_id)'; $statement = $pearDB->prepare($query); while ($sg = $dbResult->fetch()) { $statement->bindValue(':dep_id', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT); $statement->bindValue(':servicegroup_sg_id', (int) $sg['servicegroup_sg_id'], PDO::PARAM_INT); $statement->execute(); $fields['dep_sgChilds'] .= $sg['servicegroup_sg_id'] . ','; } $fields['dep_sgChilds'] = trim($fields['dep_sgChilds'], ','); $oreon->CentreonLogAction->insertLog( 'servicegroup dependency', $maxId['MAX(dep_id)'], $dep_name, 'a', $fields ); $dbResult->closeCursor(); } } } } } function updateServiceGroupDependencyInDB($dep_id = null) { if (! $dep_id) { exit(); } updateServiceGroupDependency($dep_id); updateServiceGroupDependencyServiceGroupParents($dep_id); updateServiceGroupDependencyServiceGroupChilds($dep_id); } function insertServiceGroupDependencyInDB($ret = []) { $dep_id = insertServiceGroupDependency($ret); updateServiceGroupDependencyServiceGroupParents($dep_id, $ret); updateServiceGroupDependencyServiceGroupChilds($dep_id, $ret); return $dep_id; } /** * Create a service group dependency * * @param array<string, mixed> $ret * @return int */ function insertServiceGroupDependency($ret = []): int { global $form, $pearDB, $centreon; if (! count($ret)) { $ret = $form->getSubmitValues(); } $resourceValues = sanitizeResourceParameters($ret); $statement = $pearDB->prepare( 'INSERT INTO `dependency` (dep_name, dep_description, inherits_parent, execution_failure_criteria, notification_failure_criteria, dep_comment) VALUES (:depName, :depDescription, :inheritsParent, :executionFailure, :notificationFailure, :depComment)' ); $statement->bindValue(':depName', $resourceValues['dep_name'], PDO::PARAM_STR); $statement->bindValue(':depDescription', $resourceValues['dep_description'], PDO::PARAM_STR); $statement->bindValue(':inheritsParent', $resourceValues['inherits_parent'], PDO::PARAM_STR); $statement->bindValue(':executionFailure', $resourceValues['execution_failure_criteria'], PDO::PARAM_STR); $statement->bindValue(':notificationFailure', $resourceValues['notification_failure_criteria'], PDO::PARAM_STR); $statement->bindValue(':depComment', $resourceValues['dep_comment'], PDO::PARAM_STR); $statement->execute(); $dbResult = $pearDB->query('SELECT MAX(dep_id) FROM dependency'); $depId = $dbResult->fetch(); // Prepare value for changelog $fields = CentreonLogAction::prepareChanges($resourceValues); $centreon->CentreonLogAction->insertLog( 'servicegroup dependency', $depId['MAX(dep_id)'], $resourceValues['dep_name'], 'a', $fields ); return (int) $depId['MAX(dep_id)']; } /** * Update a service group dependency * * @param null|int $depId */ function updateServiceGroupDependency($depId = null): void { if (! $depId) { exit(); } global $form, $pearDB, $centreon; $resourceValues = sanitizeResourceParameters($form->getSubmitValues()); $statement = $pearDB->prepare( 'UPDATE `dependency` SET dep_name = :depName, dep_description = :depDescription, inherits_parent = :inheritsParent, execution_failure_criteria = :executionFailure, notification_failure_criteria = :notificationFailure, dep_comment = :depComment WHERE dep_id = :depId' ); $statement->bindValue(':depName', $resourceValues['dep_name'], PDO::PARAM_STR); $statement->bindValue(':depDescription', $resourceValues['dep_description'], PDO::PARAM_STR); $statement->bindValue(':inheritsParent', $resourceValues['inherits_parent'], PDO::PARAM_STR); $statement->bindValue(':executionFailure', $resourceValues['execution_failure_criteria'], PDO::PARAM_STR); $statement->bindValue(':notificationFailure', $resourceValues['notification_failure_criteria'], PDO::PARAM_STR); $statement->bindValue(':depComment', $resourceValues['dep_comment'], PDO::PARAM_STR); $statement->bindValue(':depId', $depId, PDO::PARAM_INT); $statement->execute(); // Prepare value for changelog $fields = CentreonLogAction::prepareChanges($resourceValues); $centreon->CentreonLogAction->insertLog( 'servicegroup dependency', $depId, $resourceValues['dep_name'], 'c', $fields ); } /** * sanitize resources parameter for Create / Update a service group dependency * * @param array<string, mixed> $resources * @return array<string, mixed> */ function sanitizeResourceParameters(array $resources): array { $sanitizedParameters = []; $sanitizedParameters['dep_name'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_name']); if (empty($sanitizedParameters['dep_name'])) { throw new InvalidArgumentException(_("Dependency name can't be empty")); } $sanitizedParameters['dep_description'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_description']); if (empty($sanitizedParameters['dep_description'])) { throw new InvalidArgumentException(_("Dependency description can't be empty")); } $resources['inherits_parent']['inherits_parent'] == 1 ? $sanitizedParameters['inherits_parent'] = '1' : $sanitizedParameters['inherits_parent'] = '0'; $sanitizedParameters['execution_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags( implode( ',', array_keys($resources['execution_failure_criteria']) ) ); $sanitizedParameters['notification_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags( implode( ',', array_keys($resources['notification_failure_criteria']) ) ); $sanitizedParameters['dep_comment'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_comment']); return $sanitizedParameters; } function updateServiceGroupDependencyServiceGroupParents($dep_id = null, $ret = []) { if (! $dep_id) { exit(); } global $form; global $pearDB; if (! count($ret)) { $ret = $form->getSubmitValues(); } $rq = 'DELETE FROM dependency_servicegroupParent_relation '; $rq .= "WHERE dependency_dep_id = '" . $dep_id . "'"; $pearDB->query($rq); if (isset($ret['dep_sgParents'])) { $ret = $ret['dep_sgParents']; } else { $ret = CentreonUtils::mergeWithInitialValues($form, 'dep_sgParents'); } $counter = count($ret); for ($i = 0; $i < $counter; $i++) { $rq = 'INSERT INTO dependency_servicegroupParent_relation '; $rq .= '(dependency_dep_id, servicegroup_sg_id) '; $rq .= 'VALUES '; $rq .= "('" . $dep_id . "', '" . $ret[$i] . "')"; $pearDB->query($rq); } } function updateServiceGroupDependencyServiceGroupChilds($dep_id = null, $ret = []) { if (! $dep_id) { exit(); } global $form; global $pearDB; if (! count($ret)) { $ret = $form->getSubmitValues(); } $rq = 'DELETE FROM dependency_servicegroupChild_relation '; $rq .= "WHERE dependency_dep_id = '" . $dep_id . "'"; $pearDB->query($rq); if (isset($ret['dep_sgChilds'])) { $ret = $ret['dep_sgChilds']; } else { $ret = CentreonUtils::mergeWithInitialValues($form, 'dep_sgChilds'); } $counter = count($ret); for ($i = 0; $i < $counter; $i++) { $rq = 'INSERT INTO dependency_servicegroupChild_relation '; $rq .= '(dependency_dep_id, servicegroup_sg_id) '; $rq .= 'VALUES '; $rq .= "('" . $dep_id . "', '" . $ret[$i] . "')"; $pearDB->query($rq); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup_dependency/serviceGroupDependency.php
centreon/www/include/configuration/configObject/servicegroup_dependency/serviceGroupDependency.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 ADD_DEPENDENCY = 'a'; const WATCH_DEPENDENCY = 'w'; const MODIFY_DEPENDENCY = 'c'; const DUPLICATE_DEPENDENCY = 'm'; const DELETE_DEPENDENCY = 'd'; // Path to the configuration dir $path = './include/configuration/configObject/servicegroup_dependency/'; // PHP functions require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; $dep_id = filter_var( $_GET['dep_id'] ?? $_POST['dep_id'] ?? null, FILTER_VALIDATE_INT ); $select = filter_var_array( getSelectOption(), FILTER_VALIDATE_INT ); $dupNbr = filter_var_array( getDuplicateNumberOption(), FILTER_VALIDATE_INT ); // Set the real page if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) { $p = $ret['topology_page']; } $acl = $oreon->user->access; $sgs = $acl->getServiceGroupAclConf(null, 'broker'); $sgstring = CentreonUtils::toStringWithQuotes($sgs); switch ($o) { case ADD_DEPENDENCY: case WATCH_DEPENDENCY: case MODIFY_DEPENDENCY: require_once $path . 'formServiceGroupDependency.php'; break; case DUPLICATE_DEPENDENCY: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); multipleServiceGroupDependencyInDB( is_array($select) ? $select : [], is_array($dupNbr) ? $dupNbr : [] ); } else { unvalidFormMessage(); } require_once $path . 'listServiceGroupDependency.php'; break; case DELETE_DEPENDENCY: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); deleteServiceGroupDependencyInDB(is_array($select) ? $select : []); } else { unvalidFormMessage(); } require_once $path . 'listServiceGroupDependency.php'; break; default: require_once $path . 'listServiceGroupDependency.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/configuration/configObject/servicegroup_dependency/listServiceGroupDependency.php
centreon/www/include/configuration/configObject/servicegroup_dependency/listServiceGroupDependency.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 './class/centreonUtils.class.php'; include './include/common/autoNumLimit.php'; $list = $_GET['list'] ?? null; $aclCond = ''; if (! $centreon->user->admin) { $aclCond = " AND servicegroup_sg_id IN ({$sgstring}) "; } $search = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchSGD'] ?? $_GET['searchSGD'] ?? null ); if (isset($_POST['searchSGD']) || isset($_GET['searchSGD'])) { // saving filters values $centreon->historySearch[$url] = []; $centreon->historySearch[$url]['search'] = $search; } else { // restoring saved values $search = $centreon->historySearch[$url]['search'] ?? null; } // Dependencies list $rq = 'SELECT SQL_CALC_FOUND_ROWS dep_id, dep_name, dep_description FROM dependency dep'; $rq .= ' WHERE ((SELECT DISTINCT COUNT(*) FROM dependency_servicegroupParent_relation dsgpr WHERE dsgpr.dependency_dep_id = dep.dep_id ' . $aclCond . ') > 0 OR (SELECT DISTINCT COUNT(*) FROM dependency_servicegroupChild_relation dsgpr WHERE dsgpr.dependency_dep_id = dep.dep_id ' . $aclCond . ') > 0)'; // Search Case if ($search) { $rq .= " AND (dep_name LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8') . "%' OR dep_description LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8') . "%')"; } $rq .= ' ORDER BY dep_name, dep_description LIMIT ' . $num * $limit . ', ' . $limit; $dbResult = $pearDB->query($rq); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // Access level $lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r'; $tpl->assign('mode_access', $lvl_access); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_description', _('Description')); $tpl->assign('headerMenu_options', _('Options')); $search = tidySearchKey($search, $advanced_search); $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); // Fill a tab with a multidimensional Array we put in $tpl $elemArr = []; for ($i = 0; $dep = $dbResult->fetch(); $i++) { $moptions = ''; $selectedElements = $form->addElement('checkbox', 'select[' . $dep['dep_id'] . ']'); $moptions .= '&nbsp;<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) ' . 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;' . "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $dep['dep_id'] . "]' />"; $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(htmlentities($dep['dep_name'])), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&dep_id=' . $dep['dep_id'], 'RowMenu_description' => CentreonUtils::escapeSecure(htmlentities($dep['dep_description'])), 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); // Toolbar select ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['o'].value = _i; } </script> <?php $attrs1 = ['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 == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 3) {" . " setO(this.form.elements['o1'].value); submit();} " . '']; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs1 ); $form->setDefaults(['o1' => null]); $attrs2 = ['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 == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 3) {" . " setO(this.form.elements['o2'].value); submit();} " . '']; $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $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('searchSGD', $search); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listServiceGroupDependency.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/configuration/configCentreonBroker/listCentreonBroker.php
centreon/www/include/configuration/configCentreonBroker/listCentreonBroker.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 './class/centreonUtils.class.php'; include './include/common/autoNumLimit.php'; // nagios servers comes from DB $nagios_servers = []; $dbResult = $pearDB->query('SELECT * FROM nagios_server ORDER BY name'); while ($nagios_server = $dbResult->fetch()) { $nagios_servers[$nagios_server['id']] = $nagios_server['name']; } $dbResult->closeCursor(); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate(__DIR__); // Access level $lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r'; $tpl->assign('mode_access', $lvl_access); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_desc', _('Requester')); $tpl->assign('headerMenu_outputs', _('Outputs')); $tpl->assign('headerMenu_inputs', _('Inputs')); $tpl->assign('headerMenu_status', _('Status')); $tpl->assign('headerMenu_options', _('Options')); // Centreon Broker config list $search = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['searchCB'] ?? $_GET['searchCB'] ?? null, ); if (isset($_POST['searchCB']) || isset($_GET['searchCB'])) { // saving filters values $centreon->historySearch[$url] = []; $centreon->historySearch[$url]['search'] = $search; } else { // restoring saved values $search = $centreon->historySearch[$url]['search'] ?? null; } $aclCond = ''; if (! $centreon->user->admin && count($allowedBrokerConf)) { $aclCond = $search !== '' ? ' AND ' : ' WHERE '; $aclCond .= 'config_id IN (' . implode(',', array_keys($allowedBrokerConf)) . ') '; } if ($search !== '') { $cfgBrokerStmt = $pearDB->prepare( 'SELECT SQL_CALC_FOUND_ROWS config_id, config_name, ns_nagios_server, config_activate ' . 'FROM cfg_centreonbroker ' . 'WHERE config_name LIKE :search' . $aclCond . ' ORDER BY config_name ' . 'LIMIT :scoop, :limit' ); $cfgBrokerStmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR); } else { $cfgBrokerStmt = $pearDB->prepare( 'SELECT SQL_CALC_FOUND_ROWS config_id, config_name, ns_nagios_server, config_activate ' . 'FROM cfg_centreonbroker ' . $aclCond . ' ORDER BY config_name ' . 'LIMIT :scoop, :limit' ); } $cfgBrokerStmt->bindValue(':scoop', (int) $num * (int) $limit, PDO::PARAM_INT); $cfgBrokerStmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT); $cfgBrokerStmt->execute(); // Get results numbers $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); include './include/common/checkPagination.php'; $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; // Fill a tab with a multidimensional Array we put in $tpl $elemArr = []; $centreonToken = createCSRFToken(); $statementBrokerInfo = $pearDB->prepare( 'SELECT COUNT(DISTINCT(config_group_id)) as num ' . 'FROM cfg_centreonbroker_info ' . 'WHERE config_group = :config_group ' . 'AND config_id = :config_id' ); for ($i = 0; $config = $cfgBrokerStmt->fetch(); $i++) { $moptions = ''; $selectedElements = $form->addElement('checkbox', 'select[' . $config['config_id'] . ']'); if ($config['config_activate']) { $moptions .= "<a href='main.php?p=" . $p . '&id=' . $config['config_id'] . '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/disabled.png' class='ico-14' border='0' alt='" . _('Disabled') . "'></a>&nbsp;&nbsp;"; } else { $moptions .= "<a href='main.php?p=" . $p . '&id=' . $config['config_id'] . '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/enabled.png' class='ico-14' border='0' alt='" . _('Enabled') . "'></a>&nbsp;&nbsp;"; } $moptions .= '&nbsp;<input onKeypress="if(event.keyCode > 31 ' . '&& (event.keyCode < 45 || event.keyCode > 57)) event.returnValue = false; ' . 'if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;"' . " maxlength=\"3\" size=\"3\" value='1' " . "style=\"margin-bottom:0px;\" name='dupNbr[" . $config['config_id'] . "]'></input>"; // Number of output $statementBrokerInfo->bindValue(':config_id', (int) $config['config_id'], PDO::PARAM_INT); $statementBrokerInfo->bindValue(':config_group', 'output', PDO::PARAM_STR); $statementBrokerInfo->execute(); $row = $statementBrokerInfo->fetch(PDO::FETCH_ASSOC); $outputNumber = $row['num']; // Number of input $statementBrokerInfo->bindValue(':config_group', 'input', PDO::PARAM_STR); $statementBrokerInfo->execute(); $row = $statementBrokerInfo->fetch(PDO::FETCH_ASSOC); $inputNumber = $row['num']; $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => htmlentities($config['config_name'], ENT_QUOTES, 'UTF-8'), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&id=' . $config['config_id'], 'RowMenu_desc' => CentreonUtils::escapeSecure( substr( $nagios_servers[$config['ns_nagios_server']], 0, 40 ) ), 'RowMenu_inputs' => $inputNumber, 'RowMenu_outputs' => $outputNumber, 'RowMenu_status' => $config['config_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $config['config_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'addWizard' => _('Add with wizard'), 'delConfirm' => _('Do you confirm the deletion ?')] ); ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['o'].value = _i; } </script> <?php $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 == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 3) {" . " setO(this.form.elements['o1'].value); submit();} " . '']; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $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 == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 3) {" . " setO(this.form.elements['o2'].value); submit();} " . '']; $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs ); $form->setDefaults(['o2' => null]); $o2 = $form->getElement('o2'); $o2->setValue(null); $tpl->assign('limit', $limit); $tpl->assign('searchCB', $search); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listCentreonBroker.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/configuration/configCentreonBroker/help.php
centreon/www/include/configuration/configCentreonBroker/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 * */ echo _('Time in seconds to wait before launching failover.'); echo _('Category filter for flux in output'); echo _("Trusted CA's certificate."); echo _('When enabled, the broker engine will check whether or not the replication is up to date before attempting to update data.'); echo _('Interval in seconds before delete data from deleted pollers.'); echo _('File for external commands'); echo _('Enable or not data stream compression.'); echo _('The higher the buffer size is, the best compression. This however increase data streaming latency. Use with caution.'); echo _('Ranges from 0 (no compression) to 9 (best compression). Default is -1 (zlib compression)'); echo _('Enable or not configuration messages logging.'); echo _('IP address or hostname of the database server.'); echo _('Database name.'); echo _('Password of database user.'); echo _('Port on which the DB server listens'); echo _('Target DBMS.'); echo _('Database user.'); echo _('Enable or not debug messages logging.'); echo _('Enable or not error messages logging.'); echo _('Name of the input or output object that will act as failover.'); echo _('File where Centreon Broker statistics will be stored'); echo _('IP address or hostname of the host to connect to (leave blank for listening mode).'); echo _('Enable or not informational messages logging.'); echo _("Whether or not Broker should create entries in the index_data table. This process should be done by Centreon and this option should only be enabled by advanced users knowing what they're doing"); echo _('Interval in seconds before change status of resources from a disconnected poller'); echo _('Interval length in seconds.'); echo _('RRD storage duration in seconds.'); echo _('How much messages must be logged.'); echo _('Maximum size in bytes.'); echo _('The maximum size of log file.'); echo _('RRD file directory, for example /var/lib/centreon/metrics'); echo _("For a file logger this is the path to the file. For a standard logger, one of 'stdout' or 'stderr'."); echo _('Enable negotiation option (use only for version of Centren Broker >= 2.5)'); echo _('This allows the retention to work even if the socket is listening'); echo _('The Unix socket used to communicate with rrdcached. This is a global option, go to Administration > Options > RRDTool to modify it.'); echo _('Path to the file.'); echo _('Port to listen on (empty host) or to connect to (with host filled).'); echo _('The TCP port used to communicate with rrdcached. This is a global option, go to Administration > Options > RRDTool to modify it.'); echo _('Private key file path when TLS encryption is used.'); echo _('Serialization protocol.'); echo _('Public certificate file path when TLS encryption is used.'); echo _('The maximum queries per transaction before commit.'); echo _('The transaction timeout before running commit.'); echo _('The interval between check if some metrics must be rebuild. The default value is 300s'); echo _('Time in seconds to wait between each connection attempt (Default value: 30s).'); echo _('RRD file directory, for example /var/lib/centreon/status'); echo _('It should be enabled to control whether or not Centreon Broker should insert performance data in the data_bin table.'); echo _('Enable TLS encryption.'); echo _('This can be used to disable graph update and therefore reduce I/O'); echo _('This can be used to disable graph update and therefore reduce I/O'); echo _('Usually cpus/2.');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configCentreonBroker/formCentreonBroker.php
centreon/www/include/configuration/configCentreonBroker/formCentreonBroker.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(); } $id = filter_var( $_REQUEST['id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['default' => 0]] ); if ( ! $centreon->user->admin && $id !== 0 && count($allowedBrokerConf) && ! isset($allowedBrokerConf[$id]) ) { $msg = new CentreonMsg(); $msg->setImage('./img/icons/warning.png'); $msg->setTextStyle('bold'); $msg->setText(_('You are not allowed to access this object configuration')); return null; } $cbObj = new CentreonConfigCentreonBroker($pearDB); /** * @param mixed $data * @return mixed */ function htmlEncodeBrokerInformation(mixed $data): mixed { if (is_string($data)) { $data = htmlentities($data); } return $data; } /** * @param mixed $data * @return mixed */ function htmlDecodeBrokerInformation(mixed $data): mixed { if (is_string($data)) { $data = html_entity_decode($data); } return $data; } // nagios servers comes from DB $nagios_servers = []; $serverAcl = ''; if (! $centreon->user->admin && $serverString != "''") { $serverAcl = " WHERE id IN ({$serverString}) "; } $DBRESULT = $pearDB->query("SELECT * FROM nagios_server {$serverAcl} ORDER BY name"); while ($nagios_server = $DBRESULT->fetchRow()) { $nagios_servers[$nagios_server['id']] = HtmlSanitizer::createFromString($nagios_server['name'])->sanitize()->getString(); } $DBRESULT->closeCursor(); // Var information to format the element $attrsText = ['size' => '120']; $attrsText2 = ['size' => '50']; $attrsText3 = ['size' => '10']; $attrsTextarea = ['rows' => '5', 'cols' => '40']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p, '', ['onsubmit' => 'return formValidate()']); if ($o == ADD_BROKER_CONFIGURATION) { $form->addElement('header', 'title', _('Add a Centreon-Broker Configuration')); } elseif ($o == MODIFY_BROKER_CONFIGURATION) { $form->addElement('header', 'title', _('Modify a Centreon-Broker Configuration')); } elseif ($o == WATCH_BROKER_CONFIGURATION) { $form->addElement('header', 'title', _('View a Centreon-Broker Configuration')); } // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate(__DIR__); // TAB 1 - General informations $tpl->assign('centreonbroker_main_options', _('Main options')); $tpl->assign('centreonbroker_log_options', _('Log options')); $tpl->assign('centreonbroker_advanced_options', _('Advanced options')); $form->addElement('header', 'information', _('Centreon Broker configuration')); $form->addElement('text', 'name', _('Name'), $attrsText); $form->addElement('text', 'filename', _('Config file name'), $attrsText); $form->addElement('select', 'ns_nagios_server', _('Requester'), $nagios_servers); $form->addElement('text', 'cache_directory', _('Cache directory'), $attrsText); $form->addElement('text', 'event_queue_max_size', _('Event queue max size'), $attrsText); $form->addElement('text', 'event_queues_total_size', _('Event queues maximum total size'), $attrsText); $command = $form->addElement('text', 'command_file', _('Command file'), $attrsText); $form->addElement('text', 'pool_size', _('Pool size'), $attrsText); // logger $form->addElement('text', 'log_directory', _('Log directory'), $attrsText); $form->addRule('log_directory', _('Mandatory directory'), 'required'); $form->addElement('text', 'log_filename', _('Log filename'), $attrsText); $form->addElement('text', 'log_max_size', _('Maximum files size (in bytes)'), $attrsText2); $logs = $cbObj->getLogsOption(); $logsLevel = $cbObj->getLogsLevel(); $smartyLogs = []; $defaultLog = []; foreach ($logs as $log) { array_push($smartyLogs, 'log_' . $log); $flippedLevel = array_flip($logsLevel); $defaultLog['log_' . $log] = $log === 'core' ? $flippedLevel['info'] : $flippedLevel['error']; $form->addElement('select', 'log_' . $log, _($log), $logsLevel); } $timestamp = []; $timestamp[] = $form->createElement('radio', 'write_timestamp', null, _('Yes'), 1); $timestamp[] = $form->createElement('radio', 'write_timestamp', null, _('No'), 0); $form->addGroup($timestamp, 'write_timestamp', _('Write timestamp (deprecated)'), '&nbsp;'); $thread_id = []; $thread_id[] = $form->createElement('radio', 'write_thread_id', null, _('Yes'), 1); $thread_id[] = $form->createElement('radio', 'write_thread_id', null, _('No'), 0); $form->addGroup($thread_id, 'write_thread_id', _('Write thread id (deprecated)'), '&nbsp;'); // end logger $status = []; $status[] = $form->createElement('radio', 'activate', null, _('Enabled'), 1); $status[] = $form->createElement('radio', 'activate', null, _('Disabled'), 0); $form->addGroup($status, 'activate', _('Status'), '&nbsp;'); $centreonbroker = []; $centreonbroker[] = $form->createElement('radio', 'activate_watchdog', null, _('Yes'), 1); $centreonbroker[] = $form->createElement('radio', 'activate_watchdog', null, _('No'), 0); $form->addGroup($centreonbroker, 'activate_watchdog', _('Link to cbd service'), '&nbsp;'); $stats_activate = []; $stats_activate[] = $form->createElement('radio', 'stats_activate', null, _('Yes'), 1); $stats_activate[] = $form->createElement('radio', 'stats_activate', null, _('No'), 0); $form->addGroup($stats_activate, 'stats_activate', _('Statistics'), '&nbsp;'); $bbdo_versions = [ '3.0.0' => 'v.3.0.0 (with protobuf)', '3.0.1' => 'v.3.0.1 (full protobuf)', '3.1.0' => 'v.3.1.0', ]; $form->addElement('select', 'bbdo_version', _('BBDO version'), $bbdo_versions); $tags = $cbObj->getTags(); $tabs = []; foreach ($tags as $tagId => $tag) { $tabs[] = ['id' => $tag, 'name' => _('Centreon-Broker ' . ucfirst($tag)), 'link' => _('Add'), 'nb' => 0, 'blocks' => $cbObj->getListConfigBlock($tagId), 'forms' => []]; } /** * Default values */ if (isset($_GET['o']) && $_GET['o'] == ADD_BROKER_CONFIGURATION) { $result = array_merge( [ 'name' => '', 'cache_directory' => '/var/lib/centreon-broker/', 'log_directory' => '/var/log/centreon-broker/', 'write_timestamp' => '1', 'write_thread_id' => '1', 'stats_activate' => '1', 'activate' => '1', 'activate_watchdog' => '1', 'bbdo_version' => '3.0.1', ], $defaultLog ); $form->setDefaults($result); $tpl->assign('config_id', 0); } elseif ($id !== 0) { $tpl->assign('config_id', $id); $defaultBrokerInformation = getCentreonBrokerInformation($id); $defaultBrokerInformation = array_map('htmlEncodeBrokerInformation', $defaultBrokerInformation); if (! isset($defaultBrokerInformation['log_core'])) { $defaultBrokerInformation = array_merge( $defaultBrokerInformation, $defaultLog ); } $form->setDefaults($defaultBrokerInformation); // Get informations for modify textdomain('help'); $nbTabs = count($tabs); for ($i = 0; $i < $nbTabs; $i++) { $tabs[$i]['forms'] = $cbObj->getForms($id, $tabs[$i]['id'], $p, $tpl); $tabs[$i]['helps'] = $cbObj->getHelps($id, $tabs[$i]['id']); $tabs[$i]['nb'] = count($tabs[$i]['forms']); } textdomain('messages'); } $form->addElement('hidden', 'id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); /** * Form Rules */ $form->registerRule('exist', 'callback', 'testExistence'); $form->registerRule('isPositiveNumeric', 'callback', 'isPositiveNumeric'); $form->addRule('name', _('Mandatory name'), 'required'); $form->addRule('name', _('Name is already in use'), 'exist'); $form->addRule('filename', _('Mandatory filename'), 'required'); $form->addRule('cache_directory', _('Mandatory cache directory'), 'required'); $form->addRule('event_queue_max_size', _('Value must be numeric'), 'numeric'); $form->addRule('event_queues_total_size', _('Value must be numeric'), 'numeric'); $form->addRule('pool_size', _('Value must be a positive numeric'), 'isPositiveNumeric'); if ($o == WATCH_BROKER_CONFIGURATION) { if ($centreon->user->access->page($p) != 2) { $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&id=' . $ndo2db_id . "'"] ); } $form->freeze(); } elseif ($o == MODIFY_BROKER_CONFIGURATION) { // Modify a Centreon Broker information $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); } elseif ($o == ADD_BROKER_CONFIGURATION) { // Add a nagios information $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); } $valid = false; if ($form->validate()) { $nagiosObj = $form->getElement('id'); $data = array_map('htmlDecodeBrokerInformation', $_POST); if ($form->getSubmitValue('submitA')) { $cbObj->insertConfig($data); } elseif ($form->getSubmitValue('submitC')) { $cbObj->updateConfig((int) $data['id'], $data); } $o = null; $valid = true; } if ($valid) { require_once __DIR__ . LISTING_FILE; } 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('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('p', $p); $tpl->assign('sort1', _('General')); $tpl->assign('tabs', $tabs); $tpl->assign('smartyLogs', $smartyLogs); $tpl->display('formCentreonBroker.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/configuration/configCentreonBroker/centreon-broker.php
centreon/www/include/configuration/configCentreonBroker/centreon-broker.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 ADD_BROKER_CONFIGURATION = 'a'; const WATCH_BROKER_CONFIGURATION = 'w'; const MODIFY_BROKER_CONFIGURATION = 'c'; const ACTIVATE_BROKER_CONFIGURATION = 's'; const DEACTIVATE_BROKER_CONFIGURATION = 'u'; const DUPLICATE_BROKER_CONFIGURATIONS = 'm'; const DELETE_BROKER_CONFIGURATIONS = 'd'; const LISTING_FILE = '/listCentreonBroker.php'; const FORM_FILE = '/formCentreonBroker.php'; $cG = $_GET['id'] ?? null; $cP = $_POST['id'] ?? null; $id = $cG ?: $cP; $cG = $_GET['select'] ?? null; $cP = $_POST['select'] ?? null; $select = $cG ?: $cP; $cG = $_GET['dupNbr'] ?? null; $cP = $_POST['dupNbr'] ?? null; $dupNbr = $cG ?: $cP; require_once './class/centreonConfigCentreonBroker.php'; // Path to the configuration dir // PHP functions require_once __DIR__ . '/DB-Func.php'; require_once './include/common/common-Func.php'; /** * Page forbidden if server is a remote */ if ($isRemote) { require_once __DIR__ . '/../../core/errors/alt_error.php'; exit(); } // Set the real page if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) { $p = $ret['topology_page']; } $acl = $centreon->user->access; $serverString = trim($acl->getPollerString()); $allowedBrokerConf = []; if ($serverString != "''" && ! empty($serverString)) { $sql = 'SELECT config_id FROM cfg_centreonbroker WHERE ns_nagios_server IN (' . $serverString . ')'; $res = $pearDB->query($sql); while ($row = $res->fetchRow()) { $allowedBrokerConf[$row['config_id']] = true; } } switch ($o) { case ADD_BROKER_CONFIGURATION: case WATCH_BROKER_CONFIGURATION: case MODIFY_BROKER_CONFIGURATION: require_once __DIR__ . FORM_FILE; break; case ACTIVATE_BROKER_CONFIGURATION: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); enableCentreonBrokerInDB($id); } else { unvalidFormMessage(); } require_once __DIR__ . LISTING_FILE; break; // Activate a CentreonBroker CFG case DEACTIVATE_BROKER_CONFIGURATION: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); disablCentreonBrokerInDB($id); } else { unvalidFormMessage(); } require_once __DIR__ . LISTING_FILE; break; // Desactivate a CentreonBroker CFG case DUPLICATE_BROKER_CONFIGURATIONS: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); multipleCentreonBrokerInDB($select ?? [], $dupNbr); } else { unvalidFormMessage(); } require_once __DIR__ . LISTING_FILE; break; // Duplicate n CentreonBroker CFGs case DELETE_BROKER_CONFIGURATIONS: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); deleteCentreonBrokerInDB($select ?? []); } else { unvalidFormMessage(); } require_once __DIR__ . LISTING_FILE; break; // Delete n CentreonBroker CFG default: require_once __DIR__ . LISTING_FILE; 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/configuration/configCentreonBroker/DB-Func.php
centreon/www/include/configuration/configCentreonBroker/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 _CENTREON_PATH_ . 'www/include/common/vault-functions.php'; use App\Kernel; use Centreon\Domain\Log\Logger; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Common\Infrastructure\FeatureFlags; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; use Core\Security\Vault\Domain\Model\VaultConfiguration; /** * Test broker file config existance * @param $name */ function testExistence($name = null) { global $pearDB, $form; $id = null; if (isset($form)) { $id = $form->getSubmitValue('id'); } $dbResult = $pearDB->query("SELECT config_name, config_id FROM `cfg_centreonbroker` WHERE `config_name` = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'"); $ndomod = $dbResult->fetch(); if ($dbResult->rowCount() >= 1 && $ndomod['config_id'] == $id) { return true; } return ! ($dbResult->rowCount() >= 1 && $ndomod['config_id'] != $id); } /** * Enable a Centreon Broker configuration * * @param int $id The Centreon Broker configuration in database */ function enableCentreonBrokerInDB($id) { global $pearDB; if (! $id) { return; } $query = "UPDATE cfg_centreonbroker SET config_activate = '1' WHERE config_id = :config_id"; $statement = $pearDB->prepare($query); $statement->bindValue(':config_id', (int) $id, PDO::PARAM_INT); $statement->execute(); } /** * Disable a Centreon Broker configuration * * @param int $id The Centreon Broker configuration in database */ function disablCentreonBrokerInDB($id) { global $pearDB; if (! $id) { return; } $query = "UPDATE cfg_centreonbroker SET config_activate = '0' WHERE config_id = :config_id"; $statement = $pearDB->prepare($query); $statement->bindValue(':config_id', (int) $id, PDO::PARAM_INT); $statement->execute(); } /** * Delete Centreon Broker configurations * * @param array $id The Centreon Broker configuration in database * @param mixed $ids */ function deleteCentreonBrokerInDB($ids = []) { global $pearDB; $brokerIds = array_keys($ids); $kernel = Kernel::createForWeb(); /** @var Logger $logger */ $logger = $kernel->getContainer()->get(Logger::class); /** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */ $readVaultConfigurationRepository = $kernel->getContainer()->get( ReadVaultConfigurationRepositoryInterface::class ); /** @var FeatureFlags $featureFlagManager */ $featureFlagManager = $kernel->getContainer()->get(FeatureFlags::class); $vaultConfiguration = $readVaultConfigurationRepository->find(); /** @var Core\Common\Application\Repository\WriteVaultRepositoryInterface $writeVaultRepository */ $writeVaultRepository = $kernel->getContainer()->get(Core\Common\Application\Repository\WriteVaultRepositoryInterface::class); $writeVaultRepository->setCustomPath(Core\Common\Infrastructure\Repository\AbstractVaultRepository::BROKER_VAULT_PATH); if ($featureFlagManager->isEnabled('vault_broker') && $vaultConfiguration !== null) { deleteBrokerConfigsFromVault($writeVaultRepository, $brokerIds); } $statement = $pearDB->prepare('DELETE FROM cfg_centreonbroker WHERE config_id = :config_id'); foreach ($brokerIds as $id) { $statement->bindValue(':config_id', $id, PDO::PARAM_INT); $statement->execute(); } } /** * Get the information of a server * * @param int $id * @return array */ function getCentreonBrokerInformation($id) { global $pearDB; $query = 'SELECT config_name, config_filename, ns_nagios_server, stats_activate, config_write_timestamp, config_write_thread_id, config_activate, event_queue_max_size, event_queues_total_size, cache_directory, command_file, daemon, pool_size, log_directory, log_filename, log_max_size, bbdo_version FROM cfg_centreonbroker WHERE config_id = ' . $id; try { $res = $pearDB->query($query); } catch (PDOException $e) { $brokerConf = [ 'name' => '', 'filename' => '', 'log_directory' => '/var/log/centreon-broker/', 'write_timestamp' => '1', 'write_thread_id' => '1', 'activate_watchdog' => '1', 'activate' => '1', 'event_queue_max_size' => '', 'pool_size' => null, ]; } $row = $res->fetch(); if (! isset($brokerConf)) { $brokerConf = [ 'id' => $id, 'name' => $row['config_name'], 'filename' => $row['config_filename'], 'ns_nagios_server' => $row['ns_nagios_server'], 'activate' => $row['config_activate'], 'activate_watchdog' => $row['daemon'], 'stats_activate' => $row['stats_activate'], 'write_timestamp' => $row['config_write_timestamp'], 'write_thread_id' => $row['config_write_thread_id'], 'event_queue_max_size' => $row['event_queue_max_size'], 'event_queues_total_size' => $row['event_queues_total_size'], 'cache_directory' => $row['cache_directory'], 'command_file' => $row['command_file'], 'daemon' => $row['daemon'], 'pool_size' => $row['pool_size'], 'log_directory' => $row['log_directory'], 'log_filename' => $row['log_filename'], 'log_max_size' => $row['log_max_size'], 'bbdo_version' => $row['bbdo_version'], ]; } // Log $brokerLogConf = []; $query = 'SELECT log.`name`, relation.`id_level` FROM `cb_log` log LEFT JOIN `cfg_centreonbroker_log` relation ON relation.`id_log` = log.`id` WHERE relation.`id_centreonbroker` = ' . $id; try { $res = $pearDB->query($query); } catch (PDOException $e) { return $brokerConf; } while ($row = $res->fetch()) { $brokerLogConf['log_' . $row['name']] = $row['id_level']; } $result = array_merge($brokerConf, $brokerLogConf); return $result; } /** * Duplicate a configuration * * @param array $ids List of id CentreonBroker configuration * @param array $nbr List of number a duplication * @param mixed $nbrDup */ function multipleCentreonBrokerInDB($ids, $nbrDup) { global $pearDB; foreach ($ids as $id => $value) { $cbObj = new CentreonConfigCentreonBroker($pearDB); $row = getCfgBrokerData((int) $id); // Prepare values $values = []; $values['activate_watchdog']['activate_watchdog'] = '0'; $values['activate']['activate'] = '0'; $values['ns_nagios_server'] = $row['ns_nagios_server']; $values['event_queue_max_size'] = $row['event_queue_max_size']; $values['cache_directory'] = $row['cache_directory']; $values['activate_watchdog']['activate_watchdog'] = $row['daemon']; $values['output'] = []; $values['input'] = []; $brokerCfgInfoData = getCfgBrokerInfoData((int) $id); foreach ($brokerCfgInfoData as $rowOpt) { if ($rowOpt['config_key'] == 'filters') { continue; } if ($rowOpt['config_key'] == 'category') { $configKey = 'filters__' . $rowOpt['config_group_id'] . '__category'; $values[$rowOpt['config_group']][$rowOpt['config_group_id']][$configKey][] = $rowOpt['config_value']; } elseif ($rowOpt['fieldIndex'] !== null) { $configKey = $rowOpt['config_key'] . '_' . $rowOpt['fieldIndex']; $values[$rowOpt['config_group']][$rowOpt['config_group_id']][$configKey] = $rowOpt['config_value']; } else { $values[$rowOpt['config_group']][$rowOpt['config_group_id']][$rowOpt['config_key']] = $rowOpt['config_value']; } } // Convert values radio button foreach ($values as $group => $groups) { if (is_array($groups)) { foreach ($groups as $gid => $infos) { if (isset($infos['blockId'])) { [$tagId, $typeId] = explode('_', $infos['blockId']); $fieldtype = $cbObj->getFieldtypes($typeId); } else { $fieldtype = []; } if (is_array($infos)) { foreach ($infos as $key => $value) { if (isset($fieldtype[$key]) && $fieldtype[$key] == 'radio') { $values[$group][$gid][$key] = [$key => $value]; } } } } } } // Copy the configuration $j = 1; $query = 'SELECT COUNT(*) as nb FROM cfg_centreonbroker WHERE config_name = :config_name'; $statement = $pearDB->prepare($query); for ($i = 1; $i <= $nbrDup[$id]; $i++) { $nameNOk = true; // Find the name while ($nameNOk) { $newname = $row['config_name'] . '_' . $j; $newfilename = $j . '_' . $row['config_filename']; $statement->bindValue(':config_name', $newname, PDO::PARAM_STR); $statement->execute(); $rowNb = $statement->fetch(PDO::FETCH_ASSOC); if ($rowNb['nb'] == 0) { $nameNOk = false; } $j++; } $values['name'] = $newname; $values['filename'] = $newfilename; retrieveOriginalPasswordValuesFromVault($values); $cbObj->insertConfig($values); } } } /** * Rule to check if given value is positive and numeric * * @param $size * @return bool */ function isPositiveNumeric($size): bool { if (! is_numeric($size)) { return false; } $isPositive = false; if ((int) $size === (int) abs($size)) { $isPositive = true; } return $isPositive; } /** * Getting Centreon CFG broker data * * @param int $configId * @return array */ function getCfgBrokerData(int $configId): array { global $pearDB; $query = 'SELECT config_name, config_filename, config_activate, ns_nagios_server, event_queue_max_size, cache_directory, daemon ' . 'FROM cfg_centreonbroker ' . 'WHERE config_id = :config_id '; try { $statement = $pearDB->prepare($query); $statement->bindValue(':config_id', $configId, PDO::PARAM_INT); $statement->execute(); $cfgBrokerData = $statement->fetch(PDO::FETCH_ASSOC); } catch (PDOException $exception) { throw new Exception('Cannot fetch Broker config data'); } $statement->closeCursor(); return $cfgBrokerData; } /** * Getting Centreon CFG broker Info data * * @param int $configId * @return array */ function getCfgBrokerInfoData(int $configId): array { global $pearDB; $query = <<<'SQL' SELECT config_key, config_value, config_group, config_group_id, fieldIndex FROM cfg_centreonbroker_info WHERE config_id = :config_id SQL; try { $statement = $pearDB->prepare($query); $statement->bindValue(':config_id', $configId, PDO::PARAM_INT); $statement->execute(); $cfgBrokerInfoData = $statement->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $exception) { throw new Exception('Cannot fetch Broker info config data'); } $statement->closeCursor(); return $cfgBrokerInfoData; } /** * Replace the vaultPath by the actual value in the values array. * * @param array{ * name:string, * output:array<string,array>, * input:array<string,array> * } $values */ function retrieveOriginalPasswordValuesFromVault(array &$values): void { $kernel = Kernel::createForWeb(); /** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */ $readVaultConfigurationRepository = $kernel->getContainer()->get( ReadVaultConfigurationRepositoryInterface::class ); $vaultConfiguration = $readVaultConfigurationRepository->find(); if ($vaultConfiguration !== null) { /** @var Logger $logger */ $logger = $kernel->getContainer()->get(Logger::class); /** @var ReadVaultRepositoryInterface $readVaultRepository */ $readVaultRepository = $kernel->getContainer()->get(ReadVaultRepositoryInterface::class); foreach (['input', 'output'] as $tag) { foreach ($values[$tag] as $key => $inputOutput) { foreach ($inputOutput as $name => $value) { if (is_string($value) && str_starts_with($value, VaultConfiguration::VAULT_PATH_PATTERN)) { [$groupName, $subName] = explode('__', $name); [$subName, $subKey] = explode('_', $subName); if ($subName === 'value') { $vaultKey = implode( '_', [$inputOutput['name'], $groupName, $inputOutput["{$groupName}__name_{$subKey}"]] ); } else { $vaultKey = $inputOutput['name'] . '_' . $name; } $passwordValue = findBrokerConfigValueFromVault( $readVaultRepository, $logger, $vaultKey, $value, ); $values[$tag][$key][$name] = $passwordValue; } } } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configGenerateTraps/formGenerateTraps.php
centreon/www/include/configuration/configGenerateTraps/formGenerateTraps.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 (! $centreon->user->admin && $centreon->user->access->checkAction('generate_trap') === 0) { require_once _CENTREON_PATH_ . 'www/include/core/errors/alt_error.php'; return null; } // Init Centcore Pipe $centcore_pipe = defined('_CENTREON_VARLIB_') ? _CENTREON_VARLIB_ . '/centcore.cmd' : '/var/lib/centreon/centcore.cmd'; // Get Poller List $acl = $centreon->user->access; $tab_nagios_server = $acl->getPollerAclConf(['get_row' => 'name', 'order' => ['name'], 'keys' => ['id'], 'conditions' => ['ns_activate' => 1]]); // Sort the list of poller server $pollersId = isset($_GET['poller']) ? explode(',', $_GET['poller']) : []; foreach ($tab_nagios_server as $key => $name) { if (in_array($key, $pollersId)) { $tab_nagios_server[$key] = $name; } } $n = count($tab_nagios_server); // Display all server options if ($n > 1) { foreach ($tab_nagios_server as $key => $name) { $tab_nagios_server[$key] = HtmlSanitizer::createFromString($name)->sanitize()->getString(); } $tab_nagios_server = [0 => _('All Pollers')] + $tab_nagios_server; } // Form begin $attrSelect = ['style' => 'width: 220px;']; $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); // Init Header for tables in template $form->addElement('header', 'title', _('SNMP Trap Generation')); $form->addElement('header', 'opt', _('Export Options')); $form->addElement('header', 'result', _('Actions')); $form->addElement('header', 'infos', _('Implied Server')); $form->addElement('select', 'host', _('Poller'), $tab_nagios_server, $attrSelect); // Add checkbox for enable restart $form->addElement('checkbox', 'generate', _('Generate trap database ')); $form->addElement('checkbox', 'apply', _('Apply configurations')); $options = [null => null, 'RELOADCENTREONTRAPD' => _('Reload'), 'RESTARTCENTREONTRAPD' => _('Restart')]; $form->addElement('select', 'signal', _('Send signal'), $options); // Set checkbox checked. $form->setDefaults(['generate' => '1', 'generate' => '1', 'opt' => '1']); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $sub = $form->addElement('submit', 'submit', _('Generate'), ['class' => 'btc bt_success']); $msg = null; $stdout = null; $msg_generate = ''; $trapdPath = '/etc/snmp/centreon_traps/'; if ($form->validate()) { $ret = $form->getSubmitValues(); $host_list = []; foreach ($tab_nagios_server as $key => $value) { if ($key && ($ret['host'] == 0 || $ret['host'] == $key)) { $host_list[$key] = $value; } } if ($ret['host'] == 0 || $ret['host'] != -1) { // Create Server List to snmptt generation file $tab_server = []; $query = 'SELECT `name`, `id`, `snmp_trapd_path_conf`, `localhost` FROM `nagios_server` ' . "WHERE `ns_activate` = '1' ORDER BY `localhost` DESC"; $DBRESULT_Servers = $pearDB->query($query); while ($tab = $DBRESULT_Servers->fetchRow()) { if (isset($ret['host']) && ($ret['host'] == 0 || $ret['host'] == $tab['id'])) { $tab_server[$tab['id']] = ['id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost']]; } if ($tab['localhost'] && $tab['snmp_trapd_path_conf']) { $trapdPath = $tab['snmp_trapd_path_conf']; // handle path traversal vulnerability if (str_contains($trapdPath, '..')) { throw new Exception('Path traversal found'); } } } if (isset($ret['generate']) && $ret['generate']) { $msg_generate .= sprintf('<strong>%s</strong><br/>', _('Database generation')); $stdout = ''; foreach ($tab_server as $host) { if (! is_dir("{$trapdPath}/{$host['id']}")) { mkdir("{$trapdPath}/{$host['id']}"); } $filename = "{$trapdPath}/{$host['id']}/centreontrapd.sdb"; $output = []; $returnVal = 0; exec( escapeshellcmd(_CENTREON_PATH_ . "/bin/generateSqlLite '{$host['id']}' '{$filename}'") . ' 2>&1', $output, $returnVal ); $stdout .= implode('<br/>', $output) . '<br/>'; if ($returnVal != 0) { break; } } $msg_generate .= str_replace("\n", '<br/>', $stdout) . '<br/>'; } if (isset($ret['apply']) && $ret['apply'] && $returnVal == 0) { $msg_generate .= sprintf('<strong>%s</strong><br/>', _('Centcore commands')); foreach ($tab_server as $host) { passthru( escapeshellcmd("echo 'SYNCTRAP:{$host['id']}'") . ' >> ' . escapeshellcmd($centcore_pipe), $return ); if ($return) { $msg_generate .= "Error while writing into {$centcore_pipe}<br/>"; } else { $msg_generate .= "Poller (id:{$host['id']}): SYNCTRAP sent to centcore.cmd<br/>"; } } } if (isset($ret['signal']) && in_array($ret['signal'], ['RELOADCENTREONTRAPD', 'RESTARTCENTREONTRAPD'])) { foreach ($tab_server as $host) { passthru( escapeshellcmd("echo '{$ret['signal']}:{$host['id']}'") . ' >> ' . escapeshellcmd($centcore_pipe), $return ); if ($return) { $msg_generate .= "Error while writing into {$centcore_pipe}<br/>"; } else { $msg_generate .= "Poller (id:{$host['id']}): {$ret['signal']} sent to centcore.cmd<br/>"; } } } } } $form->addElement('header', 'status', _('Status')); if (isset($msg) && $msg) { $tpl->assign('msg', $msg); } if (isset($msg_generate) && $msg_generate) { $tpl->assign('msg_generate', $msg_generate); } if (isset($tab_server) && $tab_server) { $tpl->assign('tab_server', $tab_server); } if (isset($host_list) && $host_list) { $tpl->assign('host_list', $host_list); } $tpl->assign( 'helpattr', 'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, ' . '"orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"],' . 'WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"' ); $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->display('formGenerateTraps.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/configuration/configGenerateTraps/help.php
centreon/www/include/configuration/configGenerateTraps/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['generate'] = dgettext('help', 'Generate a light database for traps.'); $help['apply'] = dgettext('help', 'Push database to poller.'); $help['signal'] = dgettext('help', 'Send restart or reload signal to centreontrapd.'); $help['host'] = dgettext('help', 'Poller to interact with.');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configGenerateTraps/generateTraps.php
centreon/www/include/configuration/configGenerateTraps/generateTraps.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(); } // Path to the option dir $path = './include/configuration/configGenerateTraps/'; // PHP functions require_once './include/common/common-Func.php'; switch ($o) { default: require_once $path . 'formGenerateTraps.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/configuration/configKnowledge/display-hostTemplates.php
centreon/www/include/configuration/configKnowledge/display-hostTemplates.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(); } $modules_path = $centreon_path . 'www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; require_once $centreon_path . '/bootstrap.php'; $pearDB = $dependencyInjector['configuration_db']; if (! isset($limit) || (int) $limit < 0) { $limit = $centreon->optGen['maxViewConfiguration']; } $orderBy = 'host_name'; $order = 'ASC'; // Use whitelist as we can't bind ORDER BY sort parameter if (! empty($_POST['order']) && in_array($_POST['order'], ['ASC', 'DESC'])) { $order = $_POST['order']; } require_once './include/common/autoNumLimit.php'; // Add paths set_include_path(get_include_path() . PATH_SEPARATOR . $modules_path); require_once $centreon_path . '/www/class/centreon-knowledge/procedures.class.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($modules_path); try { $postHostTemplate = ! empty($_POST['searchHostTemplate']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHostTemplate']) : ''; $searchHasNoProcedure = ! empty($_POST['searchHasNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHasNoProcedure']) : ''; $templatesHasNoProcedure = ! empty($_POST['searchTemplatesWithNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchTemplatesWithNoProcedure']) : ''; $conf = getWikiConfig($pearDB); $WikiURL = $conf['kb_wiki_url']; $currentPage = 'hostTemplates'; require_once $modules_path . 'search.php'; // Init Status Template $status = [ 0 => "<font color='orange'> " . _('No wiki page defined') . ' </font>', 1 => "<font color='green'> " . _('Wiki page defined') . ' </font>', ]; $proc = new procedures($pearDB); $proc->fetchProcedures(); $query = " SELECT SQL_CALC_FOUND_ROWS host_name, host_id, host_register, ehi_icon_image FROM host, extended_host_information ehi WHERE host.host_id = ehi.host_host_id AND host.host_register = '0' AND host.host_locked = '0' "; if (! empty($postHostTemplate)) { $query .= 'AND host.host_name LIKE :postHostTemplate '; } $query .= 'ORDER BY ' . $orderBy . ' ' . $order . ' LIMIT :offset, :limit'; $statement = $pearDB->prepare($query); if (! empty($postHostTemplate)) { $statement->bindValue(':postHostTemplate', '%' . $postHostTemplate . '%', PDO::PARAM_STR); } $statement->bindValue(':offset', $num * $limit, PDO::PARAM_INT); $statement->bindValue(':limit', $limit, PDO::PARAM_INT); $statement->execute(); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); $selection = []; while ($data = $statement->fetch(PDO::FETCH_ASSOC)) { if ($data['host_register'] == 0) { $selection[$data['host_name']] = $data['host_id']; } } $statement->closeCursor(); unset($data); // Create Diff $tpl->assign('host_name', _('Hosts Templates')); $diff = []; $templateHostArray = []; foreach ($selection as $key => $value) { $tplStr = ''; $tplArr = $proc->getMyHostMultipleTemplateModels($value); $diff[$key] = $proc->hostTemplateHasProcedure($key, $tplArr) == true ? 1 : 0; if (! empty($templatesHasNoProcedure)) { if ( $diff[$key] == 1 || $proc->hostTemplateHasProcedure($key, $tplArr, PROCEDURE_INHERITANCE_MODE) == true ) { $rows--; unset($diff[$key]); continue; } } elseif (! empty($searchHasNoProcedure)) { if ($diff[$key] == 1) { $rows--; unset($diff[$key]); continue; } } if (count($tplArr)) { $firstTpl = 1; foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= " <a href='" . $WikiURL . '/index.php?title=Host-Template_:_' . $value1 . "' target = '_blank' > " . $value1 . '</a > '; $firstTpl = 0; } else { $tplStr .= "&nbsp;|&nbsp;<a href = '" . $WikiURL . '/index.php?title=Host-Template_:_' . $value1 . "' target = '_blank' > " . $value1 . '</a > '; } } } $templateHostArray[$key] = $tplStr; unset($tplStr); } include './include/common/checkPagination.php'; if (isset($templateHostArray)) { $tpl->assign('templateHostArray', $templateHostArray); } $WikiVersion = getWikiVersion($WikiURL . '/api.php'); $tpl->assign('WikiVersion', $WikiVersion); $tpl->assign('WikiURL', $WikiURL); $tpl->assign('content', $diff); $tpl->assign('status', $status); $tpl->assign('selection', 2); // Send template in order to open // translations $tpl->assign('status_trans', _('Status')); $tpl->assign('actions_trans', _('Actions')); $tpl->assign('template_trans', _('Template')); // Template $tpl->registerObject('lineTemplate', getLineTemplate('list_one', 'list_two')); $tpl->assign('limit', $limit); $tpl->assign('order', $order); $tpl->assign('orderBy', $orderBy); $tpl->assign('defaultOrderby', 'host_name'); // Apply a template definition $tpl->display($modules_path . 'templates/display.ihtml'); } catch (Exception $e) { $tpl->assign('errorMsg', $e->getMessage()); $tpl->display($modules_path . 'templates/NoWiki.tpl'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/search.php
centreon/www/include/configuration/configKnowledge/search.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 . '/bootstrap.php'; $pearDB = $dependencyInjector['configuration_db']; $searchOptions = [ 'host' => 0, 'service' => 0, 'hostTemplate' => 0, 'serviceTemplate' => 0, 'poller' => 0, 'hostgroup' => 0, 'servicegroup' => 0, 'hasNoProcedure' => 0, 'templatesWithNoProcedure' => 0, ]; $labels = [ 'host' => _('Host'), 'service' => _('Service'), 'hostTemplate' => _('Host Template'), 'serviceTemplate' => _('Service Template'), 'poller' => _('Poller'), 'hostgroup' => _('Hostgroup'), 'servicegroup' => _('Servicegroup'), 'hasNoProcedure' => _('Show wiki pageless only'), 'templatesWithNoProcedure' => _('Show wiki pageless only - inherited templates included'), 'search' => _('Search'), ]; if ($currentPage == 'hosts') { $searchOptions['host'] = 1; $searchOptions['poller'] = 1; $searchOptions['hostgroup'] = 1; $searchOptions['hasNoProcedure'] = 1; $searchOptions['templatesWithNoProcedure'] = 1; } elseif ($currentPage == 'services') { $searchOptions['host'] = 1; $searchOptions['service'] = 1; $searchOptions['poller'] = 1; $searchOptions['hostgroup'] = 1; $searchOptions['servicegroup'] = 1; $searchOptions['hasNoProcedure'] = 1; $searchOptions['templatesWithNoProcedure'] = 1; } elseif ($currentPage == 'hostTemplates') { $searchOptions['hostTemplate'] = 1; $searchOptions['hasNoProcedure'] = 1; $searchOptions['templatesWithNoProcedure'] = 1; } elseif ($currentPage == 'serviceTemplates') { $searchOptions['serviceTemplate'] = 1; $searchOptions['hasNoProcedure'] = 1; $searchOptions['templatesWithNoProcedure'] = 1; } $tpl->assign('searchHost', $postHost ?? ''); $tpl->assign('searchService', $postService ?? ''); $tpl->assign('searchHostTemplate', $postHostTemplate ?? ''); $tpl->assign( 'searchServiceTemplate', $postServiceTemplate ?? '' ); $checked = ''; if (! empty($searchHasNoProcedure)) { $checked = 'checked'; } $tpl->assign('searchHasNoProcedure', $checked); $checked2 = ''; if (! empty($templatesHasNoProcedure)) { $checked2 = 'checked'; } $tpl->assign('searchTemplatesWithNoProcedure', $checked2); /** * Get Poller List */ if ($searchOptions['poller']) { $res = $pearDB->query( 'SELECT id, name FROM nagios_server ORDER BY name' ); $searchPoller = "<option value='0'></option>"; while ($row = $res->fetchRow()) { if ( isset($postPoller) && $postPoller !== false && $row['id'] == $postPoller ) { $searchPoller .= "<option value='" . $row['id'] . "' selected>" . $row['name'] . '</option>'; } else { $searchPoller .= "<option value='" . $row['id'] . "'>" . $row['name'] . '</option>'; } } $tpl->assign('searchPoller', $searchPoller); } /** * Get Hostgroup List */ if ($searchOptions['hostgroup']) { $res = $pearDB->query( 'SELECT hg_id, hg_name FROM hostgroup ORDER BY hg_name' ); $searchHostgroup = "<option value='0'></option>"; while ($row = $res->fetchRow()) { if ( isset($postHostgroup) && $postHostgroup !== false && $row['hg_id'] == $postHostgroup ) { $searchHostgroup .= "<option value ='" . $row['hg_id'] . "' selected>" . $row['hg_name'] . '</option>'; } else { $searchHostgroup .= "<option value ='" . $row['hg_id'] . "'>" . $row['hg_name'] . '</option>'; } } $tpl->assign('searchHostgroup', $searchHostgroup); } /** * Get Servicegroup List */ if ($searchOptions['servicegroup']) { $res = $pearDB->query( 'SELECT sg_id, sg_name FROM servicegroup ORDER BY sg_name' ); $searchServicegroup = "<option value='0'></option>"; while ($row = $res->fetchRow()) { if ( isset($postServicegroup) && $postServicegroup !== false && $row['sg_id'] == $postServicegroup ) { $searchServicegroup .= "<option value ='" . $row['sg_id'] . "' selected>" . $row['sg_name'] . '</option>'; } else { $searchServicegroup .= "<option value ='" . $row['sg_id'] . "'>" . $row['sg_name'] . '</option>'; } } $tpl->assign('searchServicegroup', $searchServicegroup); } $tpl->assign('labels', $labels); $tpl->assign('searchOptions', $searchOptions);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/pagination.php
centreon/www/include/configuration/configKnowledge/pagination.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 * */ global $centreon; if (! isset($centreon)) { exit(); } global $bNewChart, $num, $limit, $search, $url, $pearDB, $search_type_service, $search_type_host, $host_name, $rows, $p, $gopt, $pagination, $poller, $order, $orderby; $type = $_REQUEST['type'] ?? null; $o = $_GET['o'] ?? null; // saving current pagination filter value and current displayed page $centreon->historyPage[$url] = $num; $centreon->historyLastUrl = $url; $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; if (isset($_GET['search_type_service'])) { $search_type_service = $_GET['search_type_service']; $centreon->search_type_service = $_GET['search_type_service']; } elseif (isset($centreon->search_type_service)) { $search_type_service = $centreon->search_type_service; } else { $search_type_service = null; } if (isset($_GET['search_type_host'])) { $search_type_host = $_GET['search_type_host']; $centreon->search_type_host = $_GET['search_type_host']; } elseif (isset($centreon->search_type_host)) { $search_type_host = $centreon->search_type_host; } else { $search_type_host = null; } if (! isset($_GET['search_type_host']) && ! isset($centreon->search_type_host) && ! isset($_GET['search_type_service']) && ! isset($centreon->search_type_service) ) { $search_type_host = 1; $centreon->search_type_host = 1; $search_type_service = 1; $centreon->search_type_service = 1; } $url_var = ''; if (isset($search_type_service)) { $url_var .= '&search_type_service=' . $search_type_service; } if (isset($search_type_host)) { $url_var .= '&search_type_host=' . $search_type_host; } if (isset($_REQUEST['searchHost']) && $_REQUEST['searchHost']) { $url_var .= '&searchHost=' . $_REQUEST['searchHost']; } if (isset($_REQUEST['searchHostgroup']) && $_REQUEST['searchHostgroup']) { $url_var .= '&searchHostgroup=' . $_REQUEST['searchHostgroup']; } if (isset($_REQUEST['searchPoller']) && $_REQUEST['searchPoller']) { $url_var .= '&searchPoller=' . $_REQUEST['searchPoller']; } if (isset($_REQUEST['searchService']) && $_REQUEST['searchService']) { $url_var .= '&searchService=' . $_REQUEST['searchService']; } if (isset($_REQUEST['searchServicegroup']) && $_REQUEST['searchServicegroup']) { $url_var .= '&searchServicegroup=' . $_REQUEST['searchServicegroup']; } if (isset($_REQUEST['searchHostTemplate']) && $_REQUEST['searchHostTemplate']) { $url_var .= '&searchHostTemplate=' . $_REQUEST['searchHostTemplate']; } if (isset($_REQUEST['searchServiceTemplate']) && $_REQUEST['searchServiceTemplate']) { $url_var .= '&searchServiceTemplate=' . $_REQUEST['searchServiceTemplate']; } if (isset($_GET['sort_types'])) { $url_var .= '&sort_types=' . $_GET['sort_types']; $sort_type = $_GET['sort_types']; } // Smarty template initialization $path = './include/configuration/configKnowledge/'; $tpl = SmartyBC::createSmartyTemplate($path, './'); $page_max = ceil($rows / $limit); if ($num >= $page_max && $rows) { $num = $page_max - 1; } $pageArr = []; $iStart = 0; for ($i = 5, $iStart = $num; $iStart && $i > 0; $i--) { $iStart--; } for ($i2 = 0, $iEnd = $num; ($iEnd < ($rows / $limit - 1)) && ($i2 < (5 + $i)); $i2++) { $iEnd++; } if ($rows != 0) { for ($i = $iStart; $i <= $iEnd; $i++) { $urlPage = 'main.php?p=' . $p . '&order=' . $order . '&orderby=' . $orderby . '&num=' . $i . '&limit=' . $limit . '&type=' . $type . '&o=' . $o . $url_var; $pageArr[$i] = ['url_page' => $urlPage, 'label_page' => '<b>' . ($i + 1) . '</b>', 'num' => $i]; } if ($i > 1) { $tpl->assign('pageArr', $pageArr); } $tpl->assign('num', $num); $tpl->assign('first', _('First page')); $tpl->assign('previous', _('Previous page')); $tpl->assign('next', _('Next page')); $tpl->assign('last', _('Last page')); if (($prev = $num - 1) >= 0) { $tpl->assign( 'pagePrev', ('./main.php?p=' . $p . '&order=' . $order . '&orderby=' . $orderby . '&num=' . $prev . '&limit=' . $limit . '&type=' . $type . '&o=' . $o . $url_var) ); } if (($next = $num + 1) < ($rows / $limit)) { $tpl->assign( 'pageNext', ('./main.php?p=' . $p . '&order=' . $order . '&orderby=' . $orderby . '&num=' . $next . '&limit=' . $limit . '&type=' . $type . '&o=' . $o . $url_var) ); } $pageNumber = ceil($rows / $limit); if (($rows / $limit) > 0) { $tpl->assign('pageNumber', ($num + 1) . '/' . $pageNumber); } else { $tpl->assign('pageNumber', ($num) . '/' . $pageNumber); } if ($page_max > 5 && $num != 0) { $tpl->assign( 'firstPage', ('./main.php?p=' . $p . '&order=' . $order . '&orderby=' . $orderby . '&num=0&limit=' . $limit . '&type=' . $type . '&o=' . $o . $url_var) ); } if ($page_max > 5 && $num != ($pageNumber - 1)) { $tpl->assign( 'lastPage', ('./main.php?p=' . $p . '&order=' . $order . '&orderby=' . $orderby . '&num=' . ($pageNumber - 1) . '&limit=' . $limit . '&type=' . $type . '&o=' . $o . $url_var) ); } // Select field to change the number of row on the page for ($i = 10; $i <= 100; $i = $i + 10) { $select[$i] = $i; } if (isset($gopt[$pagination]) && $gopt[$pagination]) { $select[$gopt[$pagination]] = $gopt[$pagination]; } if (isset($rows) && $rows) { $select[$rows] = $rows; } ksort($select); } ?> <script type="text/javascript"> function setL(_this) { var _l = document.getElementsByName('l'); document.forms['form'].elements['limit'].value = _this; _l[0].value = _this; _l[1].value = _this; } </script> <?php $form = new HTML_QuickFormCustom( 'select_form', 'GET', '?p=' . $p . '&search_type_service=' . $search_type_service . '&search_type_host=' . $search_type_host ); $selLim = $form->addElement( 'select', 'l', _('Rows'), $select, ['onChange' => 'setL(this.value); this.form.submit()'] ); $selLim->setSelected($limit); // Element we need when we reload the page $form->addElement('hidden', 'p'); $form->addElement('hidden', 'search'); $form->addElement('hidden', 'num'); $form->addElement('hidden', 'order'); $form->addElement('hidden', 'type'); $form->addElement('hidden', 'sort_types'); $form->setDefaults(['p' => $p, 'search' => $search, 'num' => $num]); // Init QuickForm $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $host_name = $_GET['host_name'] ?? null; $status = $_GET['status'] ?? null; $tpl->assign('host_name', $host_name); $tpl->assign('status', $status); $tpl->assign('limite', $limite ?? null); $tpl->assign('begin', $num); $tpl->assign('end', $limit); $tpl->assign('pagin_page', _('Page')); $tpl->assign( 'order', isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC' ); $tpl->assign('tab_order', $tab_order); $tpl->assign('form', $renderer->toArray()); $tpl->display('templates/pagination.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/configuration/configKnowledge/functions.php
centreon/www/include/configuration/configKnowledge/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 * */ /** * This returns an anonymous class to manage alternate CSS class for table lines TR. */ function getLineTemplate(string $evenCssClass, string $oddCssClass): object { return new class ($evenCssClass, $oddCssClass) { private int $counter = 0; public function __construct(private string $evenCssClass, private string $oddCssClass) { } public function get(): string { return ($this->counter++ % 2) ? $this->oddCssClass : $this->evenCssClass; } public function reset(): string { $this->counter = 0; return ''; } }; } function versionCentreon($pearDB) { if (is_null($pearDB)) { throw new Exception('No Database connect available'); } $query = 'SELECT `value` FROM `informations` WHERE `key` = "version"'; $dbResult = $pearDB->query($query); if (! $dbResult) { throw new Exception('An error occured'); } $row = $dbResult->fetch(); return $row['value']; } function getWikiConfig($pearDB) { $errorMsg = 'MediaWiki is not installed or configured. Please refer to the ' . '<a href="https://docs.centreon.com/docs/administration/knowledge-base/" target="_blank" >' . 'documentation.</a>'; if (is_null($pearDB)) { throw new Exception($errorMsg); } $res = $pearDB->query("SELECT * FROM `options` WHERE options.key LIKE 'kb_wiki_url'"); if ($res->rowCount() == 0) { throw new Exception($errorMsg); } $gopt = []; $opt = $res->fetchRow(); if (empty($opt['value'])) { throw new Exception($errorMsg); } $gopt[$opt['key']] = html_entity_decode($opt['value'], ENT_QUOTES, 'UTF-8'); $pattern = '#^http://|https://#'; $WikiURL = $gopt['kb_wiki_url']; $checkWikiUrl = preg_match($pattern, $WikiURL); if (! $checkWikiUrl) { $gopt['kb_wiki_url'] = 'http://' . $WikiURL; } $res->closeCursor(); return $gopt; } function getWikiVersion($apiWikiURL) { if (is_null($apiWikiURL)) { return; } $post = [ 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', ]; $data = http_build_query($post); // Get contents $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $apiWikiURL); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/x-www-form-urlencoded']); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $content = curl_exec($curl); curl_close($curl); $content = json_decode($content); $wikiStringVersion = $content->query->general->generator; $wikiDataVersion = explode(' ', $wikiStringVersion); return (float) $wikiDataVersion[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/configuration/configKnowledge/display-serviceTemplates.php
centreon/www/include/configuration/configKnowledge/display-serviceTemplates.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(); } $modules_path = $centreon_path . 'www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; require_once $centreon_path . '/bootstrap.php'; $pearDB = $dependencyInjector['configuration_db']; if (! isset($limit) || (int) $limit < 0) { $limit = $centreon->optGen['maxViewConfiguration']; } $orderBy = 'service_description'; $order = 'ASC'; // Use whitelist as we can't bind ORDER BY values if (! empty($_POST['order'])) { if (in_array($_POST['order'], ['ASC', 'DESC'])) { $order = $_POST['order']; } } require_once './include/common/autoNumLimit.php'; // Add paths set_include_path(get_include_path() . PATH_SEPARATOR . $modules_path); require_once $centreon_path . '/www/class/centreon-knowledge/procedures.class.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($modules_path); try { $postServiceTemplate = ! empty($_POST['searchServiceTemplate']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchServiceTemplate']) : ''; $searchHasNoProcedure = ! empty($_POST['searchHasNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHasNoProcedure']) : ''; $templatesHasNoProcedure = ! empty($_POST['searchTemplatesWithNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchTemplatesWithNoProcedure']) : ''; $conf = getWikiConfig($pearDB); $WikiURL = $conf['kb_wiki_url']; $currentPage = 'serviceTemplates'; require_once $modules_path . 'search.php'; // Init Status Template $status = [ 0 => "<font color='orange'> " . _('No wiki page defined') . ' </font>', 1 => "<font color='green'> " . _('Wiki page defined') . ' </font>', ]; $proc = new procedures($pearDB); $proc->fetchProcedures(); // Get Services Template Informations $query = " SELECT SQL_CALC_FOUND_ROWS service_description, service_id FROM service WHERE service_register = '0' AND service_locked = '0' "; if (! empty($postServiceTemplate)) { $query .= ' AND service_description LIKE :postServiceTemplate '; } $query .= 'ORDER BY ' . $orderBy . ' ' . $order . ' LIMIT :offset, :limit'; $statement = $pearDB->prepare($query); if (! empty($postServiceTemplate)) { $statement->bindValue(':postServiceTemplate', '%' . $postServiceTemplate . '%', PDO::PARAM_STR); } $statement->bindValue(':offset', $num * $limit, PDO::PARAM_INT); $statement->bindValue(':limit', $limit, PDO::PARAM_INT); $statement->execute(); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); $selection = []; while ($data = $statement->fetch(PDO::FETCH_ASSOC)) { $data['service_description'] = str_replace('#S#', '/', $data['service_description']); $data['service_description'] = str_replace('#BS#', '\\', $data['service_description']); $selection[$data['service_description']] = $data['service_id']; } $statement->closeCursor(); unset($data); // Create Diff $tpl->assign('host_name', _('Services Templates')); $diff = []; $templateHostArray = []; foreach ($selection as $key => $value) { $tplStr = ''; $tplArr = $proc->getMyServiceTemplateModels($value); $diff[$key] = $proc->serviceTemplateHasProcedure($key, $tplArr) == true ? 1 : 0; if (! empty($templatesHasNoProcedure)) { if ( $diff[$key] == 1 || $proc->serviceTemplateHasProcedure($key, $tplArr, PROCEDURE_INHERITANCE_MODE) == true ) { $rows--; unset($diff[$key]); continue; } } elseif (! empty($searchHasNoProcedure)) { if ($diff[$key] == 1) { $rows--; unset($diff[$key]); continue; } } if (count($tplArr)) { $firstTpl = 1; foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= "<a href='" . $WikiURL . '/index.php?title=Service-Template_:_' . $value1 . "' target='_blank'>" . $value1 . '</a>'; $firstTpl = 0; } else { $tplStr .= "&nbsp;|&nbsp;<a href='" . $WikiURL . '/index.php?title=Service-Template_:_' . $value1 . "' target='_blank'>" . $value1 . '</a>'; } } } $templateHostArray[$key] = $tplStr; unset($tplStr); } include './include/common/checkPagination.php'; if (isset($templateHostArray)) { $tpl->assign('templateHostArray', $templateHostArray); } $WikiVersion = getWikiVersion($WikiURL . '/api.php'); $tpl->assign('WikiVersion', $WikiVersion); $tpl->assign('WikiURL', $WikiURL); $tpl->assign('content', $diff); $tpl->assign('status', $status); $tpl->assign('selection', 3); // Send template in order to open // translations $tpl->assign('status_trans', _('Status')); $tpl->assign('actions_trans', _('Actions')); $tpl->assign('template_trans', _('Template')); // Template $tpl->registerObject('lineTemplate', getLineTemplate('list_one', 'list_two')); $tpl->assign('limit', $limit); $tpl->assign('order', $order); $tpl->assign('orderby', $orderBy); $tpl->assign('defaultOrderby', 'service_description'); // Apply a template definition $tpl->display($modules_path . 'templates/display.ihtml'); } catch (Exception $e) { $tpl->assign('errorMsg', $e->getMessage()); $tpl->display($modules_path . 'templates/NoWiki.tpl'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/popup.php
centreon/www/include/configuration/configKnowledge/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 * */ // TODO Security // Add paths $centreon_path = realpath(__DIR__ . '/../../../../'); require_once $centreon_path . '/config/centreon.config.php'; set_include_path( get_include_path() . PATH_SEPARATOR . $centreon_path . 'config/' . PATH_SEPARATOR . $centreon_path . 'www/class/' ); require_once 'centreon-knowledge/procedures.class.php'; require_once 'centreonLog.class.php'; $modules_path = $centreon_path . '/www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; require_once $centreon_path . '/bootstrap.php'; // Connect to centreon DB $pearDB = $dependencyInjector['configuration_db']; $conf = getWikiConfig($pearDB); $WikiURL = $conf['kb_wiki_url']; header("Location: {$WikiURL}/index.php?title=" . htmlentities($_GET['object'], ENT_QUOTES) . '&action=edit');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/display-hosts.php
centreon/www/include/configuration/configKnowledge/display-hosts.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(); } $modules_path = $centreon_path . 'www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; require_once $centreon_path . '/bootstrap.php'; $pearDB = $dependencyInjector['configuration_db']; if (! isset($limit) || (int) $limit < 0) { $limit = $centreon->optGen['maxViewConfiguration']; } $orderBy = 'host_name'; $order = 'ASC'; // Use whitelist as we can't bind ORDER BY sort parameter if (! empty($_POST['order']) && in_array($_POST['order'], ['ASC', 'DESC'])) { $order = $_POST['order']; } require_once './include/common/autoNumLimit.php'; // Add paths set_include_path(get_include_path() . PATH_SEPARATOR . $modules_path); require_once $centreon_path . '/www/class/centreon-knowledge/procedures.class.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($modules_path); try { $postHost = ! empty($_POST['searchHost']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHost']) : ''; $postHostgroup = ! empty($_POST['searchHostgroup']) ? filter_input(INPUT_POST, 'searchHostgroup', FILTER_VALIDATE_INT) : false; $postPoller = ! empty($_POST['searchPoller']) ? filter_input(INPUT_POST, 'searchPoller', FILTER_VALIDATE_INT) : false; $searchHasNoProcedure = ! empty($_POST['searchHasNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHasNoProcedure']) : ''; $templatesHasNoProcedure = ! empty($_POST['searchTemplatesWithNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchTemplatesWithNoProcedure']) : ''; $conf = getWikiConfig($pearDB); $WikiURL = $conf['kb_wiki_url']; $currentPage = 'hosts'; require_once $modules_path . 'search.php'; // Init Status Template $status = [ 0 => "<font color='orange'> " . _('No wiki page defined') . ' </font>', 1 => "<font color='green'> " . _('Wiki page defined') . ' </font>', ]; $proc = new procedures($pearDB); $proc->fetchProcedures(); $queryValues = []; $query = ' SELECT SQL_CALC_FOUND_ROWS host_name, host_id, host_register, ehi_icon_image FROM extended_host_information ehi, host '; if ($postPoller !== false) { $query .= 'JOIN ns_host_relation nhr ON nhr.host_host_id = host.host_id '; } if ($postHostgroup !== false) { $query .= 'JOIN hostgroup_relation hgr ON hgr.host_host_id = host.host_id '; } $query .= 'WHERE host.host_id = ehi.host_host_id '; if ($postPoller !== false) { $query .= 'AND nhr.nagios_server_id = :postPoller '; $queryValues[':postPoller'] = [ PDO::PARAM_INT => $postPoller, ]; } $query .= "AND host.host_register = '1' "; if ($postHostgroup !== false) { $query .= 'AND hgr.hostgroup_hg_id = :postHostgroup '; $queryValues[':postHostgroup'] = [ PDO::PARAM_INT => $postHostgroup, ]; } if (! empty($postHost)) { $query .= 'AND host_name LIKE :postHost '; $queryValues[':postHost'] = [ PDO::PARAM_STR => '%' . $postHost . '%', ]; } $query .= 'ORDER BY ' . $orderBy . ' ' . $order . ' LIMIT :offset, :limit'; $statement = $pearDB->prepare($query); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $statement->bindValue($bindId, $bindValue, $bindType); } } $statement->bindValue(':offset', $num * $limit, PDO::PARAM_INT); $statement->bindValue(':limit', $limit, PDO::PARAM_INT); $statement->execute(); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); $selection = []; while ($data = $statement->fetch(PDO::FETCH_ASSOC)) { if ($data['host_register'] == 1) { $selection[$data['host_name']] = $data['host_id']; } } $statement->closeCursor(); unset($data); // Create Diff $tpl->assign('host_name', _('Hosts')); $diff = []; $templateHostArray = []; foreach ($selection as $key => $value) { $tplStr = ''; $tplArr = $proc->getMyHostMultipleTemplateModels($value); $diff[$key] = $proc->hostHasProcedure($key, $tplArr) == true ? 1 : 0; if (! empty($templatesHasNoProcedure)) { if ($diff[$key] == 1 || $proc->hostHasProcedure($key, $tplArr, PROCEDURE_INHERITANCE_MODE) == true) { $rows--; unset($diff[$key]); continue; } } elseif (! empty($searchHasNoProcedure)) { if ($diff[$key] == 1) { $rows--; unset($diff[$key]); continue; } } if (count($tplArr)) { $firstTpl = 1; foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= "<a href='" . $WikiURL . '/index.php?title=Host-Template_:_' . $value1 . "' target='_blank'>" . $value1 . '</a>'; $firstTpl = 0; } else { $tplStr .= "&nbsp;|&nbsp;<a href='" . $WikiURL . '/index.php?title=Host-Template_:_' . $value1 . "' target='_blank'>" . $value1 . '</a>'; } } } $templateHostArray[$key] = $tplStr; unset($tplStr); } include './include/common/checkPagination.php'; if (isset($templateHostArray)) { $tpl->assign('templateHostArray', $templateHostArray); } $WikiVersion = getWikiVersion($WikiURL . '/api.php'); $tpl->assign('WikiVersion', $WikiVersion); $tpl->assign('WikiURL', $WikiURL); $tpl->assign('content', $diff); $tpl->assign('status', $status); $tpl->assign('selection', 0); // Send template in order to open // translations $tpl->assign('status_trans', _('Status')); $tpl->assign('actions_trans', _('Actions')); $tpl->assign('template_trans', _('Template')); // Template $tpl->registerObject('lineTemplate', getLineTemplate('list_one', 'list_two')); $tpl->assign('limit', $limit); $tpl->assign('order', $order); $tpl->assign('orderby', $orderBy); $tpl->assign('defaultOrderby', 'host_name'); // Apply a template definition $tpl->display($modules_path . 'templates/display.ihtml'); } catch (Exception $e) { $tpl->assign('errorMsg', $e->getMessage()); $tpl->display($modules_path . 'templates/NoWiki.tpl'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/display-services.php
centreon/www/include/configuration/configKnowledge/display-services.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(); } $modules_path = $centreon_path . 'www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; require_once $centreon_path . '/bootstrap.php'; $pearDB = $dependencyInjector['configuration_db']; if (! isset($limit) || (int) $limit < 0) { $limit = $centreon->optGen['maxViewConfiguration']; } $order = 'ASC'; $orderBy = 'host_name'; // Use whitelist as we can't bind ORDER BY values if (! empty($_POST['order']) && ! empty($_POST['orderby'])) { if (in_array($_POST['order'], ['ASC', 'DESC'])) { $order = $_POST['order']; } if (in_array($_POST['orderby'], ['host_name', 'service_description'])) { $orderBy = $_POST['orderby']; } } require_once './include/common/autoNumLimit.php'; // Add paths set_include_path(get_include_path() . PATH_SEPARATOR . $modules_path); require_once $centreon_path . '/www/class/centreon-knowledge/procedures.class.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($modules_path); try { $postHost = ! empty($_POST['searchHost']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHost']) : ''; $postService = ! empty($_POST['searchService']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchService']) : ''; $postHostgroup = ! empty($_POST['searchHostgroup']) ? filter_input(INPUT_POST, 'searchHostgroup', FILTER_VALIDATE_INT) : false; $postServicegroup = ! empty($_POST['searchServicegroup']) ? filter_input(INPUT_POST, 'searchServicegroup', FILTER_VALIDATE_INT) : false; $postPoller = ! empty($_POST['searchPoller']) ? filter_input(INPUT_POST, 'searchPoller', FILTER_VALIDATE_INT) : false; $searchHasNoProcedure = ! empty($_POST['searchHasNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchHasNoProcedure']) : ''; $templatesHasNoProcedure = ! empty($_POST['searchTemplatesWithNoProcedure']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchTemplatesWithNoProcedure']) : ''; $conf = getWikiConfig($pearDB); $WikiURL = $conf['kb_wiki_url']; $currentPage = 'services'; require_once $modules_path . 'search.php'; // Init Status Template $status = [ 0 => "<font color='orange'> " . _('No wiki page defined') . ' </font>', 1 => "<font color='green'> " . _('Wiki page defined') . ' </font>', ]; $proc = new procedures($pearDB); $proc->fetchProcedures(); $queryValues = []; $query = " SELECT SQL_CALC_FOUND_ROWS t1.* FROM ( SELECT s.service_id, s.service_description, h.host_name, h.host_id FROM service s LEFT JOIN host_service_relation hsr ON hsr.service_service_id = s.service_id RIGHT JOIN host h ON h.host_id = hsr.host_host_id WHERE s.service_register = '1' "; if (! empty($postHost)) { $query .= 'AND h.host_name LIKE :postHost '; $queryValues[':postHost'] = [ PDO::PARAM_STR => '%' . $postHost . '%', ]; } if ($postHostgroup !== false) { $query .= ' AND hsr.host_host_id IN (SELECT host_host_id FROM hostgroup_relation hgr WHERE hgr.hostgroup_hg_id = :postHostgroup ) '; $queryValues[':postHostgroup'] = [ PDO::PARAM_INT => $postHostgroup, ]; } if ($postServicegroup !== false) { $query .= ' AND s.service_id IN (SELECT service_service_id FROM servicegroup_relation WHERE servicegroup_sg_id = :postServicegroup ) '; $queryValues[':postServicegroup'] = [ PDO::PARAM_INT => $postServicegroup, ]; } if ($postPoller !== false) { $query .= ' AND hsr.host_host_id IN (SELECT host_host_id FROM ns_host_relation WHERE nagios_server_id = :postPoller ) '; $queryValues[':postPoller'] = [ PDO::PARAM_INT => $postPoller, ]; } if (! empty($postService)) { $query .= 'AND s.service_description LIKE :postService '; $queryValues[':postService'] = [ PDO::PARAM_STR => '%' . $postService . '%', ]; } $query .= " UNION SELECT s2.service_id, s2.service_description, h2.host_name, h2.host_id FROM service s2 LEFT JOIN host_service_relation hsr2 ON hsr2.service_service_id = s2.service_id RIGHT JOIN hostgroup_relation hgr ON hgr.hostgroup_hg_id = hsr2.hostgroup_hg_id LEFT JOIN host h2 ON h2.host_id = hgr.host_host_id WHERE s2.service_register = '1' "; if ($postHostgroup !== false) { $query .= ' AND (h2.host_id IN (SELECT host_host_id FROM hostgroup_relation hgr WHERE hgr.hostgroup_hg_id = :postHostgroup ) OR hgr.hostgroup_hg_id = :postHostgroup ) '; } if (! empty($postHost)) { $query .= 'AND h2.host_name LIKE :postHost '; } if ($postServicegroup !== false) { $query .= ' AND s2.service_id IN (SELECT service_service_id FROM servicegroup_relation WHERE servicegroup_sg_id = :postServicegroup) '; } if ($postPoller !== false) { $query .= ' AND h2.host_id IN (SELECT host_host_id FROM ns_host_relation WHERE nagios_server_id = :postPoller ) '; } if (! empty($postService)) { $query .= 'AND s2.service_description LIKE :postService '; } $query .= ') as t1 '; $query .= "ORDER BY {$orderBy} " . $order . ' LIMIT :offset, :limit'; $statement = $pearDB->prepare($query); foreach ($queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $statement->bindValue($bindId, $bindValue, $bindType); } } $statement->bindValue(':offset', $num * $limit, PDO::PARAM_INT); $statement->bindValue(':limit', $limit, PDO::PARAM_INT); $statement->execute(); $serviceList = []; while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { $row['service_description'] = str_replace('#S#', '/', $row['service_description']); $row['service_description'] = str_replace('#BS#', '\\', $row['service_description']); if (isset($row['host_id']) && $row['host_id']) { $serviceList[$row['host_name'] . '_/_' . $row['service_description']] = [ 'id' => $row['service_id'], 'svc' => $row['service_description'], 'h' => $row['host_name'], ]; } } $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); // Create Diff $tpl->assign('host_name', _('Hosts')); $tpl->assign('p', 61002); $tpl->assign('service_description', _('Services')); $diff = []; $templateHostArray = []; foreach ($serviceList as $key => $value) { $tplStr = ''; $tplArr = $proc->getMyServiceTemplateModels($value['id']); $key_nospace = str_replace(' ', '_', $key); $diff[$key] = $proc->serviceHasProcedure($key_nospace, $tplArr) == true ? 1 : 0; if (! empty($templatesHasNoProcedure)) { if ( $diff[$key] == 1 || $proc->serviceHasProcedure($key_nospace, $tplArr, PROCEDURE_INHERITANCE_MODE) == true ) { $rows--; unset($diff[$key], $serviceList[$key]); continue; } } elseif (! empty($searchHasNoProcedure)) { if ($diff[$key] == 1) { $rows--; unset($diff[$key], $serviceList[$key]); continue; } } if (count($tplArr)) { $firstTpl = 1; foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $firstTpl = 0; } else { $tplStr .= '&nbsp;|&nbsp;'; } $tplStr .= "<a href='" . $WikiURL . '/index.php?title=Service-Template_:_' . $value1 . "' target='_blank'>" . $value1 . '</a>'; } } $templateHostArray[$key] = $tplStr; unset($tplStr); } include './include/common/checkPagination.php'; if (isset($templateHostArray)) { $tpl->assign('templateHostArray', $templateHostArray); } $WikiVersion = getWikiVersion($WikiURL . '/api.php'); $tpl->assign('WikiVersion', $WikiVersion); $tpl->assign('WikiURL', $WikiURL); $tpl->assign('content', $diff); $tpl->assign('services', $serviceList); $tpl->assign('status', $status); $tpl->assign('selection', 1); // Send template in order to open // translations $tpl->assign('status_trans', _('Status')); $tpl->assign('actions_trans', _('Actions')); $tpl->assign('template_trans', _('Template')); // Template $tpl->registerObject('lineTemplate', getLineTemplate('list_one', 'list_two')); $tpl->assign('limit', $limit); $tpl->assign('order', $order); $tpl->assign('orderby', $orderBy); $tpl->assign('defaultOrderby', 'host_name'); // Apply a template definition $tpl->display($modules_path . 'templates/display.ihtml'); } catch (Exception $e) { $tpl->assign('errorMsg', $e->getMessage()); $tpl->display($modules_path . 'templates/NoWiki.tpl'); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configKnowledge/proxy/proxy.php
centreon/www/include/configuration/configKnowledge/proxy/proxy.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', 'On'); $centreon_path = realpath(__DIR__ . '/../../../../../'); global $etc_centreon; require_once $centreon_path . '/config/centreon.config.php'; set_include_path( get_include_path() . PATH_SEPARATOR . $centreon_path . 'www/class/centreon-knowledge/' . PATH_SEPARATOR . $centreon_path . 'www/' ); require_once 'include/common/common-Func.php'; require_once 'class/centreonLog.class.php'; require_once $centreon_path . '/bootstrap.php'; require_once 'class/centreon-knowledge/procedures.class.php'; require_once 'class/centreon-knowledge/ProceduresProxy.class.php'; $modules_path = $centreon_path . 'www/include/configuration/configKnowledge/'; require_once $modules_path . 'functions.php'; // DB connexion $pearDB = $dependencyInjector['configuration_db']; try { $wikiConf = getWikiConfig($pearDB); } catch (Exception $e) { echo $e->getMessage(); exit(); } $wikiURL = $wikiConf['kb_wiki_url']; $proxy = new ProceduresProxy($pearDB); // Check if user want host or service procedures $url = null; if (isset($_GET['host_name'])) { $hostName = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_name']); } if (isset($_GET['service_description'])) { $serviceDescription = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['service_description']); } if (! empty($hostName) && ! empty($serviceDescription)) { $url = $proxy->getServiceUrl($hostName, $serviceDescription); } elseif (! empty($hostName)) { $url = $proxy->getHostUrl($hostName); } if (! empty($url)) { header('Location: ' . $url); } elseif (! empty($hostName) && ! empty($serviceDescription)) { header("Location: {$wikiURL}/?title=Service_:_" . $hostName . '_/_' . $serviceDescription); } elseif (! empty($hostname)) { header("Location: {$wikiURL}/?title=Host_:_" . $hostName); } else { header('Location: ' . $wikiURL); } 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/configuration/configNagios/comments.php
centreon/www/include/configuration/configNagios/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 * */ $nagios_comment = []; $nagios_comment['log_file'] = 'This is the main log file where service ' . 'and host events are logged for historical purposes. ' . 'This should be the first option specified in the config file!!!'; $nagios_comment['cfg_file'] = ' This is the configuration file in which you define ' . 'hosts, host groups, contacts, contact groups, services, etc. ' . 'I guess it would be better called an object definition file, ' . "but for historical reasons it isn\'t. " . 'You can split object definitions into several ' . 'different config files by using multiple cfg_file statements here. ' . 'Nagios will read and process all the config files you define. ' . 'This can be very useful if you want to keep command definitions ' . 'separate from host and contact definitions... ' . 'Plugin commands (service and host check commands) ' . 'Arguments are likely to change between different releases of the ' . 'plugins, so you should use the same config file provided ' . 'with the plugin release rather than the one provided with Nagios. '; $nagios_comment['status_file'] = 'This is where the current status of all monitored services and ' . 'hosts is stored. Its contents are read and processed by the CGIs. ' . 'The contentsof the status file are deleted every time Nagios ' . 'restarts. '; $nagios_comment['check_external_commands'] = 'This option allows you to specify whether or not Nagios should check ' . 'for external commands (in the command file defined below). By default ' . 'Nagios will *not* check for external commands, just to be on the ' . 'cautious side. If you want to be able to use the CGI command interface ' . 'you will have to enable this. Setting this value to 0 disables command ' . 'checking (the default), other values enable it. '; $nagios_comment['command_check_interval'] = 'This is the interval at which Nagios should check for external commands. ' . 'This value works of the interval_length you specify later. If you leave ' . 'that at its default value of 60 (seconds), a value of 1 here will cause ' . 'Nagios to check for external commands every minute. If you specify a ' . 'number followed by an &laquo;s&raquo; (i.e. 15s), this will be interpreted to mean ' . 'actual seconds rather than a multiple of the interval_length variable. ' . 'Note: In addition to reading the external command file at regularly ' . 'scheduled intervals, Nagios will also check for external commands after ' . 'event handlers are executed. ' . 'NOTE: Setting this value to -1 causes Nagios to check the external ' . 'command file as often as possible. '; $nagios_comment['command_file'] = 'This is the file that Nagios checks for external command requests. ' . 'It is also where the command CGI will write commands that are submitted ' . 'by users, so it must be writeable by the user that the web server ' . 'is running as (usually &laquo;nobody&raquo;). Permissions should be set at the ' . 'directory level instead of on the file, as the file is deleted every ' . 'time its contents are processed. '; $nagios_comment['use_syslog'] = 'If you want messages logged to the syslog facility, as well as the ' . 'NetAlarm log file set this option to 1. If not, set it to 0. '; $nagios_comment['log_notifications'] = "If you don\'t want notifications to be logged, set this value to 0. " . 'If notifications should be logged, set the value to 1. '; $nagios_comment['log_service_retries'] = "If you don\'t want service check retries to be logged, set this value " . 'to 0. If retries should be logged, set the value to 1. '; $nagios_comment['log_host_retries'] = "If you don\'t want host check retries to be logged, set this value to " . '0. If retries should be logged, set the value to 1. '; $nagios_comment['log_event_handlers'] = "If you don\'t want host and service event handlers to be logged, set " . 'this value to 0. If event handlers should be logged, set the value ' . 'to 1.'; $nagios_comment['log_external_commands'] = "If you don\'t want Nagios to log external commands, set this value " . 'to 0. If external commands should be logged, set this value to 1. ' . 'Note: This option does not include logging of passive service ' . 'checks - see the option below for controlling whether or not ' . 'passive checks are logged. '; $nagios_comment['log_passive_service_checks'] = "If you don\'t want Nagios to log passive service checks, set this " . 'value to 0. If passive service checks should be logged, set this ' . 'value to 1. '; $nagios_comment['inter_check'] = 'This is the method that Nagios should use when initially ' . '&laquo;spreading out&raquo; service checks when it starts monitoring. The ' . 'default is to use smart delay calculation, which will try to ' . 'space all service checks out evenly to minimize CPU load. ' . 'Using the dumb setting will cause all checks to be scheduled ' . 'at the same time (with no delay between them)! This is not a ' . 'good thing for production, but is useful when testing the ' . 'parallelization functionality. <br />' . "n = None - don\'t use any delay between checks <br />" . 'd = Use a &laquo;dumb&raquo; delay of 1 second between checks <br />' . 's = Use &laquo;smart&raquo; inter-check delay calculation <br />' . ' x.xx = Use an inter-check delay of x.xx seconds '; $nagios_comment['service_inter_check'] = 'This option allows you to control ' . 'how service checks are initially &laquo;spread out&laquo; in the event queue.<br />' . 'Using a &laquo;smart&laquo; delay calculation (the default) will cause Nagios ' . 'to calculate an average check interval and spread initial checks of all services out over that interval, ' . 'thereby helping to eliminate CPU load spikes.<br />' . 'Using no delay is generally not recommended unless you are testing ' . 'the service check parallelization functionality.<br />' . 'no delay will cause all service checks to be scheduled for execution at the same time.<br />' . 'This means that you will generally have large CPU spikes when the services are all executed in parallel.<br />' . 'Values are as follows :<br /> ' . "n = None - don\'t use any delay between checks to run immediately (i.e. at the same time!) <br />" . 'd = Use a &laquo;dumb&raquo; delay of 1 second between checks <br />' . 's = Use &laquo;smart&raquo; inter-check delay calculation to spread service checks out evenly (default)<br />' . ' x.xx = Use a user-supplied inter-check delay of x.xx seconds'; $nagios_comment['host_inter_check'] = 'This option allows you to control ' . 'how host checks that are scheduled to be checked on a regular basis ' . 'are initially &laquo;spread out&laquo; in the event queue.<br />' . 'Using a &laquo;smart&laquo; delay calculation (the default) ' . 'will cause Nagios to calculate an average check interval ' . 'and spread initial checks of all hosts out over that interval, ' . 'thereby helping to eliminate CPU load spikes.<br />' . 'Using no delay is generally not recommended.<br />' . 'Using no delay will cause all host checks to be scheduled for execution at the same time.<br />' . 'Values are as follows :<br /> ' . "n = None - don\'t use any delay - schedule all host checks to run immediately (i.e. at the same time!) <br />" . 'd = Use a &laquo;dumb&raquo; delay of 1 second between host checks <br />' . 's = Use &laquo;smart&raquo; delay calculation to spread host checks out evenly (default) <br />' . ' x.xx = Use a user-supplied inter-check delay of x.xx seconds'; $nagios_comment['service_interleave_factor'] = 'This variable determines how service checks are interleaved. ' . 'Interleaving the service checks allows for a more even ' . 'distribution of service checks and reduced load on remote' . 'hosts. Setting this value to 1 is equivalent to how versions ' . 'of Nagios previous to 0.0.5 did service checks. Set this ' . 'value to s (smart) for automatic calculation of the interleave ' . 'factor unless you have a specific reason to change it.<br /> ' . ' s = Use &laquo;smart&raquo; interleave factor calculation<br /> ' . ' x = Use an interleave factor of x, where x is a <br />' . ' number greater than or equal to 1. '; $nagios_comment['max_concurrent_checks'] = 'This option allows you to specify the maximum number of ' . 'service checks that can be run in parallel at any given time. ' . 'Specifying a value of 1 for this variable essentially prevents ' . 'any service checks from being parallelized. A value of 0 ' . 'will not restrict the number of concurrent checks that are ' . 'being executed. '; $nagios_comment['max_service_check_spread'] = 'This option determines the maximum number of minutes ' . 'from when Nagios starts that all services ' . '(that are scheduled to be regularly checked) are checked.<br />' . 'This option will automatically adjust the service inter-check delay (if necessary) ' . 'to ensure that the initial checks of all services occur within the timeframe you specify.<br />' . 'In general, this option will not have an effect on service check ' . 'scheduling if scheduling information is being retained using the use_retained_scheduling_info option.<br />' . 'Default value is 30 (minutes). '; $nagios_comment['max_host_check_spread'] = 'This option determines the maximum number of minutes ' . 'from when Nagios starts that all hosts ' . '(that are scheduled to be regularly checked) are checked.<br />' . 'This option will automatically adjust the host inter-check delay (if necessary) ' . 'to ensure that the initial checks of all hosts occur within the timeframe you specify.<br />' . 'In general, this option will not have an effect on host check scheduling ' . 'if scheduling information is being retained using the use_retained_scheduling_info option.<br />' . 'Default value is 30 (minutes). '; $nagios_comment['check_result_reaper_frequency'] = 'This is the frequency (in seconds!) that Nagios will process ' . 'the results of services that have been checked. '; $nagios_comment['sleep_time'] = 'This is the number of seconds to sleep between checking for system ' . 'events and service checks that need to be run. I would recommend ' . '*not* changing this from its default value of 1 second. '; $nagios_comment['timeout'] = 'These options control how much time Nagios will allow various ' . 'types of commands to execute before killing them off. Options ' . 'are available for controlling maximum time allotted for ' . 'service checks, host checks, event handlers, notifications, the ' . 'ocsp command, and performance data commands. All values are in ' . 'seconds. '; $nagios_comment['retain_state_information'] = 'This setting determines whether or not Nagios will save state ' . 'information for services and hosts before it shuts down. Upon ' . 'startup Nagios will reload all saved service and host state ' . 'information before starting to monitor. This is useful for ' . 'maintaining long-term data on state statistics, etc, but will ' . 'slow Nagios down a bit when it re starts. Since its only ' . 'a one-time penalty, I think its well worth the additional ' . 'startup delay. '; $nagios_comment['state_retention_file'] = 'This is the file that Nagios should use to store host and ' . 'service state information before it shuts down. The state ' . 'information in this file is also read immediately prior to ' . 'starting to monitor the network when Nagios is restarted. ' . 'This file is used only if the preserve_state_information ' . 'variable is set to 1. '; $nagios_comment['retention_update_interval'] = 'This setting determines how often (in minutes) that Nagios ' . 'will automatically save retention data during normal operation. ' . 'If you set this value to 0, Nagios will not save retention ' . 'data at regular interval, but it will still save retention ' . 'data before shutting down or restarting. If you have disabled ' . 'state retention, this option has no effect. '; $nagios_comment['use_retained_program_state'] = 'This setting determines whether or not Nagios will set ' . 'program status variables based on the values saved in the ' . 'retention file. If you want to use retained program status ' . 'information, set this value to 1. If not, set this value ' . 'to 0. '; $nagios_comment['use_retained_scheduling_info'] = 'This setting determines whether or not ' . 'Nagios will retain scheduling info (next check times) for hosts and services when it restarts.<br />' . 'If you are adding a large number (or percentage) of hosts and services, ' . 'I would recommend disabling this option when you first restart Nagios, ' . 'as it can adversely skew the spread of initial checks.<br />' . 'Otherwise you will probably want to leave it enabled.'; $nagios_comment['execute_service_checks'] = 'This determines whether or not Nagios will actively execute ' . 'service checks when it initially starts. If this option is ' . 'disabled, checks are not actively made, but Nagios can still ' . 'receive and process passive check results that come in. Unless ' . "you\'re implementing redundant hosts or have a special need for " . 'disabling the execution of service checks, leave this enabled! ' . 'Values: 1 = enable checks, 0 = disable checks '; $nagios_comment['accept_passive_service_checks'] = 'This determines whether or not Nagios will accept passive ' . 'service checks results when it initially (re)starts. ' . 'Values: 1 = accept passive checks, 0 = reject passive checks '; $nagios_comment['log_passive_checks'] = 'This variable determines whether or not ' . 'Nagios will log passive host and service checks that ' . 'it receives from the external command file.<br />' . 'If you are setting up a distributed monitoring environment ' . 'or plan on handling a large number of passive checks on a regular basis, ' . "you may wish to disable this option so your log file doesn\'t get too large."; $nagios_comment['execute_host_checks'] = 'This option determines whether or not ' . 'Nagios will execute on-demand and regularly scheduled host checks when it initially (re)starts. ' . 'If this option is disabled, Nagios will not actively execute any host checks, ' . "although it can still accept passive host checks unless you\'ve disabled them).<br />" . 'This option is most often used when configuring backup monitoring servers, ' . 'as described in the documentation on redundancy, or when setting up a distributed monitoring environment.'; $nagios_comment['accept_passive_host_checks'] = 'This option determines whether or not Nagios will accept ' . 'passive host checks when it initially (re)starts.<br />' . 'If this option is disabled, Nagios will not accept any passive host checks.'; $nagios_comment['enable_notifications'] = 'This determines whether or not Nagios will sent out any host or ' . 'service notifications when it is initially (re)started. ' . 'Values: 1 = enable notifications, 0 = disable notifications '; $nagios_comment['enable_event_handlers'] = 'This determines whether or not Nagios will run any host or ' . 'service event handlers when it is initially (re)started. Unless ' . "you\'re implementing redundant hosts, leave this option enabled. " . 'Values: 1 = enable event handlers, 0 = disable event handlers '; $nagios_comment['check_for_orphaned_services'] = 'This determines whether or not Nagios will periodically ' . 'check for orphaned services. Since service checks are not ' . 'rescheduled until the results of their previous execution ' . 'instance are processed, there exists a possibility that some ' . 'checks may never get rescheduled. This seems to be a rare ' . 'problem and should not happen under normal circumstances. ' . 'If you have problems with service checks never getting ' . 'rescheduled, you might want to try enabling this option. ' . 'Values: 1 = enable checks, 0 = disable checks '; $nagios_comment['check_service_freshness'] = 'This option determines whether or not Nagios will periodically ' . 'check the freshness of service results. Enabling this option ' . 'is useful for ensuring passive checks are received in a timely ' . 'manner. ' . 'Values: 1 = enabled freshness checking, 0 = disable freshness checking '; $nagios_comment['service_freshness_check_interval'] = 'This setting determines how often (in seconds) ' . 'Nagios will periodically check the &laquo;freshness&laquo; of service check results.<br />' . 'If you have disabled service freshness checking (with the check_service_freshness option), ' . 'this option has no effect.'; $nagios_comment['check_host_freshness'] = 'This option determines whether or not Nagios ' . 'will periodically check the &laquo;freshness&laquo; of host checks.<br />' . 'Enabling this option is useful for helping to ensure that passive host checks are received in a timely manner.'; $nagios_comment['host_freshness_check_interval'] = 'This setting determines how often (in seconds) ' . 'Nagios will periodically check the &laquo;freshness&laquo; of host check results.<br />' . 'If you have disabled host freshness checking (with the check_host_freshness option), this option has no effect.'; $nagios_comment['freshness_check_interval'] = 'This setting determines how often (in seconds) Nagios will ' . 'check the freshness of service check results. If you have ' . 'disabled service freshness checking, this option has no effect. '; $nagios_comment['status_update_interval'] = 'Combined with the aggregate_status_updates option, ' . 'this option determines the frequency (in seconds!) that ' . 'Nagios will periodically dump program, host, and ' . 'service status data. If you are not using aggregated ' . 'status data updates, this option has no effect. '; $nagios_comment['enable_flap_detection'] = 'This option determines whether or not Nagios will try ' . 'and detect hosts and services that are flapping. ' . 'Flapping occurs when a host or service changes between ' . 'states too frequently. When Nagios detects that a ' . 'host or service is flapping, it will temporarily supress ' . 'notifications for that host/service until it stops ' . 'flapping. Flap detection is very experimental, so read ' . 'the HTML documentation before enabling this feature! ' . 'Values: 1 = enable flap detection ' . ' 0 = disable flap detection (default) '; $nagios_comment['flap_threshold'] = 'Read the HTML documentation on flap detection for ' . 'an explanation of what this option does. This option ' . 'has no effect if flap detection is disabled. '; $nagios_comment['date_format'] = 'This option determines how short dates are displayed. Valid options ' . 'include:<br /> ' . 'us (MM-DD-YYYY HH:MM:SS) <br />' . 'euro (DD-MM-YYYY HH:MM:SS) <br />' . 'iso8601 (YYYY-MM-DD HH:MM:SS) <br />' . 'strict-iso8601 (YYYY-MM-DDTHH:MM:SS) '; $nagios_comment['illegal_object_name_chars'] = 'This options allows you ' . 'to specify illegal characters that cannot ' . 'be used in host names, service descriptions, or names of other ' . 'object types. '; $nagios_comment['use_regexp_matching'] = "If you\'ve enabled regular expression matching of various object directives " . 'using the use_regexp_matching option, this option will determine ' . 'when object directives are treated as regular expressions.<br />' . 'If this option is disabled (the default), directives will only be treated ' . 'as regular expressions if the contain a * or ? wildcard character.<br />' . 'If this option is enabled, all appropriate directives will be treated ' . 'as regular expression - be careful when enabling this!<br />' . "0 = Don\'t use true regular expression matching " . '(default)<br />1 = Use true regular expression matching '; $nagios_comment['use_true_regexp_matching'] = "If you\'ve enabled regular expression matching " . 'of various object directives using the use_regexp_matching option, ' . 'this option will determine when object directives are treated as regular expressions.<br />' . 'If this option is disabled (the default), directives will only be treated ' . 'as regular expressions if the contain a * or ? wildcard character..<br />' . 'If this option is enabled, all appropriate directives will be treated ' . 'as regular expression - be careful when enabling this!<br />' . "0 = Don\'t use regular expression matching (default)<br />1 = Use regular expression matching "; $nagios_comment['illegal_macro_output_chars'] = 'This options allows you to specify illegal characters that are ' . 'stripped from macros before being used in notifications, event ' . 'handlers, etc. This DOES NOT affect macros used in service or ' . 'host check commands. ' . 'The following macros are stripped of the characters you specify: ' . ' $OUTPUT$, $PERFDATA$ '; $nagios_comment['admin_email'] = 'The email address of the administrator of *this* machine (the one ' . 'doing the monitoring). Nagios never uses this value itself, but ' . 'you can access this value by using the $ADMINEMAIL$ macro in your ' . 'notification commands. '; $nagios_comment['admin_pager'] = 'The pager number/address for the administrator of *this* machine. ' . 'Nagios never uses this value itself, but you can access this ' . 'value by using the $ADMINPAGER$ macro in your notification ' . 'commands. '; $nagios_comment['auto_reschedule_checks'] = 'This option determines whether or not Nagios will attempt ' . 'to automatically reschedule active host and service checks to &laquo;smooth&laquo; them out over time.<br />' . 'This can help to balance the load on the monitoring server, as it will attempt ' . 'to keep the time between consecutive checks consistent, at the expense of executing checks ' . 'on a more rigid schedule.'; $nagios_comment['auto_rescheduling_interval'] = 'This option determines how often (in seconds) ' . 'Nagios will attempt to automatically reschedule checks.<br />' . 'This option only has an effect if the auto_reschedule_checks option is enabled.<br />' . 'Default is 30 seconds.'; $nagios_comment['auto_rescheduling_window'] = 'This option determines the &laquo;window&laquo; of time (in seconds) ' . 'that Nagios will look at when automatically rescheduling checks.<br />' . 'Only host and service checks that occur in the next X seconds ' . '(determined by this variable) will be rescheduled.<br />' . 'This option only has an effect if the auto_reschedule_checks option is enabled.<br />' . 'Default is 180 seconds (3 minutes).';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configNagios/help.php
centreon/www/include/configuration/configNagios/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['use_timezone'] = dgettext( 'help', 'Define the poller timezone. If not set, default Centreon timezone is used (parameters). ' . 'This timezone is used for hosts which have not configured timezone.' ); $help['status_file'] = dgettext( 'help', 'This is the file that Monitoring Engine uses to store the current status, ' . 'comment, and downtime information. ' . 'This file is deleted every time Monitoring Engine stops and recreated when it starts.' ); $help['status_update_interval'] = dgettext( 'help', 'Combined with the aggregate_status_updates option, this option determines ' . 'the frequency (in seconds!) that Nagios will periodically dump program, ' . 'host, and service status data. If you are not using aggregated status data updates, ' . 'this option has no effect. The minimum update interval is 2 seconds.' ); $help['log_file'] = dgettext( 'help', 'Location (path and filename) where Monitoring Engine should create its main log file.' ); $help['cfg_dir'] = dgettext( 'help', 'Directory where Centreon will export Monitoring Engine object configuration files to. ' . 'Monitoring Engine will parse all .cfg files in this directory.' ); $help['enable_notifications'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will send out notifications ' . 'when it initially (re)starts. If this option is disabled, Monitoring Engine ' . 'will not send out notifications for any host or service. Note: If you have ' . 'state retention enabled, Monitoring Engine will ignore this setting when ' . 'it (re)starts and use the last known setting for this option (as stored in the state ' . 'retention file), unless you disable the use_retained_program_state option. ' . 'If you want to change this option when state retention is active ' . "(and the use_retained_program_state is enabled), you'll have to use the appropriate " . 'external command or change it via the web interface. Notifications are enabled by default.' ); $help['execute_service_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will execute service checks ' . 'when it initially (re)starts. If this option is disabled, Monitoring Engine ' . 'will not actively execute any service checks and will remain in a sort of "sleep" mode ' . "(it can still accept passive checks unless you've disabled them). This option is most " . 'often used when configuring backup monitoring servers, as described in the documentation ' . 'on redundancy, or when setting up a distributed monitoring environment. Note: ' . 'If you have state retention enabled, Monitoring Engine will ignore this setting ' . 'when it (re)starts and use the last known setting for this option (as stored in the state ' . 'retention file), unless you disable the use_retained_program_state option. If you want ' . 'to change this option when state retention is active ' . "(and the use_retained_program_state is enabled), you'll have to use the appropriate " . 'external command or change it via the web interface. Service checks are enabled by default.' ); $help['execute_host_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will execute host checks ' . 'when it initially (re)starts. If this option is disabled, Monitoring Engine ' . 'will not actively execute any host checks and will remain in a sort of "sleep" mode ' . "(it can still accept passive checks unless you've disabled them). This option is most " . 'often used when configuring backup monitoring servers, as described in the documentation ' . 'on redundancy, or when setting up a distributed monitoring environment. Note: If you have ' . 'state retention enabled, Monitoring Engine will ignore this setting when it (re)starts ' . 'and use the last known setting for this option (as stored in the state retention file), ' . 'unless you disable the use_retained_program_state option. If you want to change ' . 'this option when state retention is active (and the use_retained_program_state is enabled), ' . "you'll have to use the appropriate external command or change it via the web interface. " . 'Host checks are enabled by default.' ); $help['accept_passive_service_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will accept passive service checks ' . 'when it initially (re)starts. If this option is disabled, Monitoring Engine will not ' . 'accept any passive service checks. Note: If you have state retention enabled, ' . 'Monitoring Engine will ignore this setting when it (re)starts and use the last known ' . 'setting for this option (as stored in the state retention file), unless you disable ' . 'the use_retained_program_state option. If you want to change this option when state ' . "retention is active (and the use_retained_program_state is enabled), you'll have to " . 'use the appropriate external command or change it via the web interface. ' . 'Option is enabled by default.' ); $help['accept_passive_host_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will accept passive host checks ' . 'when it initially (re)starts. If this option is disabled, Monitoring Engine will not ' . 'accept any passive host checks. Note: If you have state retention enabled, ' . 'Monitoring Engine will ignore this setting when it (re)starts and use the last known ' . 'setting for this option (as stored in the state retention file), unless you disable the ' . 'use_retained_program_state option. If you want to change this option when state retention ' . "is active (and the use_retained_program_state is enabled), you'll have to use the " . 'appropriate external command or change it via the web interface. Option is enabled by default.' ); $help['enable_event_handlers'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will run event handlers when it ' . 'initially (re)starts. If this option is disabled, Monitoring Engine will not run any host ' . 'or service event handlers. Note: If you have state retention enabled, Monitoring Engine ' . 'will ignore this setting when it (re)starts and use the last known setting for this option ' . '(as stored in the state retention file), unless you disable the use_retained_program_state ' . 'option. If you want to change this option when state retention is active (and the ' . "use_retained_program_state is enabled), you'll have to use the appropriate external command " . 'or change it via the web interface. Option is enabled by default.' ); $help['check_external_commands'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will check the command file ' . 'for commands that should be executed. This option must be enabled if you plan ' . 'on using Centreon to issue commands via the web interface.' ); $help['command_check_interval'] = dgettext( 'help', 'If you specify a number with an "s" appended to it (i.e. 30s), this is the number ' . 'of seconds to wait between external command checks. If you leave off the "s", ' . 'this is the number of "time units" to wait between external command checks. ' . "Unless you've changed the interval_length value (as defined below) from the default " . 'value of 60, this number will mean minutes. By setting this value to -1, Monitoring Engine ' . 'will check for external commands as often as possible. Each time Monitoring Engine checks ' . 'for external commands it will read and process all commands present in the command file ' . 'before continuing on with its other duties.' ); $help['command_file'] = dgettext( 'help', 'This is the file that Monitoring Engine will check for external commands to process. ' . 'Centreon writes commands to this file. The external command file is implemented ' . 'as a named pipe (FIFO), which is created when Monitoring Engine starts and removed ' . 'when it shuts down. If the file exists when Monitoring Engine starts, the Monitoring Engine ' . 'process will terminate with an error message.' ); $help['external_command_buffer_slots'] = dgettext( 'help', 'This is an advanced feature. This option determines how many buffer slots Monitoring Engine ' . 'will reserve for caching external commands that have been read from the external command file ' . 'by a worker thread, but have not yet been processed by the main thread of the Monitoring Engine ' . 'daemon. This option essentially determines how many commands can be buffered. For installations ' . 'where you process a large number of passive checks (e.g. distributed setups), you may need to ' . "increase this number. You should consider using MRTG to graph Monitoring Engine' usage of " . 'external command buffers.' ); $help['retain_state_information'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will retain state information for hosts ' . 'and services between program restarts. If you enable this option, you should supply a value ' . 'for the state_retention_file variable. When enabled, Monitoring Engine will save all state ' . 'information for hosts and service before it shuts down (or restarts) and will read in ' . 'previously saved state information when it starts up again. Option is enabled by default.' ); $help['state_retention_file'] = dgettext( 'help', 'This is the file that Monitoring Engine will use for storing status, downtime, and comment ' . 'information before it shuts down. When Monitoring Engine is restarted it will use the ' . 'information stored in this file for setting the initial states of services and hosts before ' . 'it starts monitoring anything. In order to make Monitoring Engine retain state information ' . 'between program restarts, you must enable the retain_state_information option.' ); $help['retention_update_interval'] = dgettext( 'help', 'This setting determines how often (in minutes) that Monitoring Engine will automatically ' . 'save retention data during normal operation. If you set this value to 0, Monitoring Engine ' . 'will not save retention data at regular intervals, but it will still save retention data ' . 'before shutting down or restarting. If you have disabled state retention (with the ' . 'retain_state_information option), this option has no effect.' ); $help['use_retained_program_state'] = dgettext( 'help', 'This setting determines whether or not Monitoring Engine will set various program-wide state ' . 'variables based on the values saved in the retention file. Some of these program-wide state ' . 'variables that are normally saved across program restarts if state retention is enabled ' . 'include the enable_notifications, enable_flap_detection, enable_event_handlers, ' . 'execute_service_checks, and accept_passive_service_checks options. If you do not have state ' . 'retention enabled, this option has no effect. This option is enabled by default.' ); $help['use_retained_scheduling_info'] = dgettext( 'help', 'This setting determines whether or not Monitoring Engine will retain scheduling info ' . '(next check times) for hosts and services when it restarts. If you are adding a large number ' . '(or percentage) of hosts and services, I would recommend disabling this option ' . 'when you first restart Monitoring Engine, as it can adversely skew the spread of ' . 'initial checks. Otherwise you will probably want to leave it enabled.' ); $help['use_syslog'] = dgettext( 'help', 'This option determines whether messages are logged to the syslog facility ' . 'on your local host.' ); $help['log_notifications'] = dgettext( 'help', 'This option determines whether or not notification messages are logged. ' . 'If you have a lot of contacts or regular service failures your log file will ' . 'grow relatively quickly. Use this option to keep contact notifications ' . 'from being logged.' ); $help['log_service_retries'] = dgettext( 'help', 'This option determines whether or not service check retries are logged. ' . 'Service check retries occur when a service check results in a non-OK state, ' . 'but you have configured Monitoring Engine to retry the service more than once ' . 'before responding to the error. Services in this situation are considered ' . 'to be in "soft" states. Logging service check retries is mostly useful ' . 'when attempting to debug Monitoring Engine or test out service event handlers.' ); $help['log_host_retries'] = dgettext( 'help', 'This option determines whether or not host check retries are logged. Logging host ' . 'check retries is mostly useful when attempting to debug Monitoring Engine ' . 'or test out host event handlers.' ); $help['log_event_handlers'] = dgettext( 'help', 'This option determines whether or not service and host event handlers are logged. ' . 'Event handlers are optional commands that can be run whenever a service or hosts ' . 'changes state. Logging event handlers is most useful when debugging Monitoring ' . 'Engine or first trying out your event handler scripts.' ); $help['log_external_commands'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will log external ' . 'commands that it receives from the external command file. This option is ' . 'enabled by default.' ); $help['log_passive_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will log passive host ' . 'and service checks that it receives from the external command file. ' . 'This option is enabled by default. If you are setting up a distributed ' . 'monitoring environment or plan on handling a large number of passive checks ' . 'on a regular basis, you may wish to disable this option so your log file ' . "doesn't get too large." ); $help['global_host_event_handler'] = dgettext( 'help', 'This option allows you to specify a host event handler command that is to be ' . 'run for every host state change. The global event handler is executed ' . 'immediately prior to the event handler that you have optionally specified ' . 'in each host definition. The maximum amount of time that this command can ' . 'run is controlled by the event_handler_timeout option.' ); $help['global_service_event_handler'] = dgettext( 'help', 'This option allows you to specify a service event handler command that is to ' . 'be run for every service state change. The global event handler is executed ' . 'immediately prior to the event handler that you have optionally specified ' . 'in each service definition. The maximum amount of time that this command ' . 'can run is controlled by the event_handler_timeout option.' ); $help['sleep_time'] = dgettext( 'help', 'This is the number of seconds that Monitoring Engine will sleep before ' . 'checking to see if the next service or host check in the scheduling queue ' . 'should be executed. Note that Monitoring Engine will only sleep after ' . 'it "catches up" with queued service checks that have fallen behind.' ); $help['max_concurrent_checks'] = dgettext( 'help', 'This option allows you to specify the maximum number of service checks that ' . 'can be run in parallel at any given time. Specifying a value of 1 for ' . 'this variable essentially prevents any service checks from being run in parallel. ' . 'Specifying a value of 0 (the default) does not place any restrictions on ' . "the number of concurrent checks. You'll have to modify this value based on " . 'the system resources you have available on the machine that runs Monitoring Engine, ' . 'as it directly affects the maximum load that will be imposed on the ' . 'system (processor utilization, memory, etc.).' ); $help['max_host_check_spread'] = dgettext( 'help', 'This option determines the maximum number of minutes from when Monitoring Engine ' . 'starts that all hosts (that are scheduled to be regularly checked) are checked. ' . 'This option will automatically adjust the host inter-check delay method ' . '(if necessary) to ensure that the initial checks of all hosts occur within ' . 'the timeframe you specify. In general, this option will not have an effect ' . 'on host check scheduling if scheduling information is being retained using ' . 'the use_retained_scheduling_info option. Default value is 30 (minutes).' ); $help['max_service_check_spread'] = dgettext( 'help', 'This option determines the maximum number of minutes from when Monitoring Engine starts until all services ' . '(that are scheduled to be regularly checked) are checked. This option will automatically adjust the service ' . 'inter-check delay method (if necessary) to ensure that the initial checks of all services occur within the ' . 'timeframe you specify. In general, this option will not have an effect on service check scheduling if ' . 'scheduling information is being retained using the use_retained_scheduling_info option. Default value in ' . 'centengine is 5 (minutes) but it should be raised to 30 if the poller monitors more than 5000 services to ' . 'avoid load issues.' ); $help['service_interleave_factor'] = dgettext( 'help', 'This option determines how service checks are interleaved. Interleaving allows for a more even ' . 'distribution of service checks, reduced load on remote hosts, and faster overall detection of ' . 'host problems. By default this value is set to s (smart) for automatic calculation of the interleave factor. ' . "Don't change unless you have a specific reason to change it. Setting this value to a number greater " . 'than or equal to 1 specifies the interleave factor to use. A value of 1 is equivalent to not interleaving ' . 'the service checks.' ); $help['service_inter_check_delay_method'] = dgettext( 'help', 'This option allows you to control how service checks are initially "spread out" in the event queue. ' . 'Enter "s" for using a "smart" delay calculation (the default), which will cause ' . 'Monitoring Engine to calculate an average check interval and spread initial checks of all ' . 'services out over that interval, thereby helping to eliminate CPU load spikes. Using no ' . 'delay ("n") is generally not recommended, as it will cause all service checks to be scheduled ' . 'for execution at the same time. This means that you will generally have large CPU spikes when the ' . 'services are all executed in parallel. Use a "d" for a "dumb" delay of 1 second between service ' . 'checks or supply a fixed value of x.xx seconds for the inter-check delay.' ); $help['host_inter_check_delay_method'] = dgettext( 'help', 'This option allows you to control how host checks are initially "spread out" in the event queue. ' . 'Enter "s" for using a "smart" delay calculation (the default), which will cause Monitoring Engine ' . 'to calculate an average check interval and spread initial checks of all hosts out over that interval, ' . 'thereby helping to eliminate CPU load spikes. Using no delay ("n") is generally not recommended, ' . 'as it will cause all host checks to be scheduled for execution at the same time. This means that you will ' . 'generally have large CPU spikes when the hosts are all executed in parallel. ' . 'Use a "d" for a "dumb" delay of 1 second between host checks or supply a fixed value of x.xx seconds ' . 'for the inter-check delay.' ); $help['check_result_reaper_frequency'] = dgettext( 'help', 'This option allows you to control the frequency in seconds of check result "reaper" events. ' . '"Reaper" events process the results from host and service checks that have finished executing. These events ' . 'constitute the core of the monitoring logic in Monitoring Engine.' ); $help['passive_host_checks_are_soft'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will treat passive host checks as HARD states or ' . 'SOFT states. By default, a passive host check result will put a host into a HARD state type. This option is ' . 'disabled by default.' ); $help['auto_reschedule_checks'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will attempt to automatically reschedule active ' . 'host and service checks to "smooth" them out over time. This can help to balance the load on ' . 'the monitoring server, as it will attempt to keep the time between consecutive checks consistent, ' . 'at the expense of executing checks on a more rigid schedule.<br><b>Warning:</b> this is an experimental ' . 'feature and may be removed in future versions. Enabling this option can degrade performance - rather than ' . 'increase it - if used improperly!' ); $help['auto_rescheduling_interval'] = dgettext( 'help', 'This option determines how often Monitoring Engine will attempt to automatically reschedule checks. ' . 'This option only has an effect if the auto_reschedule_checks option is enabled. Default is 30 seconds.' ); $help['auto_rescheduling_window'] = dgettext( 'help', 'This option determines the "window" of time that Monitoring Engine will look at when automatically ' . 'rescheduling checks. Only host and service checks that occur in the next X seconds ' . '(determined by this variable) will be rescheduled. This option only has an effect if the ' . 'auto_reschedule_checks option is enabled. Default is 180 seconds (3 minutes).' ); $help['enable_flap_detection'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will try and detect hosts and services ' . 'that are "flapping". Flapping occurs when a host or service changes between states too frequently, ' . 'resulting in a barrage of notifications being sent out. When Monitoring Engine detects that a host ' . 'or service is flapping, it will temporarily suppress notifications for that host/service until it stops ' . 'flapping. Flap detection is very experimental at this point, so use this feature with caution! ' . 'More information on how flap detection and handling works can be found here. Note: If you have ' . 'state retention enabled, Monitoring Engine will ignore this setting when it (re)starts and use the ' . 'last known setting for this option (as stored in the state retention file), unless you disable the ' . 'use_retained_program_state option. This option is disabled by default.' ); $help['low_service_flap_threshold'] = dgettext( 'help', 'This option is used to set the low threshold for detection of service flapping. For more information ' . 'read the Monitoring Engine section about flapping.' ); $help['high_service_flap_threshold'] = dgettext( 'help', 'This option is used to set the high threshold for detection of service flapping. For more ' . 'information read the Monitoring Engine section about flapping.' ); $help['low_host_flap_threshold'] = dgettext( 'help', 'This option is used to set the low threshold for detection of host flapping. For more information ' . 'read the Monitoring Engine section about flapping.' ); $help['high_host_flap_threshold'] = dgettext( 'help', 'This option is used to set the high threshold for detection of host flapping. For more information ' . 'read the Monitoring Engine section about flapping.' ); $help['soft_state_dependencies'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will use soft state information when checking ' . 'host and service dependencies. Normally Monitoring Engine will only use the latest hard host or ' . 'service state when checking dependencies. If you want it to use the latest state (regardless of ' . 'whether its a soft or hard state type), enable this option.' ); $help['service_check_timeout'] = dgettext( 'help', 'This is the maximum number of seconds that the monitoring engine will allow service checks to run. ' . 'If checks exceed this limit, they are killed and an UNKNOWN state is returned. A timeout error will ' . 'also be logged. This option is meant to be used as a last ditch mechanism to kill off plugins ' . 'which are misbehaving and not exiting in a timely manner. It should be set to something high ' . '(like 60 seconds or more), so that each service check normally finishes executing within this ' . 'time limit. If a service check runs longer than this limit, the monitoring engine will kill it off, ' . 'thinking it is a runaway process.' ); $help['host_check_timeout'] = dgettext( 'help', 'This is the maximum number of seconds that Monitoring Engine will allow host checks to run. ' . 'If checks exceed this limit, they are killed and a CRITICAL state is returned and the host will be assumed ' . 'to be DOWN. A timeout error will also be logged. This option is meant to be used as a last ditch mechanism ' . 'to kill off plugins which are misbehaving and not exiting in a timely manner. It should be set to ' . 'something high (like 60 seconds or more), so that each host check normally finishes executing within ' . 'this time limit. If a host check runs longer than this limit, Monitoring Engine will kill it off thinking ' . 'it is a runaway processes.' ); $help['event_handler_timeout'] = dgettext( 'help', 'This is the maximum number of seconds that Monitoring Engine will allow event handlers to be run. ' . 'If an event handler exceeds this time limit it will be killed and a warning will be logged. This option ' . 'is meant to be used as a last ditch mechanism to kill off commands which are misbehaving and not exiting ' . 'in a timely manner. It should be set to something high (like 60 seconds or more), so that each event handler ' . 'command normally finishes executing within this time limit. If an event handler runs longer than this limit, ' . 'Monitoring Engine will kill it off thinking it is a runaway processes.' ); $help['notification_timeout'] = dgettext( 'help', 'This is the maximum number of seconds that Monitoring Engine will allow notification commands to be run. ' . 'If a notification command exceeds this time limit it will be killed and a warning will be logged. ' . 'This option is meant to be used as a last ditch mechanism to kill off commands which are misbehaving ' . 'and not exiting in a timely manner. It should be set to something high (like 60 seconds or more), so that ' . 'each notification command finishes executing within this time limit. If a notification command runs ' . 'longer than this limit, Monitoring Engine will kill it off thinking it is a runaway processes.' ); $help['check_for_orphaned_services'] = dgettext( 'help', 'This option allows you to enable or disable checks for orphaned service checks. Orphaned service checks ' . 'are checks which have been executed and have been removed from the event queue, but have not had any results ' . 'reported in a long time. Since no results have come back in for the service, it is not rescheduled in ' . 'the event queue. This can cause service checks to stop being executed. Normally it is very rare for ' . 'this to happen - it might happen if an external user or process killed off the process that was ' . 'being used to execute a service check. If this option is enabled and Monitoring Engine finds that results ' . 'for a particular service check have not come back, it will log an error message and reschedule the ' . 'service check. This option is enabled by default.' ); $help['check_for_orphaned_hosts'] = dgettext( 'help', 'This option allows you to enable or disable checks for orphaned hoste checks. Orphaned host checks are ' . 'checks which have been executed and have been removed from the event queue, but have not had any results ' . 'reported in a long time. Since no results have come back in for the host, it is not rescheduled in ' . 'the event queue. This can cause host checks to stop being executed. Normally it is very rare for ' . 'this to happen - it might happen if an external user or process killed off the process that was being ' . 'used to execute a host check. If this option is enabled and Monitoring Engine finds that results for a ' . 'particular host check have not come back, it will log an error message and reschedule the host check. ' . 'This option is enabled by default.' ); $help['check_service_freshness'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will periodically check the "freshness" of ' . 'service checks. Enabling this option is useful for helping to ensure that passive service checks are ' . 'received in a timely manner. If the check results is found to be not fresh, Monitoring Engine will ' . 'force an active check of the host or service by executing the command specified by in the host or ' . 'service definition. This option is enabled by default.' ); $help['service_freshness_check_interval'] = dgettext( 'help', 'This setting determines how often (in seconds) Monitoring Engine will periodically check the "freshness" of ' . 'service check results. If you have disabled service freshness checking (with the ' . 'check_service_freshness option), this option has no effect.' ); $help['check_host_freshness'] = dgettext( 'help', 'This option determines whether or not Monitoring Engine will periodically check the "freshness" of ' . 'host checks. Enabling this option is useful for helping to ensure that passive host checks are ' . 'received in a timely manner. If the check results is found to be not fresh, Monitoring Engine will ' . 'force an active check of the host or service by executing the command specified by in the host or ' . 'service definition. This option is enabled by default.' ); $help['host_freshness_check_interval'] = dgettext( 'help', 'This setting determines how often (in seconds) Monitoring Engine will periodically check the "freshness" of ' . 'host check results. If you have disabled host freshness checking (with the check_host_freshness option), ' . 'this option has no effect.' ); $help['additional_freshness_latency'] = dgettext( 'help', 'This option determines the number of seconds Monitoring Engine will add to any host or services ' . 'freshness threshold it automatically calculates (e.g. those not specified explicitly by the user).' ); $help['date_format'] = dgettext( 'help', 'This option allows you to specify what kind of date/time format Monitoring Engine should use in the web ' . 'interface and date/time macros.' ); $help['instance_heartbeat_interval'] = dgettext( 'help', "Time interval in seconds between two heartbeat events. This event is the one responsible of the 'Last Update' " . 'column update in the Pollers listing. Value must be between 5 and 600. Default value is 30.' ); $help['admin_email'] = dgettext( 'help', 'This is the email address for the administrator of the local machine (i.e. the one that Monitoring ' . 'Engine is running on). This value can be used in notification commands by using the $ADMINEMAIL$ macro.' ); $help['admin_pager'] = dgettext( 'help', 'This is the pager number (or pager email gateway) for the administrator of the local machine (i.e. '
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configNagios/formNagios.php
centreon/www/include/configuration/configNagios/formNagios.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 ( ! $centreon->user->admin && isset($nagiosId) && count($allowedMainConf) && ! isset($allowedMainConf[$nagiosId]) ) { $msg = new CentreonMsg(); $msg->setImage('./img/icons/warning.png'); $msg->setTextStyle('bold'); $msg->setText(_('You are not allowed to access this object configuration')); return null; } require_once _CENTREON_PATH_ . 'www/class/centreon-config/centreonMainCfg.class.php'; $objMain = new CentreonMainCfg(); // Database retrieve information for Nagios $nagios = []; $nagiosLogV1 = []; $nagiosLogV2 = []; $defaultEventBrokerOptions['event_broker_options'][-1] = 1; if (($o === 'c' || $o === 'w') && $nagiosId) { $statement = $pearDB->prepare('SELECT * FROM cfg_nagios WHERE nagios_id = :nagiosId LIMIT 1'); $statement->bindValue(':nagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); // Set base value $nagios = array_map('myDecode', $statement->fetch()); // Log V1 $tmp = explode(',', $nagios['debug_level_opt']); foreach ($tmp as $key => $value) { $nagiosLogV1['nagios_debug_level'][$value] = 1; } // Log V2 if ($nagios['logger_version'] === 'log_v2_enabled') { $statement = $pearDB->prepare('SELECT * FROM cfg_nagios_logger WHERE cfg_nagios_id = :nagiosId'); $statement->bindValue(':nagiosId', $nagiosId, PDO::PARAM_INT); $statement->execute(); if ($result = $statement->fetch()) { $nagiosLogV2 = $result; } } $defaultEventBrokerOptions['event_broker_options'] = $objMain->explodeEventBrokerOptions( (int) $nagios['event_broker_options'] ); unset($nagios['event_broker_options']); } // Preset values of broker directives $mainCfg = new CentreonConfigEngine($pearDB); $cdata = CentreonData::getInstance(); if ($o != 'a') { $dirArray = $mainCfg->getBrokerDirectives($nagiosId ?? null); } else { $dirArray[0]['in_broker_#index#'] = '/usr/lib64/centreon-engine/externalcmd.so'; } $cdata->addJsData( 'clone-values-broker', htmlspecialchars( json_encode($dirArray), ENT_QUOTES ) ); $cdata->addJsData( 'clone-count-broker', count($dirArray) ); // Set the values for list of whitelist macros $macrosWhitelist = []; if ($o != 'a') { $macrosWhitelist = array_map( function ($macro) { return [ 'macros_filter_#index#' => $macro, ]; }, explode(',', $nagios['macros_filter']) ); unset($nagios['macros_filter']); } $cdata->addJsData( 'clone-values-macros_filter', htmlspecialchars( json_encode($macrosWhitelist), ENT_QUOTES ) ); $cdata->addJsData( 'clone-count-macros_filter', count($macrosWhitelist) ); /* * Database retrieve information for different elements list we need on the page * * Check commands comes from DB -> Store in $checkCmds Array * */ $checkCmds = []; $dbResult = $pearDB->query('SELECT command_id, command_name FROM command WHERE command_type = 3 ORDER BY command_name'); $checkCmds = [null => null]; while ($checkCmd = $dbResult->fetch()) { $checkCmds[$checkCmd['command_id']] = $checkCmd['command_name']; } $dbResult->closeCursor(); // Get all nagios servers $nagios_server = [null => '']; $result = $oreon->user->access->getPollerAclConf( ['fields' => ['name', 'id'], 'keys' => ['id']] ); foreach ($result as $ns) { $nagios_server[$ns['id']] = HtmlSanitizer::createFromString($ns['name'])->sanitize()->getString(); } $attrsText = ['size' => '30']; $attrsText2 = ['size' => '50']; $attrsText3 = ['size' => '10']; $attrsTextarea = ['rows' => '5', 'cols' => '40']; // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o == 'a') { $form->addElement('header', 'title', _('Add a Monitoring Engine Configuration File')); } elseif ($o == 'c') { $form->addElement('header', 'title', _('Modify a Monitoring Engine Configuration File')); } elseif ($o == 'w') { $form->addElement('header', 'title', _('View a Monitoring Engine Configuration File')); } // Nagios Configuration basic information $form->addElement('header', 'information', _('Information')); $form->addElement('text', 'nagios_name', _('Configuration Name'), $attrsText); $form->addElement('textarea', 'nagios_comment', _('Comments'), $attrsTextarea); $nagTab = []; $nagTab[] = $form->createElement('radio', 'nagios_activate', null, _('Enabled'), '1'); $nagTab[] = $form->createElement('radio', 'nagios_activate', null, _('Disabled'), '0'); $form->addGroup($nagTab, 'nagios_activate', _('Status'), '&nbsp;'); $form->addElement('select', 'nagios_server_id', _('Linked poller'), $nagios_server); $attrTimezones = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './include/common/webServices/rest/internal.php?' . 'object=centreon_configuration_timezone&action=list', 'multiple' => false, 'linkedObject' => 'centreonGMT']; $form->addElement('select2', 'use_timezone', _('Timezone / Location'), [], $attrTimezones); // Part 1 $form->addElement('text', 'status_file', _('Status file'), $attrsText2); $form->addElement('text', 'status_update_interval', _('Status File Update Interval'), $attrsText3); $form->addElement('text', 'log_file', _('Log file'), $attrsText2); $form->addElement('text', 'cfg_dir', _('Object Configuration Directory'), $attrsText2); $form->addElement('text', 'cfg_file', _('Object Configuration File'), $attrsText2); // Enable / Disable functionalities $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_notifications', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_notifications', null, _('No'), '0'); $form->addGroup($nagTab, 'enable_notifications', _('Notification Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'execute_service_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'execute_service_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'execute_service_checks', _('Service Check Execution Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'accept_passive_service_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'accept_passive_service_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'accept_passive_service_checks', _('Passive Service Check Acceptance Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'execute_host_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'execute_host_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'execute_host_checks', _('Host Check Execution Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'accept_passive_host_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'accept_passive_host_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'accept_passive_host_checks', _('Passive Host Check Acceptance Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_event_handlers', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_event_handlers', null, _('No'), '0'); $form->addGroup($nagTab, 'enable_event_handlers', _('Event Handler Option'), '&nbsp;'); // External Commands $nagTab = []; $nagTab[] = $form->createElement('radio', 'check_external_commands', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'check_external_commands', null, _('No'), '0'); $form->addGroup($nagTab, 'check_external_commands', _('External Command Check Option'), '&nbsp;'); $form->addElement('text', 'command_check_interval', _('External Command Check Interval'), $attrsText3); $form->addElement('text', 'external_command_buffer_slots', _('External Command Buffer Slots'), $attrsText3); $form->addElement('text', 'command_file', _('External Command File'), $attrsText2); // Retention $nagTab = []; $nagTab[] = $form->createElement('radio', 'retain_state_information', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'retain_state_information', null, _('No'), '0'); $form->addGroup($nagTab, 'retain_state_information', _('State Retention Option'), '&nbsp;'); $form->addElement('text', 'state_retention_file', _('State Retention File'), $attrsText2); $form->addElement('text', 'retention_update_interval', _('Automatic State Retention Update Interval'), $attrsText3); $nagTab = []; $nagTab[] = $form->createElement('radio', 'use_retained_program_state', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'use_retained_program_state', null, _('No'), '0'); $form->addGroup($nagTab, 'use_retained_program_state', _('Use Retained Program State Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'use_retained_scheduling_info', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'use_retained_scheduling_info', null, _('No'), '0'); $form->addGroup( $nagTab, 'use_retained_scheduling_info', _('Use Retained Scheduling Info Option'), '&nbsp;' ); // logging options $nagTab = []; $nagTab[] = $form->createElement( 'radio', 'logger_version', null, _('V1 (legacy, with epoch timestamps)'), 'log_legacy_enabled' ); $nagTab[] = $form->createElement( 'radio', 'logger_version', null, _('V2 (ISO-8601, with log level fine tuning)'), 'log_v2_enabled' ); $form->addGroup($nagTab, 'logger_version', _('Logger version'), '&nbsp;'); // LOG V1 $nagTab = []; $nagTab[] = $form->createElement('radio', 'use_syslog', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'use_syslog', null, _('No'), '0'); $form->addGroup($nagTab, 'use_syslog', _('Syslog Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_notifications', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_notifications', null, _('No'), '0'); $form->addGroup($nagTab, 'log_notifications', _('Notification Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_service_retries', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_service_retries', null, _('No'), '0'); $form->addGroup($nagTab, 'log_service_retries', _('Service Check Retry Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_host_retries', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_host_retries', null, _('No'), '0'); $form->addGroup($nagTab, 'log_host_retries', _('Host Retry Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_event_handlers', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_event_handlers', null, _('No'), '0'); $form->addGroup($nagTab, 'log_event_handlers', _('Event Handler Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_external_commands', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_external_commands', null, _('No'), '0'); $form->addGroup($nagTab, 'log_external_commands', _('External Command Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_passive_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_passive_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'log_passive_checks', _('Passive Check Logging Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'log_pid', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'log_pid', null, _('No'), '0'); $form->addGroup($nagTab, 'log_pid', _('Enable logging pid information'), '&nbsp;'); // LOG V2 $loggerOptions = [ 'file' => _('File'), 'syslog' => _('Syslog'), ]; $form->addElement('select', 'log_v2_logger', _('Log destination'), $loggerOptions); $logLevelOptions = [ 'trace' => _('Trace'), 'debug' => _('Debug'), 'info' => _('Info'), 'warning' => _('Warning'), 'err' => _('Error'), 'critical' => _('Critical'), 'off' => _('Disabled'), ]; $form->addElement('select', 'log_level_checks', _('Checks'), $logLevelOptions); $form->addElement('select', 'log_level_commands', _('Commands'), $logLevelOptions); $form->addElement('select', 'log_level_comments', _('Comments'), $logLevelOptions); $form->addElement('select', 'log_level_config', _('Configuration'), $logLevelOptions); $form->addElement('select', 'log_level_downtimes', _('Downtimes'), $logLevelOptions); $form->addElement('select', 'log_level_eventbroker', _('Broker events'), $logLevelOptions); $form->addElement('select', 'log_level_events', _('Events'), $logLevelOptions); $form->addElement('select', 'log_level_external_command', _('External commands'), $logLevelOptions); $form->addElement('select', 'log_level_functions', _('Functions'), $logLevelOptions); $form->addElement('select', 'log_level_macros', _('Macros'), $logLevelOptions); $form->addElement('select', 'log_level_notifications', _('Notifications'), $logLevelOptions); $form->addElement('select', 'log_level_process', _('Process'), $logLevelOptions); $form->addElement('select', 'log_level_runtime', _('Runtime'), $logLevelOptions); $form->addElement('select', 'log_level_otl', _('Opentelemetry'), $logLevelOptions); // Debug Configuration (Log V1) $form->addElement('text', 'debug_file', _('Debug file (Directory + File)'), $attrsText); $form->addElement('text', 'max_debug_file_size', _('Debug file Maximum Size'), $attrsText); $verboseOptions = ['0' => _('Basic information'), '1' => _('More detailed information'), '2' => _('Highly detailed information')]; $form->addElement('select', 'debug_verbosity', _('Debug Verbosity'), $verboseOptions); $debugLevel = []; $debugLevel['-1'] = _('Log everything'); $debugLevel['0'] = _('Log nothing (default)'); $debugLevel['1'] = _('Function enter/exit information'); $debugLevel['2'] = _('Config information'); $debugLevel['4'] = _('Process information'); $debugLevel['8'] = _('Scheduled event information'); $debugLevel['16'] = _('Host/service check information'); $debugLevel['32'] = _('Notification information'); $debugLevel['64'] = _('Event broker information'); $debugLevel['128'] = _('External Commands'); $debugLevel['256'] = _('Commands'); $debugLevel['512'] = _('Downtimes'); $debugLevel['1024'] = _('Comments'); $debugLevel['2048'] = _('Macros'); foreach ($debugLevel as $key => $val) { $debugCheck[] = $form->createElement( 'checkbox', $key, '&nbsp;', $val, [ 'id' => 'debug' . $key, 'onClick' => in_array((string) $key, ['-1', '0'], true) ? "unCheckOthers('debug-level', this.name);" : "unCheckAllAndNaught('debug-level');", 'class' => 'debug-level', ] ); } $form->addGroup($debugCheck, 'nagios_debug_level', _('Debug Level'), '<br/>'); // Event handler $form->addElement('select', 'global_host_event_handler', _('Global Host Event Handler'), $checkCmds); $form->addElement('select', 'global_service_event_handler', _('Global Service Event Handler'), $checkCmds); // General Options $form->addElement('text', 'sleep_time', _('Inter-Check Sleep Time'), $attrsText3); $form->addElement('text', 'max_concurrent_checks', _('Maximum Concurrent Service Checks'), $attrsText3); $form->addElement('text', 'max_host_check_spread', _('Maximum Host Check Spread'), $attrsText3); $form->addElement('text', 'max_service_check_spread', _('Maximum Service Check Spread'), $attrsText3); $form->addElement('text', 'service_interleave_factor', _('Service Interleave Factor'), $attrsText3); $form->addElement('text', 'host_inter_check_delay_method', _('Host Inter-Check Delay Method'), $attrsText3); $form->addElement('text', 'service_inter_check_delay_method', _('Service Inter-Check Delay Method'), $attrsText3); $form->addElement('text', 'check_result_reaper_frequency', _('Check Result Reaper Frequency'), $attrsText3); // Auto Rescheduling Option $nagTab = []; $nagTab[] = $form->createElement('radio', 'auto_reschedule_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'auto_reschedule_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'auto_reschedule_checks', _('Auto-Rescheduling Option'), '&nbsp;'); $form->addElement('text', 'auto_rescheduling_interval', _('Auto-Rescheduling Interval'), $attrsText3); $form->addElement('text', 'auto_rescheduling_window', _('Auto-Rescheduling Window'), $attrsText3); // Flapping management. $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_flap_detection', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_flap_detection', null, _('No'), '0'); $form->addGroup($nagTab, 'enable_flap_detection', _('Flap Detection Option'), '&nbsp;'); $form->addElement('text', 'low_service_flap_threshold', _('Low Service Flap Threshold'), $attrsText3); $form->addElement('text', 'high_service_flap_threshold', _('High Service Flap Threshold'), $attrsText3); $form->addElement('text', 'low_host_flap_threshold', _('Low Host Flap Threshold'), $attrsText3); $form->addElement('text', 'high_host_flap_threshold', _('High Host Flap Threshold'), $attrsText3); // SOFT dependencies options $nagTab = []; $nagTab[] = $form->createElement('radio', 'soft_state_dependencies', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'soft_state_dependencies', null, _('No'), '0'); $form->addGroup($nagTab, 'soft_state_dependencies', _('Soft Service Dependencies Option'), '&nbsp;'); // Timeout. $form->addElement('text', 'service_check_timeout', _('Service Check Timeout'), $attrsText3); $form->addElement('text', 'host_check_timeout', _('Host Check Timeout'), $attrsText3); $form->addElement('text', 'event_handler_timeout', _('Event Handler Timeout'), $attrsText3); $form->addElement('text', 'notification_timeout', _('Notification Timeout'), $attrsText3); // Check orphaned $nagTab = []; $nagTab[] = $form->createElement('radio', 'check_for_orphaned_services', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'check_for_orphaned_services', null, _('No'), '0'); $form->addGroup($nagTab, 'check_for_orphaned_services', _('Orphaned Service Check Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'check_for_orphaned_hosts', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'check_for_orphaned_hosts', null, _('No'), '0'); $form->addGroup($nagTab, 'check_for_orphaned_hosts', _('Orphaned Host Check Option'), '&nbsp;'); // Freshness $nagTab = []; $nagTab[] = $form->createElement('radio', 'check_service_freshness', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'check_service_freshness', null, _('No'), '0'); $form->addGroup($nagTab, 'check_service_freshness', _('Service Freshness Check Option'), '&nbsp;'); $form->addElement('text', 'service_freshness_check_interval', _('Service Freshness Check Interval'), $attrsText3); $nagTab = []; $nagTab[] = $form->createElement('radio', 'check_host_freshness', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'check_host_freshness', null, _('No'), '0'); $form->addGroup($nagTab, 'check_host_freshness', _('Host Freshness Check Option'), '&nbsp;'); $form->addElement('text', 'host_freshness_check_interval', _('Host Freshness Check Interval'), $attrsText3); $form->addElement('text', 'additional_freshness_latency', _('Additional freshness latency'), $attrsText3); // General Informations $dateFormats = ['euro' => 'euro (30/06/2002 03:15:00)', 'us' => 'us (06/30/2002 03:15:00)', 'iso8601' => 'iso8601 (2002-06-30 03:15:00)', 'strict-iso8601' => 'strict-iso8601 (2002-06-30 03:15:00)']; $form->addElement('select', 'date_format', _('Date Format'), $dateFormats); $form->addElement('text', 'instance_heartbeat_interval', _('Heartbeat Interval'), $attrsText); $form->addElement('text', 'admin_email', _('Administrator Email Address'), $attrsText); $form->addElement('text', 'admin_pager', _('Administrator Pager'), $attrsText); $form->addElement('text', 'illegal_object_name_chars', _('Illegal Object Name Characters'), $attrsText2); $form->addElement('text', 'illegal_macro_output_chars', _('Illegal Macro Output Characters'), $attrsText2); $nagTab = []; $nagTab[] = $form->createElement('radio', 'use_regexp_matching', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'use_regexp_matching', null, _('No'), '0'); $form->addGroup($nagTab, 'use_regexp_matching', _('Regular Expression Matching Option'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'use_true_regexp_matching', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'use_true_regexp_matching', null, _('No'), '0'); $form->addGroup($nagTab, 'use_true_regexp_matching', _('True Regular Expression Matching Option'), '&nbsp;'); // Event Broker Option $form->addElement('text', 'multiple_broker_module', _('Multiple Broker Module'), $attrsText2); $form->addElement( 'static', 'bkTextMultiple', _('This directive can be used multiple times, see nagios documentation.') ); $cloneSet = []; $cloneSet[] = $form->addElement( 'text', 'in_broker[#index#]', _('Event broker directive'), ['id' => 'in_broker_#index#', 'size' => 100] ); $eventBrokerOptionsData = []; // Add checkbox for each of event broker options foreach (CentreonMainCfg::EVENT_BROKER_OPTIONS as $bit => $label) { if ($bit === -1 || $bit === 0) { $onClick = 'unCheckOthers("event-broker-options", this.name);'; } else { $onClick = 'unCheckAllAndNaught("event-broker-options");'; } $eventBrokerOptionsData[] = $form->createElement( 'checkbox', $bit, '', _($label), [ 'onClick' => $onClick, 'class' => 'event-broker-options', ] ); } $form->addGroup($eventBrokerOptionsData, 'event_broker_options', _('Broker Module Options'), '&nbsp;'); $form->addElement('text', 'broker_module_cfg_file', _('Broker Module Configuration File'), $attrsText2); // New options for enable whitelist of macros sent to Centreon Broker $enableMacrosFilter = []; $enableMacrosFilter[] = $form->createElement('radio', 'enable_macros_filter', null, _('Yes'), 1); $enableMacrosFilter[] = $form->createElement('radio', 'enable_macros_filter', null, _('No'), 0); $form->addGroup($enableMacrosFilter, 'enable_macros_filter', _('Enable macro filtering'), '&nbsp;'); // Dynamic field for macros whitelisted $form->addElement( 'static', 'macros_filter', _('Macros whitelist') ); $cloneSetMacrosFilter = []; $cloneSetMacrosFilter[] = $form->addElement( 'text', 'macros_filter[#index#]', _('Macros whitelist'), [ 'id' => 'macros_filter_#index#', 'size' => 100, ] ); $tab = []; $tab[] = $form->createElement('radio', 'action', null, _('List'), '1'); $tab[] = $form->createElement('radio', 'action', null, _('Form'), '0'); $form->addGroup($tab, 'action', _('Post Validation'), '&nbsp;'); // Predictive dependancy options $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_predictive_host_dependency_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_predictive_host_dependency_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'enable_predictive_host_dependency_checks', _('Predictive Host Dependency Checks'), '&nbsp;'); $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_predictive_service_dependency_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_predictive_service_dependency_checks', null, _('No'), '0'); $form->addGroup( $nagTab, 'enable_predictive_service_dependency_checks', _('Predictive Service Dependency Checks'), '&nbsp;' ); // Disable Service Checks When Host Down option $nagTab = []; $nagTab[] = $form->createElement('radio', 'host_down_disable_service_checks', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'host_down_disable_service_checks', null, _('No'), '0'); $form->addGroup($nagTab, 'host_down_disable_service_checks', _('Disable Service Checks When Host Down'), '&nbsp;'); // Cache check horizon. $form->addElement('text', 'cached_host_check_horizon', _('Cached Host Check'), $attrsText3); $form->addElement('text', 'cached_service_check_horizon', _('Cached Service Check'), $attrsText3); // Tunning $nagTab = []; $nagTab[] = $form->createElement('radio', 'enable_environment_macros', null, _('Yes'), '1'); $nagTab[] = $form->createElement('radio', 'enable_environment_macros', null, _('No'), '0'); $form->addGroup($nagTab, 'enable_environment_macros', _('Enable environment macros'), '&nbsp;'); $form->setDefaults($defaultEventBrokerOptions); $form->setDefaults($objMain->getDefaultMainCfg()); $form->setDefaults($objMain->getDefaultLoggerCfg()); $form->setDefaults(['action' => '1']); $form->addElement('hidden', 'nagios_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); function isNum($value) { return is_numeric($value); } $form->registerRule('exist', 'callback', 'testExistence'); $form->registerRule('isNum', 'callback', 'isNum'); /** * @param $value * @return bool */ function isValidHeartbeat($value): bool { return ! (! is_numeric($value) || $value < 5 || $value > 600); } $form->registerRule('isValidHeartbeat', 'callback', 'isValidHeartbeat'); // Add validator for macro name format /** * Validate the macro name * * @param string $value Not used * @return bool If all name are valid */ function validMacroName($value) { // Get the list of invalid characters $invalidCharacters = str_split($_REQUEST['illegal_macro_output_chars']); foreach ($_REQUEST['macros_filter'] as $name) { $parsed = str_replace($invalidCharacters, '', $name); // Contains one of invalid characters if ($parsed !== $name) { return false; } } return true; } $form->registerRule('validMacroName', 'callback', 'validMacroName'); $form->applyFilter('cfg_dir', 'slash'); $form->applyFilter('__ALL__', 'myTrim'); $form->addRule('instance_heartbeat_interval', _('Number between 5 and 600'), 'isValidHeartbeat'); $form->addRule('nagios_name', _('Compulsory Name'), 'required'); $form->addRule('cfg_file', _('Required Field'), 'required'); $form->addRule('nagios_comment', _('Required Field'), 'required'); $form->addRule('nagios_name', _('Name is already in use'), 'exist'); // Add rule to field for whitelist macro $form->addRule('macros_filter', _('A macro is malformated.'), 'validMacroName'); // Get Values $ret = $form->getSubmitValues(); $form->setRequiredNote("<font style='color: red;'>*</font>&nbsp;" . _('Required fields')); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate(__DIR__); if ($o == 'w') { // Just watch a nagios information if ($centreon->user->access->page($p) != 2) { $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&nagios_id=' . $nagiosId . "'"] ); } $form->setDefaults($nagios); $form->setDefaults($nagiosLogV1); $form->setDefaults($nagiosLogV2); $form->freeze(); } elseif ($o == 'c') { // Modify nagios information $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement( 'reset', 'reset', _('Reset'), ['onClick' => "javascript:resetBroker('" . $o . "')", 'class' => 'btc bt_default'] ); $form->setDefaults($nagios); $form->setDefaults($nagiosLogV1); $form->setDefaults($nagiosLogV2); } elseif ($o == 'a') { // Add nagios information $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement( 'reset', 'reset', _('Reset'), ['onClick' => "javascript:resetBroker('" . $o . "')", 'class' => 'btc bt_default'] ); } $tpl->assign('msg', ['nagios' => $oreon->user->get_version()]); $tpl->assign( 'helpattr', 'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", ' . 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ' . '["","black", "white", "red"], WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"' ); // 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()) { $nagiosObj = $form->getElement('nagios_id'); if ($form->getSubmitValue('submitA')) { $nagiosObj->setValue(insertNagiosInDB()); } elseif ($form->getSubmitValue('submitC')) { updateNagiosInDB($nagiosObj->getValue()); } $o = 'w'; if ($centreon->user->access->page($p) != 2) { $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&nagios_id=' . $nagiosObj->getValue() . "'"] ); } $valid = true; } if ($valid) { require_once __DIR__ . '/listNagios.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('form', $renderer->toArray()); $tpl->assign('o', $o); $tpl->assign('sort1', _('Files')); $tpl->assign('sort2', _('Check Options')); $tpl->assign('sort3', _('Log Options')); $tpl->assign('sort4', _('Data')); $tpl->assign('sort5', _('Tuning')); $tpl->assign('sort6', _('Admin')); $tpl->assign('Status', _('Status')); $tpl->assign('Folders', _('Folders')); $tpl->assign('Files', _('Files')); $tpl->assign('ExternalCommandes', _('External Commands')); $tpl->assign('HostCheckOptions', _('Host Check Options')); $tpl->assign('ServiceCheckOptions', _('Service Check Options')); $tpl->assign('EventHandler', _('Event Handler')); $tpl->assign('Freshness', _('Freshness')); $tpl->assign('FlappingOptions', _('Flapping Options')); $tpl->assign('CachedCheck', _('Cached Check')); $tpl->assign('MiscOptions', _('Misc Options')); $tpl->assign('LoggingOptions', _('Logging Options')); $tpl->assign('Timouts', _('Timeouts')); $tpl->assign('Archives', _('Archives')); $tpl->assign('StatesRetention', _('States Retention')); $tpl->assign('BrokerModule', _('Broker Module')); $tpl->assign('MacrosMgmt', _('Macros Filters Configuration')); $tpl->assign('TimeUnit', _('Time Unit')); $tpl->assign('HostCheckSchedulingOptions', _('Host Check Scheduling Options')); $tpl->assign('ServiceCheckSchedulingOptions', _('Service Check Scheduling Options')); $tpl->assign('AutoRescheduling', _('Auto Rescheduling')); $tpl->assign('Optimization', _('Optimization')); $tpl->assign('Advanced', _('Advanced')); $tpl->assign('AdminInfo', _('Admin information')); $tpl->assign('DebugConfiguration', _('Debug Configuration')); $tpl->assign('Seconds', _('seconds')); $tpl->assign('Minutes', _('minutes')); $tpl->assign('Bytes', _('bytes')); $tpl->assign( 'BrokerOptionsWarning', _('Warning: this value can be dangerous, use -1 if you have any doubt.') ); $tpl->assign('cloneSet', $cloneSet); $tpl->assign('cloneSetMacrosFilter', $cloneSetMacrosFilter); $tpl->assign('centreon_path', _CENTREON_PATH_); $tpl->assign('initial_state_warning', _('This option must be enabled for Centreon Dashboard module.')); $tpl->assign('aggressive_host_warning', _('This option must be disable in order to avoid latency problem.')); $tpl->display('formNagios.ihtml'); } ?> <script type="text/javascript"> function unCheckOthers(className, name) { var elements = document.querySelectorAll("." + className);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configNagios/listNagios.php
centreon/www/include/configuration/configNagios/listNagios.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'; $search = $_POST['searchN'] ?? $_GET['searchN'] ?? null; if (! is_null($search)) { $search = HtmlSanitizer::createFromString($search)->sanitize()->getString(); // saving filters values $centreon->historySearch[$url] = []; $centreon->historySearch[$url]['search'] = $search; } else { // restoring saved values $search = $centreon->historySearch[$url]['search'] ?? null; } $SearchTool = ''; if (! is_null($search)) { $SearchTool .= " WHERE nagios_name LIKE '%{$search}%' "; } $aclCond = ''; if (! $centreon->user->admin && count($allowedMainConf)) { $aclCond = isset($search) && $search ? ' AND ' : ' WHERE '; $aclCond .= 'nagios_id IN (' . implode(',', array_keys($allowedMainConf)) . ') '; } // nagios servers comes from DB $nagios_servers = [null => '']; $dbResult = $pearDB->query('SELECT * FROM nagios_server ORDER BY name'); while ($nagios_server = $dbResult->fetch()) { $nagios_servers[$nagios_server['id']] = HtmlSanitizer::createFromString($nagios_server['name'])->sanitize()->getString(); } $dbResult->closeCursor(); $dbResult = $pearDB->query( 'SELECT SQL_CALC_FOUND_ROWS nagios_id, nagios_name, nagios_comment, nagios_activate, nagios_server_id ' . 'FROM cfg_nagios ' . $SearchTool . $aclCond . ' ORDER BY nagios_name LIMIT ' . $num * $limit . ', ' . $limit ); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate(__DIR__); // Access level $lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r'; $tpl->assign('mode_access', $lvl_access); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_instance', _('Satellites')); $tpl->assign('headerMenu_desc', _('Description')); $tpl->assign('headerMenu_status', _('Status')); $tpl->assign('headerMenu_options', _('Options')); // Nagios list $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; // Fill a tab with a multidimensional Array we put in $tpl $elemArr = []; $centreonToken = createCSRFToken(); for ($i = 0; $nagios = $dbResult->fetch(); $i++) { $moptions = ''; $selectedElements = $form->addElement('checkbox', 'select[' . $nagios['nagios_id'] . ']'); if ($nagios['nagios_activate']) { $moptions .= "<a href='main.php?p=" . $p . '&nagios_id=' . $nagios['nagios_id'] . '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/disabled.png' class='ico-14' border='0' " . "alt='" . _('Disabled') . "'></a>&nbsp;&nbsp;"; } else { $moptions .= "<a href='main.php?p=" . $p . '&nagios_id=' . $nagios['nagios_id'] . '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/enabled.png' " . "class='ico-14' border='0' alt='" . _('Enabled') . "'></a>&nbsp;&nbsp;"; } $moptions .= '&nbsp;<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) ' . 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) ' . "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $nagios['nagios_id'] . "]' />"; $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $nagios['nagios_name'], 'RowMenu_instance' => $nagios_servers[$nagios['nagios_server_id']], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&nagios_id=' . $nagios['nagios_id'], 'RowMenu_desc' => substr($nagios['nagios_comment'], 0, 40), 'RowMenu_status' => $nagios['nagios_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $nagios['nagios_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); ?> <script type="text/javascript"> function setO(_i) { document.forms['form'].elements['o'].value = _i; } </script> <?php foreach (['o1', 'o2'] as $option) { $attrs = ['onchange' => 'javascript: ' . "if (this.form.elements['" . $option . "'].selectedIndex == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['" . $option . "'].value); submit();} " . "else if (this.form.elements['" . $option . "'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['" . $option . "'].value); submit();} " . "else if (this.form.elements['" . $option . "'].selectedIndex == 3) {" . " setO(this.form.elements['" . $option . "'].value); submit();} " . '']; $form->addElement( 'select', $option, null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs ); $form->setDefaults([$option => null]); $o1 = $form->getElement($option); $o1->setValue(null); } $tpl->assign('limit', $limit); $tpl->assign('searchN', $search); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listNagios.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/configuration/configNagios/DB-Func.php
centreon/www/include/configuration/configNagios/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 testExistence($name = null) { global $pearDB, $form; $id = null; if (isset($form)) { $id = $form->getSubmitValue('nagios_id'); } $dbResult = $pearDB->query( "SELECT nagios_name, nagios_id FROM cfg_nagios WHERE nagios_name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'" ); $nagios = $dbResult->fetch(); if ($dbResult->rowCount() >= 1 && $nagios['nagios_id'] == $id) { return true; } return ! ($dbResult->rowCount() >= 1 && $nagios['nagios_id'] != $id); } /** * @param null $nagiosId * @throws Exception */ function enableNagiosInDB($nagiosId = null) { global $pearDB, $centreon; if (! $nagiosId) { return; } $dbResult = $pearDB->query( "SELECT `nagios_server_id` FROM cfg_nagios WHERE nagios_id = '" . $nagiosId . "'" ); $data = $dbResult->fetch(); $statement = $pearDB->prepare( "UPDATE `cfg_nagios` SET `nagios_activate` = '0' WHERE `nagios_server_id` = :nagios_server_id" ); $statement->bindValue(':nagios_server_id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); $pearDB->query( "UPDATE cfg_nagios SET nagios_activate = '1' WHERE nagios_id = '" . $nagiosId . "'" ); $query = "SELECT `id`, `name` FROM nagios_server WHERE `ns_activate` = '0' AND `id` = :id"; $statement = $pearDB->prepare($query); $statement->bindValue(':id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); $activate = $statement->fetch(PDO::FETCH_ASSOC); if ($activate && $activate['name']) { $query = "UPDATE `nagios_server` SET `ns_activate` = '1' WHERE `id` = :id"; $statement = $pearDB->prepare($query); $statement->bindValue(':id', (int) $activate['id'], PDO::PARAM_INT); $statement->execute(); $centreon->CentreonLogAction->insertLog('poller', $activate['id'], $activate['name'], 'enable'); } } /** * @param null $nagiosId * @throws Exception */ function disableNagiosInDB($nagiosId = null) { global $pearDB, $centreon; if (! $nagiosId) { return; } $dbResult = $pearDB->query( "SELECT `nagios_server_id` FROM cfg_nagios WHERE nagios_id = '" . $nagiosId . "'" ); $data = $dbResult->fetch(); $pearDB->query( "UPDATE cfg_nagios SET nagios_activate = '0' WHERE `nagios_id` = '" . $nagiosId . "'" ); $query = "SELECT `nagios_id` FROM cfg_nagios WHERE `nagios_activate` = '1' " . 'AND `nagios_server_id` = :nagios_server_id'; $statement = $pearDB->prepare($query); $statement->bindValue(':nagios_server_id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); $activate = $statement->fetch(PDO::FETCH_ASSOC); if (! $activate['nagios_id']) { $query = "UPDATE `nagios_server` SET `ns_activate` = '0' WHERE `id` = :id"; $statement = $pearDB->prepare($query); $statement->bindValue(':id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); $query = 'SELECT `id`, `name` FROM nagios_server WHERE `id` = :id'; $statement = $pearDB->prepare($query); $statement->bindValue(':id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); $poller = $statement->fetch(PDO::FETCH_ASSOC); $centreon->CentreonLogAction->insertLog('poller', $poller['id'], $poller['name'], 'disable'); } } function deleteNagiosInDB($nagios = []) { global $pearDB; foreach ($nagios as $key => $value) { $pearDB->query( "DELETE FROM cfg_nagios WHERE nagios_id = '" . $key . "'" ); $pearDB->query( "DELETE FROM cfg_nagios_broker_module WHERE cfg_nagios_id = '" . $key . "'" ); } $dbResult = $pearDB->query( "SELECT nagios_id FROM cfg_nagios WHERE nagios_activate = '1'" ); if (! $dbResult->rowCount()) { $dbResult2 = $pearDB->query( 'SELECT MAX(nagios_id) FROM cfg_nagios' ); $nagios_id = $dbResult2->fetch(); $statement = $pearDB->prepare( "UPDATE cfg_nagios SET nagios_activate = '1' WHERE nagios_id = :nagios_id" ); $statement->bindValue(':nagios_id', (int) $nagios_id['MAX(nagios_id)'], PDO::PARAM_INT); $statement->execute(); } $dbResult->closeCursor(); } // Duplicate Engine Configuration file in DB function multipleNagiosInDB($nagios = [], $nbrDup = []) { foreach ($nagios as $originalNagiosId => $value) { global $pearDB; $stmt = $pearDB->prepare('SELECT * FROM cfg_nagios WHERE nagios_id = :nagiosId LIMIT 1'); $stmt->bindValue('nagiosId', (int) $originalNagiosId, PDO::PARAM_INT); $stmt->execute(); $row = $stmt->fetch(); $row['nagios_id'] = ''; $row['nagios_activate'] = '0'; $stmt->closeCursor(); $rowBks = []; $stmt = $pearDB->prepare('SELECT * FROM cfg_nagios_broker_module WHERE cfg_nagios_id = :nagiosId'); $stmt->bindValue('nagiosId', (int) $originalNagiosId, PDO::PARAM_INT); $stmt->execute(); while ($rowBk = $stmt->fetch()) { $rowBks[] = $rowBk; } $stmt->closeCursor(); for ($i = 1; $i <= $nbrDup[$originalNagiosId]; $i++) { $val = null; foreach ($row as $key2 => $value2) { $value2 = is_int($value2) ? (string) $value2 : $value2; $value2 = $pearDB->escape($value2); if ($key2 == 'nagios_name') { $nagios_name = $value2 . '_' . $i; $value2 = $value2 . '_' . $i; } $val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL') : $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL'); } if (testExistence($nagios_name)) { $rq = $val ? 'INSERT INTO cfg_nagios VALUES (' . $val . ')' : null; $dbResult = $pearDB->query($rq); // Find the new last nagios_id once $dbResult = $pearDB->query('SELECT MAX(nagios_id) FROM cfg_nagios'); $nagiosId = $dbResult->fetch(); $dbResult->closeCursor(); foreach ($rowBks as $keyBk => $valBk) { if ($valBk['broker_module']) { $stmt = $pearDB->prepare( 'INSERT INTO cfg_nagios_broker_module (`cfg_nagios_id`, `broker_module`) VALUES (:nagiosId, :brokerModule)' ); $stmt->bindValue('nagiosId', (int) $nagiosId['MAX(nagios_id)'], PDO::PARAM_INT); $stmt->bindValue('brokerModule', $valBk['broker_module'], PDO::PARAM_STR); $stmt->execute(); } } duplicateLoggerV2Cfg($pearDB, $originalNagiosId, $nagiosId['MAX(nagios_id)']); } } } } /** * @param CentreonDB $pearDB * @param int $originalNagiosId * @param int $duplicatedNagiosId */ function duplicateLoggerV2Cfg(CentreonDB $pearDB, int $originalNagiosId, int $duplicatedNagiosId): void { $statement = $pearDB->prepare( 'INSERT INTO cfg_nagios_logger SELECT null, :duplicatedNagiosId, `log_v2_logger`, `log_level_functions`, `log_level_config`, `log_level_events`, `log_level_checks`, `log_level_notifications`, `log_level_eventbroker`, `log_level_external_command`, `log_level_commands`, `log_level_downtimes`, `log_level_comments`, `log_level_macros`, `log_level_process`, `log_level_runtime` FROM cfg_nagios_logger WHERE cfg_nagios_id = :originalNagiosId' ); $statement->bindValue(':duplicatedNagiosId', $duplicatedNagiosId, PDO::PARAM_INT); $statement->bindValue(':originalNagiosId', $originalNagiosId, PDO::PARAM_INT); $statement->execute(); } function updateNagiosInDB($nagios_id = null) { if (! $nagios_id) { return; } updateNagios($nagios_id); } function insertNagiosInDB() { return insertNagios(); } /** * Calculate the sum of bitwise for a POST QuickForm array * * The array format * * array[key] => enable * Key int the bit * Enable 0|1 if the bit is activate * * if found the bit -1 (all) or 0 (none) activate return the value * * @param array $list The POST QuickForm table * @return int The bitwise */ function calculateBitwise($list) { $bitwise = 0; foreach ($list as $bit => $value) { if ($value == 1) { if ($bit === -1 || $bit === 0) { return $bit; } $bitwise += $bit; } } return $bitwise; } /** * @param array $levels * @return int */ function calculateDebugLevel(array $levels): int { $level = 0; foreach ($levels as $key => $value) { $level += (int) $key; } return $level; } /** * @param array $levels * @return string */ function implodeDebugLevel(array $levels): string { return implode(',', array_keys($levels)); } /** * @param array $macros * @return string */ function concatMacrosWhitelist(array $macros): string { return trim( implode( ',', array_map(function ($macro) { return CentreonDB::escape($macro); }, $macros) ) ); } /** * @return array<string,mixed> */ function getNagiosCfgColumnsDetails(): array { return [ 'additional_freshness_latency' => ['default' => null], 'admin_email' => ['default' => null], 'admin_pager' => ['default' => null], 'auto_rescheduling_interval' => ['default' => 30], 'auto_rescheduling_window' => ['default' => 180], 'cached_host_check_horizon' => ['default' => null], 'cached_service_check_horizon' => ['default' => null], 'cfg_dir' => ['default' => null], 'cfg_file' => ['default' => null], 'command_check_interval' => ['default' => null], 'command_file' => ['default' => null], 'check_result_reaper_frequency' => ['default' => 5], 'date_format' => ['default' => 'euro'], 'debug_level' => ['callback' => 'calculateDebugLevel', 'default' => '0'], 'debug_log_opt' => ['callback' => 'implodeDebugLevel', 'default' => '0'], 'debug_file' => ['default' => null], 'debug_verbosity' => ['default' => '2'], 'event_broker_options' => ['callback' => 'calculateBitwise', 'default' => '-1'], 'event_handler_timeout' => ['default' => 30], 'external_command_buffer_slots' => ['default' => null], 'global_host_event_handler' => ['default' => null], 'global_service_event_handler' => ['default' => null], 'high_host_flap_threshold' => ['default' => null], 'high_service_flap_threshold' => ['default' => null], 'host_check_timeout' => ['default' => 12], 'host_freshness_check_interval' => ['default' => null], 'host_inter_check_delay_method' => ['default' => null], 'log_file' => ['default' => null], 'low_host_flap_threshold' => ['default' => null], 'low_service_flap_threshold' => ['default' => null], 'macros_filter' => ['callback' => 'concatMacrosWhitelist', 'default' => null], 'max_debug_file_size' => ['default' => null], 'max_concurrent_checks' => ['default' => 0], 'max_host_check_spread' => ['default' => 15], 'max_service_check_spread' => ['default' => 15], 'nagios_comment' => ['default' => null], 'nagios_name' => ['default' => null], 'nagios_server_id' => ['default' => null], 'notification_timeout' => ['default' => 30], 'use_timezone' => ['default' => null], 'retention_update_interval' => ['default' => null], 'service_check_timeout' => ['default' => 60], 'service_freshness_check_interval' => ['default' => null], 'service_inter_check_delay_method' => ['default' => null], 'service_interleave_factor' => ['default' => 's'], 'status_file' => ['default' => null], 'status_update_interval' => ['default' => null], 'state_retention_file' => ['default' => null], 'sleep_time' => ['default' => null], 'illegal_macro_output_chars' => ['default' => null], 'illegal_object_name_chars' => ['default' => null], 'instance_heartbeat_interval' => ['default' => '30'], // Radio inputs 'accept_passive_host_checks' => ['isRadio' => true, 'default' => '1'], 'accept_passive_service_checks' => ['isRadio' => true, 'default' => '1'], 'auto_reschedule_checks' => ['isRadio' => true, 'default' => '0'], 'check_external_commands' => ['isRadio' => true, 'default' => '1'], 'check_for_orphaned_hosts' => ['isRadio' => true, 'default' => '0'], 'check_for_orphaned_services' => ['isRadio' => true, 'default' => '1'], 'check_host_freshness' => ['isRadio' => true, 'default' => '0'], 'check_service_freshness' => ['isRadio' => true, 'default' => '1'], 'enable_environment_macros' => ['isRadio' => true, 'default' => '0'], 'enable_event_handlers' => ['isRadio' => true, 'default' => '1'], 'enable_flap_detection' => ['isRadio' => true, 'default' => '0'], 'enable_macros_filter' => ['isRadio' => true, 'default' => '0'], 'enable_notifications' => ['isRadio' => true, 'default' => '1'], 'enable_predictive_host_dependency_checks' => ['isRadio' => true, 'default' => '0'], 'enable_predictive_service_dependency_checks' => ['isRadio' => true, 'default' => '0'], 'host_down_disable_service_checks' => ['isRadio' => true, 'default' => '0'], 'execute_host_checks' => ['isRadio' => true, 'default' => '1'], 'execute_service_checks' => ['isRadio' => true, 'default' => '1'], 'log_event_handlers' => ['isRadio' => true, 'default' => '1'], 'log_external_commands' => ['isRadio' => true, 'default' => '1'], 'log_host_retries' => ['isRadio' => true, 'default' => '1'], 'log_notifications' => ['isRadio' => true, 'default' => '1'], 'log_passive_checks' => ['isRadio' => true, 'default' => '1'], 'log_pid' => ['isRadio' => true, 'default' => '0'], 'log_service_retries' => ['isRadio' => true, 'default' => '1'], 'nagios_activate' => ['isRadio' => true, 'default' => '0'], 'passive_host_checks_are_soft' => ['isRadio' => true, 'default' => '0'], 'retain_state_information' => ['isRadio' => true, 'default' => '1'], 'soft_state_dependencies' => ['isRadio' => true, 'default' => '0'], 'use_regexp_matching' => ['isRadio' => true, 'default' => '0'], 'use_retained_program_state' => ['isRadio' => true, 'default' => '1'], 'use_retained_scheduling_info' => ['isRadio' => true, 'default' => '1'], 'use_syslog' => ['isRadio' => true, 'default' => '0'], 'use_true_regexp_matching' => ['isRadio' => true, 'default' => '0'], 'logger_version' => ['isRadio' => true, 'default' => 'log_v2_enabled'], ]; } /** * @return string[] */ function getLoggerV2Columns(): array { return [ 'log_v2_logger', 'log_level_functions', 'log_level_config', 'log_level_events', 'log_level_checks', 'log_level_notifications', 'log_level_eventbroker', 'log_level_external_command', 'log_level_commands', 'log_level_downtimes', 'log_level_comments', 'log_level_macros', 'log_level_process', 'log_level_runtime', 'log_level_otl', ]; } /** * @param CentreonDB $pearDB * @param array $data * @param int $nagiosId */ function insertLoggerV2Cfg(CentreonDB $pearDB, array $data, int $nagiosId): void { $loggerCfg = getLoggerV2Columns(); $statement = $pearDB->prepare( 'INSERT INTO cfg_nagios_logger (`cfg_nagios_id`, `' . implode('`, `', $loggerCfg) . '`) VALUES (:cfg_nagios_id, :' . implode(', :', $loggerCfg) . ')' ); $statement->bindValue(':cfg_nagios_id', $nagiosId, PDO::PARAM_INT); foreach ($loggerCfg as $columnName) { $statement->bindValue(':' . $columnName, $data[$columnName] ?? null, PDO::PARAM_STR); } $statement->execute(); } /** * @param CentreonDB $pearDB * @param array<string,mixed> $data * @param int $nagiosId */ function updateLoggerV2Cfg(CentreonDB $pearDB, array $data, int $nagiosId): void { $loggerCfg = getLoggerV2Columns(); $queryPieces = array_map(fn ($columnName) => "`{$columnName}` = :{$columnName}", $loggerCfg); $statement = $pearDB->prepare( 'UPDATE cfg_nagios_logger SET ' . implode(', ', $queryPieces) . ' WHERE cfg_nagios_id = :cfg_nagios_id' ); $statement->bindValue(':cfg_nagios_id', $nagiosId, PDO::PARAM_INT); foreach ($loggerCfg as $columnName) { $statement->bindValue(':' . $columnName, $data[$columnName] ?? null, PDO::PARAM_STR); } $statement->execute(); } /** * Insert logger V2 config if doesn't exist, otherwise update it * * @param CentreonDB $pearDB * @param array<string,mixed> $data * @param int $nagiosId */ function insertOrUpdateLogger(CentreonDB $pearDB, array $data, int $nagiosId): void { $statement = $pearDB->prepare('SELECT id FROM cfg_nagios_logger WHERE cfg_nagios_id = :cfg_nagios_id'); $statement->bindValue(':cfg_nagios_id', $nagiosId, PDO::PARAM_INT); $statement->execute(); if ($statement->fetch()) { updateLoggerV2Cfg($pearDB, $data, $nagiosId); } else { insertLoggerV2Cfg($pearDB, $data, $nagiosId); } } /** * This function is here to manage legacy encoded field while allowing to avoid this * bad design for specific fields : this is why these fields are hard coded here. * * @param string $value * @param string $columnName * @return string */ function encodeFieldNagios(string $value, string $columnName): string { $notEncodedFields = [ 'illegal_macro_output_chars', 'illegal_object_name_chars', ]; return in_array($columnName, $notEncodedFields, true) ? $value : htmlentities($value, ENT_QUOTES, 'UTF-8'); } function insertNagios($data = [], $brokerTab = []) { global $form, $pearDB, $centreon; if (! count($data)) { $data = $form->getSubmitValues(); } $nagiosColumns = getNagiosCfgColumnsDetails(); $nagiosCfg = []; foreach ($data as $columnName => $rawValue) { if (! array_key_exists($columnName, $nagiosColumns)) { continue; } if (! empty($nagiosColumns[$columnName]['callback'])) { $value = isset($rawValue) ? ($nagiosColumns[$columnName]['callback'])($rawValue) : $nagiosColumns[$columnName]['default']; } elseif (! empty($nagiosColumns[$columnName]['isRadio'])) { $value = isset($rawValue[$columnName]) ? encodeFieldNagios($rawValue[$columnName], $columnName) : $nagiosColumns[$columnName]['default']; } else { $value = isset($rawValue) && $rawValue !== '' ? encodeFieldNagios($rawValue, $columnName) : $nagiosColumns[$columnName]['default']; } $nagiosCfg[$columnName] = $value; } $statement = $pearDB->prepare( 'INSERT INTO cfg_nagios (`' . implode('`, `', array_keys($nagiosCfg)) . '`) VALUES (:' . implode(', :', array_keys($nagiosCfg)) . ')' ); array_walk( $nagiosCfg, fn ($value, $param, $statement) => $statement->bindValue(':' . $param, $value, PDO::PARAM_STR), $statement ); $statement->execute(); $dbResult = $pearDB->query('SELECT MAX(nagios_id) FROM cfg_nagios'); $nagios_id = $dbResult->fetch(); $dbResult->closeCursor(); if (isset($nagiosCfg['logger_version']) && $nagiosCfg['logger_version'] === 'log_v2_enabled') { insertLoggerV2Cfg($pearDB, $data, $nagios_id['MAX(nagios_id)']); } if (isset($_REQUEST['in_broker'])) { $mainCfg = new CentreonConfigEngine($pearDB); $mainCfg->insertBrokerDirectives($nagios_id['MAX(nagios_id)'], $_REQUEST['in_broker']); } // Manage the case where you have to main.cfg on the same poller if (isset($data['nagios_activate']['nagios_activate']) && $data['nagios_activate']['nagios_activate']) { $statement = $pearDB->prepare( "UPDATE cfg_nagios SET nagios_activate = '0' WHERE nagios_id != :nagios_id AND nagios_server_id = :nagios_server_id" ); $statement->bindValue(':nagios_id', (int) $nagios_id['MAX(nagios_id)'], PDO::PARAM_INT); $statement->bindValue(':nagios_server_id', (int) $data['nagios_server_id'], PDO::PARAM_INT); $statement->execute(); } // Prepare value for changelog $fields = CentreonLogAction::prepareChanges($data); $centreon->CentreonLogAction->insertLog( 'engine', $nagios_id['MAX(nagios_id)'], $pearDB->escape($data['nagios_name']), 'a', $fields ); return $nagios_id['MAX(nagios_id)']; } function updateNagios($nagiosId = null) { global $form, $pearDB, $centreon; if (! $nagiosId) { return; } $data = []; $data = $form->getSubmitValues(); $nagiosColumns = getNagiosCfgColumnsDetails(); $nagiosCfg = []; foreach ($data as $columnName => $rawValue) { if (! array_key_exists($columnName, $nagiosColumns)) { continue; } if (! empty($nagiosColumns[$columnName]['callback'])) { $value = isset($rawValue) ? ($nagiosColumns[$columnName]['callback'])($rawValue) : $nagiosColumns[$columnName]['default']; } elseif (! empty($nagiosColumns[$columnName]['isRadio'])) { $value = isset($rawValue[$columnName]) ? encodeFieldNagios($rawValue[$columnName], $columnName) : $nagiosColumns[$columnName]['default']; } else { $value = isset($rawValue) && $rawValue !== '' ? encodeFieldNagios($rawValue, $columnName) : $nagiosColumns[$columnName]['default']; } $nagiosCfg[$columnName] = $value; } $queryPieces = array_map(fn ($columnName) => "`{$columnName}` = :{$columnName}", array_keys($nagiosCfg)); $statement = $pearDB->prepare( 'UPDATE cfg_nagios SET ' . implode(', ', $queryPieces) . " WHERE nagios_id = {$nagiosId}" ); array_walk( $nagiosCfg, fn ($value, $param, $statement) => $statement->bindValue(':' . $param, $value, PDO::PARAM_STR), $statement ); $statement->execute(); if (isset($nagiosCfg['logger_version']) && $nagiosCfg['logger_version'] === 'log_v2_enabled') { insertOrUpdateLogger($pearDB, $data, $nagiosId); } $mainCfg = new CentreonConfigEngine($pearDB); if (isset($_REQUEST['in_broker'])) { $mainCfg->insertBrokerDirectives($nagiosId, $_REQUEST['in_broker']); } else { $mainCfg->insertBrokerDirectives($nagiosId); } if ($data['nagios_activate']['nagios_activate']) { enableNagiosInDB($nagiosId); } // Prepare value for changelog $fields = CentreonLogAction::prepareChanges($data); $centreon->CentreonLogAction->insertLog( 'engine', $nagiosId, $pearDB->escape($data['nagios_name']), 'c', $fields ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configNagios/nagios.php
centreon/www/include/configuration/configNagios/nagios.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(); } $nagiosId = filter_var( $_GET['nagios_id'] ?? $_POST['nagios_id'] ?? null, FILTER_VALIDATE_INT ) ?: null; $select = filter_var_array( $_GET['select'] ?? $_POST['select'] ?? [], FILTER_VALIDATE_INT ); $dupNbr = filter_var_array( $_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [], FILTER_VALIDATE_INT ); // PHP functions require_once __DIR__ . '/DB-Func.php'; require_once './include/common/common-Func.php'; /** * Page forbidden if server is a remote */ if ($isRemote) { require_once __DIR__ . '/../../core/errors/alt_error.php'; exit(); } // Set the real page if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) { $p = $ret['topology_page']; } $acl = $oreon->user->access; $serverString = $acl->getPollerString(); $allowedMainConf = []; if ($serverString != "''" && ! empty($serverString)) { $sql = 'SELECT nagios_id FROM cfg_nagios WHERE nagios_server_id IN (' . $serverString . ')'; $res = $pearDB->query($sql); while ($row = $res->fetchRow()) { $allowedMainConf[$row['nagios_id']] = true; } } switch ($o) { case 'a': require_once __DIR__ . '/formNagios.php'; break; // Add Nagios.cfg case 'w': require_once __DIR__ . '/formNagios.php'; break; // Watch Nagios.cfg case 'c': require_once __DIR__ . '/formNagios.php'; break; // Modify Nagios.cfg case 's': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); enableNagiosInDB($nagiosId); } else { unvalidFormMessage(); } require_once __DIR__ . '/listNagios.php'; break; // Activate a nagios CFG case 'u': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); disableNagiosInDB($nagiosId); } else { unvalidFormMessage(); } require_once __DIR__ . '/listNagios.php'; break; // Desactivate a nagios CFG case 'm': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); multipleNagiosInDB($select ?? [], $dupNbr); } else { unvalidFormMessage(); } require_once __DIR__ . '/listNagios.php'; break; // Duplicate n nagios CFGs case 'd': purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); deleteNagiosInDB($select ?? []); } else { unvalidFormMessage(); } require_once __DIR__ . '/listNagios.php'; break; // Delete n nagios CFG default: require_once __DIR__ . '/listNagios.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/reporting/dashboard/common-Func.php
centreon/www/include/reporting/dashboard/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 that returns the time interval to report * * @param string|null $alternate Needed to choose between the localized or the unlocalized date format * @return array */ function getPeriodToReport(?string $alternate = null): array { $period = ''; $period_choice = ''; $start_date = ''; $end_date = ''; if (isset($_POST['period'])) { $period = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['period']); } elseif (isset($_GET['period'])) { $period = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['period']); } if (isset($_POST['period_choice'])) { $period_choice = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['period_choice']); } if ($alternate != null) { if (isset($_POST['alternativeDateStartDate'])) { $start_date = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['alternativeDateStartDate']); } if (isset($_POST['alternativeDateEndDate'])) { $end_date = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['alternativeDateEndDate']); } } else { if (isset($_POST['StartDate'])) { $start_date = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['StartDate']); } elseif (isset($_GET['StartDate'])) { $start_date = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['StartDate']); } if (isset($_POST['EndDate'])) { $end_date = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['EndDate']); } elseif (isset($_GET['EndDate'])) { $end_date = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['EndDate']); } } $interval = [0, 0]; if ( $period_choice === 'custom' && $start_date !== '' && $end_date !== '' ) { $period = ''; } if ( $period === '' && $start_date === '' && $end_date === '' ) { $period = 'yesterday'; } if ( $period === '' && $start_date !== '' ) { $interval = getDateSelectCustomized($start_date, $end_date); } else { $interval = getDateSelectPredefined($period); } [$start_date, $end_date] = $interval; return [$start_date, $end_date]; } /* * Return a table containing all stats information that will * be displayed on dashboard for host and hostgroup */ function getHostStatsValueName() { return [ 'UP_T', 'UP_A', 'DOWN_T', 'DOWN_A', 'UNREACHABLE_T', 'UNREACHABLE_A', 'UNDETERMINED_T', 'MAINTENANCE_T', 'UP_TP', 'UP_MP', 'DOWN_TP', 'DOWN_MP', 'UNREACHABLE_TP', 'UNREACHABLE_MP', 'UNDETERMINED_TP', 'MAINTENANCE_TP', 'TOTAL_ALERTS', ]; } /* * Return a table containing all stats information that will be * displayed on dashboard for services and servicegroup */ function getServicesStatsValueName() { return [ 'OK_T', 'OK_A', 'WARNING_T', 'WARNING_A', 'CRITICAL_T', 'CRITICAL_A', 'UNKNOWN_T', 'UNKNOWN_A', 'UNDETERMINED_T', 'MAINTENANCE_T', 'OK_TP', 'OK_MP', 'WARNING_TP', 'WARNING_MP', 'CRITICAL_TP', 'CRITICAL_MP', 'UNKNOWN_TP', 'UNKNOWN_MP', 'UNDETERMINED_TP', 'MAINTENANCE_TP', 'TOTAL_ALERTS', ]; } /* * return start and end date to report in timestamp * ==>> function must be optimized */ function getDateSelectPredefined($period) { $time = time(); $day = date('d', $time); $year = date('Y', $time); $month = date('m', $time); if (! is_null($period)) { if ($period == 'yesterday') { $start_date = mktime(0, 0, 0, $month, $day - 1, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } elseif ($period == 'thisweek') { $dd = (date('D', mktime(24, 0, 0, $month, $day - 1, $year))); for ($ct = 1; $dd != 'Mon'; $ct++) { $dd = (date('D', mktime(0, 0, 0, $month, ($day - $ct), $year))); } $start_date = mktime(0, 0, 0, $month, $day - $ct, $year); $end_date = mktime(24, 0, 0, $month, ($day - 1), $year); } elseif ($period == 'last7days') { $start_date = mktime(0, 0, 0, $month, $day - 7, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } elseif ($period == 'last30days') { $start_date = mktime(0, 0, 0, $month, $day - 30, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } elseif ($period == 'lastyear') { $start_date = mktime(0, 0, 0, 1, 1, $year - 1); $end_date = mktime(0, 0, 0, 1, 1, $year); } elseif ($period == 'thismonth') { $start_date = mktime(0, 0, 0, $month, 1, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } elseif ($period == 'thisyear') { $start_date = mktime(0, 0, 0, 1, 1, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } else { // last month $start_date = mktime(0, 0, 0, $month - 1, 1, $year); $end_date = mktime(0, 0, 0, $month, 1, $year); } } else { $start_date = mktime(0, 0, 0, $month, $day - 1, $year); $end_date = mktime(24, 0, 0, $month, $day - 1, $year); } if ($start_date > $end_date) { $start_date = $end_date; } return [$start_date, $end_date]; } function getDateSelectCustomized($start, $end) { $time = time(); $day = date('d', $time); $year = date('Y', $time); $month = date('m', $time); $end_time = mktime(0, 0, 0, $month, $day, $year); if (is_numeric($end)) { $end_time = $end; } elseif (isset($end) && $end != '') { [$m, $d, $y] = preg_split('/\//', $end); $end = mktime(24, 0, 0, $m, $d, $y); if ($end < $end_time) { $end_time = $end; } } if ( ! is_numeric($start) && isset($start) && $start != '' ) { [$m, $d, $y] = preg_split('/\//', $start); $start_time = mktime(0, 0, 0, $m, $d, $y); } else { $start_time = $start; } if ($start_time >= $end_time) { $start_time = $end_time - (60 * 60 * 24); } return [$start_time, $end_time]; } /* * Return time between two timestamp * excluding days and time which are not in the parameters * defined in menu "Options>General Options>Reporting" */ function getTotalTimeFromInterval($start, $end, $reportTimePeriod) { $one_day_real_duration = 60 * 60 * 24; $totalTime = 0; $reportTime = 0; $reportTimePeriodEnd = mktime( $reportTimePeriod['report_hour_end'], $reportTimePeriod['report_minute_end'], 0, 0, 0, 0 ); $reportTimePeriodStart = mktime( $reportTimePeriod['report_hour_start'], $reportTimePeriod['report_minute_start'], 0, 0, 0, 0 ); $day_duration = $reportTimePeriodEnd - $reportTimePeriodStart; while ($start < $end) { if ($day_duration > $end - $start) { $day_duration = $end - $start; } if ( isset($reportTimePeriod['report_' . date('l', $start)]) && $reportTimePeriod['report_' . date('l', $start)] ) { $reportTime += $day_duration; }// if the day is selected in the timeperiod $totalTime += $day_duration; // $start = $day_real_end; $start += $one_day_real_duration; } return ['totalTime' => $totalTime, 'reportTime' => $reportTime]; } function myGetTimeTamps($dateSTR) { [$m, $d, $y] = preg_split('/\//', $dateSTR); return mktime(0, 0, 0, $m, $d, $y); } function getPeriodList() { return [ '' => '', 'yesterday' => _('Yesterday'), 'thisweek' => _('This Week'), 'last7days' => _('Last 7 Days'), 'thismonth' => _('This Month'), 'last30days' => _('Last 30 Days'), 'lastmonth' => _('Last Month'), 'thisyear' => _('This Year'), 'lastyear' => _('Last Year'), ]; } function createDateTimelineFormat($time_unix) { $tab_month = ['01' => 'Jan', '02' => 'Feb', '03' => 'Mar', '04' => 'Apr', '05' => 'May', '06' => 'Jun', '07' => 'Jul', '08' => 'Aug', '09' => 'Sep', '10' => 'Oct', '11' => 'Nov', '12' => 'Dec']; return $tab_month[date('m', $time_unix)] . date(' d Y G:i:s', $time_unix); } function getTimeString($time, $reportTimePeriod) { $min = 60; $hour = $min * 60; $day = mktime($reportTimePeriod['report_hour_end'], $reportTimePeriod['report_minute_end'], 0, 0, 0, 0) - mktime($reportTimePeriod['report_hour_start'], $reportTimePeriod['report_minute_start'], 0, 0, 0, 0); $str = ''; if ($day && $time / $day >= 1) { $str .= floor($time / $day) . 'd '; $time = $time % $day; } if ($hour && $time / $hour >= 1) { $str .= floor($time / $hour) . 'h '; $time = $time % $hour; } if ($min && $time / $min >= 1) { $str .= floor($time / $min) . 'm '; $time = $time % $min; } if ($time) { $str .= $time . 's'; } return $str; } function formatData($state, $time, $timeTOTAL, $time_none, $nb_alert, $color) { return ['state' => _($state), 'time' => CentreonDuration::toString($time), 'timestamp' => $time, 'pourcentTime' => round($time / ($timeTOTAL + 1) * 100, 2), 'pourcentkTime' => $state != 'Undetermined' ? round($time / ($timeTOTAL - $time_none + 1) * 100, 2) . '%' : null, 'nbAlert' => $nb_alert, 'style' => "class='ListColCenter' style='background:" . $color . "'"]; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/ajaxReporting_js.php
centreon/www/include/reporting/dashboard/ajaxReporting_js.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'); $arg = $type == 'Service' ? 'id=' . $serviceId . '&host_id=' . $hostId : 'id=' . $id; $arg .= '&color[UP]=#' . $colors['up'] . '&color[UNDETERMINED]=#' . $colors['undetermined'] . '&color[DOWN]=#' . $colors['down'] . '&color[UNREACHABLE]=#' . $colors['unreachable'] . '&color[OK]=#' . $colors['ok'] . '&color[WARNING]=#' . $colors['warning'] . '&color[CRITICAL]=#' . $colors['critical'] . '&color[UNKNOWN]=#' . $colors['unknown'] . '&startDate=' . $startDate . '&endDate=' . $endDate; $arg = str_replace('#', '%23', $arg); $url = './include/reporting/dashboard/xmlInformations/GetXml' . $type . '.php?' . $arg; ?> <script type="text/javascript"> var tl; function initTimeline() { var eventSource = new Timeline.DefaultEventSource(); var bandInfos = [ Timeline.createBandInfo({ eventSource: eventSource, width: "70%", intervalUnit: Timeline.DateTime.DAY, intervalPixels: 300 }), Timeline.createBandInfo({ showEventText: false, eventSource: eventSource, width: "30%", intervalUnit: Timeline.DateTime.MONTH, intervalPixels: 300 }) ]; bandInfos[1].syncWith = 0; bandInfos[1].highlight = true; bandInfos[1].eventPainter.setLayout(bandInfos[0].eventPainter.getLayout()); tl = Timeline.create(document.getElementById("my-timeline"), bandInfos); Timeline.loadXML('<?php echo $url; ?>', function(xml, url) { eventSource.loadXML(xml, url); }); } </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/reporting/dashboard/initReport.php
centreon/www/include/reporting/dashboard/initReport.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; } $path = './include/reporting/dashboard'; // Require Centreon Class require_once './class/centreonDuration.class.php'; require_once './class/centreonDB.class.php'; // Require centreon common lib require_once './include/reporting/dashboard/common-Func.php'; require_once './include/reporting/dashboard/DB-Func.php'; require_once './include/common/common-Func.php'; // Create DB connexion $pearDBO = new CentreonDB('centstorage'); $debug = 0; // QuickForm templates $attrsTextI = ['size' => '3']; $attrsText = ['size' => '30']; $attrsTextarea = ['rows' => '5', 'cols' => '40']; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, ''); $tpl->assign('o', $o); // Assign centreon path $tpl->assign('centreon_path', _CENTREON_PATH_); // Status colors $colors = ['up' => '88b917', 'down' => 'e00b3d', 'unreachable' => '818285', 'maintenance' => 'cc99ff', 'downtime' => 'cc99ff', 'ok' => '88b917', 'warning' => 'ff9a13', 'critical' => 'e00b3d', 'unknown' => 'bcbdc0', 'undetermined' => 'd1d2d4']; $tpl->assign('colors', $colors); $color = []; $color['UNKNOWN'] = $colors['unknown']; $color['UP'] = $colors['up']; $color['DOWN'] = $colors['down']; $color['UNREACHABLE'] = $colors['unreachable']; $color['UNDETERMINED'] = $colors['undetermined']; $color['OK'] = $colors['ok']; $color['WARNING'] = $colors['warning']; $color['CRITICAL'] = $colors['critical']; $tpl->assign('color', $color); $startDate = 0; $endDate = 0; // Translations and styles $tpl->assign('style_ok', "class='ListColCenter' style='padding:5px;background:#" . $colors['ok'] . "'"); $tpl->assign('style_ok_top', " style='color:#" . $colors['ok'] . "'"); $tpl->assign('style_ok_alert', "class='ListColCenter' style='width: 25px; background:#" . $colors['ok'] . "'"); $tpl->assign('style_warning', "class='ListColCenter' style='padding:5px;background:#" . $colors['warning'] . "'"); $tpl->assign('style_warning_top', "style='color:#" . $colors['warning'] . "'"); $tpl->assign( 'style_warning_alert', "class='ListColCenter' style='width: 25px; background:#" . $colors['warning'] . "'" ); $tpl->assign('style_critical', "class='ListColCenter' style='padding:5px;background:#" . $colors['critical'] . "'"); $tpl->assign('style_critical_top', "style='color:#" . $colors['critical'] . "'"); $tpl->assign( 'style_critical_alert', "class='ListColCenter' style='width: 25px; background:#" . $colors['critical'] . "'" ); $tpl->assign('style_unknown', "class='ListColCenter' style='padding:5px;background:#" . $colors['unknown'] . "'"); $tpl->assign('style_unknown_top', ''); $tpl->assign( 'style_unknown_alert', "class='ListColCenter' style='width: 25px; background:#" . $colors['unknown'] . "'" ); $tpl->assign('style_pending', "class='ListColCenter' style='padding:5px;background:#" . $colors['undetermined'] . "'"); $tpl->assign('style_pending_top', ''); $tpl->assign( 'style_pending_alert', "class='ListColCenter' style='width: 25px; background:#" . $colors['undetermined'] . "'" ); $tpl->assign( 'style_maintenance', "class='ListColCenter' style='padding:5px;background:#" . $colors['maintenance'] . "'" ); $tpl->assign('style_maintenance_top', "style='color:#" . $colors['maintenance'] . "'"); $tpl->assign('badge_UP', "class='ListColCenter state_badge host_up'"); $tpl->assign('badge_DOWN', "class='ListColCenter state_badge host_down'"); $tpl->assign('badge_UNREACHABLE', "class='ListColCenter state_badge host_unreachable'"); $tpl->assign('badge_UNDETERMINED', "class='ListColCenter state_badge badge_undetermined'"); $tpl->assign('badge_MAINTENANCE', "class='ListColCenter state_badge badge_downtime'"); $tpl->assign('badge_ok', "class='ListColCenter state_badge service_ok'"); $tpl->assign('badge_warning', "class='ListColCenter state_badge service_warning'"); $tpl->assign('badge_critical', "class='ListColCenter state_badge service_critical'"); $tpl->assign('badge_unknown', "class='ListColCenter state_badge service_unknown'"); $tpl->assign('badge_pending', "class='ListColCenter state_badge badge_undetermined'"); $tpl->assign('badge_maintenance', "class='ListColCenter state_badge badge_downtime'"); $tpl->assign('actualTitle', _('Actual')); $tpl->assign('serviceTitle', _('Service')); $tpl->assign('hostTitle', _('Host name')); $tpl->assign('allTilte', _('All')); $tpl->assign('averageTilte', _('Average')); $tpl->assign('OKTitle', _('OK')); $tpl->assign('WarningTitle', _('Warning')); $tpl->assign('UnknownTitle', _('Unknown')); $tpl->assign('CriticalTitle', _('Critical')); $tpl->assign('PendingTitle', _('Undetermined')); $tpl->assign('MaintenanceTitle', _('Scheduled downtime')); $tpl->assign('stateLabel', _('State')); $tpl->assign('totalLabel', _('Total')); $tpl->assign('durationLabel', _('Duration')); $tpl->assign('totalTimeLabel', _('Total Time')); $tpl->assign('meanTimeLabel', _('Mean Time')); $tpl->assign('alertsLabel', _('Alerts')); $tpl->assign('DateTitle', _('Date')); $tpl->assign('EventTitle', _('Event')); $tpl->assign('InformationsTitle', _('Info')); $tpl->assign('periodTitle', _('Reporting Period')); $tpl->assign('periodORlabel', _('or')); $tpl->assign('logTitle', _("Today's Host log")); $tpl->assign('svcTitle', _('State Breakdowns For Host Services')); // Definition of status $state['UP'] = _('UP'); $state['DOWN'] = _('DOWN'); $state['UNREACHABLE'] = _('UNREACHABLE'); $state['UNDETERMINED'] = _('UNDETERMINED'); $state['MAINTENANCE'] = _('SCHEDULED DOWNTIME'); $tpl->assign('states', $state); // CSS Definition for status colors $style['UP'] = "style='padding:5px;color:#" . $colors['up'] . "'"; $style['UP_BOTTOM'] = "style='padding:5px;background-color:#" . $colors['up'] . "'"; $style['DOWN'] = "style='padding:5px;color:#" . $colors['down'] . "'"; $style['DOWN_BOTTOM'] = "style='padding:5px;background-color:#" . $colors['down'] . "'"; $style['UNREACHABLE'] = "style='padding:5px'"; $style['UNREACHABLE_BOTTOM'] = "style='padding:5px;background-color:#" . $colors['unreachable'] . "'"; $style['UNDETERMINED'] = "style='padding:5px'"; $style['UNDETERMINED_BOTTOM'] = "style='padding:5px;background-color:#" . $colors['undetermined'] . "'"; $style['MAINTENANCE'] = "style='padding:5px;color:#" . $colors['maintenance'] . "'"; $style['MAINTENANCE_BOTTOM'] = "style='padding:5px;background-color:#" . $colors['maintenance'] . "'"; $tpl->assign('style', $style); // Init Timeperiod List // Getting period table list to make the form period selection (today, this week etc.) $periodList = getPeriodList(); // Getting timeperiod by day (example : 9:30 to 19:30 on monday,tue,wed,thu,fri) $reportingTimePeriod = getreportingTimePeriod(); // CSV export parameters $var_url_export_csv = ''; // LCA $lcaHoststr = $centreon->user->access->getHostsString('ID', $pearDBO); $lcaHostGroupstr = $centreon->user->access->getHostGroupsString(); $lcaSvcstr = $centreon->user->access->getServicesString('ID', $pearDBO); // setting variables for link with services $period_choice = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['period_choice'] ?? 'preset' ); $period = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['period'] ?? $_GET['period'] ?? '' ); $get_date_start = HtmlAnalyzer::sanitizeAndRemoveTags( $_GET['start'] ?? $_POST['StartDate'] ?? '' ); $get_date_end = HtmlAnalyzer::sanitizeAndRemoveTags( $_GET['end'] ?? $_POST['EndDate'] ?? '' ); if ($get_date_start == '' && $get_date_end == '' && $period == '') { $period = 'yesterday'; } $tpl->assign('get_date_start', $get_date_start); $tpl->assign('get_date_end', $get_date_end); $tpl->assign('get_period', $period); $tpl->assign('link_csv_url', null); $tpl->assign('infosTitle', null); // Settings default variables for all state. $tpl->assign('name', null); $tpl->assign('totalAlert', null); $tpl->assign('totalTime', null); $initialStates = [ 'OK_TP' => null, 'OK_MP' => null, 'OK_A' => null, 'WARNING_TP' => null, 'WARNING_MP' => null, 'WARNING_A' => null, 'CRITICAL_TP' => null, 'CRITICAL_MP' => null, 'CRITICAL_A' => null, 'UNKNOWN_TP' => null, 'UNKNOWN_MP' => null, 'UNKNOWN_A' => null, 'UP_TF' => null, 'UP_TP' => null, 'UP_MP' => null, 'UP_A' => null, 'DOWN_TF' => null, 'DOWN_TP' => null, 'DOWN_MP' => null, 'DOWN_A' => null, 'UNREACHABLE_TF' => null, 'UNREACHABLE_TP' => null, 'UNREACHABLE_MP' => null, 'UNREACHABLE_A' => null, 'UNDETERMINED_TF' => null, 'UNDETERMINED_TP' => null, 'MAINTENANCE_TF' => null, 'MAINTENANCE_TP' => null, 'NAME' => null, 'ID' => null, 'DESCRIPTION' => null, 'HOST_ID' => null, 'HOST_NAME' => null, 'SERVICE_ID' => null, 'SERVICE_DESC' => null, ]; $tpl->assign('summary', $initialStates); $tpl->assign('components_avg', $initialStates); $tpl->assign('components', ['tb' => $initialStates]); $tpl->assign('period_name', _('From')); $tpl->assign('date_start', null); $tpl->assign('to', _('to')); $tpl->assign('date_end', null); $tpl->assign('period', null); $tpl->assign('host_id', null); $tpl->assign('hostgroup_id', null); $tpl->assign('servicegroup_id', null); $tpl->assign('Alert', _('Alert')); $tpl->assign('host_up', null); $tpl->assign('host_down', null); $tpl->assign('host_unreachable', null); $tpl->assign('host_undetermined', null); $tpl->assign('host_maintenance', null); $tpl->assign('service_ok', null); $tpl->assign('service_warning', null); $tpl->assign('service_critical', null); $tpl->assign('service_unknown', null); $tpl->assign('service_undetermined', null); $tpl->assign('service_maintenance', null); $tpl->assign('hostgroup_up', null); $tpl->assign('hostgroup_down', null); $tpl->assign('hostgroup_unreachable', null); $tpl->assign('hostgroup_undetermined', null); $tpl->assign('hostgroup_maintenance', null); $tpl->assign('servicegroup_ok', null); $tpl->assign('servicegroup_warning', null); $tpl->assign('servicegroup_critical', null); $tpl->assign('servicegroup_unknown', null); $tpl->assign('servicegroup_undetermined', null); $tpl->assign('servicegroup_maintenance', null); $tpl->assign('period_choice', $period_choice); // Period Selection form $formPeriod = new HTML_QuickFormCustom('FormPeriod', 'post', '?p=' . $p); $formPeriod->addElement('select', 'period', '', $periodList, ['id' => 'presetPeriod']); $formPeriod->addElement('hidden', 'timeline', '1'); $formPeriod->addElement( 'text', 'StartDate', _('From'), ['id' => 'StartDate', 'size' => 10, 'class' => 'datepicker', 'onClick' => 'javascript: togglePeriodType();'] ); $formPeriod->addElement( 'text', 'EndDate', _('to'), ['id' => 'EndDate', 'size' => 10, 'class' => 'datepicker', 'onClick' => 'javascript: togglePeriodType();'] ); // adding hidden fields to get the result of datepicker in an unlocalized format $formPeriod->addElement( 'hidden', 'alternativeDateStartDate', '', ['size' => 10, 'class' => 'alternativeDate'] ); $formPeriod->addElement( 'hidden', 'alternativeDateEndDate', 'test', ['size' => 10, 'class' => 'alternativeDate'] ); $formPeriod->addElement('submit', 'button', _('Apply period'), ['class' => 'btc bt_success ml-2']); $formPeriod->setDefaults( [ 'period' => $period, 'StartDate' => $get_date_start, 'EndDate' => $get_date_end, ] ); ?> <script type='text/javascript'> function togglePeriodType() { document.getElementById("presetPeriod").selectedIndex = 0; } </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/reporting/dashboard/viewServicesLog.php
centreon/www/include/reporting/dashboard/viewServicesLog.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; } // Required files require_once './include/reporting/dashboard/initReport.php'; // Getting service to report $hostId = filter_var($_GET['host_id'] ?? $_POST['host_id'] ?? false, FILTER_VALIDATE_INT); $serviceId = filter_var($_GET['item'] ?? $_POST['itemElement'] ?? false, FILTER_VALIDATE_INT); // FORMS $form = new HTML_QuickFormCustom('formItem', 'post', '?p=' . $p); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); $host_name = getMyHostName($hostId); $items = $centreon->user->access->getHostServices($pearDBO, $hostId); $itemsForUrl = []; foreach ($items as $key => $value) { $itemsForUrl[str_replace(':', '%3A', $key)] = str_replace(':', '%3A', $value); } $service_name = $itemsForUrl[$serviceId]; $select = $formPeriod->addElement( 'select', 'itemElement', _('Service'), $items, [ 'onChange' => 'this.form.submit();', ] ); $select->setSelected((string) $serviceId); $form->addElement( 'hidden', 'period', $period ); $form->addElement( 'hidden', 'StartDate', $get_date_start ); $form->addElement( 'hidden', 'EndDate', $get_date_end ); $form->addElement('hidden', 'p', $p); // Set service id with period selection form if ($serviceId !== false && $hostId !== false) { $formPeriod->addElement( 'hidden', 'item', $serviceId ); $formPeriod->addElement( 'hidden', 'host_id', $hostId ); $form->addElement( 'hidden', 'host_id', $hostId ); $form->setDefaults(['itemElement' => $serviceId]); // Getting periods values $dates = getPeriodToReport('alternate'); $startDate = $dates[0]; $endDate = $dates[1]; // Getting hostgroup and his hosts stats $servicesStats = getServicesLogs( [[ 'hostId' => $hostId, 'serviceId' => $serviceId, ]], $startDate, $endDate, $reportingTimePeriod ); if (! empty($servicesStats)) { $serviceStats = $servicesStats[$hostId][$serviceId]; } else { $serviceStats = [ 'OK_TF' => null, 'OK_MP' => null, 'OK_TP' => null, 'OK_A' => null, 'WARNING_TP' => null, 'WARNING_A' => null, 'WARNING_MP' => null, 'WARNING_TF' => null, 'CRITICAL_TP' => null, 'CRITICAL_A' => null, 'CRITICAL_MP' => null, 'CRITICAL_TF' => null, 'UNKNOWN_TP' => null, 'UNKNOWN_A' => null, 'UNKNOWN_MP' => null, 'UNKNOWN_TF' => null, 'UNDETERMINED_TP' => 100, 'UNDETERMINED_A' => null, 'UNDETERMINED_TF' => null, 'MAINTENANCE_TP' => null, 'MAINTENANCE_TF' => null, 'TOTAL_ALERTS' => null, 'TOTAL_TIME_F' => null, ]; } // Chart datas $tpl->assign('service_ok', $serviceStats['OK_TP']); $tpl->assign('service_warning', $serviceStats['WARNING_TP']); $tpl->assign('service_critical', $serviceStats['CRITICAL_TP']); $tpl->assign('service_unknown', $serviceStats['UNKNOWN_TP']); $tpl->assign('service_undetermined', $serviceStats['UNDETERMINED_TP']); $tpl->assign('service_maintenance', $serviceStats['MAINTENANCE_TP']); // Exporting variables for ihtml $tpl->assign('host_name', $host_name); $tpl->assign('name', $itemsForUrl[$serviceId]); $tpl->assign('totalAlert', $serviceStats['TOTAL_ALERTS']); $tpl->assign('totalTime', $serviceStats['TOTAL_TIME_F']); $tpl->assign('summary', $serviceStats); $tpl->assign('from', _('From')); $tpl->assign('date_start', $startDate); $tpl->assign('to', _('to')); $tpl->assign('date_end', $endDate); $formPeriod->setDefaults(['period' => $period]); $tpl->assign('id', $serviceId); /* * Ajax timeline and CSV export initialization * CSV Export */ $tpl->assign( 'link_csv_url', './include/reporting/dashboard/csvExport/csv_ServiceLogs.php?host=' . $hostId . '&service=' . $serviceId . '&start=' . $startDate . '&end=' . $endDate ); $tpl->assign('link_csv_name', _('Export in CSV format')); // status colors $color = substr($colors['up'], 1) . ':' . substr($colors['down'], 1) . ':' . substr($colors['unreachable'], 1) . ':' . substr($colors['undetermined'], 1) . ':' . substr($colors['maintenance'], 1); // Ajax timeline $type = 'Service'; include './include/reporting/dashboard/ajaxReporting_js.php'; } else { ?><script type="text/javascript"> function initTimeline() {;} </script> <?php } $tpl->assign('resumeTitle', _('Service state')); // Rendering forms $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formPeriod->accept($renderer); $tpl->assign('formPeriod', $renderer->toArray()); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('formItem', $renderer->toArray()); if ( ! $formPeriod->isSubmitted() || ($formPeriod->isSubmitted() && $formPeriod->validate()) ) { $tpl->display('template/viewServicesLog.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/reporting/dashboard/viewServicesGroupLog.php
centreon/www/include/reporting/dashboard/viewServicesGroupLog.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; } // Required files require_once './include/reporting/dashboard/initReport.php'; // Getting service group to report $id = filter_var($_GET['item'] ?? $_POST['itemElement'] ?? false, FILTER_VALIDATE_INT); // FORMS $serviceGroupForm = new HTML_QuickFormCustom('formServiceGroup', 'post', '?p=' . $p); $redirect = $serviceGroupForm->addElement('hidden', 'o'); $redirect->setValue($o); $serviceGroupRoute = ['datasourceOrigin' => 'ajax', 'multiple' => false, 'linkedObject' => 'centreonServicegroups', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_servicegroup&action=list', 'defaultDatasetRoute' => './api/internal.php?object=centreon_configuration_servicegroup' . '&action=defaultValues&target=service&field=service_sgs&id=' . $id]; $serviceGroupSelectBox = $formPeriod->addElement( 'select2', 'itemElement', _('Service Group'), [], $serviceGroupRoute ); $serviceGroupSelectBox->addJsCallback( 'change', 'this.form.submit();' ); $serviceGroupForm->addElement( 'hidden', 'period', $period ); $serviceGroupForm->addElement( 'hidden', 'StartDate', $get_date_start ); $serviceGroupForm->addElement( 'hidden', 'EndDate', $get_date_end ); if (isset($id)) { $formPeriod->setDefaults(['itemElement' => $id]); } // Set servicegroup id with period selection form if ($id !== false) { $formPeriod->addElement( 'hidden', 'item', $id ); /* * Stats Display for selected services group * Getting periods values */ $dates = getPeriodToReport('alternate'); $startDate = $dates[0]; $endDate = $dates[1]; // Getting servicegroups logs $servicesgroupStats = getLogInDbForServicesGroup($id, $startDate, $endDate, $reportingTimePeriod); // Chart datas $tpl->assign('servicegroup_ok', $servicesgroupStats['average']['OK_TP']); $tpl->assign('servicegroup_warning', $servicesgroupStats['average']['WARNING_TP']); $tpl->assign('servicegroup_critical', $servicesgroupStats['average']['CRITICAL_TP']); $tpl->assign('servicegroup_unknown', $servicesgroupStats['average']['UNKNOWN_TP']); $tpl->assign('servicegroup_undetermined', $servicesgroupStats['average']['UNDETERMINED_TP']); $tpl->assign('servicegroup_maintenance', $servicesgroupStats['average']['MAINTENANCE_TP']); // Exporting variables for ihtml $tpl->assign('totalAlert', $servicesgroupStats['average']['TOTAL_ALERTS']); $tpl->assign('summary', $servicesgroupStats['average']); // Removing average infos from table $servicesgroupFinalStats = []; foreach ($servicesgroupStats as $key => $value) { if ($key != 'average') { $servicesgroupFinalStats[$key] = $value; } } $tpl->assign('components', $servicesgroupFinalStats); $tpl->assign('period_name', _('From')); $tpl->assign('date_start', $startDate); $tpl->assign('to', _('to')); $tpl->assign('date_end', $endDate); $tpl->assign('period', $period); $formPeriod->setDefaults(['period' => $period]); $tpl->assign('servicegroup_id', $id); $tpl->assign('Alert', _('Alert')); /* * Ajax timeline and CSV export initialization * CSV export */ $tpl->assign( 'link_csv_url', './include/reporting/dashboard/csvExport/csv_ServiceGroupLogs.php?servicegroup=' . $id . '&start=' . $startDate . '&end=' . $endDate ); $tpl->assign( 'link_csv_name', _('Export in CSV format') ); // Status colors $color = substr($colors['up'], 1) . ':' . substr($colors['down'], 1) . ':' . substr($colors['unreachable'], 1) . ':' . substr($colors['maintenance'], 1) . ':' . substr($colors['undetermined'], 1); // Ajax timeline $type = 'ServiceGroup'; include './include/reporting/dashboard/ajaxReporting_js.php'; } else { ?><script type="text/javascript"> function initTimeline() {;} </script> <?php } $tpl->assign('resumeTitle', _('Service group state')); $tpl->assign('p', $p); // Rendering forms $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formPeriod->accept($renderer); $tpl->assign('formPeriod', $renderer->toArray()); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $serviceGroupForm->accept($renderer); $tpl->assign('serviceGroupForm', $renderer->toArray()); if ( ! $formPeriod->isSubmitted() || ($formPeriod->isSubmitted() && $formPeriod->validate()) ) { $tpl->display('template/viewServicesGroupLog.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/reporting/dashboard/viewHostLog.php
centreon/www/include/reporting/dashboard/viewHostLog.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; } // Required files require_once './include/reporting/dashboard/initReport.php'; // Getting host to report $id = filter_var($_GET['host'] ?? $_POST['hostElement'] ?? false, FILTER_VALIDATE_INT); // Formulary // Host Selection $formHost = new HTML_QuickFormCustom('formHost', 'post', '?p=' . $p); $redirect = $formHost->addElement('hidden', 'o'); $redirect->setValue($o); $hostsRoute = ['datasourceOrigin' => 'ajax', 'multiple' => false, 'linkedObject' => 'centreonHost', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_host&action=list', 'defaultDatasetRoute' => './api/internal.php?object=centreon_configuration_host &action=defaultValues&target=host&field=host_id&id=' . $id]; $selHost = $formPeriod->addElement( 'select2', 'hostElement', _('Host'), [], $hostsRoute ); $selHost->addJsCallback( 'change', 'this.form.submit();' ); $formHost->addElement( 'hidden', 'period', $period ); $formHost->addElement( 'hidden', 'StartDate', $get_date_start ); $formHost->addElement( 'hidden', 'EndDate', $get_date_end ); if (isset($id)) { $formPeriod->setDefaults(['hostElement' => $id]); } // Set host id with period selection form if ($id !== false) { $formPeriod->addElement( 'hidden', 'host', $id ); /* * Stats Display for selected host * Getting periods values */ $dates = getPeriodToReport('alternate'); $startDate = $dates[0]; $endDate = $dates[1]; // $formPeriod->setDefaults(array('period' => $period)); // Getting host and his services stats $hostStats = getLogInDbForHost($id, $startDate, $endDate, $reportingTimePeriod); $hostServicesStats = getLogInDbForHostSVC($id, $startDate, $endDate, $reportingTimePeriod); // Chart datas $tpl->assign('host_up', $hostStats['UP_TP']); $tpl->assign('host_down', $hostStats['DOWN_TP']); $tpl->assign('host_unreachable', $hostStats['UNREACHABLE_TP']); $tpl->assign('host_undetermined', $hostStats['UNDETERMINED_TP']); $tpl->assign('host_maintenance', $hostStats['MAINTENANCE_TP']); // Exporting variables for ihtml $tpl->assign('totalAlert', $hostStats['TOTAL_ALERTS']); $tpl->assign('totalTime', $hostStats['TOTAL_TIME_F']); $tpl->assign('summary', $hostStats); $tpl->assign('components_avg', array_shift($hostServicesStats)); $tpl->assign('components', $hostServicesStats); $tpl->assign('period_name', _('From')); $tpl->assign('date_start', $startDate); $tpl->assign('to', _('to')); $tpl->assign('date_end', $endDate); $tpl->assign('period', $period); $tpl->assign('host_id', $id); $tpl->assign('Alert', _('Alert')); /* * Ajax TimeLine and CSV export initialization * CSV export */ $tpl->assign( 'link_csv_url', './include/reporting/dashboard/csvExport/csv_HostLogs.php?host=' . $id . '&start=' . $startDate . '&end=' . $endDate ); $tpl->assign('link_csv_name', _('Export in CSV format')); // Status colors $color = substr($colors['up'], 1) . ':' . substr($colors['down'], 1) . ':' . substr($colors['unreachable'], 1) . ':' . substr($colors['undetermined'], 1) . ':' . substr($colors['maintenance'], 1); // Ajax timeline $type = 'Host'; include './include/reporting/dashboard/ajaxReporting_js.php'; } else { ?><script type="text/javascript"> function initTimeline() {;} </script> <?php } $tpl->assign('resumeTitle', _('Host state')); // Rendering Forms $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formPeriod->accept($renderer); $tpl->assign('formPeriod', $renderer->toArray()); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formHost->accept($renderer); $tpl->assign('formHost', $renderer->toArray()); if ( ! $formPeriod->isSubmitted() || ($formPeriod->isSubmitted() && $formPeriod->validate()) ) { $tpl->display('template/viewHostLog.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/reporting/dashboard/viewHostGroupLog.php
centreon/www/include/reporting/dashboard/viewHostGroupLog.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; } // Required files require_once './include/reporting/dashboard/initReport.php'; // Getting hostgroup to report $id = filter_var($_GET['item'] ?? $_POST['itemElement'] ?? false, FILTER_VALIDATE_INT); /* * Formulary * * Hostgroup Selection * */ $formHostGroup = new HTML_QuickFormCustom('formHostGroup', 'post', '?p=' . $p); $redirect = $formHostGroup->addElement('hidden', 'o'); $redirect->setValue($o); $hostsGroupRoute = ['datasourceOrigin' => 'ajax', 'multiple' => false, 'linkedObject' => 'centreonHostgroups', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_hostgroup&action=list', 'defaultDatasetRoute' => './api/internal.php?object=centreon_configuration_hostgroup' . '&action=defaultValues&target=service&field=service_hgPars&id=' . $id]; $hostGroupSelectBox = $formPeriod->addElement( 'select2', 'itemElement', _('Host Group'), [], $hostsGroupRoute ); $hostGroupSelectBox->addJsCallback( 'change', 'this.form.submit();' ); $formHostGroup->addElement( 'hidden', 'period', $period ); $formHostGroup->addElement( 'hidden', 'StartDate', $get_date_start ); $formHostGroup->addElement( 'hidden', 'EndDate', $get_date_end ); if (isset($id)) { $formPeriod->setDefaults(['itemElement' => $id]); } // Set hostgroup id with period selection form if ($id !== false) { $formPeriod->addElement('hidden', 'item', $id); /* * Stats Display for selected hostgroup * Getting periods values */ $dates = getPeriodToReport('alternate'); $start_date = $dates[0]; $end_date = $dates[1]; // Getting hostgroup and his hosts stats $hostgroupStats = []; $hostgroupStats = getLogInDbForHostGroup($id, $start_date, $end_date, $reportingTimePeriod); // Chart datas $tpl->assign('hostgroup_up', $hostgroupStats['average']['UP_TP']); $tpl->assign('hostgroup_down', $hostgroupStats['average']['DOWN_TP']); $tpl->assign('hostgroup_unreachable', $hostgroupStats['average']['UNREACHABLE_TP']); $tpl->assign('hostgroup_undetermined', $hostgroupStats['average']['UNDETERMINED_TP']); $tpl->assign('hostgroup_maintenance', $hostgroupStats['average']['MAINTENANCE_TP']); // Exporting variables for ihtml $tpl->assign('totalAlert', $hostgroupStats['average']['TOTAL_ALERTS']); $tpl->assign('summary', $hostgroupStats['average']); // removing average infos from table $hostgroupFinalStats = []; foreach ($hostgroupStats as $key => $value) { if ($key != 'average') { $hostgroupFinalStats[$key] = $value; } } $tpl->assign('components', $hostgroupFinalStats); $tpl->assign('period_name', _('From')); $tpl->assign('date_start', $start_date); $tpl->assign('to', _('to')); $tpl->assign('date_end', $end_date); $tpl->assign('period', $period); $formPeriod->setDefaults(['period' => $period]); $tpl->assign('hostgroup_id', $id); $tpl->assign('Alert', _('Alert')); /* * Ajax timeline and CSV export initialization * CSV export */ $tpl->assign( 'link_csv_url', './include/reporting/dashboard/csvExport/csv_HostGroupLogs.php?hostgroup=' . $id . '&start=' . $start_date . '&end=' . $end_date ); $tpl->assign('link_csv_name', _('Export in CSV format')); // Status colors $color = substr($colors['up'], 1) . ':' . substr($colors['down'], 1) . ':' . substr($colors['unreachable'], 1) . ':' . substr($colors['maintenance'], 1) . ':' . substr($colors['undetermined'], 1); // Ajax timeline $type = 'HostGroup'; include './include/reporting/dashboard/ajaxReporting_js.php'; } else { ?><script type="text/javascript"> function initTimeline() {;} </script><?php } $tpl->assign('resumeTitle', _('Hosts group state')); // Rendering Forms $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formPeriod->accept($renderer); $tpl->assign('formPeriod', $renderer->toArray()); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $formHostGroup->accept($renderer); $tpl->assign('formHostGroup', $renderer->toArray()); if ( ! $formPeriod->isSubmitted() || ($formPeriod->isSubmitted() && $formPeriod->validate()) ) { $tpl->display('template/viewHostGroupLog.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/reporting/dashboard/DB-Func.php
centreon/www/include/reporting/dashboard/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 * */ // returns days of week taken in account for reporting in a string function getReportDaysStr($reportTimePeriod) { $tab = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; $str = ''; foreach ($tab as $key => $value) { if (isset($reportTimePeriod['report_' . $value]) && $reportTimePeriod['report_' . $value]) { if ($str != '') { $str .= ", '" . $value . "'"; } else { $str .= "'" . $value . "'"; } } } if ($str == '') { $str = 'NULL'; } return $str; } /* * Return a table a (which reference is given in parameter) that * contains stats on a given host defined by $host_id */ function getLogInDbForHost($host_id, $start_date, $end_date, $reportTimePeriod) { global $pearDBO; // Initialising hosts stats values to 0 foreach (getHostStatsValueName() as $name) { $hostStats[$name] = 0; } $days_of_week = getReportDaysStr($reportTimePeriod); $rq = 'SELECT sum(`UPnbEvent`) as UP_A, sum(`UPTimeScheduled`) as UP_T, ' . ' sum(`DOWNnbEvent`) as DOWN_A, sum(`DOWNTimeScheduled`) as DOWN_T, ' . ' sum(`UNREACHABLEnbEvent`) as UNREACHABLE_A, sum(`UNREACHABLETimeScheduled`) as UNREACHABLE_T, ' . ' sum(`UNDETERMINEDTimeScheduled`) as UNDETERMINED_T, ' . ' sum(`MaintenanceTime`) as MAINTENANCE_T ' . 'FROM `log_archive_host` ' . 'WHERE `host_id` = ' . $host_id . ' AND `date_start` >= ' . $start_date . ' AND `date_end` <= ' . $end_date . ' ' . "AND DATE_FORMAT( FROM_UNIXTIME( `date_start`), '%W') IN (" . $days_of_week . ') ' . 'GROUP BY `host_id` '; $dbResult = $pearDBO->query($rq); if ($row = $dbResult->fetch()) { $hostStats = $row; } /* * If there where no log in several days for this host, there is no * entry in log_archive_host for these days * So the following instructions count these missing days as undetermined time */ $timeTab = getTotalTimeFromInterval($start_date, $end_date, $reportTimePeriod); if ($timeTab['reportTime'] > 0) { $hostStats['UNDETERMINED_T'] += $timeTab['reportTime'] - ($hostStats['UP_T'] + $hostStats['DOWN_T'] + $hostStats['UNREACHABLE_T'] + $hostStats['UNDETERMINED_T'] + $hostStats['MAINTENANCE_T']); } else { $hostStats['UNDETERMINED_T'] = $timeTab['totalTime']; } // Calculate percentage of time (_TP => Total time percentage) for each status $time = $hostStats['TOTAL_TIME'] = $hostStats['UP_T'] + $hostStats['DOWN_T'] + $hostStats['UNREACHABLE_T'] + $hostStats['UNDETERMINED_T'] + $hostStats['MAINTENANCE_T']; $hostStats['UP_TP'] = round($hostStats['UP_T'] / $time * 100, 2); $hostStats['DOWN_TP'] = round($hostStats['DOWN_T'] / $time * 100, 2); $hostStats['UNREACHABLE_TP'] = round($hostStats['UNREACHABLE_T'] / $time * 100, 2); $hostStats['UNDETERMINED_TP'] = round($hostStats['UNDETERMINED_T'] / $time * 100, 2); $hostStats['MAINTENANCE_TP'] = round($hostStats['MAINTENANCE_T'] / $time * 100, 2); // Calculate percentage of time (_MP => Mean Time percentage) for each status ignoring undetermined time $time = $hostStats['MEAN_TIME'] = $hostStats['UP_T'] + $hostStats['DOWN_T'] + $hostStats['UNREACHABLE_T']; if ($time <= 0) { $hostStats['UP_MP'] = 0; $hostStats['DOWN_MP'] = 0; $hostStats['UNREACHABLE_MP'] = 0; } else { $hostStats['UP_MP'] = round($hostStats['UP_T'] / $time * 100, 2); $hostStats['DOWN_MP'] = round($hostStats['DOWN_T'] / $time * 100, 2); $hostStats['UNREACHABLE_MP'] = round($hostStats['UNREACHABLE_T'] / $time * 100, 2); } // Format time for each status (_TF => Time Formated), total time and mean time $hostStats['MEAN_TIME_F'] = getTimeString($hostStats['MEAN_TIME'], $reportTimePeriod); $hostStats['TOTAL_TIME_F'] = getTimeString($hostStats['TOTAL_TIME'], $reportTimePeriod); $hostStats['UP_TF'] = getTimeString($hostStats['UP_T'], $reportTimePeriod); $hostStats['DOWN_TF'] = getTimeString($hostStats['DOWN_T'], $reportTimePeriod); $hostStats['UNREACHABLE_TF'] = getTimeString($hostStats['UNREACHABLE_T'], $reportTimePeriod); $hostStats['UNDETERMINED_TF'] = getTimeString($hostStats['UNDETERMINED_T'], $reportTimePeriod); $hostStats['MAINTENANCE_TF'] = getTimeString($hostStats['MAINTENANCE_T'], $reportTimePeriod); // Number Total of alerts $hostStats['TOTAL_ALERTS'] = $hostStats['UP_A'] + $hostStats['DOWN_A'] + $hostStats['UNREACHABLE_A']; return $hostStats; } /* * Return a table ($hostgroupStats) that contains availability (average with availability of all hosts from hostgroup) * and alerts (the sum of alerts of all hosts from hostgroup) for given hostgroup defined by $hostgroup_id */ function getLogInDbForHostGroup($hostgroup_id, $start_date, $end_date, $reportTimePeriod) { global $centreon; $hostStatsLabels = getHostStatsValueName(); // Initialising hostgroup stats to 0 foreach ($hostStatsLabels as $name) { $hostgroupStats['average'][$name] = 0; } $hosts_id = $centreon->user->access->getHostHostGroupAclConf($hostgroup_id, 'broker'); if (count($hosts_id) == 0) { $hostgroupStats['average']['UNDETERMINED_TP'] = 100; return $hostgroupStats; } // get availability stats for each host $count = 0; foreach ($hosts_id as $hostId => $host_name) { $host_stats = []; $host_stats = getLogInDbForHost($hostId, $start_date, $end_date, $reportTimePeriod); $hostgroupStats[$hostId] = $host_stats; $hostgroupStats[$hostId]['NAME'] = $host_name; $hostgroupStats[$hostId]['ID'] = $hostId; foreach ($hostStatsLabels as $name) { $hostgroupStats['average'][$name] += $host_stats[$name]; } $count++; } // the hostgroup availability is the average availability of all host from the the hostgroup foreach ($hostStatsLabels as $name) { if ( $name == 'UP_T' || $name == 'DOWN_T' || $name == 'UNREACHABLE_T' || $name == 'UNDETERMINED_T' || $name == 'MAINTENANCE_T' ) { $hostgroupStats['average'][$name] /= $count; } } // Calculate percentage of time (_TP => Total time percentage) for each status $hostgroupStats['average']['TOTAL_TIME'] = $hostgroupStats['average']['UP_T'] + $hostgroupStats['average']['DOWN_T'] + $hostgroupStats['average']['UNREACHABLE_T'] + $hostgroupStats['average']['UNDETERMINED_T'] + $hostgroupStats['average']['MAINTENANCE_T']; $time = $hostgroupStats['average']['TOTAL_TIME']; $hostgroupStats['average']['UP_TP'] = round($hostgroupStats['average']['UP_T'] / $time * 100, 2); $hostgroupStats['average']['DOWN_TP'] = round($hostgroupStats['average']['DOWN_T'] / $time * 100, 2); $hostgroupStats['average']['UNREACHABLE_TP'] = round($hostgroupStats['average']['UNREACHABLE_T'] / $time * 100, 2); $hostgroupStats['average']['UNDETERMINED_TP'] = round($hostgroupStats['average']['UNDETERMINED_T'] / $time * 100, 2); $hostgroupStats['average']['MAINTENANCE_TP'] = round($hostgroupStats['average']['MAINTENANCE_T'] / $time * 100, 2); // Calculate percentage of time (_MP => Mean Time percentage) for each status ignoring undetermined time $hostgroupStats['average']['MEAN_TIME'] = $hostgroupStats['average']['UP_T'] + $hostgroupStats['average']['DOWN_T'] + $hostgroupStats['average']['UNREACHABLE_T']; $time = $hostgroupStats['average']['MEAN_TIME']; if ($time <= 0) { $hostgroupStats['average']['UP_MP'] = 0; $hostgroupStats['average']['DOWN_MP'] = 0; $hostgroupStats['average']['UNREACHABLE_MP'] = 0; } else { $hostgroupStats['average']['UP_MP'] = round($hostgroupStats['average']['UP_T'] / $time * 100, 2); $hostgroupStats['average']['DOWN_MP'] = round($hostgroupStats['average']['DOWN_T'] / $time * 100, 2); $hostgroupStats['average']['UNREACHABLE_MP'] = round($hostgroupStats['average']['UNREACHABLE_T'] / $time * 100, 2); } // Number Total of alerts $hostgroupStats['average']['TOTAL_ALERTS'] = $hostgroupStats['average']['UP_A'] + $hostgroupStats['average']['DOWN_A'] + $hostgroupStats['average']['UNREACHABLE_A']; return $hostgroupStats; } /* * Return a table a (which reference is given in parameter) * that contains stats on services for a given host defined by $host_id */ function getLogInDbForHostSVC($host_id, $start_date, $end_date, $reportTimePeriod) { global $centreon, $pearDBO; $hostServiceStats = []; $services_ids = []; // Getting authorized services $services_ids = $centreon->user->access->getHostServiceAclConf($host_id, 'broker'); $svcStr = ''; $status = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN', 'UNDETERMINED', 'MAINTENANCE']; // $hostServiceStats["average"] will contain services stats average foreach ($status as $name) { switch ($name) { case 'UNDETERMINED': $hostServiceStats['average']['UNDETERMINED_TP'] = 0; break; case 'MAINTENANCE': $hostServiceStats['average']['MAINTENANCE_TP'] = 0; break; default: $hostServiceStats['average'][$name . '_MP'] = 0; $hostServiceStats['average'][$name . '_TP'] = 0; $hostServiceStats['average'][$name . '_A'] = 0; break; } } $hostServiceStats['average']['DESCRIPTION'] = ''; $hostServiceStats['average']['ID'] = 0; if (count($services_ids) > 0) { foreach ($services_ids as $id => $description) { if ($svcStr) { $svcStr .= ', '; } $svcStr .= $id; } } else { $hostServiceStats['average']['UNDETERMINED_TP'] = 100; return $hostServiceStats; } // initialising all host services stats to 0 foreach ($services_ids as $id => $description) { foreach (getServicesStatsValueName() as $name) { $hostServiceStats[$id][$name] = 0; } } $days_of_week = getReportDaysStr($reportTimePeriod); $aclCondition = ''; if (! $centreon->user->admin) { $aclCondition = 'AND EXISTS (SELECT 1 FROM centreon_acl acl ' . 'WHERE las.host_id = acl.host_id AND las.service_id = acl.service_id ' . 'AND acl.group_id IN (' . $centreon->user->access->getAccessGroupsString() . ') LIMIT 1)'; } $rq = 'SELECT DISTINCT las.service_id, ' . 'sum(OKTimeScheduled) as OK_T, ' . 'sum(OKnbEvent) as OK_A, ' . 'sum(WARNINGTimeScheduled) as WARNING_T, ' . 'sum(WARNINGnbEvent) as WARNING_A, ' . 'sum(UNKNOWNTimeScheduled) as UNKNOWN_T, ' . 'sum(UNKNOWNnbEvent) as UNKNOWN_A, ' . 'sum(CRITICALTimeScheduled) as CRITICAL_T, ' . 'sum(CRITICALnbEvent) as CRITICAL_A, ' . 'sum(UNDETERMINEDTimeScheduled) as UNDETERMINED_T, ' . 'sum(MaintenanceTime) as MAINTENANCE_T ' . 'FROM log_archive_service las ' . 'WHERE las.host_id = ' . $host_id . ' ' . $aclCondition . ' ' . 'AND date_start >= ' . $start_date . ' AND date_end <= ' . $end_date . ' ' . "AND DATE_FORMAT(FROM_UNIXTIME(date_start), '%W') IN (" . $days_of_week . ') ' . 'GROUP BY las.service_id '; $dbResult = $pearDBO->query($rq); while ($row = $dbResult->fetch()) { if (isset($hostServiceStats[$row['service_id']])) { $hostServiceStats[$row['service_id']] = $row; } } $i = 0; foreach ($services_ids as $id => $description) { $hostServiceStats[$id]['DESCRIPTION'] = $description; $hostServiceStats[$id]['ID'] = $id; $timeTab = getTotalTimeFromInterval($start_date, $end_date, $reportTimePeriod); if ($timeTab['reportTime']) { $hostServiceStats[$id]['UNDETERMINED_T'] += $timeTab['reportTime'] - ($hostServiceStats[$id]['OK_T'] + $hostServiceStats[$id]['WARNING_T'] + $hostServiceStats[$id]['CRITICAL_T'] + $hostServiceStats[$id]['UNKNOWN_T'] + $hostServiceStats[$id]['UNDETERMINED_T'] + $hostServiceStats[$id]['MAINTENANCE_T']); } else { foreach ($status as $value) { $hostServiceStats[$id][$value . '_T'] = 0; } $hostServiceStats[$id]['UNDETERMINED_T'] = $timeTab['totalTime']; } // Calculate percentage of time (_TP => Total time percentage) for each status $hostServiceStats[$id]['TOTAL_TIME'] = $hostServiceStats[$id]['OK_T'] + $hostServiceStats[$id]['WARNING_T'] + $hostServiceStats[$id]['CRITICAL_T'] + $hostServiceStats[$id]['UNKNOWN_T'] + $hostServiceStats[$id]['UNDETERMINED_T'] + $hostServiceStats[$id]['MAINTENANCE_T']; $time = $hostServiceStats[$id]['TOTAL_TIME']; foreach ($status as $value) { $hostServiceStats[$id][$value . '_TP'] = round($hostServiceStats[$id][$value . '_T'] / $time * 100, 2); } // The same percentage (_MP => Mean Time percentage) is calculated ignoring undetermined time $hostServiceStats[$id]['MEAN_TIME'] = $hostServiceStats[$id]['OK_T'] + $hostServiceStats[$id]['WARNING_T'] + $hostServiceStats[$id]['CRITICAL_T'] + $hostServiceStats[$id]['UNKNOWN_T']; $time = $hostServiceStats[$id]['MEAN_TIME']; if ($hostServiceStats[$id]['MEAN_TIME'] <= 0) { foreach ($status as $value) { $hostServiceStats[$id][$value . '_MP'] = 0; } } else { foreach ($status as $value) { if ($value != 'UNDETERMINED') { $hostServiceStats[$id][$value . '_MP'] = round( $hostServiceStats[$id][$value . '_T'] / $time * 100, 2 ); } } } // Format time for each status (_TF => Time Formated), mean time and total time $hostServiceStats[$id]['MEAN_TIME_F'] = getTimeString($hostServiceStats[$id]['MEAN_TIME'], $reportTimePeriod); $hostServiceStats[$id]['TOTAL_TIME_F'] = getTimeString($hostServiceStats[$id]['TOTAL_TIME'], $reportTimePeriod); foreach ($status as $value) { $hostServiceStats[$id][$value . '_TF'] = getTimeString($hostServiceStats[$id][$value . '_T'], $reportTimePeriod); } // Services status time sum and alerts sum foreach ($status as $value) { $hostServiceStats['average'][$value . '_TP'] += $hostServiceStats[$id][$value . '_TP']; if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $hostServiceStats['average'][$value . '_MP'] += $hostServiceStats[$id][$value . '_MP']; $hostServiceStats['average'][$value . '_A'] += $hostServiceStats[$id][$value . '_A']; } } $i++; } // Services status time average if ($i) { foreach ($status as $value) { $hostServiceStats['average'][$value . '_TP'] = round($hostServiceStats['average'][$value . '_TP'] / $i, 2); if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $hostServiceStats['average'][$value . '_MP'] = round( $hostServiceStats['average'][$value . '_MP'] / $i, 2 ); } } } return $hostServiceStats; } /* * Return a table a (which reference is given in parameter) that contains stats * on services for a given host defined by $host_id and $service_id * me must specify the host id because one service can be linked to many hosts * * @param int $servicegroupId * @param int $startDate * @param int $endDate * @param array $reportTimePeriod * @return array */ function getServicesLogs(array $services, $startDate, $endDate, $reportTimePeriod) { global $pearDBO, $centreon; if ($services === []) { return []; } $status = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN', 'UNDETERMINED', 'MAINTENANCE']; foreach (getServicesStatsValueName() as $name) { $serviceStats[$name] = 0; } $daysOfWeek = getReportDaysStr($reportTimePeriod); $aclCondition = ''; if (! $centreon->user->admin) { $aclCondition = 'AND EXISTS (SELECT * FROM centreon_acl acl ' . 'WHERE las.host_id = acl.host_id AND las.service_id = acl.service_id ' . 'AND acl.group_id IN (' . $centreon->user->access->getAccessGroupsString() . ') )'; } $bindValues = [ ':startDate' => [PDO::PARAM_STR, $startDate], ':endDate' => [PDO::PARAM_STR, $endDate], ]; $servicesConditions = []; foreach ($services as $index => $service) { $servicesConditions[] = "(las.host_id = :host{$index} AND las.service_id = :service{$index})"; $bindValues[':host' . $index] = [PDO::PARAM_INT, $service['hostId']]; $bindValues[':service' . $index] = [PDO::PARAM_INT, $service['serviceId']]; } $servicesSubquery = 'AND (' . implode(' OR ', $servicesConditions) . ')'; // Use "like" instead of "=" to avoid mysql bug on partitioned tables $rq = 'SELECT DISTINCT las.host_id, las.service_id, sum(OKTimeScheduled) as OK_T, sum(OKnbEvent) as OK_A, ' . 'sum(WARNINGTimeScheduled) as WARNING_T, sum(WARNINGnbEvent) as WARNING_A, ' . 'sum(UNKNOWNTimeScheduled) as UNKNOWN_T, sum(UNKNOWNnbEvent) as UNKNOWN_A, ' . 'sum(CRITICALTimeScheduled) as CRITICAL_T, sum(CRITICALnbEvent) as CRITICAL_A, ' . 'sum(UNDETERMINEDTimeScheduled) as UNDETERMINED_T, ' . 'sum(MaintenanceTime) as MAINTENANCE_T ' . 'FROM log_archive_service las ' . 'WHERE `date_start` >= :startDate ' . 'AND date_end <= :endDate ' . $aclCondition . ' ' . $servicesSubquery . ' ' . "AND DATE_FORMAT(FROM_UNIXTIME(date_start), '%W') IN (" . $daysOfWeek . ') ' . 'GROUP BY las.host_id, las.service_id'; $statement = $pearDBO->prepare($rq); foreach ($bindValues as $bindName => $bindParams) { [$bindType, $bindValue] = $bindParams; $statement->bindValue($bindName, $bindValue, $bindType); } $statement->execute(); $servicesStats = []; $timeTab = getTotalTimeFromInterval($startDate, $endDate, $reportTimePeriod); while ($serviceStats = $statement->fetch()) { if ($timeTab['reportTime']) { $serviceStats['UNDETERMINED_T'] += $timeTab['reportTime'] - ($serviceStats['OK_T'] + $serviceStats['WARNING_T'] + $serviceStats['CRITICAL_T'] + $serviceStats['UNKNOWN_T'] + $serviceStats['UNDETERMINED_T'] + $serviceStats['MAINTENANCE_T']); } else { foreach ($status as $key => $value) { $serviceStats[$value . '_T'] = 0; } $serviceStats['UNDETERMINED_T'] = $timeTab['totalTime']; } // Calculate percentage of time (_TP => Total time percentage) for each status $serviceStats['TOTAL_TIME'] = $serviceStats['OK_T'] + $serviceStats['WARNING_T'] + $serviceStats['CRITICAL_T'] + $serviceStats['UNKNOWN_T'] + $serviceStats['UNDETERMINED_T'] + $serviceStats['MAINTENANCE_T']; $time = $serviceStats['TOTAL_TIME']; foreach ($status as $value) { $serviceStats[$value . '_TP'] = round($serviceStats[$value . '_T'] / $time * 100, 2); } // The same percentage (_MP => Mean Time percentage) is calculated ignoring undetermined time $serviceStats['MEAN_TIME'] = $serviceStats['OK_T'] + $serviceStats['WARNING_T'] + $serviceStats['CRITICAL_T'] + $serviceStats['UNKNOWN_T']; $time = $serviceStats['MEAN_TIME']; if ($serviceStats['MEAN_TIME'] <= 0) { foreach ($status as $value) { if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $serviceStats[$value . '_MP'] = 0; } } } else { foreach ($status as $value) { if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $serviceStats[$value . '_MP'] = round($serviceStats[$value . '_T'] / $time * 100, 2); } } } // Format time for each status (_TF => Time Formated), mean time and total time $serviceStats['MEAN_TIME_F'] = getTimeString($serviceStats['MEAN_TIME'], $reportTimePeriod); $serviceStats['TOTAL_TIME_F'] = getTimeString($serviceStats['TOTAL_TIME'], $reportTimePeriod); foreach ($status as $value) { $serviceStats[$value . '_TF'] = getTimeString($serviceStats[$value . '_T'], $reportTimePeriod); } $serviceStats['TOTAL_ALERTS'] = $serviceStats['OK_A'] + $serviceStats['WARNING_A'] + $serviceStats['CRITICAL_A'] + $serviceStats['UNKNOWN_A']; $servicesStats[$serviceStats['host_id']][$serviceStats['service_id']] = $serviceStats; } return $servicesStats; } /* * Return a table ($serviceGroupStats) that contains availability * (average with availability of all services from servicegroup) * and alerts (the sum of alerts of all services from servicegroup) for given servicegroup defined by $servicegroup_id * * @param int $servicegroupId * @param int $startDate * @param int $endDate * @param array $reportTimePeriod * @return array */ function getLogInDbForServicesGroup($servicegroupId, $startDate, $endDate, $reportTimePeriod) { $serviceStatsLabels = getServicesStatsValueName(); $status = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN', 'UNDETERMINED', 'MAINTENANCE']; // Initialising servicegroup stats to 0 foreach ($serviceStatsLabels as $name) { $serviceGroupStats['average'][$name] = 0; } // $count count the number of services in servicegroup $count = 0; $services = getServiceGroupActivateServices($servicegroupId); if (empty($services)) { $serviceGroupStats['average']['UNDETERMINED_TP'] = 100; return $serviceGroupStats; } $servicesParameter = []; foreach ($services as $service) { $servicesParameter[] = [ 'hostId' => $service['host_id'], 'serviceId' => $service['service_id'], ]; } $servicesStats = getServicesLogs( $servicesParameter, $startDate, $endDate, $reportTimePeriod ); foreach ($services as $hostServiceid => $service) { $hostId = $service['host_id']; $serviceId = $service['service_id']; foreach ($serviceStatsLabels as $name) { $serviceGroupStats[$hostServiceid][$name] = 0; } if (isset($servicesStats[$hostId][$serviceId])) { $serviceGroupStats[$hostServiceid] = $servicesStats[$hostId][$serviceId]; foreach ($serviceStatsLabels as $name) { $serviceGroupStats['average'][$name] += $servicesStats[$hostId][$serviceId][$name]; } } else { $serviceGroupStats['average']['UNDETERMINED_TP'] = 100; } $serviceGroupStats[$hostServiceid]['HOST_ID'] = $hostId; $serviceGroupStats[$hostServiceid]['SERVICE_ID'] = $serviceId; $serviceGroupStats[$hostServiceid]['HOST_NAME'] = $service['host_name']; $serviceGroupStats[$hostServiceid]['SERVICE_DESC'] = $service['service_description']; $count++; } if (! isset($servicesStats[$hostId][$serviceId])) { return $serviceGroupStats; } // Average time for all status (OK, Critical, Warning, Unknown) foreach ($serviceStatsLabels as $name) { if ( $name == 'OK_T' || $name == 'WARNING_T' || $name == 'CRITICAL_T' || $name == 'UNKNOWN_T' || $name == 'UNDETERMINED_T' || $name == 'MAINTENANCE_T' ) { if ($count) { $serviceGroupStats['average'][$name] /= $count; } else { $serviceGroupStats['average'][$name] = 0; } } } // Calculate percentage of time (_TP => Total time percentage) for each status $serviceGroupStats['average']['TOTAL_TIME'] = $serviceGroupStats['average']['OK_T'] + $serviceGroupStats['average']['WARNING_T'] + $serviceGroupStats['average']['CRITICAL_T'] + $serviceGroupStats['average']['UNKNOWN_T'] + $serviceGroupStats['average']['UNDETERMINED_T'] + $serviceGroupStats['average']['MAINTENANCE_T']; $time = $serviceGroupStats['average']['TOTAL_TIME']; foreach ($status as $value) { if ($time) { $serviceGroupStats['average'][$value . '_TP'] = round($serviceGroupStats['average'][$value . '_T'] / $time * 100, 2); } else { $serviceGroupStats['average'][$value . '_TP'] = 0; } } // Calculate percentage of time (_MP => Mean Time percentage) for each status ignoring undetermined time $serviceGroupStats['average']['MEAN_TIME'] = $serviceGroupStats['average']['OK_T'] + $serviceGroupStats['average']['WARNING_T'] + $serviceGroupStats['average']['CRITICAL_T'] + $serviceGroupStats['average']['UNKNOWN_T']; // Calculate total of alerts $serviceGroupStats['average']['TOTAL_ALERTS'] = $serviceGroupStats['average']['OK_A'] + $serviceGroupStats['average']['WARNING_A'] + $serviceGroupStats['average']['CRITICAL_A'] + $serviceGroupStats['average']['UNKNOWN_A']; $time = $serviceGroupStats['average']['MEAN_TIME']; if ($time <= 0) { foreach ($status as $value) { if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $serviceGroupStats['average'][$value . '_MP'] = 0; } } } else { foreach ($status as $value) { if ($value != 'UNDETERMINED' && $value != 'MAINTENANCE') { $serviceGroupStats['average'][$value . '_MP'] = round($serviceGroupStats['average'][$value . '_T'] / $time * 100, 2); } } } return $serviceGroupStats; } // Returns all activated services from a servicegroup including services by host and services by hostgroup function getServiceGroupActivateServices($sgId = null) { global $centreon; if (! $sgId) { return; } $svs = $centreon->user->access->getServiceServiceGroupAclConf($sgId, 'broker'); return $svs; } /* * Get timeperiods to take in account to retrieve log from nagios * report_hour_start, report_minute_start, report_hour_end, report_hour_end => restrict to a time period in given day * report_Monday, report_Tuesday, report_Wednesday, * report_Thursday, report_Friday, report_Sunday => days for which we can retrieve logs */ function getreportingTimePeriod() { global $pearDB; $reportingTimePeriod = []; $query = 'SELECT * FROM `contact_param` WHERE cp_contact_id is null'; $dbResult = $pearDB->query($query); while ($res = $dbResult->fetch()) { if ($res['cp_key'] == 'report_hour_start') { $reportingTimePeriod['report_hour_start'] = $res['cp_value']; } if ($res['cp_key'] == 'report_minute_start') { $reportingTimePeriod['report_minute_start'] = $res['cp_value']; } if ($res['cp_key'] == 'report_hour_end') { $reportingTimePeriod['report_hour_end'] = $res['cp_value']; } if ($res['cp_key'] == 'report_minute_end') { $reportingTimePeriod['report_minute_end'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Monday') { $reportingTimePeriod['report_Monday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Tuesday') { $reportingTimePeriod['report_Tuesday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Wednesday') { $reportingTimePeriod['report_Wednesday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Thursday') { $reportingTimePeriod['report_Thursday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Friday') { $reportingTimePeriod['report_Friday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Saturday') { $reportingTimePeriod['report_Saturday'] = $res['cp_value']; } if ($res['cp_key'] == 'report_Sunday') { $reportingTimePeriod['report_Sunday'] = $res['cp_value']; } } return $reportingTimePeriod; } // Functions to get objects names from their ID function getHostNameFromId($host_id) { global $pearDB; $req = 'SELECT `host_name` FROM `host` WHERE `host_id` = ' . $host_id; $dbResult = $pearDB->query($req); if ($row = $dbResult->fetch()) { return $row['host_name']; } return 'undefined'; } function getHostgroupNameFromId($hostgroup_id) { global $pearDB; $req = 'SELECT `hg_name` FROM `hostgroup` WHERE `hg_id` = ' . $hostgroup_id; $dbResult = $pearDB->query($req); if ($row = $dbResult->fetch()) { return $row['hg_name']; } return 'undefined'; } function getServiceDescriptionFromId($service_id) { global $pearDB; $req = 'SELECT `service_description` FROM `service` WHERE `service_id` = ' . $service_id; $dbResult = $pearDB->query($req); if ($row = $dbResult->fetch()) { return $row['service_description']; } return 'undefined'; } function getServiceGroupNameFromId($sg_id) { global $pearDB; $req = 'SELECT `sg_name` FROM `servicegroup` WHERE `sg_id` = ' . $sg_id; $dbResult = $pearDB->query($req); unset($req); if ($row = $dbResult->fetch()) { return $row['sg_name']; } $dbResult->closeCursor(); return 'undefined'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/csvExport/csv_ServiceGroupLogs.php
centreon/www/include/reporting/dashboard/csvExport/csv_ServiceGroupLogs.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 _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/common-Func.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.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/centreonDuration.class.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/DB-Func.php'; // DB Connexion $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); if (! isset($_SESSION['centreon'])) { CentreonSession::start(); if (! CentreonSession::checkSession(session_id(), $pearDB)) { echo 'Bad Session'; exit(); } } $sid = session_id(); if (! empty($sid) && isset($_SESSION['centreon'])) { $oreon = $_SESSION['centreon']; $res = $pearDB->prepare('SELECT COUNT(*) as count FROM session WHERE user_id = :id'); $res->bindValue(':id', (int) $oreon->user->user_id, PDO::PARAM_INT); $res->execute(); $row = $res->fetch(PDO::FETCH_ASSOC); if ($row['count'] < 1) { get_error('bad session id'); } } else { get_error('need session id!'); } $centreon = $oreon; $servicegroupId = filter_var( $_GET['servicegroup'] ?? $_POST['servicegroup'] ?? null, FILTER_VALIDATE_INT ); // finding the user's allowed servicegroup $allowedServicegroup = $centreon->user->access->getServiceGroupAclConf(null, 'broker'); // checking if the user has ACL rights for this resource if (! $centreon->user->admin && $servicegroupId !== null && ! array_key_exists($servicegroupId, $allowedServicegroup) ) { echo '<div align="center" style="color:red">' . '<b>You are not allowed to access this service group</b></div>'; exit(); } // Getting time interval to report $dates = getPeriodToReport(); $startDate = htmlentities($_GET['start'], ENT_QUOTES, 'UTF-8'); $endDate = htmlentities($_GET['end'], ENT_QUOTES, 'UTF-8'); $servicegroupName = getServiceGroupNameFromId($servicegroupId); // file type setting header('Cache-Control: public'); header('Pragma: public'); header('Content-Type: application/octet-stream'); header('Content-disposition: filename=' . $servicegroupName . '.csv'); echo _('ServiceGroup') . ';' . _('Begin date') . '; ' . _('End date') . '; ' . _('Duration') . "\n"; echo $servicegroupName . ';' . date(_('d/m/Y H:i:s'), $startDate) . '; ' . date(_('d/m/Y H:i:s'), $endDate) . '; ' . ($endDate - $startDate) . "s\n\n"; echo "\n"; $stringMeanTime = _('Mean Time'); $stringAlert = _('Alert'); $stringOk = _('OK'); $stringWarning = _('Warning'); $stringCritical = _('Critical'); $stringUnknown = _('Unknown'); $stringDowntime = _('Scheduled Downtimes'); $stringUndetermined = _('Undetermined'); // Getting service group start $reportingTimePeriod = getreportingTimePeriod(); $stats = []; $stats = getLogInDbForServicesGroup( $servicegroupId, $startDate, $endDate, $reportingTimePeriod ); echo _('Status') . ';' . _('Total Time') . ';' . $stringMeanTime . ';' . $stringAlert . "\n"; echo $stringOk . ';' . $stats['average']['OK_TP'] . '%;' . $stats['average']['OK_MP'] . '%;' . $stats['average']['OK_A'] . ";\n"; echo $stringWarning . ';' . $stats['average']['WARNING_TP'] . '%;' . $stats['average']['WARNING_MP'] . '%;' . $stats['average']['WARNING_A'] . ";\n"; echo $stringCritical . ';' . $stats['average']['CRITICAL_TP'] . '%;' . $stats['average']['CRITICAL_MP'] . '%;' . $stats['average']['CRITICAL_A'] . ";\n"; echo $stringUnknown . ';' . $stats['average']['UNKNOWN_TP'] . '%;' . $stats['average']['UNKNOWN_MP'] . '%;' . $stats['average']['UNKNOWN_A'] . ";\n"; echo $stringDowntime . ';' . $stats['average']['MAINTENANCE_TP'] . "%;;;\n"; echo $stringUndetermined . ';' . $stats['average']['UNDETERMINED_TP'] . "%;;;\n\n"; echo "\n\n"; // Services group services stats echo _('Host') . ';' . _('Service') . ';' . $stringOk . ' %;' . $stringOk . ' ' . $stringMeanTime . ' %;' . $stringOk . ' ' . $stringAlert . ';' . $stringWarning . ' %;' . $stringWarning . ' ' . $stringMeanTime . ' %;' . $stringWarning . ' ' . $stringAlert . ';' . $stringCritical . ' %;' . $stringCritical . ' ' . $stringMeanTime . ' %;' . $stringCritical . ' ' . $stringAlert . ';' . $stringUnknown . ' %;' . $stringUnknown . $stringMeanTime . ' %;' . $stringUnknown . ' ' . $stringAlert . ';' . $stringDowntime . ' %;' . $stringUndetermined . "\n"; foreach ($stats as $key => $tab) { if ($key != 'average') { echo $tab['HOST_NAME'] . ';' . $tab['SERVICE_DESC'] . ';' . $tab['OK_TP'] . '%;' . $tab['OK_MP'] . '%;' . $tab['OK_A'] . ';' . $tab['WARNING_TP'] . '%;' . $tab['WARNING_MP'] . '%;' . $tab['WARNING_A'] . ';' . $tab['CRITICAL_TP'] . '%;' . $tab['CRITICAL_MP'] . '%;' . $tab['CRITICAL_A'] . ';' . $tab['UNKNOWN_TP'] . '%;' . $tab['UNKNOWN_MP'] . '%;' . $tab['UNKNOWN_A'] . ';' . $tab['MAINTENANCE_TP'] . ' %;' . $tab['UNDETERMINED_TP'] . "%\n"; } } echo "\n\n"; // Services group stats evolution echo _('Day') . ';' . _('Duration') . ';' . $stringOk . ' ' . $stringMeanTime . ';' . $stringOk . ' ' . $stringAlert . ';' . $stringWarning . ' ' . $stringMeanTime . ';' . $stringWarning . ' ' . $stringAlert . ';' . $stringUnknown . ' ' . $stringMeanTime . ';' . $stringUnknown . ' ' . $stringAlert . ';' . $stringCritical . ' ' . $stringMeanTime . ';' . $stringCritical . ' ' . $stringAlert . ';' . _('Day') . "\n"; $dbResult = $pearDB->prepare( 'SELECT `service_service_id` FROM `servicegroup_relation` ' . 'WHERE `servicegroup_sg_id` = :servicegroupId' ); $dbResult->bindValue(':servicegroupId', $servicegroupId, PDO::PARAM_INT); $dbResult->execute(); $str = ''; while ($sg = $dbResult->fetch()) { if ($str != '') { $str .= ', '; } $str .= "'" . $sg['service_service_id'] . "'"; } $dbResult->closeCursor(); if ($str == '') { $str = "''"; } unset($sg, $dbResult); $res = $pearDBO->prepare( 'SELECT `date_start`, `date_end`, sum(`OKnbEvent`) as OKnbEvent, ' . 'sum(`CRITICALnbEvent`) as CRITICALnbEvent, ' . 'sum(`WARNINGnbEvent`) as WARNINGnbEvent, ' . 'sum(`UNKNOWNnbEvent`) as UNKNOWNnbEvent, ' . 'avg( `OKTimeScheduled` ) as OKTimeScheduled, ' . 'avg( `WARNINGTimeScheduled` ) as WARNINGTimeScheduled, ' . 'avg( `UNKNOWNTimeScheduled` ) as UNKNOWNTimeScheduled, ' . 'avg( `CRITICALTimeScheduled` ) as CRITICALTimeScheduled ' . 'FROM `log_archive_service` WHERE `service_id` IN (' . $str . ') ' . 'AND `date_start` >= :startDate ' . 'AND `date_end` <= :endDate ' . 'GROUP BY `date_end`, `date_start` order by `date_start` desc' ); $res->bindValue(':startDate', $startDate, PDO::PARAM_INT); $res->bindValue(':endDate', $endDate, PDO::PARAM_INT); $res->execute(); $statesTab = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN']; while ($row = $res->fetch()) { $duration = $row['OKTimeScheduled'] + $row['WARNINGTimeScheduled'] + $row['UNKNOWNTimeScheduled'] + $row['CRITICALTimeScheduled']; if ($duration === 0) { continue; } // Percentage by status $row['OK_MP'] = round($row['OKTimeScheduled'] * 100 / $duration, 2); $row['WARNING_MP'] = round($row['WARNINGTimeScheduled'] * 100 / $duration, 2); $row['UNKNOWN_MP'] = round($row['UNKNOWNTimeScheduled'] * 100 / $duration, 2); $row['CRITICAL_MP'] = round($row['CRITICALTimeScheduled'] * 100 / $duration, 2); echo $row['date_start'] . ';' . $duration . 's;' . $row['OK_MP'] . '%;' . $row['OKnbEvent'] . ';' . $row['WARNING_MP'] . '%;' . $row['WARNINGnbEvent'] . ';' . $row['UNKNOWN_MP'] . '%;' . $row['UNKNOWNnbEvent'] . ';' . $row['CRITICAL_MP'] . '%;' . $row['CRITICALnbEvent'] . ';' . date('Y-m-d H:i:s', $row['date_start']) . ";\n"; } $res->closeCursor();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/csvExport/csv_ServiceLogs.php
centreon/www/include/reporting/dashboard/csvExport/csv_ServiceLogs.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 _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/common-Func.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.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/centreonDuration.class.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/DB-Func.php'; session_start(); session_write_close(); // DB connexion $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); $sid = session_id(); if (! empty($sid) && isset($_SESSION['centreon'])) { $oreon = $_SESSION['centreon']; $res = $pearDB->prepare('SELECT COUNT(*) as count FROM session WHERE user_id = :id'); $res->bindValue(':id', (int) $oreon->user->user_id, PDO::PARAM_INT); $res->execute(); $row = $res->fetch(PDO::FETCH_ASSOC); if ($row['count'] < 1) { get_error('bad session id'); } } else { get_error('need session id!'); } $centreon = $oreon; // getting host and service id $hostId = filter_var( $_GET['host'] ?? $_POST['host'] ?? null, FILTER_VALIDATE_INT ); $serviceId = filter_var( $_GET['service'] ?? $_POST['service'] ?? null, FILTER_VALIDATE_INT ); // finding the user's allowed resources $services = $centreon->user->access->getHostServiceAclConf($hostId, 'broker', null); // checking if the user has ACL rights for this resource if (! $centreon->user->admin && $serviceId !== null && (! array_key_exists($serviceId, $services)) ) { echo '<div align="center" style="color:red">' . '<b>You are not allowed to access this service</b></div>'; exit(); } // Getting time interval to report $dates = getPeriodToReport(); $startDate = htmlentities($_GET['start'], ENT_QUOTES, 'UTF-8'); $endDate = htmlentities($_GET['end'], ENT_QUOTES, 'UTF-8'); $hostName = getHostNameFromId($hostId); $serviceDescription = getServiceDescriptionFromId($serviceId); // file type setting header('Cache-Control: public'); header('Pragma: public'); header('Content-Type: application/octet-stream'); header('Content-disposition: attachment ; filename=' . $hostName . '_' . $serviceDescription . '.csv'); echo _('Host') . ';' . _('Service') . ';' . _('Begin date') . '; ' . _('End date') . '; ' . _('Duration') . "\n"; echo $hostName . '; ' . $serviceDescription . '; ' . date(_('d/m/Y H:i:s'), $startDate) . '; ' . date(_('d/m/Y H:i:s'), $endDate) . '; ' . ($endDate - $startDate) . "s\n"; echo "\n"; echo _('Status') . ';' . _('Time') . ';' . _('Total Time') . ';' . _('Mean Time') . '; ' . _('Alert') . "\n"; $reportingTimePeriod = getreportingTimePeriod(); $servicesStats = getServicesLogs( [[ 'hostId' => $hostId, 'serviceId' => $serviceId, ]], $startDate, $endDate, $reportingTimePeriod ); $serviceStats = $servicesStats[$hostId][$serviceId]; echo 'OK;' . $serviceStats['OK_T'] . 's;' . $serviceStats['OK_TP'] . '%;' . $serviceStats['OK_MP'] . '%;' . $serviceStats['OK_A'] . ";\n"; echo 'WARNING;' . $serviceStats['WARNING_T'] . 's;' . $serviceStats['WARNING_TP'] . '%;' . $serviceStats['WARNING_MP'] . '%;' . $serviceStats['WARNING_A'] . ";\n"; echo 'CRITICAL;' . $serviceStats['CRITICAL_T'] . 's;' . $serviceStats['CRITICAL_TP'] . '%;' . $serviceStats['CRITICAL_MP'] . '%;' . $serviceStats['CRITICAL_A'] . ";\n"; echo 'UNKNOWN;' . $serviceStats['UNKNOWN_T'] . 's;' . $serviceStats['UNKNOWN_TP'] . '%;' . $serviceStats['UNKNOWN_MP'] . '%;' . $serviceStats['UNKNOWN_A'] . ";\n"; echo _('SCHEDULED DOWNTIME') . ';' . $serviceStats['MAINTENANCE_T'] . 's;' . $serviceStats['MAINTENANCE_TP'] . "%;;;\n"; echo 'UNDETERMINED;' . $serviceStats['UNDETERMINED_T'] . 's;' . $serviceStats['UNDETERMINED_TP'] . "%;;;\n"; echo "\n"; echo "\n"; // Getting evolution of service stats in time echo _('Day') . ';' . _('Duration') . ';' . _('OK') . ' (s); ' . _('OK') . ' %; ' . _('OK') . ' Alert;' . _('Warning') . ' (s); ' . _('Warning') . ' %;' . _('Warning') . ' Alert;' . _('Unknown') . ' (s); ' . _('Unknown') . ' %;' . _('Unknown') . ' Alert;' . _('Critical') . ' (s); ' . _('Critical') . ' %;' . _('Critical') . ' Alert;' . _('Day') . ";\n"; $dbResult = $pearDBO->prepare( 'SELECT * FROM `log_archive_service` ' . 'WHERE `host_id` = :hostId ' . 'AND `service_id` = :serviceId ' . 'AND `date_start` >= :startDate ' . 'AND `date_end` <= :endDate ' . 'ORDER BY `date_start` DESC' ); $dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT); $dbResult->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $dbResult->bindValue(':startDate', $startDate, PDO::PARAM_INT); $dbResult->bindValue(':endDate', $endDate, PDO::PARAM_INT); $dbResult->execute(); while ($row = $dbResult->fetch()) { $duration = $row['OKTimeScheduled'] + $row['WARNINGTimeScheduled'] + $row['UNKNOWNTimeScheduled'] + $row['CRITICALTimeScheduled']; if ($duration === 0) { continue; } // Percentage by status $row['OK_MP'] = round($row['OKTimeScheduled'] * 100 / $duration, 2); $row['WARNING_MP'] = round($row['WARNINGTimeScheduled'] * 100 / $duration, 2); $row['UNKNOWN_MP'] = round($row['UNKNOWNTimeScheduled'] * 100 / $duration, 2); $row['CRITICAL_MP'] = round($row['CRITICALTimeScheduled'] * 100 / $duration, 2); echo $row['date_start'] . ';' . $duration . ';' . $row['OKTimeScheduled'] . 's;' . $row['OK_MP'] . '%;' . $row['OKnbEvent'] . ';' . $row['WARNINGTimeScheduled'] . 's;' . $row['WARNING_MP'] . '%;' . $row['WARNINGnbEvent'] . ';' . $row['UNKNOWNTimeScheduled'] . 's;' . $row['UNKNOWN_MP'] . '%;' . $row['UNKNOWNnbEvent'] . ';' . $row['CRITICALTimeScheduled'] . 's;' . $row['CRITICAL_MP'] . '%;' . $row['CRITICALnbEvent'] . ';' . date('Y-m-d H:i:s', $row['date_start']) . ";\n"; } $dbResult->closeCursor();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/csvExport/csv_HostLogs.php
centreon/www/include/reporting/dashboard/csvExport/csv_HostLogs.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 _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/common-Func.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDuration.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/DB-Func.php'; // DB connexion $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); if (! isset($_SESSION['centreon'])) { CentreonSession::start(); if (! CentreonSession::checkSession(session_id(), $pearDB)) { echo 'Bad Session'; exit(); } } $centreon = $_SESSION['centreon']; // Checking session $sid = session_id(); if (! empty($sid) && isset($_SESSION['centreon'])) { $oreon = $_SESSION['centreon']; $res = $pearDB->prepare('SELECT COUNT(*) as count FROM session WHERE user_id = :id'); $res->bindValue(':id', (int) $oreon->user->user_id, PDO::PARAM_INT); $res->execute(); $row = $res->fetch(PDO::FETCH_ASSOC); if ($row['count'] < 1) { get_error('bad session id'); } } else { get_error('need session id!'); } // getting host id $hostId = filter_var( $_GET['host'] ?? $_POST['host'] ?? null, FILTER_VALIDATE_INT ); $allowedHosts = $centreon->user->access->getHostAclConf(null, 'broker'); // checking if the user has ACL rights for this resource if (! $centreon->user->admin && $hostId !== null && ! array_key_exists($hostId, $allowedHosts) ) { echo '<div align="center" style="color:red">' . '<b>You are not allowed to access this host</b></div>'; exit(); } // Getting time interval to report $dates = getPeriodToReport(); $startDate = htmlentities($_GET['start'], ENT_QUOTES, 'UTF-8'); $endDate = htmlentities($_GET['end'], ENT_QUOTES, 'UTF-8'); $hostName = getHostNameFromId($hostId); // file type setting header('Cache-Control: public'); header('Pragma: public'); header('Content-Type: application/octet-stream'); header('Content-disposition: filename=' . $hostName . '.csv'); echo _('Host') . ';' . _('Begin date') . '; ' . _('End date') . '; ' . _('Duration') . "\n"; echo $hostName . '; ' . date(_('d/m/Y H:i:s'), $startDate) . '; ' . date(_('d/m/Y H:i:s'), $endDate) . '; ' . ($endDate - $startDate) . "s\n"; echo "\n"; echo "\n"; echo _('Status') . ';' . _('Duration') . ';' . _('Total Time') . ';' . _('Mean Time') . '; ' . _('Alert') . "\n"; // Getting stats on Host $reportingTimePeriod = getreportingTimePeriod(); $hostStats = getLogInDbForHost( $hostId, $startDate, $endDate, $reportingTimePeriod ); echo _('DOWN') . ';' . $hostStats['DOWN_T'] . 's;' . $hostStats['DOWN_TP'] . '%;' . $hostStats['DOWN_MP'] . '%;' . $hostStats['DOWN_A'] . ";\n"; echo _('UP') . ';' . $hostStats['UP_T'] . 's;' . $hostStats['UP_TP'] . '%;' . $hostStats['UP_MP'] . '%;' . $hostStats['UP_A'] . ";\n"; echo _('UNREACHABLE') . ';' . $hostStats['UNREACHABLE_T'] . 's;' . $hostStats['UNREACHABLE_TP'] . '%;' . $hostStats['UNREACHABLE_MP'] . '%;' . $hostStats['UNREACHABLE_A'] . ";\n"; echo _('SCHEDULED DOWNTIME') . ';' . $hostStats['MAINTENANCE_T'] . 's;' . $hostStats['MAINTENANCE_TP'] . "%;;;\n"; echo _('UNDETERMINED') . ';' . $hostStats['UNDETERMINED_T'] . 's;' . $hostStats['UNDETERMINED_TP'] . "%;\n"; echo "\n"; echo "\n"; echo _('Service') . ';' . _('OK') . ' %; ' . _('OK') . ' Alert;' . _('Warning') . ' %;' . _('Warning') . ' Alert;' . _('Critical') . ' %;' . _('Critical') . ' Alert;' . _('Unknown') . ' %;' . _('Unknown') . ' Alert;' . _('Scheduled Downtimes') . ' %;' . _('Undetermined') . "%;\n"; $hostServicesStats = getLogInDbForHostSVC( $hostId, $startDate, $endDate, $reportingTimePeriod ); foreach ($hostServicesStats as $tab) { if (isset($tab['DESCRIPTION']) && $tab['DESCRIPTION'] != '') { echo $tab['DESCRIPTION'] . ';' . $tab['OK_TP'] . ' %;' . $tab['OK_A'] . ';' . $tab['WARNING_TP'] . ' %;' . $tab['WARNING_A'] . ';' . $tab['CRITICAL_TP'] . ' %;' . $tab['CRITICAL_A'] . ';' . $tab['UNKNOWN_TP'] . '%;' . $tab['UNKNOWN_A'] . ';' . $tab['MAINTENANCE_TP'] . ' %;' . $tab['UNDETERMINED_TP'] . "%;\n"; } } echo "\n"; echo "\n"; // Evolution of host availability in time echo _('Day') . ';' . _('Duration') . ';' . _('Up') . ' (s);' . _('Up') . ' %;' . _('Up') . ' ' . _('Alert') . ';' . _('Down') . ' (s);' . _('Down') . ' %;' . _('Down') . ' ' . _('Alert') . ';' . _('Unreachable') . ' (s);' . _('Unreachable') . ' %;' . _('Unreachable') . ' ' . _('Alert') . _('Day') . ";\n"; $dbResult = $pearDBO->prepare( 'SELECT * FROM `log_archive_host` ' . 'WHERE `host_id` = :hostId ' . 'AND `date_start` >= :startDate ' . 'AND `date_end` <= :endDate ' . 'ORDER BY `date_start` desc' ); $dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT); $dbResult->bindValue(':startDate', $startDate, PDO::PARAM_INT); $dbResult->bindValue(':endDate', $endDate, PDO::PARAM_INT); $dbResult->execute(); while ($row = $dbResult->fetch()) { $duration = $row['UPTimeScheduled'] + $row['DOWNTimeScheduled'] + $row['UNREACHABLETimeScheduled']; if ($duration === 0) { continue; } // Percentage by status $row['UP_MP'] = round($row['UPTimeScheduled'] * 100 / $duration, 2); $row['DOWN_MP'] = round($row['DOWNTimeScheduled'] * 100 / $duration, 2); $row['UNREACHABLE_MP'] = round($row['UNREACHABLETimeScheduled'] * 100 / $duration, 2); echo $row['date_start'] . ';' . $duration . ';' . $row['UPTimeScheduled'] . ';' . $row['UP_MP'] . '%;' . $row['UPnbEvent'] . ';' . $row['DOWNTimeScheduled'] . ';' . $row['DOWN_MP'] . '%;' . $row['DOWNnbEvent'] . ';' . $row['UNREACHABLETimeScheduled'] . ';' . $row['UNREACHABLE_MP'] . '%;' . $row['UNREACHABLEnbEvent'] . ';' . date('Y-m-d H:i:s', $row['date_start']) . ";\n"; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/csvExport/csv_HostGroupLogs.php
centreon/www/include/reporting/dashboard/csvExport/csv_HostGroupLogs.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 _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/common-Func.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.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/centreonDuration.class.php'; include_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/DB-Func.php'; // DB Connexion $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); if (! isset($_SESSION['centreon'])) { CentreonSession::start(); if (! CentreonSession::checkSession(session_id(), $pearDB)) { echo 'Bad Session'; exit(); } } $sid = session_id(); if (! empty($sid) && isset($_SESSION['centreon'])) { $oreon = $_SESSION['centreon']; $res = $pearDB->prepare('SELECT COUNT(*) as count FROM session WHERE user_id = :id'); $res->bindValue(':id', (int) $oreon->user->user_id, PDO::PARAM_INT); $res->execute(); $row = $res->fetch(PDO::FETCH_ASSOC); if ($row['count'] < 1) { get_error('bad session id'); } } else { get_error('need session id!'); } $centreon = $oreon; // Getting hostgroup id $hostgroupId = null; if (! empty($_POST['hostgroup']) || ! empty($_GET['hostgroup'])) { $hostgroupId = filter_var( $_GET['hostgroup'] ?? $_POST['hostgroup'], FILTER_VALIDATE_INT ); } if ($hostgroupId === false) { throw new InvalidArgumentException('Bad parameters'); } // finding the user's allowed hostgroups $allowedHostgroups = $centreon->user->access->getHostGroupAclConf(null, 'broker'); // checking if the user has ACL rights for this resource if (! $centreon->user->admin && $hostgroupId !== null && ! array_key_exists($hostgroupId, $allowedHostgroups) ) { echo '<div align="center" style="color:red">' . '<b>You are not allowed to access this host group</b></div>'; exit(); } // Getting time interval to report $dates = getPeriodToReport(); $startDate = null; $endDate = null; if (! empty($_GET['start'])) { $startDate = filter_var($_GET['start'], FILTER_VALIDATE_INT); } if (! empty($_GET['end'])) { $endDate = filter_var($_GET['end'], FILTER_VALIDATE_INT); } if ($startDate === false || $endDate === false) { throw new InvalidArgumentException('Bad parameters'); } $hostgroupName = getHostgroupNameFromId($hostgroupId); // file type setting header('Cache-Control: public'); header('Pragma: public'); header('Content-Type: application/octet-stream'); header('Content-disposition: filename=' . $hostgroupName . '.csv'); echo _('Hostgroup') . ';' . _('Begin date') . '; ' . _('End date') . '; ' . _('Duration') . "\n"; echo $hostgroupName . '; ' . date(_('d/m/Y H:i:s'), $startDate) . '; ' . date(_('d/m/Y H:i:s'), $endDate) . '; ' . ($endDate - $startDate) . "s\n"; echo "\n"; echo _('Status') . ';' . _('Total Time') . ';' . _('Mean Time') . '; ' . _('Alert') . "\n"; // Getting stats on Host $reportingTimePeriod = getreportingTimePeriod(); $hostgroupStats = []; $hostgroupStats = getLogInDbForHostGroup($hostgroupId, $startDate, $endDate, $reportingTimePeriod); echo _('UP') . ';' . $hostgroupStats['average']['UP_TP'] . '%;' . $hostgroupStats['average']['UP_MP'] . '%;' . $hostgroupStats['average']['UP_A'] . ";\n"; echo _('DOWN') . ';' . $hostgroupStats['average']['DOWN_TP'] . '%;' . $hostgroupStats['average']['DOWN_MP'] . '%;' . $hostgroupStats['average']['DOWN_A'] . ";\n"; echo _('UNREACHABLE') . ';' . $hostgroupStats['average']['UNREACHABLE_TP'] . '%;' . $hostgroupStats['average']['UNREACHABLE_MP'] . '%;' . $hostgroupStats['average']['UNREACHABLE_A'] . ";\n"; echo _('SCHEDULED DOWNTIME') . ';' . $hostgroupStats['average']['MAINTENANCE_TP'] . "%;\n"; echo _('UNDETERMINED') . ';' . $hostgroupStats['average']['UNDETERMINED_TP'] . "%;\n"; echo "\n\n"; echo _('Hosts') . ';' . _('Up') . ' %;' . _('Up Mean Time') . ' %;' . _('Up') . ' ' . _('Alert') . ';' . _('Down') . ' %;' . _('Down Mean Time') . ' %;' . _('Down') . ' ' . _('Alert') . ';' . _('Unreachable') . ' %;' . _('Unreachable Mean Time') . ' %;' . _('Unreachable') . ' ' . _('Alert') . ';' . _('Scheduled Downtimes') . ' %;' . _('Undetermined') . " %;\n"; foreach ($hostgroupStats as $key => $tab) { if ($key != 'average') { echo $tab['NAME'] . ';' . $tab['UP_TP'] . '%;' . $tab['UP_MP'] . '%;' . $tab['UP_A'] . ';' . $tab['DOWN_TP'] . '%;' . $tab['DOWN_MP'] . '%;' . $tab['DOWN_A'] . ';' . $tab['UNREACHABLE_TP'] . '%;' . $tab['UNREACHABLE_MP'] . '%;' . $tab['UNREACHABLE_A'] . ';' . $tab['MAINTENANCE_TP'] . '%;' . $tab['UNDETERMINED_TP'] . "%;\n"; } } echo "\n"; echo "\n"; // getting all hosts from hostgroup $str = ''; $dbResult = $pearDB->prepare( 'SELECT host_host_id FROM `hostgroup_relation` ' . 'WHERE `hostgroup_hg_id` = :hostgroupId' ); $dbResult->bindValue(':hostgroupId', $hostgroupId, PDO::PARAM_INT); $dbResult->execute(); while ($hg = $dbResult->fetch()) { if ($str != '') { $str .= ', '; } $str .= "'" . $hg['host_host_id'] . "'"; } if ($str == '') { $str = "''"; } unset($hg, $dbResult); // Getting hostgroup stats evolution $dbResult = $pearDBO->prepare( 'SELECT `date_start`, `date_end`, sum(`UPnbEvent`) as UPnbEvent, sum(`DOWNnbEvent`) as DOWNnbEvent, ' . 'sum(`UNREACHABLEnbEvent`) as UNREACHABLEnbEvent, ' . 'avg( `UPTimeScheduled` ) as UPTimeScheduled, ' . 'avg( `DOWNTimeScheduled` ) as DOWNTimeScheduled, ' . 'avg( `UNREACHABLETimeScheduled` ) as UNREACHABLETimeScheduled ' . 'FROM `log_archive_host` WHERE `host_id` IN (' . $str . ') ' . 'AND `date_start` >= :startDate ' . 'AND `date_end` <= :endDate ' . 'GROUP BY `date_end`, `date_start` ORDER BY `date_start` desc' ); $dbResult->bindValue(':startDate', $startDate, PDO::PARAM_INT); $dbResult->bindValue(':endDate', $endDate, PDO::PARAM_INT); $dbResult->execute(); echo _('Day') . ';' . _('Duration') . ';' . _('Up Mean Time') . ';' . _('Up Alert') . ';' . _('Down Mean Time') . ';' . _('Down Alert') . ';' . _('Unreachable Mean Time') . ';' . _('Unreachable Alert') . _('Day') . ";\n"; while ($row = $dbResult->fetch()) { $duration = $row['UPTimeScheduled'] + $row['DOWNTimeScheduled'] + $row['UNREACHABLETimeScheduled']; if ($duration === 0) { continue; } // Percentage by status $row['UP_MP'] = round($row['UPTimeScheduled'] * 100 / $duration, 2); $row['DOWN_MP'] = round($row['DOWNTimeScheduled'] * 100 / $duration, 2); $row['UNREACHABLE_MP'] = round($row['UNREACHABLETimeScheduled'] * 100 / $duration, 2); echo $row['date_start'] . ';' . $duration . 's;' . $row['UP_MP'] . '%;' . $row['UPnbEvent'] . ';' . $row['DOWN_MP'] . '%;' . $row['DOWNnbEvent'] . ';' . $row['UNREACHABLE_MP'] . '%;' . $row['UNREACHABLEnbEvent'] . ';' . date('Y-m-d H:i:s', $row['date_start']) . ";\n"; } $dbResult->closeCursor();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/xmlInformations/common-Func.php
centreon/www/include/reporting/dashboard/xmlInformations/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 * */ /*require_once realpath(dirname(__FILE__) . "/../../../../../config/centreon.config.php"); require_once _CENTREON_PATH_."www/class/centreonDB.class.php"; /* Translation 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"); /*CentreonSession::start(); $oreon = $_SESSION["centreon"]; $centreonLang = new CentreonLang(_CENTREON_PATH_, $oreon); $centreonLang->bindLang();*/ // Create a XML node for each day stats (in $row) for a service, a servicegroup, an host or an hostgroup function fillBuffer($statesTab, $row, $color) { global $buffer; $statTab = []; $totalTime = 0; $sumTime = 0; foreach ($statesTab as $key => $value) { if (isset($row[$value . 'TimeScheduled'])) { $statTab[$value . '_T'] = $row[$value . 'TimeScheduled']; $totalTime += $row[$value . 'TimeScheduled']; } else { $statTab[$value . '_T'] = 0; } $statTab[$value . '_A'] = $row[$value . 'nbEvent'] ?? 0; } $date_start = $row['date_start']; $date_end = $row['date_end']; foreach ($statesTab as $key => $value) { $statTab[$value . '_MP'] = $totalTime ? round(($statTab[$value . '_T'] / ($totalTime) * 100), 2) : 0; } // Popup generation for each day $Day = _('Day'); $Duration = _('Duration'); $Alert = _('Alert'); $detailPopup = '{table class=bulleDashtab}'; $detailPopup .= '{tr}{td class=bulleDashleft colspan=3}' . $Day . ': {span class ="isTimestamp isDate"}'; $detailPopup .= $date_start . '{/span} -- ' . $Duration . ': ' . CentreonDuration::toString($totalTime) . '{/td}{td class=bulleDashleft }' . $Alert . '{/td}{/tr}'; foreach ($statesTab as $key => $value) { $detailPopup .= '{tr}' . '{td class=bulleDashleft style="background:' . $color[$value] . ';" }' . _($value) . ':{/td}' . '{td class=bulleDash}' . CentreonDuration::toString($statTab[$value . '_T']) . '{/td}' . '{td class=bulleDash}' . $statTab[$value . '_MP'] . '%{/td}' . '{td class=bulleDash}' . $statTab[$value . '_A'] . '{/td}'; $detailPopup .= '{/tr}'; } $detailPopup .= '{/table}'; $t = $totalTime; $t = round(($t - ($t * 0.11574074074)), 2); foreach ($statesTab as $key => $value) { if ($statTab[$value . '_MP'] > 0) { $day = date('d', $date_start); $year = date('Y', $date_start); $month = date('m', $date_start); $start = mktime(0, 0, 0, $month, $day, $year); $start += ($statTab[$value . '_T'] / 100 * 2); $end = $start + ($statTab[$value . '_T'] / 100 * 96); $buffer->startElement('event'); $buffer->writeAttribute('start', createDateTimelineFormat($start) . ' GMT'); $buffer->writeAttribute('end', createDateTimelineFormat($end) . ' GMT'); $buffer->writeAttribute('color', $color[$value]); $buffer->writeAttribute('isDuration', 'true'); $buffer->writeAttribute('title', $statTab[$value . '_MP'] . '%'); $buffer->text($detailPopup, false); $buffer->endElement(); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/xmlInformations/GetXmlHostGroup.php
centreon/www/include/reporting/dashboard/xmlInformations/GetXmlHostGroup.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 * */ $stateType = 'host'; require_once realpath(__DIR__ . '/initXmlFeed.php'); $color = array_filter($_GET['color'] ?? [], function ($oneColor) { return filter_var($oneColor, FILTER_VALIDATE_REGEXP, [ 'options' => [ 'regexp' => '/^#[[:xdigit:]]{6}$/', ], ]); }); if (empty($color) || count($_GET['color']) !== count($color)) { $buffer->writeElement('error', 'Bad color format'); $buffer->endElement(); header('Content-Type: text/xml'); $buffer->output(); exit; } if (($id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT)) !== false) { $hosts_id = $centreon->user->access->getHostHostGroupAclConf($id, 'broker'); if (count($hosts_id) > 0) { $rq = 'SELECT `date_start`, `date_end`, sum(`UPnbEvent`) as UPnbEvent, sum(`DOWNnbEvent`) as DOWNnbEvent, ' . 'sum(`UNREACHABLEnbEvent`) as UNREACHABLEnbEvent, ' . 'avg( `UPTimeScheduled` ) as "UPTimeScheduled", ' . 'avg( `DOWNTimeScheduled` ) as "DOWNTimeScheduled", ' . 'avg( `UNREACHABLETimeScheduled` ) as "UNREACHABLETimeScheduled", ' . 'avg( `UNDETERMINEDTimeScheduled` ) as "UNDETERMINEDTimeScheduled" ' . 'FROM `log_archive_host` WHERE `host_id` IN (' . implode(',', array_keys($hosts_id)) . ') GROUP BY date_end, date_start ORDER BY date_start desc'; $DBRESULT = $pearDBO->query($rq); while ($row = $DBRESULT->fetchRow()) { fillBuffer($statesTab, $row, $color); } $DBRESULT->closeCursor(); } } else { $buffer->writeElement('error', 'Bad id format'); } $buffer->endElement(); header('Content-Type: text/xml'); $buffer->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/reporting/dashboard/xmlInformations/GetXmlService.php
centreon/www/include/reporting/dashboard/xmlInformations/GetXmlService.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 * */ $stateType = 'service'; require_once realpath(__DIR__ . '/initXmlFeed.php'); if (isset($_SESSION['centreon'])) { $centreon = $_SESSION['centreon']; } else { exit; } $color = array_filter($_GET['color'] ?? [], function ($oneColor) { return filter_var($oneColor, FILTER_VALIDATE_REGEXP, [ 'options' => [ 'regexp' => '/^#[[:xdigit:]]{6}$/', ], ]); }); if (empty($color) || count($_GET['color']) !== count($color)) { $buffer->writeElement('error', 'Bad color format'); $buffer->endElement(); header('Content-Type: text/xml'); $buffer->output(); exit; } if ( ($id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT)) !== false && ($host_id = filter_var($_GET['host_id'] ?? false, FILTER_VALIDATE_INT)) !== false && ($startDate = filter_var($_GET['startDate'] ?? false, FILTER_VALIDATE_INT)) !== false && ($endDate = filter_var($_GET['endDate'] ?? false, FILTER_VALIDATE_INT)) !== false ) { // Get ACL if user is not admin $isAdmin = $centreon->user->admin; $accessService = true; if (! $isAdmin) { $userId = $centreon->user->user_id; $acl = new CentreonACL($userId, $isAdmin); if (! $acl->checkService($id)) { $accessService = false; } } if ($accessService) { // Use "like" instead of "=" to avoid mysql bug on partitioned tables $query = 'SELECT * FROM `log_archive_service` WHERE host_id LIKE :host_id AND service_id LIKE :service_id AND date_start >= :start_date AND date_end <= :end_date ORDER BY date_start DESC'; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':host_id', $host_id, PDO::PARAM_INT); $stmt->bindValue(':service_id', $id, PDO::PARAM_INT); $stmt->bindValue(':start_date', $startDate, PDO::PARAM_INT); $stmt->bindValue(':end_date', $endDate, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch()) { fillBuffer($statesTab, $row, $color); } } else { $buffer->writeElement('error', 'Cannot access to host information'); } } else { $buffer->writeElement('error', 'Bad id format'); } $buffer->endElement(); header('Content-Type: text/xml'); $buffer->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/reporting/dashboard/xmlInformations/GetXmlServiceGroup.php
centreon/www/include/reporting/dashboard/xmlInformations/GetXmlServiceGroup.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 * */ $stateType = 'service'; require_once realpath(__DIR__ . '/initXmlFeed.php'); $color = array_filter($_GET['color'] ?? [], function ($oneColor) { return filter_var($oneColor, FILTER_VALIDATE_REGEXP, [ 'options' => [ 'regexp' => '/^#[[:xdigit:]]{6}$/', ], ]); }); if (empty($color) || count($_GET['color']) !== count($color)) { $buffer->writeElement('error', 'Bad color format'); $buffer->endElement(); header('Content-Type: text/xml'); $buffer->output(); exit; } if (($id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT)) !== false) { $services = getServiceGroupActivateServices($id); if (count($services) > 0) { $host_ids = []; $service_ids = []; foreach ($services as $host_service_id => $host_service_name) { $res = explode('_', $host_service_id); $host_ids[$res[0]] = 1; $service_ids[$res[1]] = 1; } $request = 'SELECT ' . 'date_start, date_end, OKnbEvent, CRITICALnbEvent, WARNINGnbEvent, UNKNOWNnbEvent, ' . 'avg( `OKTimeScheduled` ) as "OKTimeScheduled", ' . 'avg( `WARNINGTimeScheduled` ) as "WARNINGTimeScheduled", ' . 'avg( `UNKNOWNTimeScheduled` ) as "UNKNOWNTimeScheduled", ' . 'avg( `CRITICALTimeScheduled` ) as "CRITICALTimeScheduled", ' . 'avg( `UNDETERMINEDTimeScheduled` ) as "UNDETERMINEDTimeScheduled" ' . 'FROM `log_archive_service` WHERE `host_id` IN (' . implode(',', array_keys($host_ids)) . ') AND `service_id` IN (' . implode(',', array_keys($service_ids)) . ') group by date_end, date_start order by date_start desc'; $res = $pearDBO->query($request); while ($row = $res->fetchRow()) { fillBuffer($statesTab, $row, $color); } $DBRESULT->closeCursor(); } } else { $buffer->writeElement('error', 'Bad id format'); } $buffer->endElement(); header('Content-Type: text/xml'); $buffer->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/reporting/dashboard/xmlInformations/GetXmlHost.php
centreon/www/include/reporting/dashboard/xmlInformations/GetXmlHost.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 * */ $stateType = 'host'; require_once realpath(__DIR__ . '/initXmlFeed.php'); if (isset($_SESSION['centreon'])) { $centreon = $_SESSION['centreon']; } else { exit; } $color = array_filter($_GET['color'] ?? [], function ($oneColor) { return filter_var($oneColor, FILTER_VALIDATE_REGEXP, [ 'options' => [ 'regexp' => '/^#[[:xdigit:]]{6}$/', ], ]); }); if (empty($color) || count($_GET['color']) !== count($color)) { $buffer->writeElement('error', 'Bad color format'); $buffer->endElement(); header('Content-Type: text/xml'); $buffer->output(); exit; } if (($id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT)) !== false) { // Get ACL if user is not admin $isAdmin = $centreon->user->admin; $accessHost = true; if (! $isAdmin) { $userId = $centreon->user->user_id; $acl = new CentreonACL($userId, $isAdmin); if (! $acl->checkHost($id)) { $accessHost = false; } } if ($accessHost) { // Use "like" instead of "=" to avoid mysql bug on partitioned tables $query = 'SELECT * FROM `log_archive_host` WHERE host_id LIKE :id ORDER BY date_start DESC'; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':id', $id, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch()) { fillBuffer($statesTab, $row, $color); } } else { $buffer->writeElement('error', 'Cannot access to host information'); } } else { $buffer->writeElement('error', 'Bad id format'); } $buffer->endElement(); header('Content-Type: text/xml'); $buffer->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/reporting/dashboard/xmlInformations/initXmlFeed.php
centreon/www/include/reporting/dashboard/xmlInformations/initXmlFeed.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 _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDuration.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php'; require_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/DB-Func.php'; require_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/common-Func.php'; require_once _CENTREON_PATH_ . 'www/include/reporting/dashboard/xmlInformations/common-Func.php'; session_start(); if (isset($_SESSION['centreon'])) { $centreon = $_SESSION['centreon']; } else { exit(); } $buffer = new CentreonXML(); $buffer->startElement('data'); $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); $sid = session_id(); $DBRESULT = $pearDB->query("SELECT * FROM session WHERE session_id = '" . $pearDB->escape($sid) . "'"); if (! $DBRESULT->rowCount()) { exit(); } // Definition of status $state = []; $statesTab = []; if ($stateType == 'host') { $state['UP'] = _('UP'); $state['DOWN'] = _('DOWN'); $state['UNREACHABLE'] = _('UNREACHABLE'); $state['UNDETERMINED'] = _('UNDETERMINED'); $statesTab[] = 'UP'; $statesTab[] = 'DOWN'; $statesTab[] = 'UNREACHABLE'; } elseif ($stateType == 'service') { $state['OK'] = _('OK'); $state['WARNING'] = _('WARNING'); $state['CRITICAL'] = _('CRITICAL'); $state['UNKNOWN'] = _('UNKNOWN'); $state['UNDETERMINED'] = _('UNDETERMINED'); $statesTab[] = 'OK'; $statesTab[] = 'WARNING'; $statesTab[] = 'CRITICAL'; $statesTab[] = 'UNKNOWN'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/reporting/dashboard/imagesGenerations/pie-charts.php
centreon/www/include/reporting/dashboard/imagesGenerations/pie-charts.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 _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; CentreonSession::start(1); if (! isset($_SESSION['centreon'])) { exit(); } $oreon = $_SESSION['centreon']; // ----------------------------------------------------- $value = $_GET['value']; foreach ($value as $key => $val) { if ($val) { if (! isset($oreon->optGen['color_' . strtolower($key)])) { // $color[] = $oreon->optGen["color_undetermined"]; $color[] = '#F0F0F0'; $val = str_replace(',', '.', $val); $data[] = $val; $legend[] = ''; } else { $color[] = $oreon->optGen['color_' . strtolower($key)]; $val = str_replace(',', '.', $val); $data[] = $val; $legend[] = ''; } } } include_once _CENTREON_PATH_ . '/www/lib/ofc-library/open-flash-chart.php'; $g = new graph(); $g->bg_colour = '#F3F6F6'; // // PIE chart, 60% alpha // $g->pie(60, '#505050', '#000000'); // // pass in two arrays, one of data, the other data labels // $g->pie_values($data, $legend); // // Colours for each slice, in this case some of the colours // will be re-used (3 colurs for 5 slices means the last two // slices will have colours colour[0] and colour[1]): // $g->pie_slice_colours($color); $g->set_tool_tip('#val#%'); if (isset($_GET['service_name'], $_GET['host_name'])) { $g->title( mb_convert_encoding($_GET['service_name'], 'UTF-8', 'ISO-8859-1') . ' on ' . mb_convert_encoding($_GET['host_name'], 'UTF-8', 'ISO-8859-1'), '{font-size:15px; color: #424242}' ); } elseif (isset($_GET['host_name'])) { $g->title(mb_convert_encoding($_GET['host_name'], 'UTF-8', 'ISO-8859-1'), '{font-size:18px; color: #424242}'); } header('Cache-Control: cache, must-revalidate'); header('Pragma: public'); echo $g->render();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/home/customViews/rename.php
centreon/www/include/home/customViews/rename.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 _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . 'www/class/HtmlAnalyzer.php'; session_start(); session_write_close(); if (! isset($_SESSION['centreon'])) { exit(); } $elementId = filter_input( INPUT_POST, 'elementId', FILTER_VALIDATE_REGEXP, [ 'options' => ['regexp' => '/^title_\d+$/'], ] ); if ($elementId === null) { echo 'missing elementId argument'; exit(); } if ($elementId === false) { echo 'elementId must use following regexp format : "title_\d+"'; exit(); } $widgetId = null; if (preg_match('/^title_(\d+)$/', $_POST['elementId'], $matches)) { $widgetId = $matches[1]; } $newName = isset($_POST['newName']) ? HtmlSanitizer::createFromString($_POST['newName']) ->sanitize()->getString() : null; if ($newName === null) { echo 'missing newName argument'; exit(); } $centreon = $_SESSION['centreon']; $db = new CentreonDB(); if (CentreonSession::checkSession(session_id(), $db) === false) { exit(); } $widgetObj = new CentreonWidget($centreon, $db); try { echo $widgetObj->rename($widgetId, $newName); } catch (CentreonWidgetException $e) { echo $e->getMessage(); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/home/customViews/formLoad.php
centreon/www/include/home/customViews/formLoad.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/centreonCustomView.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php'; $db = new CentreonDB(); $viewObj = new CentreonCustomView($centreon, $db); $widgetObj = new CentreonWidget($centreon, $db); $title = ''; $action = null; $defaultTab = []; if ($_REQUEST['action'] == 'load') { $title = _('Load a public view'); $action = 'load'; } if (! isset($action)) { echo _('No action'); exit; } $query = 'select * from custom_views where public = 1'; $DBRES = $db->query($query); $arrayView = []; $arrayView[-1] = ''; while ($row = $DBRES->fetchRow()) { $arrayView[$row['custom_view_id']] = $row['name']; } // Smarty template initialization $path = './include/home/customViews/'; $template = SmartyBC::createSmartyTemplate($path, './'); /** * Field templates */ $attrsText = ['size' => '30']; $attrsAdvSelect = ['style' => 'width: 200px; height: 150px;']; $attrsTextarea = ['rows' => '5', 'cols' => '40']; $eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />' . '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>'; $form = new HTML_QuickFormCustom('Form', 'post', '?p=103'); $form->addElement('header', 'title', $title); $form->addElement('header', 'information', _('General Information')); $form->addElement('select', 'viewLoad', _('Public views list'), $arrayView); /** * Submit button */ $form->addElement('button', 'submit', _('Submit'), ['onClick' => 'submitData();']); $form->addElement('reset', 'reset', _('Reset')); $form->addElement('hidden', 'action'); $form->setDefaults(['action' => $action]); /** * Renderer */ $renderer = new HTML_QuickForm_Renderer_ArraySmarty($template, true); $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $form->accept($renderer); $template->assign('form', $renderer->toArray()); $template->display('formLoad.ihtml'); ?> <script type="text/javascript"> jQuery(function () { jQuery("input[type=text]").keypress(function (e) { var code = null; code = (e.keyCode ? e.keyCode : e.which); return (code == 13) ? false : true; }); }); function submitData() { jQuery.ajax({ type: "POST", dataType: "xml", url: "./include/home/customViews/action.php", data: jQuery("#Form").serialize(), success: function (response) { var view = response.getElementsByTagName('custom_view_id'); var error = response.getElementsByTagName('error'); if (typeof(view) != 'undefined') { var viewId = view.item(0).firstChild.data; window.top.location = './main.php?p=103&currentView=' + viewId; } else if (typeof(error) != 'undefined') { var errorMsg = error.item(0).firstChild.data; } } }); } </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/home/customViews/action.php
centreon/www/include/home/customViews/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 * */ require_once __DIR__ . '/../../../../bootstrap.php'; require_once realpath(__DIR__ . '/../../../../config/centreon.config.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/centreonCustomView.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php'; session_start(); session_write_close(); if (empty($_POST['action']) || ! isset($_SESSION['centreon'])) { exit(); } $centreon = $_SESSION['centreon']; $db = new CentreonDB(); if (CentreonSession::checkSession(session_id(), $db) === false) { exit(); } $action = $_POST['action']; $postFilter = [ 'widget_id' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'custom_view_id' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'timer' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'public' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'user_id' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'viewLoad' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'layout' => [ 'options' => [ 'default' => '', ], ], 'widget_model_id' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], 'widget_model_id' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => [ 'default' => false, ], ], ]; $postInputs = filter_input_array(INPUT_POST, $postFilter); $postInputs['name'] = isset($_POST['name']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['name']) : null; $postInputs['widget_title'] = isset($_POST['widget_title']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['widget_title']) : null; $lockedUsers = []; if (! empty($_POST['lockedUsers'])) { foreach ($_POST['lockedUsers'] as $lockedUserId) { if (filter_var($lockedUserId, FILTER_VALIDATE_INT) !== false) { $lockedUsers[] = (int) $lockedUserId; } } } $unlockedUsers = []; if (! empty($_POST['unlockedUsers'])) { foreach ($_POST['unlockedUsers'] as $unlockedUserId) { if (filter_var($unlockedUserId, FILTER_VALIDATE_INT) !== false) { $unlockedUsers[] = (int) $unlockedUserId; } } } $lockedUsergroups = []; if (! empty($_POST['lockedUsergroups'])) { foreach ($_POST['lockedUsergroups'] as $lockedUsergroupsId) { if (filter_var($lockedUsergroupsId, FILTER_VALIDATE_INT) !== false) { $lockedUsergroups[] = (int) $lockedUsergroupsId; } } } $unlockedUsergroups = []; if (! empty($_POST['unlockedUsergroups'])) { foreach ($_POST['unlockedUsergroups'] as $unlockedUsergroupsId) { if (filter_var($unlockedUsergroupsId, FILTER_VALIDATE_INT) !== false) { $unlockedUsergroups[] = (int) $unlockedUsergroupsId; } } } $positions = []; if (! empty($_POST['positions'])) { foreach ($_POST['positions'] as $position) { if (HtmlAnalyzer::sanitizeAndRemoveTags($position) !== false) { $positions[] = $position; } } } $createLoad = ''; if (! empty($_POST['create_load']['create_load'])) { $createLoad = $_POST['create_load']['create_load']; } $postInputs['layout'] = isset($_POST['layout']['layout']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_POST['layout']['layout']) : null; $viewObj = new CentreonCustomView($centreon, $db); $widgetObj = new CentreonWidget($centreon, $db); $xml = new CentreonXML(); if ($postInputs['custom_view_id']) { // check wether or not user can modify the view (locked & visible) $permission = $viewObj->checkPermission($postInputs['custom_view_id']); } else { $postInputs['custom_view_id'] = ''; } // check if the user can perform the provided action $authorized = ($centreon->user->admin === '0') ? $viewObj->checkUserActions($action) : true; $xml->startElement('response'); try { switch ($action) { case 'add': if (! empty($createLoad)) { if ($createLoad === 'create') { $postInputs['custom_view_id'] = $viewObj->addCustomView( $postInputs['name'], $postInputs['layout'], $postInputs['public'], $authorized ); if ($postInputs['widget_id']) { $widgetObj->updateViewWidgetRelations($postInputs['custom_view_id']); } } elseif ($createLoad === 'load' && ! empty($postInputs['viewLoad'])) { $postInputs['custom_view_id'] = $viewObj->loadCustomView($postInputs['viewLoad'], $authorized); } } break; case 'edit': if ($postInputs['custom_view_id']) { $viewObj->updateCustomView( $postInputs['custom_view_id'], $postInputs['name'], $postInputs['layout'], $postInputs['public'], $permission, $authorized ); if ($postInputs['widget_id']) { $widgetObj->updateViewWidgetRelations($postInputs['custom_view_id'], $postInputs['widget_id']); } // update share if (! $postInputs['public']) { $postInputs['public'] = 0; } if (empty($postInputs['user_id'])) { $userId = $centreon->user->user_id; } } break; case 'share': $viewObj->shareCustomView( $postInputs['custom_view_id'], $lockedUsers, $unlockedUsers, $lockedUsergroups, $unlockedUsergroups, $centreon->user->user_id, $permission, $authorized ); break; case 'remove': $viewObj->removeUserFromView($postInputs['user_id'], $postInputs['custom_view_id'], $permission); $xml->writeElement('contact_name', $centreon->user->getContactName($db, $postInputs['user_id'])); break; case 'removegroup': $cgObj = new CentreonContactgroup($db); $viewObj->removeUsergroupFromView($postInputs['custom_view_id'], $postInputs['usergroup_id']); $xml->writeElement('contact_name', $cgObj->getNameFromCgId($postInputs['usergroup_id'])); break; case 'setPreferences': $widgetObj->updateUserWidgetPreferences($_POST, $permission, $authorized); break; case 'deleteWidget': $widgetObj->deleteWidgetFromView( $postInputs['custom_view_id'], $postInputs['widget_id'], $authorized, $permission ); break; case 'position': $widgetObj->updateWidgetPositions($postInputs['custom_view_id'], $permission, $positions); break; case 'deleteView': if ($postInputs['custom_view_id']) { $viewObj->deleteCustomView($postInputs['custom_view_id'], $authorized); } break; case 'addWidget': $widgetObj->addWidget( $postInputs['custom_view_id'], $postInputs['widget_model_id'], $postInputs['widget_title'], $permission, $authorized ); break; case 'setDefault': if ($postInputs['custom_view_id']) { $viewObj->setDefault($postInputs['custom_view_id']); } break; case 'setRotate': if ($postInputs['timer'] >= 0) { $centreon->user->setContactParameters($db, ['widget_view_rotation' => $postInputs['timer']]); } break; case 'defaultEditMode': $_SESSION['customview_edit_mode'] = $_POST['editMode']; break; case 'get_share_info': $viewId = isset($_POST['viewId']) ? filter_var($_POST['viewId'], FILTER_VALIDATE_INT) : false; if ($viewId !== false) { $viewers = $viewObj->getUsersFromViewId($viewId); $viewerGroups = $viewObj->getUsergroupsFromViewId($viewId); $xml->startElement('contacts'); foreach ($viewers as $viewer) { if ($viewer['user_id'] != $centreon->user->user_id) { $xml->startElement('contact'); $xml->writeAttribute('locked', $viewer['locked']); $xml->writeAttribute('id', $viewer['user_id']); $xml->text($viewer['contact_name']); $xml->endElement(); } } $xml->endElement(); $xml->startElement('contactgroups'); foreach ($viewerGroups as $viewerGroup) { $xml->startElement('contactgroup'); $xml->writeAttribute('locked', $viewerGroup['locked']); $xml->writeAttribute('id', $viewerGroup['usergroup_id']); $xml->text($viewerGroup['cg_name']); $xml->endElement(); } $xml->endElement(); } break; default: throw new CentreonCustomViewException('Unsupported action provided.'); } $xml->writeElement('custom_view_id', $postInputs['custom_view_id']); } catch (CentreonCustomViewException|CentreonWidgetException $e) { $xml->writeElement('error', $e->getMessage()); } $xml->endElement(); header('Content-Type: text/xml'); header('Pragma: no-cache'); header('Expires: 0'); header('Cache-Control: no-cache, must-revalidate'); $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/home/customViews/index.php
centreon/www/include/home/customViews/index.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/centreonCustomView.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php'; try { $db = new CentreonDB(); $viewObj = new CentreonCustomView($centreon, $db); // Smarty $path = './include/home/customViews/'; // Smarty template initialization $template = SmartyBC::createSmartyTemplate($path, './'); // Assign permissions and other variables to the template $aclEdit = $centreon->user->access->page('10301', true); $template->assign('aclEdit', $aclEdit); $aclShare = $centreon->user->access->page('10302', true); $template->assign('aclShare', $aclShare); $aclParameters = $centreon->user->access->page('10303', true); $template->assign('aclParameters', $aclParameters); $aclAddWidget = $centreon->user->access->page('10304', true); $template->assign('aclAddWidget', $aclAddWidget); $aclRotation = $centreon->user->access->page('10305', true); $template->assign('aclRotation', $aclRotation); $aclDeleteView = $centreon->user->access->page('10306', true); $template->assign('aclDeleteView', $aclDeleteView); $aclAddView = $centreon->user->access->page('10307', true); $template->assign('aclAddView', $aclAddView); $aclSetDefault = $centreon->user->access->page('10308', true); $template->assign('aclSetDefault', $aclSetDefault); $template->assign('editMode', _('Show/Hide edit mode')); $viewId = $viewObj->getCurrentView(); $views = $viewObj->getCustomViews(); $contactParameters = $centreon->user->getContactParameters($db, ['widget_view_rotation']); $rotationTimer = 0; if (isset($contactParameters['widget_view_rotation'])) { $rotationTimer = $contactParameters['widget_view_rotation']; } // Assign views to template $i = 1; $indexTab = [0 => -1]; foreach ($views as $key => $val) { $indexTab[$key] = $i; $i++; $views[$key]['icon'] = ! $viewObj->checkPermission($key) ? 'locked' : 'unlocked'; $views[$key]['default'] = ''; if ($viewObj->getDefaultViewId() == $key) { $views[$key]['default'] = '<span class="ui-icon ui-icon-star" style="float:left;"></span>'; } } $template->assign('views', $views); $template->assign('empty', $i); $formAddView = new HTML_QuickFormCustom( 'formAddView', 'post', '?p=103', '_selft', ['onSubmit' => 'submitAddView(); return false;'] ); // List of shared views $arrayView = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_home_customview&action=listSharedViews', 'multiple' => false]; $formAddView->addElement('select2', 'viewLoad', _('Views'), [], $arrayView); // New view name $attrsText = ['size' => '30']; $formAddView->addElement('text', 'name', _('Name'), $attrsText); $createLoad = []; $createLoad[] = $formAddView->createElement('radio', 'create_load', null, _('Create new view '), 'create'); $createLoad[] = $formAddView->createElement('radio', 'create_load', null, _('Load from existing view'), 'load'); $formAddView->addGroup($createLoad, 'create_load', _('create or load'), '&nbsp;'); $formAddView->setDefaults(['create_load[create_load]' => 'create']); /** * Layout */ $layouts[] = $formAddView->createElement('radio', 'layout', null, _('1 Column'), 'column_1'); $layouts[] = $formAddView->createElement('radio', 'layout', null, _('2 Columns'), 'column_2'); $layouts[] = $formAddView->createElement('radio', 'layout', null, _('3 Columns'), 'column_3'); $formAddView->addGroup($layouts, 'layout', _('Layout'), '&nbsp;'); $formAddView->setDefaults(['layout[layout]' => 'column_1']); $formAddView->addElement('checkbox', 'public', '', _('Public')); /** * Submit button */ $formAddView->addElement('submit', 'submit', _('Submit'), ['class' => 'btc bt_success']); $formAddView->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $formAddView->addElement('hidden', 'action'); $formAddView->setDefaults(['action' => 'add']); /** * Renderer */ $rendererAddView = new HTML_QuickForm_Renderer_ArraySmarty($template, true); $rendererAddView->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $rendererAddView->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $formAddView->accept($rendererAddView); $template->assign('formAddView', $rendererAddView->toArray()); /** * Form for edit view */ $formEditView = new HTML_QuickFormCustom( 'formEditView', 'post', '?p=103', '', ['onSubmit' => 'submitEditView(); return false;'] ); /** * Name */ $formEditView->addElement('text', 'name', _('Name'), $attrsText); /** * Layout */ $layouts = []; $layouts[] = $formAddView->createElement('radio', 'layout', null, _('1 Column'), 'column_1'); $layouts[] = $formAddView->createElement('radio', 'layout', null, _('2 Columns'), 'column_2'); $layouts[] = $formAddView->createElement('radio', 'layout', null, _('3 Columns'), 'column_3'); $formEditView->addGroup($layouts, 'layout', _('Layout'), '&nbsp;'); $formEditView->setDefaults(['layout[layout]' => 'column_1']); $formEditView->addElement('checkbox', 'public', '', _('Public')); /** * Submit button */ $formEditView->addElement('submit', 'submit', _('Submit'), ['class' => 'btc bt_success']); $formEditView->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $formEditView->addElement('hidden', 'action'); $formEditView->addElement('hidden', 'custom_view_id'); $formEditView->setDefaults(['action' => 'edit']); /** * Renderer */ $rendererEditView = new HTML_QuickForm_Renderer_ArraySmarty($template, true); $rendererEditView->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $rendererEditView->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $formEditView->accept($rendererEditView); $template->assign('formEditView', $rendererEditView->toArray()); /** * Form share view */ $formShareView = new HTML_QuickFormCustom( 'formShareView', 'post', '?p=103', '', ['onSubmit' => 'submitShareView(); return false;'] ); /** * Users */ $attrContacts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_contact&action=list', 'multiple' => true, 'allowClear' => true, 'defaultDataset' => []]; $formShareView->addElement( 'select2', 'unlocked_user_id', _('Unlocked users'), [], $attrContacts ); $formShareView->addElement( 'select2', 'locked_user_id', _('Locked users'), [], $attrContacts ); /** * User groups */ $attrContactgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_contactgroup&action=list', 'multiple' => true, 'allowClear' => true, 'defaultDataset' => []]; $formShareView->addElement( 'select2', 'unlocked_usergroup_id', _('Unlocked user groups'), [], $attrContactgroups ); $formShareView->addElement( 'select2', 'locked_usergroup_id', _('Locked user groups'), [], $attrContactgroups ); // Widgets $attrWidgets = ['datasourceOrigin' => 'ajax', 'multiple' => false, 'availableDatasetRoute' => './api/internal.php?object=centreon_administration_widget&action=listInstalled', 'allowClear' => false]; /** * Submit button */ $formShareView->addElement('submit', 'submit', _('Share'), ['class' => 'btc bt_info']); $formShareView->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $formShareView->addElement('hidden', 'action'); $formShareView->setDefaults(['action' => 'share']); $formShareView->addElement('hidden', 'custom_view_id'); $rendererShareView = new HTML_QuickForm_Renderer_ArraySmarty($template, true); $rendererShareView->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $rendererShareView->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $formShareView->accept($rendererShareView); $template->assign('formShareView', $rendererShareView->toArray()); /** * Form add widget */ $widgetObj = new CentreonWidget($centreon, $db); $formAddWidget = new HTML_QuickFormCustom( 'formAddWidget', 'post', '?p=103', '', ['onSubmit' => 'submitAddWidget(); return false;'] ); /** * Name */ $formAddWidget->addElement('text', 'widget_title', _('Title'), $attrsText); $formAddWidget->addElement('select2', 'widget_model_id', _('Widget'), [], $attrWidgets); /** * Submit button */ $formAddWidget->addElement('submit', 'submit', _('Submit'), ['class' => 'btc bt_success']); $formAddWidget->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']); $formAddWidget->addElement('hidden', 'action'); $formAddWidget->addElement('hidden', 'custom_view_id'); $formAddWidget->setDefaults(['action' => 'addWidget']); /** * Renderer */ $rendererAddWidget = new HTML_QuickForm_Renderer_ArraySmarty($template, true); $rendererAddWidget->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>'); $rendererAddWidget->setErrorTemplate('<font color="red">{$error}</font><br />{$html}'); $formAddWidget->accept($rendererAddWidget); $template->assign('formAddWidget', $rendererAddWidget->toArray()); $template->assign('rotationTimer', $rotationTimer); $template->assign( 'editModeIcon', returnSvg( 'www/img/icons/edit_mode.svg', 'var(--icons-fill-color)', 20, 20 ) ); $template->assign( 'noEditModeIcon', returnSvg( 'www/img/icons/no_edit_mode.svg', 'var(--icons-fill-color)', 20, 20 ) ); $template->assign( 'addIcon', returnSvg('www/img/icons/add.svg', 'var(--button-icons-fill-color)', 14, 16) ); $template->assign( 'deleteIcon', returnSvg('www/img/icons/trash.svg', 'var(--button-icons-fill-color)', 14, 16) ); $template->assign( 'editIcon', returnSvg('www/img/icons/edit.svg', 'var(--button-icons-fill-color)', 14, 14) ); $template->assign( 'returnIcon', returnSvg('www/img/icons/return.svg', 'var(--button-icons-fill-color)', 14, 14) ); $template->assign( 'folderIcon', returnSvg('www/img/icons/folder.svg', 'var(--button-icons-fill-color)', 14, 14) ); $template->assign( 'playIcon', returnSvg('www/img/icons/play.svg', 'var(--button-icons-fill-color)', 14, 14) ); $template->assign( 'helpIcon', returnSvg('www/img/icons/question.svg', 'var(--help-tool-tip-icon-fill-color)', 18, 18) ); $template->display('index.ihtml'); } catch (CentreonCustomViewException $e) { echo $e->getMessage() . '<br/>'; } // Initialize $modeEdit based on session variable $modeEdit = 'false'; if (isset($_SESSION['customview_edit_mode'])) { $modeEdit = ($_SESSION['customview_edit_mode'] === 'true') ? 'true' : 'false'; } ?> <script type="text/javascript"> var defaultShow = <?php echo $modeEdit; ?>; var deleteWdgtMessage = "<?php echo _('Deleting this widget might impact users with whom you are sharing this view. ' . 'Are you sure you want to do it?'); ?>"; var deleteViewMessage = "<?php echo _('Deleting this view might impact other users. Are you sure you want to do it?'); ?>"; var setDefaultMessage = "<?php echo _('Set this view as your default view?'); ?>"; var wrenchSpan = '<span class="ui-icon ui-icon-wrench"></span>'; var trashSpan = '<span class="ui-icon ui-icon-trash"></span>'; /** * Resize widget iframe */ function iResize(ifrm, height) { if (height < 150) { height = 150; } jQuery("[name=" + ifrm + "]").height(height); } </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/home/customViews/views.php
centreon/www/include/home/customViews/views.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 _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonCustomView.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'bootstrap.php'; session_start(); session_write_close(); try { if (! isset($_SESSION['centreon'])) { throw new Exception('No session found'); } $centreon = $_SESSION['centreon']; $db = new CentreonDB(); $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'); if (CentreonSession::checkSession(session_id(), $db) === false) { throw new Exception('Invalid session'); } $viewObj = new CentreonCustomView($centreon, $db); $widgetObj = new CentreonWidget($centreon, $db); // Smarty template initialization $path = _CENTREON_PATH_ . 'www/include/home/customViews/layouts/'; $template = SmartyBC::createSmartyTemplate($path, './'); $viewId = $viewObj->getCurrentView(); $permission = $viewObj->checkPermission($viewId) ? 1 : 0; $ownership = $viewObj->checkOwnership($viewId) ? 1 : 0; $widgets = []; $columnClass = 'column_0'; $widgetNumber = 0; if ($viewId) { $columnClass = $viewObj->getLayout($viewId); $widgets = $widgetObj->getWidgetsFromViewId($viewId); foreach ($widgets as $widgetId => $val) { if (isset($widgets[$widgetId]['widget_order']) && $widgets[$widgetId]['widget_order']) { $tmp = explode('_', $widgets[$widgetId]['widget_order']); $widgets[$widgetId]['column'] = $tmp[0]; } else { $widgets[$widgetId]['column'] = 0; } if (! $permission && $widgets[$widgetId]['title'] === '') { $widgets[$widgetId]['title'] = '&nbsp;'; } $widgetNumber++; } $template->assign('columnClass', $columnClass); $template->assign('jsonWidgets', json_encode($widgets)); $template->assign('widgets', $widgets); } $template->assign('permission', $permission); $template->assign('widgetNumber', $widgetNumber); $template->assign('ownership', $ownership); $template->assign('userId', $centreon->user->user_id); $template->assign('view_id', $viewId); $template->assign( 'error_msg', _('No widget configured in this view. Please add a new widget with the "Add widget" button.') ); $template->assign( 'helpIcon', returnSvg('www/img/icons/question_2.svg', 'var(--help-tool-tip-icon-fill-color)', 18, 18) ); $template->display($columnClass . '.ihtml'); } catch (CentreonWidgetException|CentreonCustomViewException|Exception $e) { echo $e->getMessage() . '<br/>'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/home/customViews/triggers/loadServiceFromHost.php
centreon/www/include/home/customViews/triggers/loadServiceFromHost.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 _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; session_start(); session_write_close(); if (! isset($_POST['data']) || ! isset($_SESSION['centreon'])) { exit; } $centreon = $_SESSION['centreon']; $hostId = filter_var($_POST['data'], FILTER_VALIDATE_INT); $db = new CentreonDB(); $pearDB = $db; if (CentreonSession::checkSession(session_id(), $db) === false) { exit(); } $monitoringDb = new CentreonDB('centstorage'); $xml = new CentreonXML(); $xml->startElement('response'); try { $xml->startElement('options'); if ($hostId !== false && $hostId > 0) { $aclString = $centreon->user->access->queryBuilder( 'AND', 's.service_id', $centreon->user->access->getServicesString('ID', $monitoringDb) ); $sql = 'SELECT service_id, service_description, display_name FROM service s, host_service_relation hsr WHERE hsr.host_host_id = :hostId AND hsr.service_service_id = s.service_id '; $sql .= $aclString; $sql .= ' UNION '; $sql .= ' SELECT service_id, service_description, display_name FROM service s, host_service_relation hsr, hostgroup_relation hgr WHERE hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND hgr.host_host_id = :hostId AND hsr.service_service_id = s.service_id '; $sql .= $aclString; $sql .= ' ORDER BY service_description '; $stmt = $db->prepare($sql); $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $xml->startElement('option'); $xml->writeElement('id', $row['service_id']); // For meta services, use display_name column instead of service_description $serviceDescription = (preg_match('/meta_/', $row['service_description'])) ? $row['display_name'] : $row['service_description']; $xml->writeElement('label', $serviceDescription); $xml->endElement(); } } $xml->endElement(); } catch (CentreonCustomViewException|CentreonWidgetException $e) { $xml->writeElement('error', $e->getMessage()); } $xml->endElement(); header('Content-Type: text/xml'); header('Pragma: no-cache'); header('Expires: 0'); header('Cache-Control: no-cache, must-revalidate'); $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/views/componentTemplates/formComponentTemplate.php
centreon/www/include/views/componentTemplates/formComponentTemplate.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(); } // Load 2 general options $l_general_opt = []; $stmt = $pearDB->query('SELECT * FROM options'); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $l_general_opt[$row['key']] = $row['value']; } $stmt->closeCursor(); $compo = []; if (($o === MODIFY_COMPONENT_TEMPLATE || $o === WATCH_COMPONENT_TEMPLATE) && $compo_id) { $stmt = $pearDB->prepare('SELECT * FROM giv_components_template WHERE compo_id = :compo_id LIMIT 1'); $stmt->bindValue(':compo_id', $compo_id, PDO::PARAM_INT); $stmt->execute(); $compo = $stmt->fetchRow(); } // Graphs comes from DB -> Store in $graphs Array $graphs = []; $stmt = $pearDB->query('SELECT graph_id, name FROM giv_graphs_template ORDER BY name'); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $graphs[$row['graph_id']] = $row['name']; } $stmt->closeCursor(); // List of known data sources $dataSources = []; $stmt = $pearDBO->query( 'SELECT 1 AS REALTIME, `metric_name`, `unit_name` FROM `metrics` GROUP BY `metric_name`, `unit_name` ORDER BY `metric_name`' ); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $dataSources[$row['metric_name']] = $row['metric_name']; if (isset($row['unit_name']) && $row['unit_name'] !== '') { $dataSources[$row['metric_name']] .= ' (' . $row['unit_name'] . ')'; } } unset($row); $stmt->closeCursor(); // Define Styles $attrsText = [ 'size' => 40, ]; $attrsText2 = [ 'size' => 10, ]; $attrsTextarea = [ 'rows' => 4, 'cols' => 60, ]; $eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br />' . '<br /><br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>'; $availableRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list'; $attrServices = [ 'datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $availableRoute, 'linkedObject' => 'centreonService', 'multiple' => false, ]; if ($o !== ADD_COMPONENT_TEMPLATE) { $defaultRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_objects' . '&action=defaultValues&target=graphCurve&field=host_id&id=' . $compo_id; $attrServices['defaultDatasetRoute'] = $defaultRoute; } // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o === ADD_COMPONENT_TEMPLATE) { $form->addElement('header', 'ftitle', _('Add a Data Source Template')); } elseif ($o === MODIFY_COMPONENT_TEMPLATE) { $form->addElement('header', 'ftitle', _('Modify a Data Source Template')); } elseif ($o === WATCH_COMPONENT_TEMPLATE) { $form->addElement('header', 'ftitle', _('View a Data Source Template')); } // Basic information $form->addElement('header', 'information', _('General Information')); $form->addElement('header', 'options', _('Display Optional Modifier')); $form->addElement('header', 'color', _('Colors')); $form->addElement('header', 'legend', _('Legend')); $form->addElement('text', 'name', _('Template Name'), $attrsText); $form->addElement('checkbox', 'ds_stack', _('Stack')); for ($cpt = 1; $cpt <= 100; $cpt++) { $orders[$cpt] = $cpt; } $form->addElement('select', 'ds_order', _('Order'), $orders); $form->addElement('static', 'hsr_text', _('Choose a service if you want a specific curve for it.')); $form->addElement('select2', 'host_service_id', _('Linked Host Services'), [], $attrServices); $form->addElement('text', 'ds_name', _('Data Source Name'), $attrsText); $form->addElement('select', 'datasources', null, $dataSources); $l_dsColorList = [ 'ds_color_line' => [ 'label' => _('Line color'), 'color' => '#0000FF', ], 'ds_color_area' => [ 'label' => _('Area color'), 'color' => '#FFFFFF', ], 'ds_color_area_warn' => [ 'label' => _('Warning Area color'), 'color' => '#FD9B27', ], 'ds_color_area_crit' => [ 'label' => _('Critical Area color'), 'color' => '#FF4A4A', ], ]; foreach ($l_dsColorList as $l_dsColor => $l_dCData) { $l_hxColor = isset($compo[$l_dsColor]) && ! empty($compo[$l_dsColor]) ? $compo[$l_dsColor] : $l_dCData['color']; $attColText = [ 'value' => $l_hxColor, 'size' => 7, 'maxlength' => 7, 'style' => 'text-align: center;', 'class' => 'js-input-colorpicker', ]; $form->addElement('text', $l_dsColor, $l_dCData['label'], $attColText); $attColAreaR = [ 'style' => 'width:50px; height:15px; background-color: ' . $l_hxColor . '; border-width:0px; padding-bottom:2px;', ]; $attColAreaW = [ 'style' => 'width:50px; height:15px; background-color: ' . $l_hxColor . '; border-width:0px; padding-bottom:2px;', ]; $form->addElement('button', $l_dsColor . '_color', '', $attColAreaW); $form->addElement('button', $l_dsColor . '_read', '', $attColAreaR); } $attTransext = [ 'size' => 2, 'maxlength' => 3, 'style' => 'text-align: center;', ]; $form->addElement('text', 'ds_transparency', _('Transparency'), $attTransext); $form->addElement('checkbox', 'ds_filled', _('Filling')); $form->addElement('checkbox', 'ds_max', _('Print Max value')); $form->addElement('checkbox', 'ds_min', _('Print Min value')); $form->addElement('checkbox', 'ds_minmax_int', _('Round the min and max')); $form->addElement('checkbox', 'ds_average', _('Print Average')); $form->addElement('checkbox', 'ds_last', _('Print Last Value')); $form->addElement('checkbox', 'ds_total', _('Print Total Value')); $form->addElement('checkbox', 'ds_invert', _('Invert')); $form->addElement('checkbox', 'default_tpl1', _('Default Centreon Graph Template')); $form->addElement( 'select', 'ds_tickness', _('Thickness'), [ '1' => 1, '2' => 2, '3' => 3, ] ); $form->addElement('text', 'ds_legend', _('Legend Name'), $attrsText); $form->addElement('checkbox', 'ds_hidecurve', _('Display Only The Legend')); $form->addElement( 'select', 'ds_jumpline', _('Empty Line After This Legend'), [ '0' => 0, '1' => 1, '2' => 2, '3' => 3, ] ); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); // Components linked with $form->addElement('header', 'graphs', _('Graph Choice')); $form->addElement('hidden', 'compo_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); function color_line_enabled($values) { if (isset($values[0]['ds_color_line_mode']) && $values[0]['ds_color_line_mode'] == '1') { return true; } return ! (! isset($values[1]) || $values[1] == ''); } // Form Rules $form->registerRule('existName', 'callback', 'NameHsrTestExistence'); $form->registerRule('existDs', 'callback', 'DsHsrTestExistence'); $form->applyFilter('__ALL__', 'myTrim'); $form->addRule('name', _('Compulsory Name'), 'required'); $form->addRule('ds_name', _('Required Field'), 'required'); $form->addRule('name', _('Name already in use for this Host/Service'), 'existName'); $form->addRule('ds_name', _('Data Source already in use for this Host/Service'), 'existDs'); $color_mode[] = $form->createElement('radio', 'ds_color_line_mode', null, _('Random'), '1'); $color_mode[] = $form->createElement('radio', 'ds_color_line_mode', null, _('Manual'), '0'); $form->addGroup($color_mode, 'ds_color_line_mode', _('Color line mode')); $form->registerRule('color_line_enabled', 'callback', 'color_line_enabled'); $form->addRule( [ 'ds_color_line_mode', 'ds_color_line', ], _('Required Field'), 'color_line_enabled' ); $form->registerRule('checkColorFormat', 'callback', 'checkColorFormat'); $form->addRule('ds_color_line', _('Bad Format: start color by #'), 'checkColorFormat'); $form->addRule('ds_color_area', _('Bad Format: start color by #'), 'checkColorFormat'); $form->addRule('ds_color_area_warn', _('Bad Format: start color by #'), 'checkColorFormat'); $form->addRule('ds_color_area_crit', _('Bad Format: start color by #'), 'checkColorFormat'); $form->setRequiredNote("<font style='color: red;'>*</font>&nbsp;" . _('Required fields')); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); if ($o === WATCH_COMPONENT_TEMPLATE) { // Just watch $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&compo_id=' . $compo_id . "'"] ); $form->setDefaults($compo); $form->freeze(); } elseif ($o === MODIFY_COMPONENT_TEMPLATE) { // Modify $subC = $form->addElement( 'submit', 'submitC', _('Save'), ['class' => 'btc bt_success'] ); $res = $form->addElement( 'reset', 'reset', _('Reset'), [ 'class' => 'btc bt_default', ] ); $form->setDefaults($compo); } elseif ($o === ADD_COMPONENT_TEMPLATE) { // add $subA = $form->addElement( 'submit', 'submitA', _('Save'), ['class' => 'btc bt_success'] ); $res = $form->addElement( 'reset', 'reset', _('Reset'), [ 'class' => 'btc bt_default', ] ); $form->setDefaults( [ 'ds_color_area' => '#FFFFFF', 'ds_color_area_warn' => '#FD9B27', 'ds_color_area_crit' => '#FF4A4A', 'ds_color_line' => '#0000FF', 'ds_color_line_mode' => 0, 'ds_transparency' => 80, 'ds_average' => true, 'ds_last' => true, ] ); } if ($o === MODIFY_COMPONENT_TEMPLATE || $o === ADD_COMPONENT_TEMPLATE) { ?> <script type='text/javascript'> function insertValueQuery() { var e_input = document.Form.ds_name; var e_select = document.getElementById('sl_list_metrics'); var sd_o = e_select.selectedIndex; if (sd_o != -1) { var chaineAj = ''; chaineAj = e_select.options[sd_o].text; chaineAj = chaineAj.replace(/\s(\[[CV]DEF\]|)\s*$/, ""); e_input.value = chaineAj; } } function popup_color_picker(t,name) { var width = 400; var height = 300; var title = name.includes("area") ? "Area color" : "Line color"; window.open('./include/common/javascript/color_picker.php?n=' + t + '&name=' + name + "&title=" + title, 'cp', 'resizable=no, location=no, width=' + width + ', height=' + height + ', menubar=no, status=yes, scrollbars=no, menubar=no' ); } </script> <?php } $tpl->assign( 'msg', [ 'changeL' => 'main.php?p=' . $p . '&o=c&compo_id=' . $compo_id, 'changeT' => _('Modify'), ] ); $tpl->assign('sort1', _('Properties')); $tpl->assign('sort2', _('Graphs')); // prepare help texts $helptext = ''; include_once 'help.php'; foreach ($help as $key => $text) { $helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>'; } $tpl->assign('helptext', $helptext); $valid = false; if ($form->validate()) { $compoObj = $form->getElement('compo_id'); if ($form->getSubmitValue('submitA')) { $compoObj->setValue(insertComponentTemplateInDB()); } elseif ($form->getSubmitValue('submitC')) { updateComponentTemplateInDB($compoObj->getValue()); } $o = WATCH_COMPONENT_TEMPLATE; $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&compo_id=' . $compoObj->getValue() . "'"] ); $form->freeze(); $valid = true; } $action = $form->getSubmitValue('action'); if ($valid) { require_once 'listComponentTemplates.php'; } else { // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true); $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('formComponentTemplate.ihtml'); } $vdef = 0; // don't list VDEF in metrics list if ($o === MODIFY_COMPONENT_TEMPLATE || $o === WATCH_COMPONENT_TEMPLATE) { $host_service_id = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['host_service_id'] ?? ($compo['host_id'] . '-' . $compo['service_id']) ); } elseif ($o === ADD_COMPONENT_TEMPLATE) { $host_service_id = HtmlAnalyzer::sanitizeAndRemoveTags( $_POST['host_service_id'] ?? null ); } ?> <script type="text/javascript"> jQuery(function () { jQuery('#sl_list_metrics').centreonSelect2({ select2: { ajax: { url: './api/internal.php?object=centreon_metric&action=ListOfMetricsByService' }, placeholder: "List of known metrics", containerCssClass: 'filter-select' }, multiple: false, allowClear: true, additionnalFilters: { id: '#host_service_id', } }); // color picker change event in form document.querySelectorAll('.formTable .js-input-colorpicker').forEach(function (colorPickerInput){ colorPickerInput.addEventListener('change', function (e){ e.stopPropagation(); let newColor = e.target.value; let nameColorPickerblock = `${e.target.name}_color`; let divColorPickerBlock = document.querySelector(`input[name=${nameColorPickerblock}]`); let oldColor = divColorPickerBlock.style.backgroundColor; divColorPickerBlock.style.backgroundColor = (newColor !== '') ? newColor : oldColor; }) }); // disable/enable List of known metrics in function of Linked Host Services to avoid an error 400 // tip to check if we display the form const urlParams = new URLSearchParams(window.location.search); if (urlParams.has("compo_id")) { const divLinkedHostServices = document.querySelector('#host_service_id'); const j_divLinkedHostServices = $('#host_service_id'); const divListKnownMetrics = document.querySelector('#sl_list_metrics'); const j_divListKnownMetrics = $('#sl_list_metrics'); if (divLinkedHostServices.value === '') { divListKnownMetrics.disabled = true; } j_divLinkedHostServices.on("change", function (e) { e.stopPropagation(); j_divListKnownMetrics.val(null).trigger("change"); let hasService = divLinkedHostServices.value !== ''; divListKnownMetrics.disabled = !hasService; }); } }); </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/views/componentTemplates/help.php
centreon/www/include/views/componentTemplates/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 = []; /** * General Information */ $help['tip_template_name'] = dgettext('help', 'Name of curve template.'); $help['tip_host_service_data_source'] = dgettext('help', 'It is possible to define a specific service for the data source.'); $help['tip_data_source_name'] = dgettext('help', 'Must be the display name of the metric. Refer to the check plugin for more information.'); /** * Display Optional Modifier */ $help['tip_stack'] = dgettext('help', 'Enables graph stacking.'); $help['tip_order'] = dgettext('help', 'Display order.'); $help['tip_invert'] = dgettext('help', 'Inverted curve (with negative values).'); /** * Colors */ $help['tip_thickness'] = dgettext('help', 'Curve thickness.'); $help['tip_line_color'] = dgettext('help', 'Curve line color.'); $help['tip_area_color'] = dgettext( 'help', 'When filling property is enable, the area color displayed in Centreon is the curve line color with transparency.' . 'For exported graphs, the area color is defined with those fields.' ); $help['tip_transparency'] = dgettext('help', 'Curve transparency. Used to export the chart.'); $help['tip_filling'] = dgettext('help', 'Enables area filling.'); /** * Legend */ $help['tip_legend_name'] = dgettext('help', 'Legend Name.'); $help['tip_display_only_the_legend'] = dgettext('help', 'Displays the legend only, thus hiding the curve.'); $help['tip_empty_line_after_this_legend'] = dgettext('help', 'Number of line breaks after the legend.'); $help['tip_print_max_value'] = dgettext('help', 'Prints maximum value.'); $help['tip_print_min_value'] = dgettext('help', 'Prints minimum value.'); $help['tip_print_minmax_int'] = dgettext('help', 'Rounds the value.'); $help['tip_print_average'] = dgettext('help', 'Prints average value.'); $help['tip_print_last_value'] = dgettext('help', 'Prints last Value.'); $help['tip_print_total_value'] = dgettext('help', 'Print total value.'); $help['tip_comments'] = dgettext('help', 'Comments regarding the curve template.');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/componentTemplates/componentTemplates.php
centreon/www/include/views/componentTemplates/componentTemplates.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 ADD_COMPONENT_TEMPLATE = 'a'; const WATCH_COMPONENT_TEMPLATE = 'w'; const MODIFY_COMPONENT_TEMPLATE = 'c'; const DUPLICATE_COMPONENT_TEMPLATE = 'm'; const DELETE_COMPONENT_TEMPLATE = 'd'; $duplicationNumbers = []; $selectedCurveTemplates = []; // id of the curve template $compo_id = filter_var( $_GET['compo_id'] ?? $_POST['compo_id'] ?? false, FILTER_VALIDATE_INT ); if (! empty($_POST['select'])) { foreach ($_POST['select'] as $curveIdSelected => $dupFactor) { if ( filter_var($dupFactor, FILTER_VALIDATE_INT) !== false && filter_var($curveIdSelected, FILTER_VALIDATE_INT) !== false ) { $selectedCurveTemplates[$curveIdSelected] = (int) $dupFactor; } } } if (! empty($_POST['dupNbr'])) { foreach ($_POST['dupNbr'] as $curveId => $dupFactor) { if ( filter_var($dupFactor, FILTER_VALIDATE_INT) !== false && filter_var($curveId, FILTER_VALIDATE_INT) !== false ) { $duplicationNumbers[$curveId] = (int) $dupFactor; } } } // Path to the configuration dir $path = './include/views/componentTemplates/'; // PHP functions require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; switch ($o) { case ADD_COMPONENT_TEMPLATE: case WATCH_COMPONENT_TEMPLATE: case MODIFY_COMPONENT_TEMPLATE: require_once $path . 'formComponentTemplate.php'; break; case DUPLICATE_COMPONENT_TEMPLATE: if (isCSRFTokenValid()) { multipleComponentTemplateInDB( $selectedCurveTemplates ?? [], $duplicationNumbers ); } else { unvalidFormMessage(); } require_once $path . 'listComponentTemplates.php'; break; case DELETE_COMPONENT_TEMPLATE: if (isCSRFTokenValid()) { deleteComponentTemplateInDB($selectedCurveTemplates ?? []); } else { unvalidFormMessage(); } require_once $path . 'listComponentTemplates.php'; break; default: require_once $path . 'listComponentTemplates.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/views/componentTemplates/DB-Func.php
centreon/www/include/views/componentTemplates/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($centreon)) { exit(); } function DsHsrTestExistence($name = null) { global $pearDB, $form; $formValues = []; if (isset($form)) { $formValues = $form->getSubmitValues(); } $query = 'SELECT compo_id FROM giv_components_template WHERE ds_name = :ds_name'; if (! empty($formValues['host_id'])) { if (preg_match('/([0-9]+)-([0-9]+)/', $formValues['host_id'], $matches)) { $formValues['host_id'] = (int) $matches[1]; $formValues['service_id'] = (int) $matches[2]; } else { throw new InvalidArgumentException('host_id must be a combination of integers'); } } if (! empty($formValues['host_id']) && ! empty($formValues['service_id'])) { $query .= ' AND host_id = :hostId AND service_id = :serviceId'; $hostId = (filter_var($formValues['host_id'], FILTER_VALIDATE_INT) === false) ? null : (int) $formValues['host_id']; $serviceId = (filter_var($formValues['service_id'], FILTER_VALIDATE_INT) === false) ? null : (int) $formValues['service_id']; } else { $query .= ' AND host_id IS NULL AND service_id IS NULL'; } $stmt = $pearDB->prepare($query); $stmt->bindValue(':ds_name', $name, PDO::PARAM_STR); if (! empty($hostId) && ! empty($serviceId)) { $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); } $stmt->execute(); $compo = $stmt->fetch(); if ($stmt->rowCount() >= 1 && $compo['compo_id'] === (int) $formValues['compo_id']) { return true; } return ! ($stmt->rowCount() >= 1 && $compo['compo_id'] !== (int) $formValues['compo_id']); } function NameHsrTestExistence($name = null) { global $pearDB, $form; $formValues = []; if (isset($form)) { $formValues = $form->getSubmitValues(); } $query = 'SELECT compo_id FROM giv_components_template WHERE name = :name'; if (! empty($formValues['host_id'])) { if (preg_match('/([0-9]+)-([0-9]+)/', $formValues['host_id'], $matches)) { $formValues['host_id'] = (int) $matches[1]; $formValues['service_id'] = (int) $matches[2]; } else { throw new InvalidArgumentException('chartId must be a combination of integers'); } } if (! empty($formValues['host_id']) && ! empty($formValues['service_id'])) { $query .= ' AND host_id = :hostId AND service_id = :serviceId'; $hostId = (filter_var($formValues['host_id'], FILTER_VALIDATE_INT) === false) ? null : (int) $formValues['host_id']; $serviceId = (filter_var($formValues['service_id'], FILTER_VALIDATE_INT) === false) ? null : (int) $formValues['service_id']; } else { $query .= ' AND host_id IS NULL AND service_id IS NULL'; } $stmt = $pearDB->prepare($query); $stmt->bindValue(':name', $name, PDO::PARAM_STR); if (! empty($hostId) && ! empty($serviceId)) { $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); } $stmt->execute(); $compo = $stmt->fetch(); if ($stmt->rowCount() >= 1 && $compo['compo_id'] === (int) $formValues['compo_id']) { return true; } return ! ($stmt->rowCount() >= 1 && $compo['compo_id'] !== (int) $formValues['compo_id']); } function checkColorFormat($color) { return ! ($color != '' && strncmp($color, '#', 1)); } /** * DELETE components in the database * * @param array $compos * @return void */ function deleteComponentTemplateInDB($compos = []) { global $pearDB; $query = 'DELETE FROM giv_components_template WHERE compo_id IN ('; foreach (array_keys($compos) as $compoId) { $query .= ':key_' . $compoId . ', '; } $query = rtrim($query, ', '); $query .= ')'; $stmt = $pearDB->prepare($query); foreach (array_keys($compos) as $compoId) { $stmt->bindValue(':key_' . $compoId, $compoId, PDO::PARAM_INT); } $stmt->execute(); defaultOreonGraph(); } function defaultOreonGraph() { global $pearDB; $dbResult = $pearDB->query("SELECT DISTINCT compo_id FROM giv_components_template WHERE default_tpl1 = '1'"); if (! $dbResult->rowCount()) { $dbResult2 = $pearDB->query("UPDATE giv_components_template SET default_tpl1 = '1' LIMIT 1"); } } function noDefaultOreonGraph() { global $pearDB; $rq = "UPDATE giv_components_template SET default_tpl1 = '0'"; $pearDB->query($rq); } function multipleComponentTemplateInDB($compos = [], $nbrDup = []) { global $pearDB; foreach ($compos as $key => $value) { $stmt = $pearDB->prepare( 'SELECT * FROM giv_components_template WHERE compo_id = :compo_id LIMIT 1' ); $stmt->bindValue(':compo_id', $key, PDO::PARAM_INT); $stmt->execute(); $row = $stmt->fetch(); $row['compo_id'] = ''; $row['default_tpl1'] = '0'; for ($i = 1; $i <= $nbrDup[$key]; $i++) { $val = null; foreach ($row as $key2 => $value2) { $value2 = is_int($value2) ? (string) $value2 : $value2; if ($key2 == 'name') { $name = $value2 . '_' . $i; $value2 = $value2 . '_' . $i; } $val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL') : $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL'); } if (NameHsrTestExistence($name)) { $rq = $val ? 'INSERT INTO giv_components_template VALUES (' . $val . ')' : null; $pearDB->query($rq); } } } } function updateComponentTemplateInDB($compoId = null) { if (! $compoId) { return; } updateComponentTemplate($compoId); } function insertComponentTemplateInDB() { return insertComponentTemplate(); } function insertComponentTemplate() { global $form, $pearDB; $formValues = []; $formValues = $form->getSubmitValues(); if ( (isset($formValues['ds_filled']) && $formValues['ds_filled'] === '1') && (! isset($formValues['ds_color_area']) || empty($formValues['ds_color_area'])) ) { $formValues['ds_color_area'] = $formValues['ds_color_line']; } [$formValues['host_id'], $formValues['service_id']] = parseHostIdPostParameter($formValues['host_id']); $bindParams = sanitizeFormComponentTemplatesParameters($formValues); $params = []; foreach (array_keys($bindParams) as $token) { $params[] = ltrim($token, ':'); } $query = 'INSERT INTO `giv_components_template` (`compo_id`, '; $query .= implode(', ', $params) . ') '; $query .= 'VALUES (NULL, ' . implode(', ', array_keys($bindParams)) . ')'; $stmt = $pearDB->prepare($query); foreach ($bindParams as $token => [$paramType, $value]) { $stmt->bindValue($token, $value, $paramType); } $stmt->execute(); defaultOreonGraph(); $result = $pearDB->query('SELECT MAX(compo_id) FROM giv_components_template'); $compoId = $result->fetch(); return $compoId['MAX(compo_id)']; } /** * Parses the host_id parameter from the form and checks the hostId-serviceId format * and returns the hostId et serviceId when defined. * * @param string|null $hostIdParameter * @return array */ function parseHostIdPostParameter(?string $hostIdParameter): array { if (! empty($hostIdParameter)) { if (preg_match('/([0-9]+)-([0-9]+)/', $hostIdParameter, $matches)) { $hostId = (int) $matches[1]; $serviceId = (int) $matches[2]; } else { throw new InvalidArgumentException('host_id must be a combination of integers'); } } else { $hostId = null; $serviceId = null; } return [$hostId, $serviceId]; } function updateComponentTemplate($compoId = null) { if (! $compoId) { return; } global $form, $pearDB; $formValues = []; $formValues = $form->getSubmitValues(); if ( (array_key_exists('ds_filled', $formValues) && $formValues['ds_filled'] === '1') && (! array_key_exists('ds_color_area', $formValues) || empty($formValues['ds_color_area'])) ) { $formValues['ds_color_area'] = $formValues['ds_color_line']; } [$formValues['host_id'], $formValues['service_id']] = parseHostIdPostParameter($formValues['host_service_id']); // Sets the default values if they have not been sent (used to deselect the checkboxes) $checkBoxValueToSet = [ 'ds_stack', 'ds_invert', 'ds_filled', 'ds_hidecurve', 'ds_max', 'ds_min', 'ds_minmax_int', 'ds_average', 'ds_last', 'ds_total', ]; foreach ($checkBoxValueToSet as $element) { $formValues[$element] ??= '0'; } $bindParams = sanitizeFormComponentTemplatesParameters($formValues); $query = 'UPDATE `giv_components_template` SET '; foreach (array_keys($bindParams) as $token) { $query .= ltrim($token, ':') . ' = ' . $token . ', '; } $query = rtrim($query, ', '); $query .= ' WHERE compo_id = :compo_id'; $stmt = $pearDB->prepare($query); foreach ($bindParams as $token => [$paramType, $value]) { $stmt->bindValue($token, $value, $paramType); } $stmt->bindValue(':compo_id', $compoId, PDO::PARAM_INT); $stmt->execute(); defaultOreonGraph(); } /** * Sanitize all the component templates parameters from the component template form * and return a ready to bind array. * * @param array $ret * @return array $bindParams */ function sanitizeFormComponentTemplatesParameters(array $ret): array { $bindParams = []; foreach ($ret as $inputName => $inputValue) { switch ($inputName) { case 'name': case 'ds_name': case 'ds_color_line': case 'ds_color_area': case 'ds_color_area_warn': case 'ds_color_area_crit': case 'ds_legend': case 'comment': case 'ds_transparency': if (! empty($inputValue)) { $inputValue = HtmlAnalyzer::sanitizeAndRemoveTags($inputValue); $bindParams[':' . $inputName] = empty($inputValue) ? [PDO::PARAM_STR, null] : [PDO::PARAM_STR, $inputValue]; } break; case 'ds_color_line_mode': $bindParams[':' . $inputName] = [ PDO::PARAM_STR, in_array($inputValue[$inputName], ['0', '1']) ? $inputValue[$inputName] : '0', ]; break; case 'ds_max': case 'ds_min': case 'ds_minmax_int': $bindParams[':' . $inputName] = [ PDO::PARAM_STR, in_array($inputValue, ['0', '1']) ? $inputValue : null, ]; break; case 'ds_average': case 'ds_last': case 'ds_total': case 'ds_stack': case 'ds_invert': case 'ds_filled': case 'ds_hidecurve': $bindParams[':' . $inputName] = [ PDO::PARAM_STR, in_array($inputValue, ['0', '1']) ? $inputValue : '0', ]; break; case 'ds_jumpline': $bindParams[':' . $inputName] = [ PDO::PARAM_STR, in_array($inputValue, ['0', '1', '2', '3']) ? $inputValue : '0', ]; break; case 'host_id': case 'service_id': case 'ds_tickness': case 'ds_order': $bindParams[':' . $inputName] = [ PDO::PARAM_INT, (filter_var($inputValue, FILTER_VALIDATE_INT) === false) ? null : (int) $inputValue, ]; break; case 'default_tpl1': $bindParams[':' . $inputName] = [ PDO::PARAM_INT, (filter_var($inputValue, FILTER_VALIDATE_INT) === false) ? null : (int) $inputValue, ]; defaultOreonGraph(); break; } } return $bindParams; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/componentTemplates/listComponentTemplates.php
centreon/www/include/views/componentTemplates/listComponentTemplates.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'; $SearchTool = null; $queryValues = []; $search = null; if (isset($_POST['searchCurve'])) { $search = $_POST['searchCurve']; $centreon->historySearch[$url] = $search; } elseif (isset($_GET['search'])) { $search = $_GET['search']; $centreon->historySearch[$url] = $search; } elseif (isset($centreon->historySearch[$url])) { $search = $centreon->historySearch[$url]; } if ($search != null) { $SearchTool = ' WHERE name LIKE :search'; $queryValues['search'] = '%' . $search . '%'; $ClWh1 = 'AND host_id IS NULL'; $ClWh2 = 'AND gct.host_id = h.host_id'; } else { $ClWh1 = 'WHERE host_id IS NULL'; $ClWh2 = 'WHERE gct.host_id = h.host_id'; } $query = '( SELECT SQL_CALC_FOUND_ROWS compo_id, NULL as host_name, host_id, service_id, name, ds_stack, ds_order, ' . 'ds_name, ds_color_line, ds_color_area, ds_filled, ds_legend, default_tpl1, ds_tickness, ds_transparency ' . "FROM giv_components_template {$SearchTool} {$ClWh1} ) UNION ( SELECT compo_id, host_name, gct.host_id, " . 'gct.service_id, name, ds_stack, ds_order, ds_name, ds_color_line, ds_color_area, ds_filled, ds_legend, ' . "default_tpl1, ds_tickness, ds_transparency FROM giv_components_template AS gct, host AS h {$SearchTool} {$ClWh2} ) " . 'ORDER BY host_name, name LIMIT ' . $num * $limit . ', ' . $limit; $stmt = $pearDB->prepare($query); foreach ($queryValues as $key => $value) { $stmt->bindValue(':' . $key, $value, PDO::PARAM_STR); } $stmt->execute(); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_desc', _('Data Source Name')); $tpl->assign('headerMenu_legend', _('Legend')); $tpl->assign('headerMenu_stack', _('Stacked')); $tpl->assign('headerMenu_order', _('Order')); $tpl->assign('headerMenu_Transp', _('Transparency')); $tpl->assign('headerMenu_tickness', _('Thickness')); $tpl->assign('headerMenu_fill', _('Filling')); $tpl->assign('headerMenu_options', _('Options')); $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); // Fill a tab with a multidimensionnal Array we put in $tpl $yesOrNo = [null => _('No'), 0 => _('No'), 1 => _('Yes')]; $elemArr = []; for ($i = 0; $compo = $stmt->fetch(); $i++) { $selectedElements = $form->addElement('checkbox', 'select[' . $compo['compo_id'] . ']'); $moptions = '&nbsp;<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) ' . 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) ' . "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $compo['compo_id'] . "]' />"; $query = "SELECT h.host_name FROM giv_components_template AS gct, host AS h WHERE gct.host_id = '" . $compo['host_id'] . "' AND gct.host_id = h.host_id"; $titles = $pearDB->query($query); $title = $titles->rowCount() ? $titles->fetchRow() : ['host_name' => 'Global']; $titles->closeCursor(); $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'title' => $title['host_name'], 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $compo['name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&compo_id=' . $compo['compo_id'], 'RowMenu_desc' => $compo['ds_name'], 'RowMenu_legend' => $compo['ds_legend'], 'RowMenu_stack' => $yesOrNo[$compo['ds_stack']], 'RowMenu_order' => $compo['ds_order'], 'RowMenu_transp' => $compo['ds_transparency'], 'RowMenu_clrLine' => $compo['ds_color_line'], 'RowMenu_clrArea' => $compo['ds_color_area'], 'RowMenu_fill' => $yesOrNo[$compo['ds_filled']], 'RowMenu_tickness' => $compo['ds_tickness'], 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); // Toolbar select ?> <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 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex === 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "this.form.elements['o1'].selectedIndex = 0;" . '']; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs1 ); $o1 = $form->getElement('o1'); $o1->setValue(null); $attrs = ['onchange' => 'javascript: ' . "if (this.form.elements['o2'].selectedIndex === 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex === 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "this.form.elements['o2'].selectedIndex = 0;" . '']; $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs ); $o2 = $form->getElement('o2'); $o2->setValue(null); $tpl->assign('limit', $limit); $tpl->assign('searchCurve', htmlentities($search)); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listComponentTemplates.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/views/graphTemplates/graphTemplates.php
centreon/www/include/views/graphTemplates/graphTemplates.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(); } $duplicationNumbers = []; $selectedGraphTemplates = []; // id of the graph template $graph_id = filter_var( $_GET['graph_id'] ?? $_POST['graph_id'] ?? false, FILTER_VALIDATE_INT ); /* * Corresponding to the lines selected in the listing * $_POST['select'] = [ * 'graphIdSelected' => 'duplicationFactor' * ] */ if (! empty($_POST['select'])) { foreach ($_POST['select'] as $gIdSelected => $dupFactor) { if (filter_var($dupFactor, FILTER_VALIDATE_INT) !== false) { $selectedGraphTemplates[$gIdSelected] = (int) $dupFactor; } } } /* * End of line text fields (duplicationFactor) in the UI for each lines * $_POST['dupNbr'] = [ * 'graphId' => 'duplicationFactor' * ] */ if (! empty($_POST['dupNbr'])) { foreach ($_POST['dupNbr'] as $gId => $dupFactor) { if (filter_var($dupFactor, FILTER_VALIDATE_INT) !== false) { $duplicationNumbers[$gId] = (int) $dupFactor; } } } // Path to the configuration dir $path = './include/views/graphTemplates/'; // PHP functions require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; switch ($o) { case 'a': // Add a graph template require_once $path . 'formGraphTemplate.php'; break; case 'w': // watch aGraph template require_once $path . 'formGraphTemplate.php'; break; case 'c': // Modify a graph template require_once $path . 'formGraphTemplate.php'; break; case 'm': // duplicate n time selected graph template(s) purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); multipleGraphTemplateInDB($selectedGraphTemplates, $duplicationNumbers); } else { unvalidFormMessage(); } require_once $path . 'listGraphTemplates.php'; break; case 'd': // delete selected graph template(s) purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); deleteGraphTemplateInDB($selectedGraphTemplates); } else { unvalidFormMessage(); } require_once $path . 'listGraphTemplates.php'; break; default: require_once $path . 'listGraphTemplates.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/views/graphTemplates/formGraphTemplate.php
centreon/www/include/views/graphTemplates/formGraphTemplate.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(); } $graph = []; if (($o == 'c' || $o == 'w') && $graph_id !== false && $graph_id > 0) { $stmt = $pearDB->prepare('SELECT * FROM giv_graphs_template WHERE graph_id = :graphId LIMIT 1'); $stmt->bindValue(':graphId', $graph_id, PDO::PARAM_INT); $stmt->execute(); $graph = array_map('myDecode', $stmt->fetch(PDO::FETCH_ASSOC)); } // Retrieve information from database for differents elements list we need on the page $compos = []; $stmt = $pearDB->query('SELECT compo_id, name FROM giv_components_template ORDER BY name'); while ($compo = $stmt->fetch(PDO::FETCH_ASSOC)) { $compos[$compo['compo_id']] = $compo['name']; } // // End of "database-retrieved" information // ######################################################### // ######################################################### // Var information to format the element // $attrsText = ['size' => '30']; $attrsText2 = ['size' => '6']; $attrsAdvSelect = ['style' => 'width: 200px; height: 100px;']; $attrsTextarea = ['rows' => '3', 'cols' => '30']; // // # Form begin // $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o == 'a') { $form->addElement('header', 'ftitle', _('Add a Graph Template')); } elseif ($o == 'c') { $form->addElement('header', 'ftitle', _('Modify a Graph Template')); } elseif ($o == 'w') { $form->addElement('header', 'ftitle', _('View a Graph Template')); } // // # Basic information // $form->addElement('header', 'information', _('General Information')); $form->addElement('header', 'color', _('Legend')); $form->addElement('text', 'name', _('Template Name'), $attrsText); $form->addElement('select', 'img_format', _('Image Type'), ['PNG' => 'PNG', 'GIF' => 'GIF']); $form->addElement('text', 'vertical_label', _('Vertical Label'), $attrsText); $form->addElement('text', 'width', _('Width'), $attrsText2); $form->addElement('text', 'height', _('Height'), $attrsText2); $form->addElement('text', 'lower_limit', _('Lower Limit'), $attrsText2); $form->addElement('text', 'upper_limit', _('Upper Limit'), ['id' => 'upperLimitTxt', 'size' => '6']); $form->addElement('checkbox', 'size_to_max', _('Size to max'), '', ['id' => 'sizeToMax', 'onClick' => 'sizeToMaxx();']); $form->addElement('text', 'ds_name', _('Data Source Name'), $attrsText); $form->addElement('select', 'base', _('Base'), ['1000' => '1000', '1024' => '1024']); $periods = [ '10800' => _('Last 3 hours'), '21600' => _('Last 6 hours'), '43200' => _('Last 12 hours'), '86400' => _('Last 24 hours'), '172800' => _('Last 2 days'), '302400' => _('Last 4 days'), '604800' => _('Last 7 days'), '1209600' => _('Last 14 days'), '2419200' => _('Last 28 days'), '2592000' => _('Last 30 days'), '2678400' => _('Last 31 days'), '5184000' => _('Last 2 months'), '10368000' => _('Last 4 months'), '15552000' => _('Last 6 months'), '31104000' => _('Last year'), ]; $sel = $form->addElement('select', 'period', _('Graph Period'), $periods); $steps = ['0' => _('No Step'), '2' => '2', '6' => '6', '10' => '10', '20' => '20', '50' => '50', '100' => '100']; $sel = $form->addElement('select', 'step', _('Recovery Step'), $steps); if ($o == 'c' || $o == 'a') { $nameColor ??= ''; $attrsText5 ??= ''; $form->addElement('button', $nameColor . '_modify', _('Modify'), $attrsText5); } $form->addElement('checkbox', 'stacked', _('Stacking')); $form->addElement('checkbox', 'scaled', _('Scale Graph Values')); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->addElement('checkbox', 'default_tpl1', _('Default Centreon Graph Template')); $form->addElement('hidden', 'graph_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); // Form Rules $form->applyFilter('__ALL__', 'myTrim'); $form->addRule('name', _('Compulsory Name'), 'required'); $form->addRule('vertical_label', _('Required Field'), 'required'); $form->addRule('width', _('Required Field'), 'required'); $form->addRule('height', _('Required Field'), 'required'); // $form->addRule('title', _("Required Field"), 'required'); - Field is not declared so rule is not needed $form->registerRule('exist', 'callback', 'testExistence'); $form->addRule('name', _('Name is already in use'), 'exist'); $form->setRequiredNote("<font style='color: red;'>*</font>&nbsp;" . _('Required fields')); // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // Just watch if ($o == 'w') { $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&graph_id=' . $graph_id . "'"] ); $form->setDefaults($graph); $form->freeze(); } elseif ($o == 'c') { $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Delete'), ['class' => 'btc bt_danger']); $form->setDefaults($graph); } elseif ($o == 'a') { $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Delete'), ['class' => 'btc bt_danger']); } $tpl->assign('msg', ['changeL' => 'main.php?p=' . $p . '&o=c&graph_id=' . $graph_id, 'changeT' => _('Modify')]); $tpl->assign('sort1', _('Properties')); $tpl->assign('sort2', _('Data Sources')); // 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); // Picker Color JS $tpl->assign( 'colorJS', " <script type='text/javascript'> function popup_color_picker(t,name) { var width = 400; var height = 300; window.open( './include/common/javascript/color_picker.php?n=' + t + '&name=' + name, 'cp', 'resizable=no, location=no, width=' + width + ', height=' + height + ', menubar=no, status=yes, scrollbars=no, menubar=no' ); } </script>" ); // End of Picker Color $valid = false; if ($form->validate()) { $graphObj = $form->getElement('graph_id'); if ($form->getSubmitValue('submitA')) { $graphObj->setValue(insertGraphTemplateInDB()); } elseif ($form->getSubmitValue('submitC')) { updateGraphTemplateInDB($graphObj->getValue()); } $o = 'w'; $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&graph_id=' . $graphObj->getValue() . "'"] ); $form->freeze(); $valid = true; } $action = $form->getSubmitValue('action'); if ($valid) { require_once 'listGraphTemplates.php'; } else { // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true); $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('formGraphTemplate.ihtml'); } ?> <script type='text/javascript'> jQuery(function () { sizeToMaxx(); }); function sizeToMaxx() { var upperLimitTxt = $('#upperLimitTxt'); var sizeToMax = $('#sizeToMax'); if (sizeToMax.is(':checked')) { upperLimitTxt.prop('disabled', true); } else { upperLimitTxt.prop('disabled', false); } } </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/views/graphTemplates/help.php
centreon/www/include/views/graphTemplates/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 = []; /** * General Information */ $help['tip_template_name'] = dgettext('help', 'Name of graph template.'); $help['tip_vertical_label'] = dgettext('help', 'Vertical Label (Y-axis).'); $help['tip_width'] = dgettext('help', 'Width of grid. Used to export the chart.'); $help['tip_height'] = dgettext('help', 'Height of grid. Used to export the chart.'); $help['tip_lower_limit'] = dgettext('help', 'Lower limit of grid.'); $help['tip_upper_limit'] = dgettext('help', 'Upper limit of grid.'); $help['tip_base'] = dgettext('help', 'Base value.'); /** * Legend */ $help['tip_scale_graph_values'] = dgettext('help', 'Enables auto scale of graph.'); $help['tip_default_centreon_graph_template'] = dgettext('help', 'Set as default graph template.'); $help['tip_comments'] = dgettext('help', 'Comments regarding the graph template.');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphTemplates/listGraphTemplates.php
centreon/www/include/views/graphTemplates/listGraphTemplates.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'; $SearchTool = null; $queryValues = []; $search = null; if (isset($_POST['searchGT'])) { $search = $_POST['searchGT']; $centreon->historySearch[$url] = $search; } elseif (isset($_GET['searchGT'])) { $search = $_GET['searchGT']; $centreon->historySearch[$url] = $search; } elseif (isset($centreon->historySearch[$url])) { $search = $centreon->historySearch[$url]; } if ($search) { $SearchTool = ' WHERE name LIKE :search'; $queryValues['search'] = '%' . $search . '%'; } $rq = 'SELECT SQL_CALC_FOUND_ROWS graph_id, name, default_tpl1, vertical_label, base, split_component FROM ' . 'giv_graphs_template gg ' . $SearchTool . ' ORDER BY name LIMIT ' . $num * $limit . ', ' . $limit; $stmt = $pearDB->prepare($rq); foreach ($queryValues as $key => $value) { $stmt->bindValue(':' . $key, $value, PDO::PARAM_STR); } $stmt->execute(); $rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn(); include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_desc', _('Description')); $tpl->assign('headerMenu_split_component', _('Split Components')); $tpl->assign('headerMenu_base', _('Base')); $tpl->assign('headerMenu_options', _('Options')); // List $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); // Fill a tab with a mutlidimensionnal Array we put in $tpl $elemArr = []; for ($i = 0; $graph = $stmt->fetch(); $i++) { $selectedElements = $form->addElement('checkbox', 'select[' . $graph['graph_id'] . ']'); $moptions = '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) ' . 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;' . "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $graph['graph_id'] . "]' />"; $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $graph['name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&graph_id=' . $graph['graph_id'], 'RowMenu_desc' => $graph['vertical_label'], 'RowMenu_base' => $graph['base'], 'RowMenu_split_component' => $graph['split_component'] ? _('Yes') : _('No'), 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); // Toolbar select ?> <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 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 3) {" . " setO(this.form.elements['o1'].value); submit();} " . '']; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs1 ); $form->setDefaults(['o1' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $attrs = ['onchange' => 'javascript: ' . "if (this.form.elements['o2'].selectedIndex == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 3) {" . " setO(this.form.elements['o2'].value); submit();} " . '']; $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs ); $form->setDefaults(['o2' => null]); $o2 = $form->getElement('o2'); $o2->setValue(null); $tpl->assign('limit', $limit); $tpl->assign('searchGT', htmlentities($search)); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listGraphTemplates.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/views/graphTemplates/DB-Func.php
centreon/www/include/views/graphTemplates/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($centreon)) { exit(); } function testExistence($name = null) { global $pearDB, $form; $id = null; if (isset($form)) { $id = $form->getSubmitValue('graph_id'); } $query = "SELECT graph_id, name FROM giv_graphs_template WHERE name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'"; $res = $pearDB->query($query); $graph = $res->fetch(); // Modif case if ($res->rowCount() >= 1 && $graph['graph_id'] == $id) { return true; } return ! ($res->rowCount() >= 1 && $graph['graph_id'] != $id); // duplicate entry } /** * Deletes from the DB the graph templates provided * * @param int[] $graphs * @return void */ function deleteGraphTemplateInDB($graphs = []): void { global $pearDB; foreach ($graphs as $key => $value) { $stmt = $pearDB->prepare('DELETE FROM giv_graphs_template WHERE graph_id = :graphTemplateId'); $stmt->bindValue(':graphTemplateId', $key, PDO::PARAM_INT); $stmt->execute(); } defaultOreonGraph(); } /* * Duplicates the selected graph templates in the DB * by adding _n to the duplicated graph template name * * @param int[] $graphs * @param int[] $nbrDup * @return void */ function multipleGraphTemplateInDB($graphs = [], $nbrDup = []): void { global $pearDB; if (! empty($graphs) && ! empty($nbrDup)) { foreach ($graphs as $key => $value) { $stmt = $pearDB->prepare('SELECT * FROM giv_graphs_template WHERE graph_id = :graphTemplateId LIMIT 1'); $stmt->bindValue(':graphTemplateId', $key, PDO::PARAM_INT); $stmt->execute(); if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $row['graph_id'] = ''; $row['default_tpl1'] = '0'; for ($i = 1; $i <= $nbrDup[$key]; $i++) { $val = null; foreach ($row as $key2 => $value2) { $value2 = is_int($value2) ? (string) $value2 : $value2; if ($key2 == 'name') { $name = $value2 . '_' . $i; $value2 = $value2 . '_' . $i; } $val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL') : $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL'); } if (testExistence($name)) { $rq = $val ? 'INSERT INTO giv_graphs_template VALUES (' . $val . ')' : null; $pearDB->query($rq); } } } } } } function defaultOreonGraph() { global $pearDB; $rq = "SELECT DISTINCT graph_id FROM giv_graphs_template WHERE default_tpl1 = '1'"; $res = $pearDB->query($rq); if (! $res->rowCount()) { $rq = "UPDATE giv_graphs_template SET default_tpl1 = '1' " . 'WHERE graph_id = (SELECT MIN(graph_id) FROM giv_graphs_template)'; $pearDB->query($rq); } } function noDefaultOreonGraph() { global $pearDB; $rq = "UPDATE giv_graphs_template SET default_tpl1 = '0'"; $pearDB->query($rq); } /** * @param $graph_id */ function updateGraphTemplateInDB($graph_id = null): void { if (! $graph_id) { return; } updateGraphTemplate((int) $graph_id); } function insertGraphTemplateInDB() { return insertGraphTemplate(); } function insertGraphTemplate(): int { global $form, $pearDB; $ret = $form->getSubmitValues(); if (isset($ret['default_tpl1']) && ((int) $ret['default_tpl1']) === 1) { // === 1 means that the checkbox is checked noDefaultOreonGraph(); } $rq = <<<'SQL' INSERT INTO `giv_graphs_template` ( `name`, `vertical_label`, `width`, `height`, `base`, `lower_limit`, `upper_limit`, `size_to_max`, `default_tpl1`, `scaled`, `stacked` , `comment`, `split_component` ) VALUES ( :name, :vertical_label, :width, :height, :base, :lower_limit, :upper_limit, :size_to_max, :default_tpl1, :scaled, :stacked, :comment, null ) SQL; $bindValues = getBindValues($ret); $stmt = $pearDB->prepare($rq); foreach ($bindValues as $key => [$type, $value]) { $stmt->bindValue($key, $value, $type); } $stmt->execute(); $graphId = $pearDB->lastInsertId(); defaultOreonGraph(); return $graphId; } /** * @param int|null $graph_id */ function updateGraphTemplate(?int $graph_id = null): void { global $form, $pearDB; if (! $graph_id) { return; } $ret = $form->getSubmitValues(); if (isset($ret['default_tpl1']) && ((int) $ret['default_tpl1']) === 1) { // === 1 means that the checkbox is checked noDefaultOreonGraph(); } $rq = <<<'SQL' UPDATE giv_graphs_template SET name = :name, vertical_label = :vertical_label, width = :width, height = :height, base = :base, lower_limit = :lower_limit, upper_limit = :upper_limit, size_to_max = :size_to_max, default_tpl1 = :default_tpl1, split_component = null, scaled = :scaled, stacked = :stacked, comment = :comment WHERE graph_id = :graph_id SQL; $bindValues = getBindValues($ret); $bindValues[':graph_id'] = [PDO::PARAM_INT, $graph_id]; $stmt = $pearDB->prepare($rq); foreach ($bindValues as $key => [$type, $value]) { $stmt->bindValue($key, $value, $type); } $stmt->execute(); defaultOreonGraph(); } /** * @param array{ * name: string, * vertical_label: string, * width: int, * height: int, * base: int, * lower_limit: int, * upper_limit: int, * size_to_max: int, * default_tpl1: int, * stacked: int, * scaled: int, * comment: string * } $data * * @return array{string, array{int, mixed} */ function getBindValues(array $data): array { return [ ':name' => isset($data['name']) && $data['name'] !== '' ? [PDO::PARAM_STR, htmlentities($data['name'], ENT_QUOTES, 'UTF-8')] : [PDO::PARAM_NULL, null], ':vertical_label' => isset($data['vertical_label']) && $data['vertical_label'] !== '' ? [PDO::PARAM_STR, htmlentities($data['vertical_label'], ENT_QUOTES, 'UTF-8')] : [PDO::PARAM_NULL, null], ':width' => isset($data['width']) && $data['width'] !== '' ? [PDO::PARAM_INT, $data['width']] : [PDO::PARAM_NULL, null], ':height' => isset($data['height']) && $data['height'] !== '' ? [PDO::PARAM_INT, $data['height']] : [PDO::PARAM_NULL, null], ':base' => isset($data['base']) && $data['base'] !== '' ? [PDO::PARAM_INT, $data['base']] : [PDO::PARAM_NULL, null], ':lower_limit' => isset($data['lower_limit']) && $data['lower_limit'] !== '' ? [PDO::PARAM_INT, $data['lower_limit']] : [PDO::PARAM_NULL, null], ':upper_limit' => isset($data['upper_limit']) && $data['upper_limit'] !== '' ? [PDO::PARAM_INT, $data['upper_limit']] : [PDO::PARAM_NULL, null], ':size_to_max' => isset($data['size_to_max']) && $data['size_to_max'] !== '' ? [PDO::PARAM_INT, $data['size_to_max']] : [PDO::PARAM_INT, 0], ':default_tpl1' => isset($data['default_tpl1']) && $data['default_tpl1'] !== '' ? [PDO::PARAM_STR, (int) $data['default_tpl1']] : [PDO::PARAM_STR, 0], ':stacked' => isset($data['stacked']) && $data['stacked'] !== '' ? [PDO::PARAM_STR, (int) $data['stacked']] : [PDO::PARAM_NULL, null], ':scaled' => isset($data['scaled']) && $data['scaled'] !== '' ? [PDO::PARAM_STR, (int) $data['scaled']] : [PDO::PARAM_STR, 0], ':comment' => isset($data['comment']) && $data['comment'] !== '' ? [PDO::PARAM_STR, htmlentities($data['comment'], ENT_QUOTES, 'UTF-8')] : [PDO::PARAM_NULL, 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/views/graphs/common-Func.php
centreon/www/include/views/graphs/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 getServiceGroupCount($search = null) { global $pearDB; if ($search != '') { $DBRESULT = $pearDB->query( "SELECT count(sg_id) FROM `servicegroup` WHERE sg_name LIKE '%{$search}%'" ); } else { $DBRESULT = $pearDB->query('SELECT count(sg_id) FROM `servicegroup`'); } $num_row = $DBRESULT->fetchRow(); $DBRESULT->closeCursor(); return $num_row['count(sg_id)']; } function getMyHostGraphs($host_id = null) { global $pearDBO; if (! isset($host_id)) { return null; } $tab_svc = []; $DBRESULT = $pearDBO->query( 'SELECT `service_id`, `service_description` ' . 'FROM `index_data`, `metrics` ' . 'WHERE metrics.index_id = index_data.id ' . "AND `host_id` = '" . CentreonDB::escape($host_id) . "' " . "AND index_data.`hidden` = '0' " . "AND index_data.`trashed` = '0' " . 'ORDER BY `service_description`' ); while ($row = $DBRESULT->fetchRow()) { $tab_svc[$row['service_id']] = $row['service_description']; } return $tab_svc; } function getHostGraphedList() { global $pearDBO; $tab = []; $DBRESULT = $pearDBO->query( 'SELECT `host_id` FROM `index_data`, `metrics` ' . 'WHERE metrics.index_id = index_data.id ' . "AND index_data.`hidden` = '0' " . "AND index_data.`trashed` = '0' " . 'ORDER BY `host_name`' ); while ($row = $DBRESULT->fetchRow()) { $tab[$row['host_id']] = 1; } return $tab; } function checkIfServiceSgIsEn($host_id = null, $service_id = null) { global $pearDBO; if (! isset($host_id) || ! isset($service_id)) { return null; } $tab_svc = []; $DBRESULT = $pearDBO->query( 'SELECT `service_id` FROM `index_data` ' . "WHERE `host_id` = '" . CentreonDB::escape($host_id) . "' " . "AND `service_id` = '" . CentreonDB::escape($service_id) . "' " . "AND index_data.`hidden` = '0' " . "AND `trashed` = '0'" ); $num_row = $DBRESULT->rowCount(); $DBRESULT->closeCursor(); return $num_row; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphs/graph-split.php
centreon/www/include/views/graphs/graph-split.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(); } // Path to the configuration dir $path = './include/views/graphs/'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $chartId = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['chartId'] ?? null); if (preg_match('/([0-9]+)_([0-9]+)/', $chartId, $matches)) { $hostId = (int) $matches[1]; $serviceId = (int) $matches[2]; } else { throw new InvalidArgumentException('chartId must be a combination of integers'); } $metrics = []; // Get list metrics $query = 'SELECT m.metric_id, m.metric_name, i.host_name, i.service_description FROM metrics m INNER JOIN index_data i ON i.id = m.index_id AND i.service_id = :serviceId AND i.host_id = :hostId'; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $metrics[] = ['id' => $chartId . '_' . $row['metric_id'], 'title' => $row['host_name'] . ' - ' . $row['service_description'] . ' : ' . $row['metric_name']]; } $period_start = isset($_GET['start']) ? filter_var($_GET['start'], FILTER_VALIDATE_INT) : 'undefined'; $period_end = isset($_GET['end']) ? filter_var($_GET['end'], FILTER_VALIDATE_INT) : 'undefined'; if ($period_start === false) { $period_start = 'undefined'; } if ($period_end === false) { $period_end = 'undefined'; } // Form begin $form = new HTML_QuickFormCustom('FormPeriod', 'get', '?p=' . $p); $periods = [ '' => '', '3h' => _('Last 3 hours'), '6h' => _('Last 6 hours'), '12h' => _('Last 12 hours'), '1d' => _('Last 24 hours'), '2d' => _('Last 2 days'), '3d' => _('Last 3 days'), '4d' => _('Last 4 days'), '5d' => _('Last 5 days'), '7d' => _('Last 7 days'), '14d' => _('Last 14 days'), '28d' => _('Last 28 days'), '30d' => _('Last 30 days'), '31d' => _('Last 31 days'), '2M' => _('Last 2 months'), '4M' => _('Last 4 months'), '6M' => _('Last 6 months'), '1y' => _('Last year'), ]; $sel = $form->addElement( 'select', 'period', _('Graph Period'), $periods, ['onchange' => 'changeInterval()'] ); $form->addElement( 'text', 'StartDate', '', [ 'id' => 'StartDate', 'class' => 'datepicker-iso', 'size' => 10, 'onchange' => 'changePeriod()', ] ); $form->addElement( 'text', 'StartTime', '', [ 'id' => 'StartTime', 'class' => 'timepicker', 'size' => 5, 'onchange' => 'changePeriod()', ] ); $form->addElement( 'text', 'EndDate', '', [ 'id' => 'EndDate', 'class' => 'datepicker-iso', 'size' => 10, 'onchange' => 'changePeriod()', ] ); $form->addElement( 'text', 'EndTime', '', [ 'id' => 'EndTime', 'class' => 'timepicker', 'size' => 5, 'onchange' => 'changePeriod()', ] ); // adding hidden fields to get the result of datepicker in an unlocalized format $form->addElement( 'hidden', 'alternativeDateStartDate', '', [ 'size' => 10, 'class' => 'alternativeDate', ] ); $form->addElement( 'hidden', 'alternativeDateEndDate', '', [ 'size' => 10, 'class' => 'alternativeDate', ] ); if ( $period_start != 'undefined' && $period_end != 'undefined' ) { $startDay = date('Y-m-d', $period_start); $startTime = date('H:i', $period_start); $endDay = date('Y-m-d', $period_end); $endTime = date('H:i', $period_end); $form->setDefaults( [ 'alternativeDateStartDate' => $startDay, 'StartTime' => $startTime, 'alternativeDateEndDate' => $endDay, 'EndTime' => $endTime, ] ); } else { $form->setDefaults( [ 'period' => '3h', ] ); } $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('metrics', $metrics); $tpl->assign('timerDisabled', returnSvg('www/img/icons/timer.svg', 'var(--icons-disabled-fill-color)', 14, 14)); $tpl->assign('timerEnabled', returnSvg('www/img/icons/timer.svg', 'var(--icons-fill-color)', 14, 14)); $tpl->display('graph-split.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/views/graphs/graph-periods.php
centreon/www/include/views/graphs/graph-periods.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(); } // Path to the configuration dir $path = './include/views/graphs/'; // Include Pear Lib // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $chartId = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['chartId'] ?? null); if (preg_match('/([0-9]+)_([0-9]+)/', $chartId, $matches)) { $hostId = (int) $matches[1]; $serviceId = (int) $matches[2]; } else { throw new InvalidArgumentException('chartId must be a combination of integers'); } // Get host and service name $serviceName = ''; $query = 'SELECT h.name, s.description FROM hosts h, services s WHERE h.host_id = :hostId AND s.service_id = :serviceId AND h.host_id = s.host_id'; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $serviceName = $row['name'] . ' - ' . $row['description']; } $periods = [ [ 'short' => '1d', 'long' => _('last day'), ], [ 'short' => '7d', 'long' => _('last week'), ], [ 'short' => '31d', 'long' => _('last month'), ], [ 'short' => '1y', 'long' => _('last year'), ], ]; $tpl->assign('periods', $periods); $tpl->assign('svc_id', $chartId); $tpl->assign('srv_name', $serviceName); $tpl->display('graph-periods.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/views/graphs/graphs.php
centreon/www/include/views/graphs/graphs.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/centreonService.class.php'; $serviceObj = new CentreonService($pearDB); $gmtObj = new CentreonGMT(); /** * Notice that this timestamp is actually the server's time and not the UNIX time * In the future this behaviour should be changed and UNIX timestamps should be used * * date('Z') is the offset in seconds between the server's time and UTC * The problem remains that on some servers that do not use UTC based timezone, leap seconds are taken in * considerations while all other dates are in comparison wirh GMT so there will be an offset of some seconds */ $currentServerMicroTime = time() * 1000 + date('Z') * 1000; $userGmt = 0; $useGmt = 1; $userGmt = $oreon->user->getMyGMT(); $gmtObj->setMyGMT($userGmt); $sMyTimezone = $gmtObj->getMyTimezone(); $sDate = new DateTime(); if (empty($sMyTimezone)) { $sMyTimezone = date_default_timezone_get(); } $sDate->setTimezone(new DateTimeZone($sMyTimezone)); $currentServerMicroTime = $sDate->getTimestamp(); // Path to the configuration dir $path = './include/views/graphs/'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); $defaultGraphs = []; function getGetPostValue($str) { $value = null; if (isset($_GET[$str]) && $_GET[$str] ) { $value = $_GET[$str]; } if (isset($_POST[$str]) && $_POST[$str] ) { $value = $_POST[$str]; } return rawurldecode($value); } // Init $aclObj = new CentreonACL($centreon->user->user_id, $centreon->user->admin); $centreonPerformanceServiceGraphObj = new CentreonPerformanceService($pearDBO, $aclObj); // Get Arguments $svc_id = getGetPostValue('svc_id'); $DBRESULT = $pearDB->query("SELECT * FROM options WHERE `key` = 'maxGraphPerformances' LIMIT 1"); $data = $DBRESULT->fetch(); $graphsPerPage = $data['value']; if (empty($graphsPerPage)) { $graphsPerPage = '18'; } if (isset($svc_id) && $svc_id ) { $tab_svcs = explode(',', $svc_id); foreach ($tab_svcs as $svc) { $graphId = null; $graphTitle = null; if (is_numeric($svc)) { $fullName = $serviceObj->getMonitoringFullName($svc); $serviceParameters = $serviceObj->getParameters($svc, ['host_id'], true); $hostId = $serviceParameters['host_id']; $graphId = $hostId . '-' . $svc; $graphTitle = $fullName; } elseif (preg_match('/^(\d+);(\d+)/', $svc, $matches)) { $hostId = $matches[1]; $serviceId = $matches[2]; $graphId = $hostId . '-' . $serviceId; $graphTitle = $serviceObj->getMonitoringFullName($serviceId, $hostId); } elseif (preg_match('/^(.+);(.+)/', $svc, $matches)) { [$hostname, $serviceDescription] = explode(';', $svc); $hostId = getMyHostID($hostname); $serviceId = getMyServiceID($serviceDescription, $hostId); $graphId = $hostId . '-' . $serviceId; $graphTitle = $serviceObj->getMonitoringFullName($serviceId, $hostId); } else { $hostId = getMyHostID($svc); $serviceList = $centreonPerformanceServiceGraphObj->getList(['host' => [$hostId]]); $defaultGraphs = array_merge($defaultGraphs, $serviceList); } if (! is_null($graphId) && ! is_null($graphTitle) && $graphTitle != '' ) { $defaultGraphs[] = ['id' => $graphId, 'text' => $graphTitle]; } } } // Get Period if is in url $period_start = 'undefined'; $period_end = 'undefined'; if (isset($_REQUEST['start']) && is_numeric($_REQUEST['start']) ) { $period_start = $_REQUEST['start']; } if (isset($_REQUEST['end']) && is_numeric($_REQUEST['end']) ) { $period_end = $_REQUEST['end']; } // Form begin $form = new HTML_QuickFormCustom('FormPeriod', 'get', '?p=' . $p); $form->addElement( 'header', 'title', _('Choose the source to graph') ); $periods = [ '' => '', '3h' => _('Last 3 hours'), '6h' => _('Last 6 hours'), '12h' => _('Last 12 hours'), '1d' => _('Last 24 hours'), '2d' => _('Last 2 days'), '3d' => _('Last 3 days'), '4d' => _('Last 4 days'), '5d' => _('Last 5 days'), '7d' => _('Last 7 days'), '14d' => _('Last 14 days'), '28d' => _('Last 28 days'), '30d' => _('Last 30 days'), '31d' => _('Last 31 days'), '2M' => _('Last 2 months'), '4M' => _('Last 4 months'), '6M' => _('Last 6 months'), '1y' => _('Last year'), ]; $sel = $form->addElement( 'select', 'period', _('Graph Period'), $periods, ['onchange' => 'changeInterval()'] ); $form->addElement( 'text', 'StartDate', '', ['id' => 'StartDate', 'class' => 'datepicker-iso', 'size' => 10, 'onchange' => 'changePeriod()'] ); $form->addElement( 'text', 'StartTime', '', ['id' => 'StartTime', 'class' => 'timepicker', 'size' => 5, 'onchange' => 'changePeriod()'] ); $form->addElement( 'text', 'EndDate', '', ['id' => 'EndDate', 'class' => 'datepicker-iso', 'size' => 10, 'onchange' => 'changePeriod()'] ); $form->addElement( 'text', 'EndTime', '', ['id' => 'EndTime', 'class' => 'timepicker', 'size' => 5, 'onchange' => 'changePeriod()'] ); // adding hidden fields to get the result of datepicker in an unlocalized format $form->addElement( 'hidden', 'alternativeDateStartDate', '', ['size' => 10, 'class' => 'alternativeDate'] ); $form->addElement( 'hidden', 'alternativeDateEndDate', '', ['size' => 10, 'class' => 'alternativeDate'] ); $form->addElement( 'button', 'graph', _('Apply Period'), ['onclick' => 'apply_period()', 'class' => 'btc bt_success'] ); if ($period_start != 'undefined' && $period_end != 'undefined') { $startDay = date('Y-m-d', $period_start); $startTime = date('H:i', $period_start); $endDay = date('Y-m-d', $period_end); $endTime = date('H:i', $period_end); $form->setDefaults( ['StartDate' => $startDay, 'StartTime' => $startTime, 'EndTime' => $endTime, 'EndDate' => $endDay] ); } else { $form->setDefaults( ['period' => '3h'] ); } $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('periodORlabel', _('or')); $tpl->assign('nbDisplayedCharts', $graphsPerPage); $tpl->assign('from', _('From')); $tpl->assign('to', _('to')); $tpl->assign('displayStatus', _('Display Status')); $tpl->assign( 'metricExceededWarningMessage', _('Too many metrics (X). More than 20 may cause performance issues.'), ); $tpl->assign('Apply', _('Apply')); $tpl->assign('defaultCharts', json_encode($defaultGraphs)); $tpl->assign('admin', $centreon->user->admin); $tpl->assign('topologyAccess', $centreon->user->access->topology); $tpl->assign('timerDisabled', returnSvg('www/img/icons/timer.svg', 'var(--icons-disabled-fill-color)', 14, 14)); $tpl->assign('timerEnabled', returnSvg('www/img/icons/timer.svg', 'var(--icons-fill-color)', 14, 14)); $tpl->assign('removeIcon', returnSvg('www/img/icons/circle-crossed.svg', 'var(--icons-fill-color)', 20, 20)); $tpl->assign('csvIcon', returnSvg('www/img/icons/csv.svg', 'var(--icons-fill-color)', 19, 19)); $tpl->assign('pictureIcon', returnSvg('www/img/icons/picture.svg', 'var(--icons-fill-color)', 19, 19)); $tpl->display('graphs.html'); $multi = 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/views/graphs/getGraphAjax.php
centreon/www/include/views/graphs/getGraphAjax.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_ . '/www/class/centreonACL.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonLog.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonUser.class.php'; require_once _CENTREON_PATH_ . '/www/include/common/common-Func.php'; session_start(); session_write_close(); // Initialize database connection $pearDB = $dependencyInjector['configuration_db']; $pearDBO = $dependencyInjector['realtime_db']; // Load session $centreon = $_SESSION['centreon']; // Validate session and get contact $sid = session_id(); $contactId = check_session($sid, $pearDB); $isAdmin = isUserAdmin($sid); $access = new CentreonACL($contactId, $isAdmin); $lca = $access->getHostsServices($pearDBO); // Build list of services $servicesReturn = []; /** * Get the list of graph by host * * Apply ACL and if the service has a graph * * @param int $host The host ID * @param bool $isAdmin If the contact is admin * @param array $lca The ACL of the contact */ function getServiceGraphByHost($host, $isAdmin, $lca) { $listGraph = []; if ( $isAdmin || (! $isAdmin && isset($lca[$host])) ) { $services = getMyHostServices($host); foreach ($services as $svcId => $svcName) { $svcGraph = getGraphByService($host, $svcId, $svcName, $isAdmin, $lca); if ($svcGraph !== false) { $listGraph[] = $svcGraph; } } } return $listGraph; } /** * Get the graph of a service * * Apply ACL and if the service has a graph * * @param int $host The host ID * @param int $svcId The service ID * @param string $svcName The service name * @param bool $isAdmin If the contact is admin * @param array $lca The ACL of the contact * @param mixed $title */ function getGraphByService($host, $svcId, $title, $isAdmin, $lca) { if ( service_has_graph($host, $svcId) && ($isAdmin || (! $isAdmin && isset($lca[$host][$svcId]))) ) { return ['type' => 'service', 'hostId' => $host, 'serviceId' => $svcId, 'id' => $host . '_' . $svcId, 'title' => $title]; } return false; } // By hostgroups if (isset($_POST['host_group_filter'])) { foreach ($_POST['host_group_filter'] as $hgId) { $hosts = getMyHostGroupHosts($hgId); foreach ($hosts as $host) { $servicesReturn = array_merge($servicesReturn, getServiceGraphByHost($host, $isAdmin, $lca)); } } } // By hosts if (isset($_POST['host_selector'])) { foreach ($_POST['host_selector'] as $host) { $servicesReturn = array_merge($servicesReturn, getServiceGraphByHost($host, $isAdmin, $lca)); } } // By servicegroups if (isset($_POST['service_group_filter'])) { foreach ($_POST['service_group_filter'] as $sgId) { $services = getMyServiceGroupServices($sgId); foreach ($services as $hostSvcId => $svcName) { [$hostId, $svcId] = explode('_', $hostSvcId); $servicesReturn[] = getGraphByService($hostId, $svcId, $svcName, $isAdmin, $lca); } } } // By service if (isset($_POST['service_selector'])) { foreach ($_POST['service_selector'] as $selectedService) { [$hostId, $svcId] = explode('-', $selectedService['id']); $svcGraph = getGraphByService($hostId, $svcId, $selectedService['text'], $isAdmin, $lca); if ($svcGraph !== false) { $servicesReturn[] = $svcGraph; } } } // By metaservice // @todo header('Content-type: application/json'); echo json_encode(array_unique($servicesReturn, SORT_REGULAR));
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphs/exportData/ExportCSVServiceData.php
centreon/www/include/views/graphs/exportData/ExportCSVServiceData.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\ValueObject\QueryParameter; require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; include_once _CENTREON_PATH_ . 'www/class/HtmlAnalyzer.php'; $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); session_start(); session_write_close(); if (! empty($session_id = session_id())) { $query = <<<'SQL' SELECT 1 FROM session WHERE session_id = :session_id SQL; $queryParameters = QueryParameters::create([ QueryParameter::string('session_id', $session_id), ]); if (($session = $pearDB->fetchOne($query, $queryParameters)) === false) { echo 'Bad session ID<br/ >'; exit(0); } } else { echo 'Session ID is missing<br />'; exit(0); } $index = filter_var( $_GET['index'] ?? $_POST['index'] ?? false, FILTER_VALIDATE_INT ); $period = HtmlAnalyzer::sanitizeAndRemoveTags( $_GET['period'] ?? $_POST['period'] ?? 'today' ); $start = filter_var( $_GET['start'] ?? false, FILTER_VALIDATE_INT ); $end = filter_var( $_GET['end'] ?? false, FILTER_VALIDATE_INT ); $chartId = HtmlAnalyzer::sanitizeAndRemoveTags( $_GET['chartId'] ?? null ); if (! empty($chartId)) { if (preg_match('/([0-9]+)_([0-9]+)/', $chartId, $matches)) { // Should be allowed chartId matching int_int regexp $hostId = (int) $matches[1]; $serviceId = (int) $matches[2]; // Making sure that splitted values are positive. if ($hostId > 0 && $serviceId > 0) { $query = 'SELECT id' . ' FROM index_data' . ' WHERE host_id = :hostId' . ' AND service_id = :serviceId'; $stmt = $pearDBO->prepare($query); $stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT); $stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $index = $row['id']; } } } else { exit('Resource not found'); } } if ($index !== false) { $stmt = $pearDBO->prepare( 'SELECT host_name, service_description FROM index_data WHERE id = :index' ); $stmt->bindValue(':index', $index, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $hName = $row['host_name']; $sName = $row['service_description']; } header('Content-Type: application/csv-tab-delimited-table'); if (isset($hName, $sName)) { header('Content-disposition: filename=' . $hName . '_' . $sName . '.csv'); } else { header('Content-disposition: filename=' . $index . '.csv'); } if ($start === false || $end === false) { exit('Start or end time is not consistent or not an integer'); } $listMetric = []; $datas = []; $listEmptyMetric = []; $stmt = $pearDBO->prepare( 'SELECT DISTINCT metric_id, metric_name ' . 'FROM metrics, index_data ' . 'WHERE metrics.index_id = index_data.id AND id = :index ORDER BY metric_name' ); $stmt->bindValue(':index', $index, PDO::PARAM_INT); $stmt->execute(); while ($indexData = $stmt->fetch(PDO::FETCH_ASSOC)) { $listMetric[$indexData['metric_id']] = $indexData['metric_name']; $listEmptyMetric[$indexData['metric_id']] = ''; $stmt2 = $pearDBO->prepare( 'SELECT ctime, `value` FROM data_bin WHERE id_metric = :metricId ' . 'AND ctime >= :start AND ctime < :end' ); $stmt2->bindValue(':start', $start, PDO::PARAM_INT); $stmt2->bindValue(':end', $end, PDO::PARAM_INT); $stmt2->bindValue(':metricId', $indexData['metric_id'], PDO::PARAM_INT); $stmt2->execute(); while ($data = $stmt2->fetch(PDO::FETCH_ASSOC)) { $datas[$data['ctime']][$indexData['metric_id']] = $data['value']; } } } // Order by timestamp ksort($datas); foreach ($datas as $key => $data) { $datas[$key] = $data + $listEmptyMetric; // Order by metric ksort($datas[$key]); } echo 'time;humantime'; if (count($listMetric)) { ksort($listMetric); echo ';' . implode(';', $listMetric); } echo "\n"; foreach ($datas as $ctime => $tab) { echo $ctime . ';' . date('Y-m-d H:i:s', $ctime); foreach ($tab as $metric_value) { if ($metric_value !== '') { printf(';%f', $metric_value); } else { echo ';'; } } echo "\n"; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphs/generateGraphs/generateImage.php
centreon/www/include/views/graphs/generateGraphs/generateImage.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 config file */ require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once _CENTREON_PATH_ . '/www/class/centreon.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonACL.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonGraph.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . '/www/class/centreonBroker.class.php'; require_once _CENTREON_PATH_ . '/www/class/HtmlAnalyzer.php'; $pearDB = new CentreonDB(); session_start(); session_write_close(); $mySessionId = session_id(); // checks for token if (! empty($_GET['username'])) { $userName = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['username'] ?? null); } $token = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['token'] ?? $_GET['akey'] ?? null); if (! empty($userName) && ! empty($token)) { $query = "SELECT contact_id FROM `contact` WHERE `contact_alias` = :contact_alias AND `contact_activate` = '1' AND `contact_autologin_key` = :token LIMIT 1"; $statement = $pearDB->prepare($query); $statement->bindValue(':contact_alias', $userName, PDO::PARAM_STR); $statement->bindValue(':token', $token, PDO::PARAM_STR); $statement->execute(); if ($row = $statement->fetch()) { $res = $pearDB->prepare('SELECT session_id FROM session WHERE session_id = :sessionId'); $res->bindValue(':sessionId', $mySessionId, PDO::PARAM_STR); $res->execute(); if (! $res->rowCount()) { // security fix - regenerate the sid to prevent session fixation session_start(); session_regenerate_id(true); $mySessionId = session_id(); $query = 'INSERT INTO `session` (`session_id`, `user_id`, `current_page`, `last_reload`, `ip_address`) VALUES (:sessionId, :contactId, NULL, :lastReload, :ipAddress)'; $statement = $pearDB->prepare($query); $statement->bindValue(':contactId', $row['contact_id'], PDO::PARAM_INT); $statement->bindValue(':sessionId', $mySessionId, PDO::PARAM_STR); $statement->bindValue(':lastReload', time(), PDO::PARAM_INT); $statement->bindValue(':ipAddress', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); $statement->execute(); } } else { exit('Invalid token'); } } $indexDataId = filter_var( $_GET['index'] ?? 0, FILTER_VALIDATE_INT ); // Checking hostName and service if (! empty($_GET['hostname'])) { $hostName = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hostname']); } if (! empty($_GET['service'])) { $serviceDescription = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['service']); } $pearDBO = new CentreonDB('centstorage'); if (! empty($hostName) && ! empty($serviceDescription)) { $statement = $pearDBO->prepare( 'SELECT `id` FROM index_data WHERE host_name = :hostName AND service_description = :serviceDescription LIMIT 1' ); $statement->bindValue(':hostName', $hostName, PDO::PARAM_STR); $statement->bindValue(':serviceDescription', $serviceDescription, PDO::PARAM_STR); $statement->execute(); if ($res = $statement->fetch()) { $indexDataId = $res['id']; } else { exit('Resource not found'); } } $chartId = null; if (! empty($_GET['chartId'])) { $chartId = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['chartId']); } if (! empty($chartId)) { if (preg_match('/([0-9]+)_([0-9]+)/', $chartId, $matches)) { $hostId = (int) $matches[1]; $serviceId = (int) $matches[2]; } else { throw new InvalidArgumentException('chartId must be a combination of integers'); } $statement = $pearDBO->prepare( 'SELECT id FROM index_data WHERE host_id = :hostId AND service_id = :serviceId' ); $statement->bindValue(':hostId', $hostId, PDO::PARAM_INT); $statement->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch()) { $indexDataId = $row['id']; } else { exit('Resource not found'); } } $res = $pearDB->prepare( 'SELECT c.contact_id, c.contact_admin FROM session s, contact c WHERE s.session_id = :sessionId AND s.user_id = c.contact_id LIMIT 1' ); $res->bindValue(':sessionId', $mySessionId, PDO::PARAM_STR); $res->execute(); if (! $res->rowCount()) { exit('Unknown user'); } $row = $res->fetch(); $isAdmin = $row['contact_admin']; $contactId = $row['contact_id']; if (! $isAdmin) { $acl = new CentreonACL($contactId, $isAdmin); if (empty($acl->getAccessGroups())) { throw new Exception('Access denied'); } $aclGroupIds = array_keys($acl->getAccessGroups()); try { $sql = 'SELECT host_id, service_id FROM index_data WHERE id = :index_data_id'; $statement = $pearDBO->prepare($sql); $statement->bindValue(':index_data_id', (int) $indexDataId, PDO::PARAM_INT); $statement->execute(); if (! $statement->rowCount()) { exit('Graph not found'); } $row = $statement->fetch(PDO::FETCH_ASSOC); unset($statement); $hostId = $row['host_id']; $serviceId = $row['service_id']; $aclGroupQueryBinds = []; foreach ($aclGroupIds as $index => $aclGroupId) { $aclGroupQueryBinds[':acl_group_' . $index] = (int) $aclGroupId; } $aclGroupBinds = implode(',', array_keys($aclGroupQueryBinds)); $sql = <<<SQL SELECT service_id FROM centreon_acl WHERE host_id = :host_id AND service_id = :service_id AND group_id IN ({$aclGroupBinds}) SQL; $statement = $pearDBO->prepare($sql); $statement->bindValue(':host_id', (int) $hostId, PDO::PARAM_INT); $statement->bindValue(':service_id', (int) $serviceId, PDO::PARAM_INT); foreach ($aclGroupQueryBinds as $queryBind => $queryValue) { $statement->bindValue($queryBind, (int) $queryValue, PDO::PARAM_INT); } $statement->execute(); if (! $statement->rowCount()) { exit('Access denied'); } } catch (PDOException $e) { (new CentreonLog())->insertLog(2, "Error while checking acl to generate graph image : {$e->getMessage()}"); exit('Access denied'); } } // Check security session if (! CentreonSession::checkSession($mySessionId, $pearDB)) { CentreonGraph::displayError(); } require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; /** * Create XML Request Objects */ $obj = new CentreonGraph($contactId, $indexDataId, 0, 1); /** * Set arguments from GET */ $obj->setRRDOption('start', $obj->checkArgument('start', $_GET, time() - (60 * 60 * 48))); $obj->setRRDOption('end', $obj->checkArgument('end', $_GET, time())); /** * Template Management */ if (isset($_GET['template_id'])) { $obj->setTemplate($_GET['template_id']); } else { $obj->setTemplate(); } $obj->init(); if (isset($_GET['flagperiod'])) { $obj->setCommandLineTimeLimit($_GET['flagperiod']); } /** * Init Curve list */ if (isset($_GET['metric'])) { $obj->setMetricList($_GET['metric']); } $obj->initCurveList(); /** * Comment time */ $obj->setOption('comment_time'); /** * Create Legende */ $obj->createLegend(); $obj->setColor('BACK', '#FFFFFF'); $obj->setColor('FRAME', '#FFFFFF'); $obj->setColor('SHADEA', '#EFEFEF'); $obj->setColor('SHADEB', '#EFEFEF'); $obj->setColor('ARROW', '#FF0000'); /** * Display Images Binary Data */ $obj->displayImageFlow(); /** * Closing session */ if (isset($_GET['akey'])) { $dbResult = $pearDB->prepare( 'DELETE FROM session WHERE session_id = ? AND user_id = (SELECT contact_id from contact where contact_autologin_key = ?)' ); $dbResult = $pearDB->execute($dbResult, [$mySessionId, $_GET['akey']]); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphs/generateGraphs/generateMetricImage.php
centreon/www/include/views/graphs/generateGraphs/generateMetricImage.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 config file */ require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once "{$centreon_path}/www/class/centreonDB.class.php"; require_once _CENTREON_PATH_ . '/www/class/centreonGraph.class.php'; /** * Create XML Request Objects */ session_start(); session_write_close(); $sid = session_id(); $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); if (! CentreonSession::checkSession($sid, $pearDB)) { CentreonGraph::displayError(); } if (isset($_GET['index']) === false && isset($_GET['svcId']) === false) { CentreonGraph::displayError(); } if (isset($_GET['index'])) { if (is_numeric($_GET['index']) === false) { CentreonGraph::displayError(); } $index = $_GET['index']; } else { [$hostId, $svcId] = explode('_', $_GET['svcId']); if (is_numeric($hostId) === false || is_numeric($svcId) === false) { CentreonGraph::displayError(); } $query = 'SELECT id FROM index_data WHERE host_id = ' . $hostId . ' AND service_id = ' . $svcId; $res = $pearDBO->query($query); if (! $res) { CentreonGraph::displayError(); } $row = $res->fetch(); if (! $row) { CentreonGraph::displayError(); } $index = $row['id']; } require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; $contactId = CentreonSession::getUser($sid, $pearDB); $obj = new CentreonGraph($contactId, $index, 0, 1); /** * Set One curve **/ $obj->onecurve = true; /** * Set metric id */ if (isset($_GET['metric'])) { $obj->setMetricList($_GET['metric']); } /** * Set arguments from GET */ $obj->setRRDOption('start', $obj->checkArgument('start', $_GET, time() - (60 * 60 * 48))); $obj->setRRDOption('end', $obj->checkArgument('end', $_GET, time())); // $obj->GMT->getMyGMTFromSession($obj->session_id, $pearDB); /** * Template Management */ if (isset($_GET['template_id'])) { $obj->setTemplate($_GET['template_id']); } else { $obj->setTemplate(); } $obj->init(); if (isset($_GET['flagperiod'])) { $obj->setCommandLineTimeLimit($_GET['flagperiod']); } $obj->initCurveList(); /** * Comment time */ $obj->setOption('comment_time'); /** * Create Legende */ $obj->createLegend(); /** * Set Colors */ $obj->setColor('BACK', '#FFFFFF'); $obj->setColor('FRAME', '#FFFFFF'); $obj->setColor('SHADEA', '#EFEFEF'); $obj->setColor('SHADEB', '#EFEFEF'); $obj->setColor('ARROW', '#FF0000'); /** * Display Images Binary Data */ $obj->displayImageFlow();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/graphs/generateGraphs/generateImageZoom.php
centreon/www/include/views/graphs/generateGraphs/generateImageZoom.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 config file require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php'); require_once "{$centreon_path}/www/class/centreonDB.class.php"; require_once _CENTREON_PATH_ . '/www/class/centreonGraph.class.php'; // Create XML Request Objects session_start(); session_write_close(); $sid = session_id(); $pearDB = new CentreonDB(); // Check security session if (! CentreonSession::checkSession($sid, $pearDB)) { CentreonGraph::displayError(); } require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; $contactId = CentreonSession::getUser($sid, $pearDB); $obj = new CentreonGraph($contactId, $_GET['index'], 0, 1); // Set arguments from GET $obj->setRRDOption('start', $obj->checkArgument('start', $_GET, time() - (60 * 60 * 48))); $obj->setRRDOption('end', $obj->checkArgument('end', $_GET, time())); // $obj->GMT->getMyGMTFromSession($obj->session_id, $pearDB); // Template Management if (isset($_GET['template_id'])) { $obj->setTemplate($_GET['template_id']); } else { $obj->setTemplate(); } $obj->init(); if (isset($_GET['flagperiod'])) { $obj->setCommandLineTimeLimit($_GET['flagperiod']); } // Init Curve list if (isset($_GET['metric'])) { $obj->setMetricList($_GET['metric']); } $obj->initCurveList(); // Comment time $obj->setOption('comment_time'); // Create Legende $obj->createLegend(); /** * Set Colors */ $obj->setColor('BACK', '#FFFFFF'); $obj->setColor('FRAME', '#FFFFFF'); $obj->setColor('SHADEA', '#EFEFEF'); $obj->setColor('SHADEB', '#EFEFEF'); $obj->setColor('ARROW', '#FF0000'); // Display Images Binary Data $obj->displayImageFlow();
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/virtualMetrics/virtualMetrics.php
centreon/www/include/views/virtualMetrics/virtualMetrics.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(); } // Path to the configuration dir $path = './include/views/virtualMetrics/'; require_once $path . 'DB-Func.php'; require_once './include/common/common-Func.php'; define('METRIC_ADD', 'a'); define('METRIC_MODIFY', 'c'); define('METRIC_DELETE', 'd'); define('METRIC_DUPLICATE', 'm'); define('METRIC_ENABLE', 's'); define('METRIC_DISABLE', 'u'); define('METRIC_WATCH', 'w'); $action = filter_var( $_POST['o1'] ?? $_POST['o2'] ?? null, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/([a|c|d|m|s|u|w]{1})/']] ); if ($action !== false) { $o = $action; } $vmetricId = filter_var( $_GET['vmetric_id'] ?? $_POST['vmetric_id'] ?? null, FILTER_VALIDATE_INT ); $selectIds = filter_var_array( $_GET['select'] ?? $_POST['select'] ?? [], FILTER_VALIDATE_INT ); $duplicateNbr = filter_var_array( $_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [], FILTER_VALIDATE_INT ); switch ($o) { case METRIC_ADD: require_once $path . 'formVirtualMetrics.php'; break; case METRIC_WATCH: if (is_int($vmetricId)) { require_once $path . 'formVirtualMetrics.php'; } else { require_once $path . 'listVirtualMetrics.php'; } break; case METRIC_MODIFY: if (is_int($vmetricId)) { require_once $path . 'formVirtualMetrics.php'; } else { require_once $path . 'listVirtualMetrics.php'; } break; case METRIC_ENABLE: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (is_int($vmetricId)) { enableVirtualMetricInDB($vmetricId); } } else { unvalidFormMessage(); } require_once $path . 'listVirtualMetrics.php'; break; case METRIC_DISABLE: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (is_int($vmetricId)) { disableVirtualMetricInDB($vmetricId); } } else { unvalidFormMessage(); } require_once $path . 'listVirtualMetrics.php'; break; case METRIC_DUPLICATE: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (! in_array(false, $selectIds) && ! in_array(false, $duplicateNbr)) { multipleVirtualMetricInDB($selectIds, $duplicateNbr); } } else { unvalidFormMessage(); } require_once $path . 'listVirtualMetrics.php'; break; case METRIC_DELETE: purgeOutdatedCSRFTokens(); if (isCSRFTokenValid()) { purgeCSRFToken(); if (! in_array(false, $selectIds)) { deleteVirtualMetricInDB($selectIds); } } else { unvalidFormMessage(); } require_once $path . 'listVirtualMetrics.php'; break; default: require_once $path . 'listVirtualMetrics.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/views/virtualMetrics/help.php
centreon/www/include/views/virtualMetrics/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 = []; /** * General Information */ $help['tip_metric_name'] = dgettext('help', 'Name of virtual metric.'); $help['tip_host_service_data_source'] = dgettext('help', 'Host / Service Data Source.'); $help['tip_def_type'] = dgettext('help', 'DEF Type.'); /** * RPN Function */ $help['tip_rpn_function'] = dgettext('help', 'RPN (Reverse Polish Notation) Function *.'); $help['tip_metric_unit'] = dgettext('help', 'Metric unit.'); $help['tip_warning_threshold'] = dgettext('help', 'Warning threshold.'); $help['tip_critical_threshold'] = dgettext('help', 'Critical threshold.'); /** * Options */ $help['tip_hidden_graph_and_legend'] = dgettext('help', 'Hides curve and legend.'); $help['tip_comments'] = dgettext('help', 'Comments regarding the virtual metric.');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/views/virtualMetrics/formVirtualMetrics.php
centreon/www/include/views/virtualMetrics/formVirtualMetrics.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; } use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\ValueObject\QueryParameter; // Database retrieve information $vmetric = []; if (($o == METRIC_MODIFY || $o == METRIC_WATCH) && is_int($vmetricId) ) { $virtualMetricResult = $pearDB->fetchAssociative( 'SELECT *, hidden vhidden FROM virtual_metrics WHERE vmetric_id = :vmetric_id LIMIT 1', new QueryParameters([ QueryParameter::int('vmetric_id', $vmetricId), ]) ); $vmetric = array_map('myDecode', $virtualMetricResult ?? []); } /* * Database retrieve information and list the different elements we need on the page * * Existing Data Index List comes from DBO -> Store in $indds Array */ $indds = ['' => sprintf('%s%s', _('Host list'), '&nbsp;&nbsp;&nbsp;')]; $mx_l = strlen($indds['']); try { $dbindd = $pearDBO->fetchAllAssociative('SELECT DISTINCT 1 AS REALTIME, host_id, host_name FROM index_data;'); } catch (ConnectionException $e) { echo 'DB Error : ' . $e->getMessage() . '<br />'; } foreach ($dbindd as $indd) { $indds[$indd['host_id']] = $indd['host_name'] . '&nbsp;&nbsp;&nbsp;'; $hn_l = strlen($indd['host_name']); if ($hn_l > $mx_l) { $mx_l = $hn_l; } } // End of "database-retrieved" information // Var information to format the element $attrsText = ['size' => '30']; $attrsText2 = ['size' => '10']; $attrsAdvSelect = ['style' => 'width: 200px; height: 100px;']; $attrsTextarea = ['rows' => '4', 'cols' => '60']; $availableRoute = './api/internal.php?object=centreon_configuration_service&action=list'; $attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $availableRoute, 'linkedObject' => 'centreonService', 'multiple' => false]; if ($o !== METRIC_ADD) { $defaultRoute = './api/internal.php?object=centreon_configuration_graphvirtualmetric' . '&action=defaultValues&target=graphVirtualMetric&field=host_id&id=' . $vmetricId; $attrServices['defaultDatasetRoute'] = $defaultRoute; } // Form begin $form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p); if ($o == METRIC_ADD) { $form->addElement('header', 'ftitle', _('Add a Virtual Metric')); } elseif ($o == METRIC_MODIFY) { $form->addElement('header', 'ftitle', _('Modify a Virtual Metric')); } elseif ($o == METRIC_WATCH) { $form->addElement('header', 'ftitle', _('View a Virtual Metric')); } /* * Basic information * Header */ $form->addElement('header', 'information', _('General Information')); $form->addElement('header', 'function', _('RPN Function')); $form->addElement('header', 'options', _('Options')); // General Information $form->addElement('text', 'vmetric_name', _('Metric Name'), $attrsText); // $form->addElement('text', 'hs_relation', _("Host / Service Data Source"), $attrsText); $form->addElement('static', 'hsr_text', _('Choose a service if you want a specific virtual metric for it.')); $form->addElement('select2', 'host_id', _('Linked Host Services'), [], $attrServices); $form->addElement( 'select', 'def_type', _('DEF Type'), [0 => 'CDEF&nbsp;&nbsp;&nbsp;', 1 => 'VDEF&nbsp;&nbsp;&nbsp;'], 'onChange=manageVDEF();' ); // RPN Function $form->addElement('textarea', 'rpn_function', _('RPN (Reverse Polish Notation) Function'), $attrsTextarea); $form->addElement( 'static', 'rpn_text', _('<br><i><b><font color="#B22222">Notes </font>:</b></i><br>- ' . 'Do not mix metrics of different sources.<br>- ' . 'Only aggregation functions work in VDEF rpn expressions.') ); // $form->addElement('select', 'real_metrics', null, $rmetrics); $form->addElement('text', 'unit_name', _('Metric Unit'), $attrsText2); $form->addElement('text', 'warn', _('Warning Threshold'), $attrsText2); $form->addRule('warn', _('Must be a number'), 'numeric'); $form->addElement('text', 'crit', _('Critical Threshold'), $attrsText2); $form->addRule('crit', _('Must be a number'), 'numeric'); // Options $form->addElement('checkbox', 'vhidden', _('Hidden Graph And Legend'), '', 'onChange=manageVDEF();'); $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea); $form->addElement('hidden', 'vmetric_id'); $redirect = $form->addElement('hidden', 'o'); $redirect->setValue($o); // Form Rules $form->applyFilter('__ALL__', 'myTrim'); $form->addRule('vmetric_name', _('Compulsory Name'), 'required'); $form->addRule('rpn_function', _('Required Field'), 'required'); $form->addRule('host_id', _('Required service'), 'required'); $form->registerRule('existName', 'callback', 'hasVirtualNameNeverUsed'); $form->registerRule('RPNInfinityLoop', 'callback', '_TestRPNInfinityLoop'); $form->addRule( 'vmetric_name', _('Name already in use for this Host/Service'), 'existName', $vmetric['index_id'] ?? null ); $form->addRule( 'rpn_function', _("Can't Use This Virtual Metric '" . (isset($_POST['vmetric_name']) ? htmlentities($_POST['vmetric_name'], ENT_QUOTES, 'UTF-8') : '') . "' In This RPN Function"), 'RPNInfinityLoop' ); $form->setRequiredNote("<font style='color: red;'>*</font>" . _(' Required fields')); // End of form definition // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); if ($o == METRIC_WATCH) { // Just watch $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&vmetric_id=' . $vmetricId . "'"] ); $form->setDefaults($vmetric); $form->freeze(); } elseif ($o == METRIC_MODIFY) { // Modify $hostId = $vmetric['host_id'] ?? null; $subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement('reset', 'reset', _('Reset'), ['onClick' => "javascript:resetLists({$hostId},{$vmetric['index_id']});", 'class' => 'btc bt_default']); $form->setDefaults($vmetric); } elseif ($o == METRIC_ADD) { // Add $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']); $res = $form->addElement( 'reset', 'reset', _('Reset'), ['onClick' => 'javascript:resetLists(0,0)', 'class' => 'btc bt_default'] ); } if ($o == METRIC_MODIFY || $o == METRIC_ADD) { ?> <script type='text/javascript'> function insertValueQuery() { var e_txtarea = document.Form.rpn_function; var e_select = document.getElementById('sl_list_metrics'); var sd_o = e_select.selectedIndex; if (sd_o != -1) { var chaineAj = ''; chaineAj = e_select.options[sd_o].text; //chaineAj = chaineAj.substring(0, chaineAj.length - 3); chaineAj = chaineAj.replace(/\s(\[[CV]DEF\]|)\s*$/, ""); if (document.selection) { // IE support e_txtarea.focus(); sel = document.selection.createRange(); sel.text = chaineAj; document.Form.insert.focus(); } else if (e_txtarea.selectionStart || e_txtarea.selectionStart == '0') { // MOZILLA/NETSCAPE support var pos_s = e_txtarea.selectionStart; var pos_e = e_txtarea.selectionEnd; var str_rpn = e_txtarea.value; e_txtarea.value = str_rpn.substring(0, pos_s) + chaineAj + str_rpn.substring(pos_e, str_rpn.length); } else { e_txtarea.value += chaineAj; } } } function manageVDEF() { var e_checkbox = document.Form.vhidden; var vdef_state = document.Form.def_type.value; if (vdef_state == 1) { e_checkbox.checked = true; } } </script> <?php } $tpl->assign('msg', ['changeL' => 'main.php?p=' . $p . '&o=c&vmetric_id=' . $vmetricId, 'changeT' => _('Modify')]); $tpl->assign('sort1', _('Properties')); $tpl->assign('sort2', _('Graphs')); // 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()) { $vmetricObj = $form->getElement('vmetric_id'); if ($o == METRIC_ADD) { $vmetricId = insertVirtualMetricInDB(); $vmetricObj->setValue($vmetricId); try { enableVirtualMetricInDB($vmetricId); } catch (Exception $e) { $error = $e->getMessage(); } } elseif ($o == METRIC_MODIFY) { try { updateVirtualMetricInDB($vmetricObj->getValue()); } catch (Exception $e) { $error = $e->getMessage(); } } if (! isset($error)) { $o = METRIC_WATCH; $form->addElement( 'button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p={$p}&o=c&vmetric_id=" . $vmetricObj->getValue() . "'"] ); $form->freeze(); $valid = true; } } $action = $form->getSubmitValue('action'); if ($valid) { require_once 'listVirtualMetrics.php'; } else { if (isset($error)) { echo "<p style='text-align: center'><span class='msg'>{$error}</span></p>"; } // 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('formVirtualMetrics.ihtml'); } $vdef = 1; // Display VDEF too if ($o == METRIC_MODIFY || $o == METRIC_WATCH) { $host_service_id = isset($_POST['host_id']) && $_POST['host_id'] != null ? filter_var($_POST['host_id'], FILTER_SANITIZE_NUMBER_INT) : $vmetric['host_id']; } elseif ($o == METRIC_ADD) { $host_service_id = isset($_POST['host_id']) && $_POST['host_id'] != null ? filter_var($_POST['host_id'], FILTER_SANITIZE_NUMBER_INT) : 0; } ?> <script type="text/javascript"> jQuery(function () { jQuery('#sl_list_metrics').centreonSelect2({ select2: { ajax: { url: './api/internal.php?object=centreon_metric&action=ListOfMetricsByService' }, placeholder: "List of known metrics", containerCssClass: 'filter-select' }, multiple: false, allowClear: true, additionnalFilters: { id: '#host_id', } }); // disable/enable List of known metrics in function of Linked Host Services to avoid an error 400 // tip to check if we display the form const urlParams = new URLSearchParams(window.location.search); if (urlParams.has("o")) { const divLinkedHostServices = document.querySelector('#host_id'); const j_divLinkedHostServices = $('#host_id'); const divListKnownMetrics = document.querySelector('#sl_list_metrics'); const j_divListKnownMetrics = $('#sl_list_metrics'); if (divLinkedHostServices.value === '') { divListKnownMetrics.disabled = true; } j_divLinkedHostServices.on("change", function (e) { e.stopPropagation(); j_divListKnownMetrics.val(null).trigger("change"); let hasService = divLinkedHostServices.value !== ''; divListKnownMetrics.disabled = !hasService; }); } }); </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/views/virtualMetrics/listVirtualMetrics.php
centreon/www/include/views/virtualMetrics/listVirtualMetrics.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; } use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\ValueObject\QueryParameter; include './include/common/autoNumLimit.php'; $queryValues ??= []; $searchTool = ''; $search = null; if (isset($_POST['searchVM'])) { $search = htmlspecialchars($_POST['searchVM'], ENT_QUOTES, 'UTF-8'); $centreon->historySearch[$url] = $search; } elseif (isset($_GET['searchVM'])) { $search = htmlspecialchars($_GET['searchVM'], ENT_QUOTES, 'UTF-8'); $centreon->historySearch[$url] = $search; } elseif (isset($centreon->historySearch[$url])) { $search = $centreon->historySearch[$url]; } if ($search) { $searchTool .= ' WHERE vmetric_name LIKE :search'; $queryValues['search'] = '%' . $search . '%'; } $listResults = []; $rows = 0; try { $listResults = $pearDB->fetchAllAssociative( <<<SQL SELECT SQL_CALC_FOUND_ROWS * FROM virtual_metrics {$searchTool} ORDER BY index_id, vmetric_name LIMIT :offset, :limit SQL, new QueryParameters(array_filter([ QueryParameter::int('offset', $num * $limit), QueryParameter::int('limit', $limit), ...array_map( fn ($key, $value) => QueryParameter::string($key, $value), array_keys($queryValues), $queryValues ), ])) ); $rows = (int) $pearDB->fetchOne('SELECT FOUND_ROWS()'); } catch (ConnectionException $e) { echo 'DB Error : ' . $e->getMessage(); } include './include/common/checkPagination.php'; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path); // start header menu $tpl->assign('headerMenu_name', _('Name')); $tpl->assign('headerMenu_unit', _('Unit')); $tpl->assign('headerMenu_rpnfunc', _('Function')); $tpl->assign('headerMenu_count', _('Data Count')); $tpl->assign('headerMenu_dtype', _('DEF Type')); $tpl->assign('headerMenu_hidden', _('Hidden')); $tpl->assign('headerMenu_status', _('Status')); $tpl->assign('headerMenu_options', _('Options')); $form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p); // Different style between each lines $style = 'one'; $attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"]; $form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess); // Fill a tab with a multidimensionnal Array we put in $tpl $deftype = [0 => 'CDEF', 1 => 'VDEF']; $yesOrNo = [null => 'No', 0 => 'No', 1 => 'Yes']; $elemArr = []; $centreonToken = createCSRFToken(); foreach ($listResults as $i => $vmetric) { $selectedElements = $form->addElement('checkbox', 'select[' . $vmetric['vmetric_id'] . ']'); if ($vmetric['vmetric_activate']) { $moptions = "<a href='main.php?p=" . $p . '&vmetric_id=' . $vmetric['vmetric_id'] . '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/disabled.png' class='ico-14 margin_right' " . "border='0' alt='" . _('Disabled') . "'></a>"; } else { $moptions = "<a href='main.php?p=" . $p . '&vmetric_id=' . $vmetric['vmetric_id'] . '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $search . '&centreon_token=' . $centreonToken . "'><img src='img/icons/enabled.png' class='ico-14 margin_right' " . "border = '0' alt = '" . _('Enabled') . "' ></a > "; } $moptions .= ' &nbsp;<input onKeypress = "if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) ' . 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;' . "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $vmetric['vmetric_id'] . "]' />"; try { $indd = $pearDBO->fetchAssociative( <<<'SQL' SELECT id,host_id,service_id FROM index_data WHERE id = :indexId SQL, new QueryParameters([ QueryParameter::int('indexId', (int) $vmetric['index_id']), ]) ); } catch (ConnectionException $e) { echo 'DB Error : ' . $e->getMessage() . '<br />'; } if ($indd !== false) { try { $hsrname = $pearDB->fetchAssociative( <<<'SQL' (SELECT concat(h.host_name,' > ',s.service_description) full_name FROM host_service_relation AS hsr, host AS h, service AS s WHERE hsr.host_host_id = h.host_id AND hsr.service_service_id = s.service_id AND h.host_id = :hostId AND s.service_id = :serviceId ) UNION (SELECT concat(h.host_name,' > ',s.service_description) full_name FROM host_service_relation AS hsr, host AS h, service AS s, hostgroup_relation AS hr WHERE hsr.hostgroup_hg_id = hr.hostgroup_hg_id AND hr.host_host_id = h.host_id AND hsr.service_service_id = s.service_id AND h.host_id = :hostId AND s.service_id = :serviceId ) ORDER BY full_name SQL, new QueryParameters([ QueryParameter::int('hostId', (int) $indd['host_id']), QueryParameter::int('serviceId', (int) $indd['service_id']), ]) ); } catch (ConnectionException $e) { echo 'DB Error : ' . $e->getMessage() . '<br />'; } if ($hsrname !== false) { $hsrname['full_name'] = str_replace('#S#', '/', $hsrname['full_name']); $hsrname['full_name'] = str_replace('#BS#', '\\', $hsrname['full_name']); } } // ## TODO : data_count $elemArr[$i] = ['MenuClass' => 'list_' . $style, 'title' => $hsrname['full_name'] ?? null, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_ckstate' => $vmetric['ck_state'], 'RowMenu_name' => $vmetric['vmetric_name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&vmetric_id=' . $vmetric['vmetric_id'], 'RowMenu_unit' => $vmetric['unit_name'], 'RowMenu_rpnfunc' => htmlentities($vmetric['rpn_function']), 'RowMenu_count' => '-', 'RowMenu_dtype' => $deftype[$vmetric['def_type']], 'RowMenu_hidden' => $yesOrNo[$vmetric['hidden']], 'RowMenu_status' => $vmetric['vmetric_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_options' => $moptions]; $style = $style != 'two' ? 'two' : 'one'; } $tpl->assign('elemArr', $elemArr); // Different messages we put in the template $tpl->assign( 'msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')] ); // Toolbar select ?> <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 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o1'].value); submit();} " . "else if (this.form.elements['o1'].selectedIndex == 3) {" . " setO(this.form.elements['o1'].value); submit();} " . '']; $form->addElement( 'select', 'o1', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs1 ); $form->setDefaults(['o1' => null]); $o1 = $form->getElement('o1'); $o1->setValue(null); $attrs = ['onchange' => 'javascript: ' . "if (this.form.elements['o2'].selectedIndex == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {" . " setO(this.form.elements['o2'].value); submit();} " . "else if (this.form.elements['o2'].selectedIndex == 3) {" . " setO(this.form.elements['o2'].value); submit();} " . '']; $form->addElement( 'select', 'o2', null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')], $attrs ); $form->setDefaults(['o2' => null]); $o2 = $form->getElement('o2'); $o2->setValue(null); $tpl->assign('limit', $limit); $tpl->assign('searchVM', htmlentities($search)); // Apply a template definition $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->display('listVirtualMetrics.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/views/virtualMetrics/DB-Func.php
centreon/www/include/views/virtualMetrics/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; } function _TestRPNInfinityLoop() { global $form; $gsvs = null; if (isset($form)) { $gsvs = $form->getSubmitValues(); } return ! ( $gsvs['vmetric_name'] != null && preg_match('/' . $gsvs['vmetric_name'] . '/i', $gsvs['rpn_function']) ); } /** * Indicates if a virtual metric name has already been used * * @global CentreonDB $pearDB * @global CentreonDB $pearDBO * @global HTML_QuickFormCustom $form * @param string $vmetricName * @param int $indexId * @return bool Return false if the virtual metric name has already been used */ function hasVirtualNameNeverUsed($vmetricName = null, $indexId = null) { global $pearDB, $pearDBO, $form; $gsvs = null; if (isset($form)) { $gsvs = $form->getSubmitValues(); } if (is_null($vmetricName) && isset($gsvs['vmetric_name'])) { $vmetricName = htmlentities($gsvs['vmetric_name'], ENT_QUOTES, 'UTF-8'); } if (is_null($indexId) && isset($gsvs['index_id'])) { $indexId = $gsvs['index_id']; } $prepareVirtualM = $pearDB->prepare( 'SELECT vmetric_id FROM virtual_metrics WHERE ' . 'vmetric_name = :metric_name AND index_id = :index_id' ); $prepareVirtualM->bindValue(':metric_name', $vmetricName, PDO::PARAM_STR); $prepareVirtualM->bindValue(':index_id', $indexId, PDO::PARAM_INT); try { $prepareVirtualM->execute(); } catch (PDOException $e) { echo 'DB Error : ' . $e->getMessage(); } $vmetric = $prepareVirtualM->fetch(); $numberOfVirtualMetric = $prepareVirtualM->rowCount(); $prepareVirtualM->closeCursor(); $prepareMetric = $pearDBO->prepare( 'SELECT metric_id FROM metrics WHERE ' . 'metric_name = :metric_name AND index_id = :index_id' ); $prepareMetric->bindValue(':metric_name', $vmetricName, PDO::PARAM_STR); $prepareMetric->bindValue(':index_id', $indexId, PDO::PARAM_INT); try { $prepareMetric->execute(); } catch (PDOException $e) { echo 'DB Error : ' . $e->getMessage(); } $metric = $prepareMetric->fetch(); $numberOfVirtualMetric += $prepareMetric->rowCount(); $prepareMetric->closeCursor(); return ! ( ($numberOfVirtualMetric >= 1 && $vmetric['vmetric_id'] != $gsvs['vmetric_id']) || isset($metric['metric_id']) ); } /** * Delete a list of virtual metric * * @global CentreonDB $pearDB * @param int[] $vmetrics List of virtual metric id to delete */ function deleteVirtualMetricInDB($vmetrics = []) { global $pearDB; foreach (array_keys($vmetrics) as $vmetricId) { try { $prepareStatement = $pearDB->prepare( 'DELETE FROM virtual_metrics WHERE vmetric_id = :vmetric_id' ); $prepareStatement->bindValue(':vmetric_id', $vmetricId, PDO::PARAM_INT); $prepareStatement->execute(); } catch (PDOException $e) { echo 'DB Error : ' . $e->getMessage(); } } } /** * Duplicates a list of virtual metric * * @global CentreonDB $pearDB * @param int[] $vmetrics List of virtual metric id to duplicate * @param int[] $nbrDup Number of copy */ function multipleVirtualMetricInDB($vmetrics = [], $nbrDup = []) { global $pearDB; foreach (array_keys($vmetrics) as $vmetricId) { $prepareStatement = $pearDB->prepare( 'SELECT * FROM virtual_metrics WHERE vmetric_id = :vmetric_id LIMIT 1' ); $prepareStatement->bindValue(':vmetric_id', $vmetricId, PDO::PARAM_INT); try { $prepareStatement->execute(); } catch (PDOException $e) { echo 'DB Error : ' . $e->getMessage(); } $vmConfiguration = $prepareStatement->fetch(); $vmConfiguration['vmetric_id'] = ''; for ($newIndex = 1; $newIndex <= $nbrDup[$vmetricId]; $newIndex++) { $val = null; $virtualMetricName = null; foreach ($vmConfiguration as $cfgName => $cfgValue) { if ($cfgName == 'vmetric_name') { $indexId = (int) $vmConfiguration['index_id']; $count = 1; $virtualMetricName = $cfgValue . '_' . $count; while (! hasVirtualNameNeverUsed($virtualMetricName, $indexId)) { $count++; $virtualMetricName = $cfgValue . '_' . $count; } $cfgValue = $virtualMetricName; } if (is_null($val)) { $val .= ($cfgValue == null) ? 'NULL' : "'" . $pearDB->escape($cfgValue) . "'"; } else { $val .= ($cfgValue == null) ? ', NULL' : ", '" . $pearDB->escape($cfgValue) . "'"; } } if (! is_null($val)) { try { $pearDB->query("INSERT INTO virtual_metrics VALUES ({$val})"); } catch (PDOException $e) { echo 'DB Error : ' . $e->getMessage(); } } } } } function updateVirtualMetricInDB($vmetric_id = null) { if (! $vmetric_id) { return; } updateVirtualMetric($vmetric_id); } function insertVirtualMetricInDB() { return insertVirtualMetric(); } /** * Insert a virtual metric * * @global HTML_QuickFormCustom $form * @global CentreonDB $pearDB * @global CentreonDB $pearDBO * @return int New virtual metric id */ function insertVirtualMetric() { global $form, $pearDB, $pearDBO; $ret = $form->getSubmitValues(); $indexId = isset($ret['host_id']) ? getIndexIdFromHostServiceId($pearDBO, $ret['host_id']) : null; $insertStatement = $pearDB->prepare( 'INSERT INTO `virtual_metrics` (`index_id`, `vmetric_name`, `def_type` , `rpn_function`, `unit_name` , `warn`, `crit`, `hidden` , `comment` , `vmetric_activate`, `ck_state`) VALUES (:index_id, :vmetric_name, :def_type, :rpn_function, :unit_name , :warn, :crit, :hidden, :comment, NULL, NULL)' ); $insertStatement->bindValue( ':index_id', $indexId, PDO::PARAM_INT ); $insertStatement->bindValue( ':vmetric_name', isset($ret['vmetric_name']) ? htmlentities($ret['vmetric_name'], ENT_QUOTES, 'UTF-8') : null, PDO::PARAM_STR ); $insertStatement->bindValue( ':def_type', $ret['def_type'] ?? null, PDO::PARAM_STR ); $insertStatement->bindValue( ':rpn_function', $ret['rpn_function'] ?? null, PDO::PARAM_STR ); $insertStatement->bindValue( ':unit_name', $ret['unit_name'] ?? null, PDO::PARAM_STR ); $insertStatement->bindValue( ':warn', array_key_exists('warn', $ret) && is_numeric($ret['warn']) ? $ret['warn'] : null, PDO::PARAM_INT ); $insertStatement->bindValue( ':crit', array_key_exists('crit', $ret) && is_numeric($ret['crit']) ? $ret['crit'] : null, PDO::PARAM_INT ); $insertStatement->bindValue( ':hidden', $ret['vhidden'] ?? null, PDO::PARAM_STR ); $insertStatement->bindValue( ':comment', isset($ret['comment']) ? htmlentities($ret['comment'], ENT_QUOTES, 'UTF-8') : null, PDO::PARAM_STR ); $insertStatement->execute(); $dbResult = $pearDB->query('SELECT MAX(vmetric_id) FROM virtual_metrics'); $vmetricId = $dbResult->fetch(); return $vmetricId['MAX(vmetric_id)']; } /** * Update a virtual metric * * @params int|null $vmetricId * @global HTML_QuickFormCustom $form * @global CentreonDB $pearDB * @global CentreonDB $pearDBO * @param null|mixed $vmetricId */ function updateVirtualMetric($vmetricId = null) { if ($vmetricId === null) { return; } global $form, $pearDB, $pearDBO; $ret = $form->getSubmitValues(); $indexId = isset($ret['host_id']) ? getIndexIdFromHostServiceId($pearDBO, $ret['host_id']) : null; $updateStatement = $pearDB->prepare( 'UPDATE `virtual_metrics` SET `index_id` = :index_id, `vmetric_name` = :vmetric_name, `def_type` = :def_type, `rpn_function` = :rpn_function, `unit_name` = :unit_name, `warn` = :warn, `crit` = :crit, `hidden` = :hidden, `comment` = :comment, `vmetric_activate` = NULL, `ck_state` = NULL WHERE vmetric_id = :vmetric_id' ); $updateStatement->bindValue( ':index_id', $indexId, PDO::PARAM_INT ); $updateStatement->bindValue( ':vmetric_name', isset($ret['vmetric_name']) ? htmlentities($ret['vmetric_name'], ENT_QUOTES, 'UTF-8') : null, PDO::PARAM_STR ); $updateStatement->bindValue( ':def_type', $ret['def_type'] ?? null, PDO::PARAM_STR ); $updateStatement->bindValue( ':rpn_function', $ret['rpn_function'] ?? null, PDO::PARAM_STR ); $updateStatement->bindValue( ':unit_name', $ret['unit_name'] ?? null, PDO::PARAM_STR ); $updateStatement->bindValue( ':warn', array_key_exists('warn', $ret) && is_numeric($ret['warn']) ? $ret['warn'] : null, PDO::PARAM_INT ); $updateStatement->bindValue( ':crit', array_key_exists('crit', $ret) && is_numeric($ret['crit']) ? $ret['crit'] : null, PDO::PARAM_INT ); $updateStatement->bindValue( ':hidden', $ret['vhidden'] ?? null, PDO::PARAM_STR ); $updateStatement->bindValue( ':comment', isset($ret['comment']) ? htmlentities($ret['comment'], ENT_QUOTES, 'UTF-8') : null, PDO::PARAM_STR ); $updateStatement->bindValue( ':vmetric_id', $vmetricId, PDO::PARAM_INT ); $updateStatement->execute(); if (! enableVirtualMetricInDB($vmetricId)) { disableVirtualMetricInDB($vmetricId, 1); } } /** * get index id from host and service id * * @param CentreonDB $dbMonitoring * @param string $hostServiceId * @return int|null */ function getIndexIdFromHostServiceId(CentreonDB $dbMonitoring, string $hostServiceId): ?int { $indexId = null; if (preg_match('/\d+\-\d+/', $hostServiceId)) { // Get index_id [$hostId, $serviceId] = explode('-', $hostServiceId); $prepare = $dbMonitoring->prepare( 'SELECT id FROM index_data WHERE host_id = :host_id AND service_id = :service_id' ); $prepare->bindValue(':host_id', $hostId, PDO::PARAM_INT); $prepare->bindValue(':service_id', $serviceId, PDO::PARAM_INT); $prepare->execute(); if ($result = $prepare->fetch(PDO::FETCH_ASSOC)) { $indexId = $result['id']; } } return $indexId; } function disableVirtualMetricInDB($vmetric_id = null, $force = 0) { if (! $vmetric_id) { return 0; } global $pearDB; $v_dis = disableVirtualMetric($vmetric_id, $force); if (! count($v_dis)) { return 0; } $statement = $pearDB->prepare( "UPDATE `virtual_metrics` SET `vmetric_activate` = '0' WHERE `vmetric_id` = :vmetric_id" ); foreach ($v_dis as $vm) { $statement->bindValue(':vmetric_id', (int) $vm, PDO::PARAM_INT); $statement->execute(); } return 1; } function &disableVirtualMetric($v_id = null, $force = 0) { global $pearDB; $v_dis = []; $repA = ['*', '+', '-', '?', '^', '$']; $repB = ['\\\\*', '\\\\+', '\\\\-', '\\\\?', '\\\\^', '\\\$']; $l_where = ($force == 0) ? " AND `vmetric_activate` = '1'" : ''; $statement = $pearDB->prepare( "SELECT index_id, vmetric_name FROM `virtual_metrics` WHERE `vmetric_id`=:vmetric_id{$l_where}" ); $statement->bindValue(':vmetric_id', (int) $v_id, PDO::PARAM_INT); $statement->execute(); if ($statement->rowCount() == 1) { $vmetric = $statement->fetch(PDO::FETCH_ASSOC); $statement->closeCursor(); $query = "SELECT vmetric_id FROM `virtual_metrics` WHERE `index_id`= :index_id AND `vmetric_activate` = '1' " . 'AND `rpn_function` REGEXP :rpn_function'; $statement = $pearDB->prepare($query); $statement->bindValue(':index_id', (int) $vmetric['index_id'], PDO::PARAM_INT); $statement->bindValue( ':rpn_function', '(^|,)' . str_replace($repA, $repB, $vmetric['vmetric_name']) . '(,|$)', PDO::PARAM_STR ); $statement->execute(); while ($d_vmetric = $statement->fetch(PDO::FETCH_ASSOC)) { $lv_dis = disableVirtualMetric($d_vmetric['vmetric_id']); if (is_array($lv_dis)) { foreach ($lv_dis as $pkey => $vm) { $v_dis[] = $vm; } } } $statement->closeCursor(); if (! $force) { $v_dis[] = $v_id; } } return $v_dis; } function enableVirtualMetricInDB($vmetric_id = null) { if (! $vmetric_id) { return 0; } global $pearDB; $v_ena = enableVirtualMetric($vmetric_id); if (! count($v_ena)) { return 0; } $statement = $pearDB->prepare( "UPDATE `virtual_metrics` SET `vmetric_activate` = '1' WHERE `vmetric_id` = :vmetric_id" ); foreach ($v_ena as $v_id) { [$rc, $output] = checkRRDGraphData($v_id); if ($rc) { $error = preg_replace('/^ERROR:\s*/', '', $output); throw new Exception("Wrong RPN syntax (RRDtool said: {$error})"); } $statement->bindValue(':vmetric_id', (int) $v_id, PDO::PARAM_INT); $statement->execute(); } return 1; } function enableVirtualMetric($v_id, $v_name = null, $index_id = null) { global $pearDB; $v_ena = []; $l_where = 'vmetric_id = :vmetric_id'; if (is_null($v_id)) { $l_where = 'vmetric_name = :vmetric_name AND index_id = :index_id'; } $query = 'SELECT vmetric_id, index_id, rpn_function FROM virtual_metrics ' . "WHERE {$l_where} AND (vmetric_activate = '0' OR vmetric_activate IS NULL);"; $statement = $pearDB->prepare($query); if (is_null($v_id)) { $statement->bindValue(':vmetric_name', $v_name, PDO::PARAM_STR); $statement->bindValue(':index_id', (int) $index_id, PDO::PARAM_INT); } else { $statement->bindValue(':vmetric_id', (int) $v_id, PDO::PARAM_INT); } $statement->execute(); if ($statement->rowCount() == 1) { $p_vmetric = $statement->fetch(PDO::FETCH_ASSOC); $l_mlist = preg_split("/\,/", $p_vmetric['rpn_function']); foreach ($l_mlist as $l_mnane) { $lv_ena = enableVirtualMetric(null, $l_mnane, $p_vmetric['index_id']); if (is_array($lv_ena)) { foreach ($lv_ena as $pkey => $vm) { $v_ena[] = $vm; } } } $v_ena[] = $p_vmetric['vmetric_id']; } $statement->closeCursor(); return $v_ena; } function checkRRDGraphData($v_id = null, $force = 0) { global $pearDB, $oreon; if (! isset($v_id)) { } // Check if already Valid $query = 'SELECT vmetric_id, def_type FROM virtual_metrics ' . "WHERE vmetric_id = :vmetric_id AND ( ck_state <> '1' OR ck_state IS NULL );"; $statement = $pearDB->prepare($query); $statement->bindValue(':vmetric_id', (int) $v_id, PDO::PARAM_INT); $statement->execute(); if ($statement->rowCount() == 1) { /** * Create XML Request Objects */ $centreon = &$_SESSION['centreon']; $obj = new CentreonGraph($centreon->user->get_id(), null, 0, 1); /** * We check only one curve **/ $obj->onecurve = true; $obj->checkcurve = true; $obj->init(); /** * Init Curve list */ $obj->setMetricList("v{$v_id}"); $obj->initCurveList(); /** * Create Legend */ $obj->createLegend(); /** * Display Images Binary Data */ $lastline = exec($oreon->optGen['rrdtool_path_bin'] . $obj->displayImageFlow() . ' 2>&1', $result, $rc); $ckstate = (! $rc) ? '1' : '2'; $statement = $pearDB->prepare( 'UPDATE `virtual_metrics` SET `ck_state` = :ck_state WHERE `vmetric_id` = :vmetric_id' ); $statement->bindValue(':ck_state', $ckstate, PDO::PARAM_STR); $statement->bindValue(':vmetric_id', (int) $v_id, PDO::PARAM_INT); $statement->execute(); return [$rc, $lastline]; } 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/eventLogs/viewLog.php
centreon/www/include/eventLogs/viewLog.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(); } $user_params = ['log_filter_host' => true, 'log_filter_svc' => true, 'log_filter_host_down' => true, 'log_filter_host_up' => true, 'log_filter_host_unreachable' => true, 'log_filter_svc_ok' => true, 'log_filter_svc_warning' => true, 'log_filter_svc_critical' => true, 'log_filter_svc_unknown' => true, 'log_filter_notif' => false, 'log_filter_error' => true, 'log_filter_alert' => true, 'log_filter_oh' => false, 'search_H' => '', 'search_S' => '', 'log_filter_period' => '', 'output' => '']; // Add QuickSearch ToolBar $FlagSearchService = 1; // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate('./include/eventLogs/template'); $getInputs = [ 'engine' => filter_input(INPUT_GET, 'engine', FILTER_VALIDATE_BOOLEAN, ['options' => ['default' => false]]), 'id' => filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['default' => 1]]), 'h' => isset($_GET['h']) ? HtmlSanitizer::createFromString($_GET['h'])->sanitize()->getString() : null, 'hg' => isset($_GET['hg']) ? HtmlSanitizer::createFromString($_GET['hg'])->sanitize()->getString() : null, 'poller' => isset($_GET['poller']) ? HtmlSanitizer::createFromString($_GET['poller'])->sanitize()->getString() : null, 'svc' => isset($_GET['svc']) ? HtmlSanitizer::createFromString($_GET['svc'])->sanitize()->getString() : null, 'svcg' => isset($_GET['svcg']) ? HtmlSanitizer::createFromString($_GET['svcg'])->sanitize()->getString() : null, 'output' => isset($_GET['output']) ? HtmlSanitizer::createFromString($_GET['output'])->sanitize()->getString() : null, ]; $postInputs = [ 'engine' => filter_input(INPUT_POST, 'engine', FILTER_VALIDATE_BOOLEAN, ['options' => ['default' => false]]), 'id' => filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, ['options' => ['default' => 1]]), 'h' => isset($_POST['h']) ? HtmlSanitizer::createFromString($_POST['h'])->sanitize()->getString() : null, 'hg' => isset($_POST['hg']) ? HtmlSanitizer::createFromString($_POST['hg'])->sanitize()->getString() : null, 'poller' => isset($_POST['poller']) ? HtmlSanitizer::createFromString($_POST['poller'])->sanitize()->getString() : null, 'svc' => isset($_POST['svc']) ? HtmlSanitizer::createFromString($_POST['svc'])->sanitize()->getString() : null, 'svcg' => isset($_POST['svcg']) ? HtmlSanitizer::createFromString($_POST['svcg'])->sanitize()->getString() : null, 'output' => isset($_POST['output']) ? HtmlSanitizer::createFromString($_POST['output'])->sanitize()->getString() : null, ]; $serviceGrpArray = []; $pollerArray = []; $defaultHosts = []; if (isset($getInputs['h'])) { $h = explode(',', $getInputs['h']); $hostObj = new CentreonHost($pearDB); $hostArray = $hostObj->getHostsNames($h); foreach ($hostArray as $defaultHost) { $defaultHosts[$defaultHost['name']] = $defaultHost['id']; } } $defaultHostgroups = []; if (isset($getInputs['hg'])) { $hg = explode(',', $getInputs['hg']); $hostGrpObj = new CentreonHostgroups($pearDB); $hostGrpArray = $hostGrpObj->getHostsgroups($hg); foreach ($hostGrpArray as $defaultHostgroup) { $defaultHostgroups[$defaultHostgroup['name']] = $defaultHostgroup['id']; } } $defaultServices = []; if (isset($getInputs['svc'])) { $services = explode(',', $getInputs['svc']); // Verify that each services is a couple hostId_serviceId foreach ($services as $service) { if (! preg_match('/^\d+_\d+$/', $service)) { throw new Exception('Invalid format provided for service. Expected hostId_serviceId'); } } $serviceObj = new CentreonService($pearDB); $serviceArray = $serviceObj->getServicesDescr($services); foreach ($serviceArray as $defaultService) { if ($defaultService['host_name'] === '_Module_Meta' && preg_match('/^meta_(\d+)/', $defaultService['description'], $matches) ) { $defaultService['host_name'] = 'Meta'; $serviceParameters = $serviceObj->getParameters($defaultService['service_id'], ['display_name']); $defaultService['description'] = $serviceParameters['display_name']; } $defaultServices[$defaultService['host_name'] . ' - ' . $defaultService['description']] = $defaultService['host_id'] . '_' . $defaultService['service_id']; } } $defaultServicegroups = []; if (isset($getInputs['svcg'])) { $svcg = explode(',', $getInputs['svcg']); $serviceGrpObj = new CentreonServicegroups($pearDB); $serviceGrpArray = $serviceGrpObj->getServicesGroups($svcg); foreach ($serviceGrpArray as $defaultServicegroup) { $defaultServicegroups[$defaultServicegroup['name']] = $defaultServicegroup['id']; } } $defaultPollers = []; if (isset($getInputs['poller'])) { $poller = explode(',', $getInputs['poller']); $pollerObj = new CentreonInstance($pearDB, $pearDBO); $pollerArray = $pollerObj->getInstancesMonitoring($poller); foreach ($pollerArray as $defaultPoller) { $defaultPollers[$defaultPoller['name']] = $defaultPoller['id']; } } // Form begin $form = new HTML_QuickFormCustom('FormPeriod', 'get', '?p=' . $p); $form->addElement('header', 'title', _('Choose the source')); $periods = [ '' => '', '10800' => _('Last 3 hours'), '21600' => _('Last 6 hours'), '43200' => _('Last 12 hours'), '86400' => _('Last 24 hours'), '172800' => _('Last 2 days'), '302400' => _('Last 4 days'), '604800' => _('Last 7 days'), '1209600' => _('Last 14 days'), '2419200' => _('Last 28 days'), '2592000' => _('Last 30 days'), '2678400' => _('Last 31 days'), '5184000' => _('Last 2 months'), '10368000' => _('Last 4 months'), '15552000' => _('Last 6 months'), '31104000' => _('Last year'), ]; $lang = [ 'ty' => _('Message Type'), 'n' => _('Notifications'), 'a' => _('Alerts'), 'e' => _('Errors'), 's' => _('Status'), 'do' => _('Down'), 'up' => _('Up'), 'un' => _('Unreachable'), 'w' => _('Warning'), 'ok' => _('Ok'), 'cr' => _('Critical'), 'uk' => _('Unknown'), 'oh' => _('Hard Only'), 'sch' => _('Search'), ]; $form->addElement('select', 'period', _('Log Period'), $periods); $form->addElement( 'text', 'StartDate', '', ['id' => 'StartDate', 'onClick' => 'resetPeriod()', 'class' => 'datepicker', 'size' => 8] ); $form->addElement( 'text', 'StartTime', '', ['id' => 'StartTime', 'onChange' => 'resetPeriod()', 'class' => 'timepicker', 'size' => 5] ); $form->addElement( 'text', 'EndDate', '', ['id' => 'EndDate', 'onClick' => 'resetPeriod()', 'class' => 'datepicker', 'size' => 8] ); $form->addElement( 'text', 'EndTime', '', ['id' => 'EndTime', 'onChange' => 'resetPeriod()', 'class' => 'timepicker', 'size' => 5] ); $form->addElement( 'text', 'output', _('Output'), ['id' => 'output', 'style' => 'width: 203px;', 'size' => 15, 'value' => $user_params['output']] ); // adding hidden fields to get the result of datepicker in an unlocalized format $form->addElement( 'hidden', 'alternativeDateStartDate', '', ['size' => 10, 'class' => 'alternativeDate'] ); $form->addElement( 'hidden', 'alternativeDateEndDate', '', ['size' => 10, 'class' => 'alternativeDate'] ); if (! $getInputs['engine']) { $form->addElement( 'button', 'graph', _('Apply period'), ['onclick' => 'apply_period()', 'class' => 'btc bt_success'] ); } else { $form->addElement( 'button', 'graph', _('Apply period'), ['onclick' => 'apply_period_engine()', 'class' => 'btc bt_success'] ); } $hostRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list'; $attrHost1 = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => $hostRoute, 'multiple' => true, 'defaultDataset' => $defaultHosts]; $form->addElement( 'select2', 'host_filter', _('Hosts'), [], $attrHost1 ); $serviceGroupRoute = './include/common/webServices/rest/' . 'internal.php?object=centreon_configuration_servicegroup&action=list'; $attrServicegroup1 = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => $serviceGroupRoute, 'multiple' => true, 'defaultDataset' => $defaultServicegroups]; $form->addElement( 'select2', 'service_group_filter', _('Service Groups'), [], $attrServicegroup1 ); $serviceRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list'; $attrService1 = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => $serviceRoute, 'multiple' => true, 'defaultDataset' => $defaultServices]; $form->addElement( 'select2', 'service_filter', _('Services'), [], $attrService1 ); $hostGroupRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup&action=list'; $attrHostGroup1 = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => $hostGroupRoute, 'multiple' => true, 'defaultDataset' => $defaultHostgroups]; $form->addElement( 'select2', 'host_group_filter', _('Host Groups'), [], $attrHostGroup1 ); $pollerRoute = './include/common/webServices/rest/internal.php?object=centreon_monitoring_poller&action=list'; $attrPoller1 = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => $pollerRoute, 'multiple' => true, 'defaultDataset' => $defaultPollers]; $form->addElement( 'select2', 'poller_filter', _('Pollers'), [], $attrPoller1 ); $form->setDefaults( ['period' => $user_params['log_filter_period']] ); $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('user_params', $user_params); $tpl->assign('lang', $lang); if (! $getInputs['engine']) { $tpl->display('viewLog.ihtml'); } else { $tpl->display('viewLogEngine.ihtml'); } ?> <script language='javascript' src='./include/common/javascript/tool.js'></script> <script> /* * Selecting chosen Host, Service, HG and/or SG */ function apply_period() { var openid = getArgsForHost(); const args = openid[0]; document.getElementById('openid').innerHTML = args; logs(args, '', ''); } function apply_period_engine() { logsEngine(); } var _limit = 30; function setL(_this) { _limit = _this; } var _num = 0; function log_4_host_page(id, formu, num) { _num = num; logs(id, formu, ''); } function log_4_engine_page(id, formu, num) { _num = num; logsEngine(); } var _host = <?php echo ! empty($user_params['log_filter_host']) ? $user_params['log_filter_host'] : 'false'; ?>; var _service = <?php echo ! empty($user_params['log_filter_svc']) ? $user_params['log_filter_svc'] : 'false'; ?>; // Casting engine variable so that it can be properly interpreted in JS var _engine = <?php echo (int) $getInputs['engine']; ?>; var _down = <?php echo $user_params['log_filter_host_down']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _up = <?php echo $user_params['log_filter_host_up']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _unreachable = <?php echo $user_params['log_filter_host_unreachable']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _ok = <?php echo $user_params['log_filter_svc_ok']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _warning = <?php echo $user_params['log_filter_svc_warning']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _critical = <?php echo $user_params['log_filter_svc_critical']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; var _unknown = <?php echo $user_params['log_filter_svc_unknown']; ?>; <?php echo ! empty($user_params['log_filter_notif']) ? $user_params['log_filter_notif'] : 'false'; ?>; <?php $filterNotif = $user_params['log_filter_notif']; ?> var _notification = <?php echo ! empty($filterNotif) ? $user_params['log_filter_notif'] : 'false'; ?>; var _error = <?php echo ! empty($user_params['log_filter_error']) ? $user_params['log_filter_error'] : 'false'; ?>; var _alert = <?php echo ! empty($user_params['log_filter_alert']) ? $user_params['log_filter_alert'] : 'false'; ?>; var _oh = <?php echo ! empty($user_params['log_filter_oh']) ? $user_params['log_filter_oh'] : 'false'; ?>; var _search_H = "<?php echo $user_params['search_H']; ?>"; var _search_S = "<?php echo $user_params['search_S']; ?>"; var _output = "<?php ?>"; // Period var currentTime = new Date(); var period = ''; var _zero_hour = ''; var _zero_min = ''; var StartDate = ''; var EndDate = ''; var StartTime = ''; var EndTime = ''; var opid = ''; if (document.FormPeriod && document.FormPeriod.period.value != "") { period = document.FormPeriod.period.value; } if (document.FormPeriod && document.FormPeriod.period.value == "") { jQuery("input[name=alternativeDateStartDate]").val(StartDate); jQuery("input[name=alternativeDateEndDate]").val(EndDate); document.FormPeriod.StartTime.value = StartTime; document.FormPeriod.EndTime.value = EndTime; } function logsEngine(type) { _output = jQuery("#output").val(); var poller_value = jQuery("#poller_filter").val(); var args = ""; var urlargs = ""; if (poller_value !== null) { urlargs += "&poller="; var flagfirst = true; poller_value.forEach(function (val) { if (val !== " " && val !== "") { if (args !== "") { args += ","; } if (!flagfirst) { urlargs += ","; } else { flagfirst = false; } urlargs += val; args += val; } }); } if (window.history.pushState) { window.history.pushState("", "", "main.php?p=20302&engine=true" + urlargs); } controlTimePeriod(); var proc = new Transformation(); var _addrXSL = "./include/eventLogs/xsl/logEngine.xsl"; if (!type) { var _addr = './include/eventLogs/xml/data.php?engine=true&output=' + _output + '&error=true&alert=false&ok=false&unreachable=false&down=false&up=false' + '&unknown=false&critical=false&warning=false&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&num=' + _num + '&limit=' + _limit + '&id=' + args; proc.setXml(_addr); proc.setXslt(_addrXSL); proc.setCallback(function(t){formatDateMoment(t); proc = null;}); proc.transform("logView4xml"); } else { if (type == 'CSV') { var _addr = './include/eventLogs/export/data.php?engine=true&output=' + _output + '&error=true&alert=false&ok=false&unreachable=false&down=false&up=false' + '&unknown=false&critical=false&warning=false&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&num=' + _num + '&limit=' + _limit + '&id=' + args + '&export=1'; } else if (type == 'XML') { var _addr = './include/eventLogs/xml/data.php?engine=true&output=' + _output + '&error=true&alert=false&ok=false&unreachable=false&down=false&up=false' + '&unknown=false&critical=false&warning=false&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&num=' + _num + '&limit=' + _limit + '&id=' + args + '&export=1'; } document.location.href = _addr; } } function resetPeriod(){ document.FormPeriod.period.value = ""; } function controlTimePeriod() { if (document.FormPeriod) { if (document.FormPeriod.period.value != "") { period = document.FormPeriod.period.value; jQuery("input[name=alternativeDateStartDate]").val(""); jQuery("#StartDate").val(""); jQuery("#StartTime").val(""); jQuery("input[name=alternativeDateEndDate]").val(""); jQuery("#EndDate").val(""); jQuery("#EndTime").val(""); } else { period = ''; StartTime = '00:00'; EndTime = '24:00'; if (jQuery("input[name=alternativeDateStartDate]").val() != "" && jQuery("input[name=alternativeDateEndDate]").val() != "" ) { StartDate = jQuery("input[name=alternativeDateStartDate]").val(); EndDate = jQuery("input[name=alternativeDateEndDate]").val(); } if (document.FormPeriod.StartTime.value != "") { StartTime = document.FormPeriod.StartTime.value; } if (document.FormPeriod.EndTime.value != "") { EndTime = document.FormPeriod.EndTime.value; } } } } function logs(id, formu, type) { opid = id; if (jQuery("#output") !== "undefined") { _output = jQuery("#output").val(); } controlTimePeriod(); if (document.formu2 && document.formu2.notification) _notification = document.formu2.notification.checked; if (document.formu2 && document.formu2.error) _error = document.formu2.error.checked; if (document.formu2 && document.formu2.alert) _alert = document.formu2.alert.checked; if (document.formu2 && document.formu2.up) _up = document.formu2.up.checked; if (document.formu2 && document.formu2.down) _down = document.formu2.down.checked; if (document.formu2 && document.formu2.unreachable) _unreachable = document.formu2.unreachable.checked; if (document.formu2 && document.formu2.ok) _ok = document.formu2.ok.checked; if (document.formu2 && document.formu2.warning) _warning = document.formu2.warning.checked; if (document.formu2 && document.formu2.critical) _critical = document.formu2.critical.checked; if (document.formu2 && document.formu2.unknown) _unknown = document.formu2.unknown.checked; if (document.formu2 && document.formu2.oh) _oh = document.formu2.oh.checked; if (document.formu2 && document.formu2.search_H) _search_H = document.formu2.search_H.checked; if (document.formu2 && document.formu2.search_S) _search_S = document.formu2.search_S.checked; var proc = new Transformation(); var _addrXSL = "./include/eventLogs/xsl/log.xsl"; if (!type) { var _addr = './include/eventLogs/xml/data.php?output=' + _output + '&oh=' + _oh + '&warning=' + _warning + '&unknown=' + _unknown + '&critical=' + _critical + '&ok=' + _ok + '&unreachable=' + _unreachable + '&down=' + _down + '&up=' + _up + '&num=' + _num + '&error=' + _error + '&alert=' + _alert + '&notification=' + _notification + '&search_H=' + _search_H + '&search_S=' + _search_S + '&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&limit=' + _limit + '&id=' + id <?php if (isset($search) && $search) { echo ' + &search_host=' . $search; } if (isset($search_service) && $search_service) { echo ' + &search_service=' . $search_service; } ?>; proc.setXml(_addr) proc.setXslt(_addrXSL) proc.setCallback(function(t){formatDateMoment(t); proc = null;}); proc.transform("logView4xml"); } else { var openid = document.getElementById('openid').innerHTML; if (_engine == 0) { if (type == 'CSV') { var _addr = './include/eventLogs/export/data.php?output=' + _output + '&oh=' + _oh + '&warning=' + _warning + '&unknown=' + _unknown + '&critical=' + _critical + '&ok=' + _ok + '&unreachable=' + _unreachable + '&down=' + _down + '&up=' + _up + '&num=' + _num + '&error=' + _error + '&alert=' + _alert + '&notification=' + _notification + '&search_H=' + _search_H + '&search_S=' + _search_S + '&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&limit=' + _limit + '&id=' + openid <?php if (isset($search) && $search) { echo ' + &search_host=' . $search; } if (isset($search_service) && $search_service) { echo ' + &search_service=' . $search_service; } ?> +'&export=1'; } else if (type == 'XML') { var _addr = './include/eventLogs/xml/data.php?output=' + _output + '&oh=' + _oh + '&warning=' + _warning + '&unknown=' + _unknown + '&critical=' + _critical + '&ok=' + _ok + '&unreachable=' + _unreachable + '&down=' + _down + '&up=' + _up + '&num=' + _num + '&error=' + _error + '&alert=' + _alert + '&notification=' + _notification + '&search_H=' + _search_H + '&search_S=' + _search_S + '&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&limit=' + _limit + '&id=' + openid <?php if (isset($search) && $search) { echo ' + &search_host=' . $search; echo '&search_host=' . $search; } if (isset($search_service) && $search_service) { echo ' + &search_service=' . $search_service; } ?> +'&export=1'; } } else { var poller_value = jQuery("#poller_filter").val(); var args = ""; if (poller_value !== null) { poller_value.forEach(function (val) { if (val !== " " && val !== "") { if (args !== "") { args += ","; } args += val; } }); } if (type == 'CSV') { var _addr = './include/eventLogs/export/data.php?engine=true&output=' + _output + '&error=true&alert=false&ok=false&unreachable=false&down=false&up=false' + '&unknown=false&critical=false&warning=false&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&num=' + _num + '&limit=' + _limit + '&id=' + args + '&export=1' } else if (type == 'XML') { var _addr = './include/eventLogs/xml/data.php?engine=true&output=' + _output + '&error=true&alert=false&ok=false&unreachable=false&down=false&up=false' + '&unknown=false&critical=false&warning=false&period=' + period + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&StartTime=' + StartTime + '&EndTime=' + EndTime + '&num=' + _num + '&limit=' + _limit + '&id=' + args + '&export=1'; } } document.location.href = _addr; } } /** * Javascript action depending on the status checkboxes * * @param bool isChecked * @return void */ function checkStatusCheckbox(isChecked) { var alertCb = document.getElementById('alertId'); if (isChecked == true) { alertCb.checked = true; } } /** * Javascript action depending on the alert/notif checkboxes * * @return void */ function checkAlertNotifCheckbox() { if (document.getElementById('alertId').checked == false && document.getElementById('notifId').checked == false ) { document.getElementById('cb_up').checked = false; document.getElementById('cb_down').checked = false; document.getElementById('cb_unreachable').checked = false; document.getElementById('cb_ok').checked = false; document.getElementById('cb_warning').checked = false; document.getElementById('cb_critical').checked = false; document.getElementById('cb_unknown').checked = false; } } function getArgsForHost() { var host_value = jQuery("#host_filter").val(); const serviceValues = jQuery("#service_filter").select2('data'); var hg_value = jQuery("#host_group_filter").val(); var sg_value = jQuery("#service_group_filter").val(); var args = ""; var urlargs = ""; if (host_value !== null) { urlargs += "&h="; var flagfirst = true; host_value.forEach(function (val) { if (val !== " " && val !== "") { if (args !== "") { args += ","; } if (!flagfirst) { urlargs += ","; } else { flagfirst = false; } urlargs += val; args += "HH_" + val; } }); } if (serviceValues.length > 0) { urlargs += "&svc="; var flagfirst = true; serviceValues.forEach(function (val) { if (val.id !== " " && val.id !== "") { if (args !== "") { args += ","; } if (!flagfirst) { urlargs += ","; } else { flagfirst = false; } urlargs += val.id.replace("-", "_"); if (val.text.substring(0, 5) === 'Meta ') { args += "MS_" + val.id.replace("-", "_"); } else { args += "HS_" + val.id.replace("-", "_"); } } }); } if (hg_value !== null) { urlargs += "&hg="; var flagfirst = true; hg_value.forEach(function (val) { if (val !== " " && val !== "") { if (args !== "") { args += ","; } if (!flagfirst) { urlargs += ","; } else { flagfirst = false; } urlargs += val; args += "HG_" + val; } }); } if (sg_value !== null) { urlargs += "&svcg="; var flagfirst = true; sg_value.forEach(function (val) { if (val !== " " && val !== "") { if (args !== "") { args += ","; } if (!flagfirst) { urlargs += ","; } else { flagfirst = false; } urlargs += val; args += "SG_" + val; } }); } return new Array(args, urlargs); } jQuery(function () { if (_engine == 0) { // Here is your precious function // You can call as many functions as you want here; /* initializing datepicker and the alternative format field */ initDatepicker("datepicker", "mm/dd/yy", null); jQuery("#service_group_filter, #host_filter, #service_filter, #host_group_filter").change( function (event, infos) { var argArray = getArgsForHost(); args = argArray[0]; urlargs = argArray[1]; if (typeof infos !== "undefined" && infos.origin === "select2defaultinit") { return false; } if (window.history.pushState) { window.history.pushState("", "", "main.php?p=20301" + urlargs); } document.getElementById('openid').innerHTML = args; logs(args, '', false); }); //setServiceGroup jQuery("#setHostGroup").click(function () { var hg_value = jQuery("#host_group_filter").val(); var host_value = jQuery("#host_filter").val(); if (host_value === null) { host_value = new Array(); } jQuery.ajax({ url: "./api/internal.php?object=centreon_configuration_hostgroup&action=hostList", type: "GET", dataType: "json", data: "hgid=" + hg_value, success: function (json) { json.items.forEach(function (elem) { if (jQuery.inArray(elem.id, host_value) === -1) { var existingOptions = jQuery("#host_filter").find('option'); var existFlag = false; existingOptions.each(function (el) { if (jQuery(this).val() == elem.id) { existFlag = true; } }); if (!existFlag) { jQuery("#host_filter").append(jQuery('<option>').val(elem.id).html(elem.text)); } host_value.push(elem.id); } }); jQuery("#host_filter").val(host_value).trigger("change", [{origin: "select2defaultinit"}]); jQuery("#host_group_filter").val(''); jQuery("#host_group_filter").empty().append(jQuery('<option>')); jQuery("#host_group_filter").trigger("change", [{origin: "select2defaultinit"}]); } }); }); jQuery("#setServiceGroup").click(function () { var service_value = jQuery("#service_filter").val(); var sg_value = jQuery("#service_group_filter").val(); if (service_value === null) { service_value = new Array(); } jQuery.ajax({
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/Paginator.php
centreon/www/include/eventLogs/Paginator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); /** * @implements IteratorAggregate<int, int> */ class Paginator implements IteratorAggregate { /** * Maximum number of pages displayed after / before the current page. */ public const PAGER_SPAN = 5; /** @var positive-int */ public readonly int $currentPageNb; /** @var positive-int */ public readonly int $nbResultsPerPage; /** @var int<0, max> */ public readonly int $totalRecordsCount; /** @var positive-int */ public readonly int $totalPagesCount; public function __construct(int $currentPageNb, int $nbResultsPerPage, int $totalRecordsCount = 0) { $this->currentPageNb = max(1, $currentPageNb); $this->nbResultsPerPage = max(1, $nbResultsPerPage); $this->totalRecordsCount = max(0, $totalRecordsCount); $this->totalPagesCount = max(1, (int) ceil($totalRecordsCount / $nbResultsPerPage)); } public function withTotalRecordCount(int $count): self { return new self($this->currentPageNb, $this->nbResultsPerPage, $count); } public function getOffset(): int { return $this->nbResultsPerPage * ($this->currentPageNb - 1); } public function getOffsetMaximum(): int { return $this->isOutOfUpperBound() ? $this->nbResultsPerPage * ($this->totalPagesCount - 1) : $this->getOffset(); } public function isOutOfUpperBound(): bool { return $this->currentPageNb > $this->totalPagesCount; } public function isActive(int $pageNb): bool { return $pageNb === $this->currentPageNb || ($pageNb === $this->totalPagesCount && $this->isOutOfUpperBound()); } public function getUrl(int $pageNb): string { return sprintf('&num=%d&limit=%d', $pageNb, $this->nbResultsPerPage); } public function getPageNumberPrevious(): ?int { return $this->currentPageNb > 1 ? $this->currentPageNb - 1 : null; } public function getPageNumberNext(): ?int { return $this->currentPageNb < $this->totalPagesCount ? $this->currentPageNb + 1 : null; } /** * @return Generator<int, int> */ public function getIterator(): Generator { $currentPage = min($this->currentPageNb, $this->totalPagesCount); $lowestPageNb = max(1, $currentPage - self::PAGER_SPAN); $highestPageNb = min($this->totalPagesCount, $currentPage + self::PAGER_SPAN); yield from range($lowestPageNb, $highestPageNb); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/xml/data.php
centreon/www/include/eventLogs/xml/data.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', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); // Include configurations files include_once '../../../../config/centreon.config.php'; // Require Classes require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; require_once __DIR__ . '/../../../../bootstrap.php'; require_once __DIR__ . '/../Paginator.php'; require_once __DIR__ . '/PaginationRenderer.php'; require_once __DIR__ . '/../../../class/centreonLog.class.php'; require_once __DIR__ . '/../../../class/exceptions/CentreonDbException.php'; // Connect to DB $pearDB = $dependencyInjector['configuration_db']; $pearDBO = $dependencyInjector['realtime_db']; // Check Session CentreonSession::start(); if (! CentreonSession::checkSession(session_id(), $pearDB)) { echo 'Bad Session'; exit(); } /** * @var Centreon $centreon */ $centreon = $_SESSION['centreon']; /** * true: URIs will correspond to deprecated pages * false: URIs will correspond to new page (Resource Status) */ $useDeprecatedPages = $centreon->user->doesShowDeprecatedPages(); /** * Language informations init */ $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'); define('STATUS_OK', 0); define('STATUS_WARNING', 1); define('STATUS_CRITICAL', 2); define('STATUS_UNKNOWN', 3); define('STATUS_PENDING', 4); define('STATUS_ACKNOWLEDGEMENT', 5); define('STATUS_UP', 0); define('STATUS_DOWN', 1); define('STATUS_UNREACHABLE', 2); define('TYPE_SOFT', 0); define('TYPE_HARD', 1); /** * Defining constants for the ACK message types */ define('SERVICE_ACKNOWLEDGEMENT_MSG_TYPE', 10); define('HOST_ACKNOWLEDGEMENT_MSG_TYPE', 11); // Include Access Class include_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php'; $defaultLimit = $centreon->optGen['maxViewConfiguration'] > 1 ? (int) $centreon->optGen['maxViewConfiguration'] : 30; /** * Retrieves and optionally sanitizes a value from GET or POST input, with fallback defaults. * * This function checks for a specified key in the `$_GET` or `$_POST` arrays, * applying optional sanitization and filtering if required. It supports a * fallback default value if the key does not exist in either array. * * @param string $key the name of the input key to retrieve from `$_GET` or `$_POST` * @param bool $sanitize if true, applies HTML sanitization to the value * @param mixed $default a default value returned if the key does not exist in the inputs * @param int|null $filter Optional filter constant for input validation, e.g., `FILTER_VALIDATE_INT`. * * @return mixed The sanitized and filtered input value, or the default value if the key is not found. * * Usage: * ```php * $name = getInput('name', true, 'Guest'); * $age = getInput('age', false, 0, FILTER_VALIDATE_INT); * ``` */ function getInput($key, $sanitize = false, $default = null, $filter = null) { $value = $_GET[$key] ?? $_POST[$key] ?? $default; if ($filter !== null && $value !== null) { $value = filter_var($value, $filter, FILTER_NULL_ON_FAILURE) ?? $default; } if ($sanitize && $value !== null) { // Sanitizing the input $value = HtmlSanitizer::createFromString($value) ->removeTags() // Remove all HTML tags ->sanitize() // Convert special characters to HTML entities ->getString(); } return $value; } // Define input specifications $inputDefinitions = [ 'lang' => ['sanitize' => true, 'default' => null], 'id' => ['sanitize' => true, 'default' => '-1'], 'num' => ['default' => 0, 'filter' => FILTER_VALIDATE_INT], 'limit' => ['default' => $defaultLimit, 'filter' => FILTER_VALIDATE_INT], 'StartDate' => ['sanitize' => true, 'default' => ''], 'EndDate' => ['sanitize' => true, 'default' => ''], 'StartTime' => ['sanitize' => true, 'default' => ''], 'EndTime' => ['sanitize' => true, 'default' => ''], 'period' => ['default' => -1, 'filter' => FILTER_VALIDATE_INT], 'engine' => ['default' => 'false'], 'up' => ['default' => 'true'], 'down' => ['default' => 'true'], 'unreachable' => ['default' => 'true'], 'ok' => ['default' => 'true'], 'warning' => ['default' => 'true'], 'critical' => ['default' => 'true'], 'unknown' => ['default' => 'true'], 'acknowledgement' => ['default' => 'true'], 'notification' => ['default' => 'false'], 'alert' => ['default' => 'true'], 'oh' => ['default' => 'false'], 'error' => ['default' => 'false'], 'output' => ['sanitize' => true, 'default' => ''], 'search_H' => ['default' => 'VIDE'], 'search_S' => ['default' => 'VIDE'], 'search_host' => ['default' => ''], 'search_service' => ['default' => ''], 'export' => ['default' => 0], ]; // Collect inputs $inputs = []; foreach ($inputDefinitions as $key => $properties) { $sanitize = $properties['sanitize'] ?? false; $default = $properties['default'] ?? null; $filter = $properties['filter'] ?? null; $inputs[$key] = getInput($key, $sanitize, $default, $filter); } $kernel = App\Kernel::createForWeb(); $resourceController = $kernel->getContainer()->get( Centreon\Application\Controller\MonitoringResourceController::class ); // Start XML document root $buffer = new CentreonXML(); $buffer->startElement('root'); // Security check $lang_ = $inputs['lang'] ?? '-1'; $openid = $inputs['id']; $sid = session_id(); $sid ??= '-1'; // Init GMT class $centreonGMT = new CentreonGMT(); $centreonGMT->getMyGMTFromSession($sid); // Check Session $contact_id = check_session($sid, $pearDB); $is_admin = isUserAdmin($sid); if (isset($sid) && $sid) { $access = new CentreonAcl($contact_id, $is_admin); $lca = [ 'LcaHost' => $access->getHostsServices($pearDBO, 1), 'LcaHostGroup' => $access->getHostGroups(), 'LcaSG' => $access->getServiceGroups(), ]; } // Binding limit value $num = filter_var($inputs['num'], FILTER_VALIDATE_INT, ['options' => ['default' => 0, 'min_range' => 0]]); $limit = filter_var($inputs['limit'], FILTER_VALIDATE_INT, ['options' => ['default' => 30]]); // use Binding, to avoid SQL injection $StartDate = $inputs['StartDate']; $EndDate = $inputs['EndDate']; $StartTime = $inputs['StartTime']; $EndTime = $inputs['EndTime']; $auto_period = (int) $inputs['period']; $engine = $inputs['engine']; $up = $inputs['up']; $down = $inputs['down']; $unreachable = $inputs['unreachable']; $ok = $inputs['ok']; $warning = $inputs['warning']; $critical = $inputs['critical']; $unknown = $inputs['unknown']; $acknowledgement = $inputs['acknowledgement']; $notification = $inputs['notification']; $alert = $inputs['alert']; $oh = $inputs['oh']; $error = $inputs['error']; $output = isset($inputs['output']) ? urldecode($inputs['output']) : ''; $search_H = $inputs['search_H']; $search_S = $inputs['search_S']; $search_host = $inputs['search_host']; $search_service = $inputs['search_service']; $export = $inputs['export']; $start = 0; $end = time(); if ($engine == 'true') { $ok = 'false'; $up = 'false'; $unknown = 'false'; $unreachable = 'false'; $down = 'false'; $warning = 'false'; $critical = 'false'; $acknowledgement = 'false'; $oh = 'false'; $alert = 'false'; } if ($StartDate != '' && $StartTime == '') { $StartTime = '00:00'; } if ($EndDate != '' && $EndTime == '') { $EndTime = '00:00'; } if ($StartDate != '') { $dateTime = DateTime::createFromFormat('m/d/Y H:i', "{$StartDate} {$StartTime}"); if ($dateTime !== false) { $start = $dateTime->getTimestamp(); } else { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, "Invalid date format: {$StartDate} {$StartTime}" ); } } if ($EndDate != '') { $dateTime = DateTime::createFromFormat('m/d/Y H:i', "{$EndDate} {$EndTime}"); if ($dateTime !== false) { $end = $dateTime->getTimestamp(); } else { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, "Invalid date format: {$EndDate} {$EndTime}" ); } } // Setting the startDate/Time using the user's chosen period $period = 86400; if ($auto_period > 0 || $start === 0) { $period = $auto_period; $start = time() - $period; $end = time(); } $general_opt = getStatusColor($pearDB); $tab_color_service = [ STATUS_OK => 'service_ok', STATUS_WARNING => 'service_warning', STATUS_CRITICAL => 'service_critical', STATUS_UNKNOWN => 'service_unknown', STATUS_ACKNOWLEDGEMENT => 'service_acknowledgement', STATUS_PENDING => 'pending', ]; $tab_color_host = [ STATUS_UP => 'host_up', STATUS_DOWN => 'host_down', STATUS_UNREACHABLE => 'host_unreachable', ]; $tab_type = ['1' => 'HARD', '0' => 'SOFT']; $tab_class = ['0' => 'list_one', '1' => 'list_two']; $tab_status_host = ['0' => 'UP', '1' => 'DOWN', '2' => 'UNREACHABLE']; $tab_status_service = ['0' => 'OK', '1' => 'WARNING', '2' => 'CRITICAL', '3' => 'UNKNOWN', '5' => 'ACKNOWLEDGEMENT']; $acknowlegementMessageType = [ 'badgeColor' => 'ack', 'badgeText' => 'ACK', ]; // Create IP Cache if ($export) { $HostCache = []; try { $dbResult = $pearDB->executeQuery("SELECT host_name, host_address FROM host WHERE host_register = '1'"); while ($h = $pearDB->fetch($dbResult)) { $HostCache[$h['host_name']] = $h['host_address']; } $pearDB->closeQuery($dbResult); } catch (CentreonDbException $e) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Error while fetching hosts', $e->getContext() ); } } $logs = []; // Print infos.. $buffer->startElement('infos'); $buffer->writeElement('opid', $openid); $buffer->writeElement('start', $start); $buffer->writeElement('end', $end); $buffer->writeElement('notification', $notification); $buffer->writeElement('alert', $alert); $buffer->writeElement('error', $error); $buffer->writeElement('up', $up); $buffer->writeElement('down', $down); $buffer->writeElement('unreachable', $unreachable); $buffer->writeElement('ok', $ok); $buffer->writeElement('warning', $warning); $buffer->writeElement('critical', $critical); $buffer->writeElement('unknown', $unknown); $buffer->writeElement('acknowledgement', $acknowledgement); $buffer->writeElement('oh', $oh); $buffer->writeElement('search_H', $search_H); $buffer->writeElement('search_S', $search_S); $buffer->endElement(); // Build message type and status conditions $msg_type_set = []; if ($alert == 'true') { array_push($msg_type_set, 0, 1); } if ($notification == 'true') { array_push($msg_type_set, 2, 3); } if ($error == 'true') { array_push($msg_type_set, 4); } $host_msg_status_set = []; if ($up == 'true') { $host_msg_status_set[] = STATUS_UP; } if ($down == 'true') { $host_msg_status_set[] = STATUS_DOWN; } if ($unreachable == 'true') { $host_msg_status_set[] = STATUS_UNREACHABLE; } $svc_msg_status_set = []; if ($ok == 'true') { $svc_msg_status_set[] = STATUS_OK; } if ($warning == 'true') { $svc_msg_status_set[] = STATUS_WARNING; } if ($critical == 'true') { $svc_msg_status_set[] = STATUS_CRITICAL; } if ($unknown == 'true') { $svc_msg_status_set[] = STATUS_UNKNOWN; } if ($acknowledgement == 'true') { $svc_msg_status_set[] = STATUS_ACKNOWLEDGEMENT; } $whereClauses = []; $queryValues = []; // Time range conditions $whereClauses[] = 'logs.ctime > :startTime'; $queryValues[':startTime'] = [$start, PDO::PARAM_INT]; $whereClauses[] = 'logs.ctime <= :endTime'; $queryValues[':endTime'] = [$end, PDO::PARAM_INT]; // Output filter if (! empty($output)) { $whereClauses[] = 'logs.output LIKE :output'; $queryValues[':output'] = ['%' . $output . '%', PDO::PARAM_STR]; } // Message type and status conditions $msgConditions = []; if ($notification == 'true') { if ($host_msg_status_set !== []) { [$bindValues, $bindQuery] = createMultipleBindQuery($host_msg_status_set, ':host_msg_status_set_', PDO::PARAM_INT); $msgConditions[] = "(logs.msg_type = 3 AND logs.status IN ({$bindQuery}))"; $queryValues = array_merge($queryValues, $bindValues); } if ($svc_msg_status_set !== []) { [$bindValues, $bindQuery] = createMultipleBindQuery($svc_msg_status_set, ':svc_msg_status_set_', PDO::PARAM_INT); $msgConditions[] = "(logs.msg_type = 2 AND logs.status IN ({$bindQuery}))"; $queryValues = array_merge($queryValues, $bindValues); } } if ($alert == 'true') { $alertConditions = []; $alertMsgTypesHost = [1, 10, 11]; $alertMsgTypesSvc = [0, 10, 11]; if ($host_msg_status_set !== []) { [$bindValuesHost, $bindQueryHost] = createMultipleBindQuery($host_msg_status_set, ':host_msg_status_set_', PDO::PARAM_INT); [$bindValuesAlert, $bindQueryAlert] = createMultipleBindQuery($alertMsgTypesHost, ':alertMsgTypesHost_', PDO::PARAM_INT); $alertConditions[] = "(logs.msg_type IN ({$bindQueryAlert}) AND logs.status IN ({$bindQueryHost}))"; $queryValues = array_merge($queryValues, $bindValuesHost, $bindValuesAlert); } if ($svc_msg_status_set !== []) { [$bindValuesSvc, $bindQuerySvc] = createMultipleBindQuery($svc_msg_status_set, ':svc_msg_status_set_', PDO::PARAM_INT); [$bindValuesAlert, $bindQueryAlert] = createMultipleBindQuery($alertMsgTypesSvc, ':alertMsgTypesSvc_', PDO::PARAM_INT); $alertConditions[] = "(logs.msg_type IN ({$bindQueryAlert}) AND logs.status IN ({$bindQuerySvc}))"; $queryValues = array_merge($queryValues, $bindValuesSvc, $bindValuesAlert); } if ($oh == 'true') { // Apply 'logs.type = :logType' only to alert conditions with $oh = true $whereClauses[] = 'logs.type = :logType'; $queryValues[':logType'] = [TYPE_HARD, PDO::PARAM_INT]; } // Add alert conditions to msgConditions $msgConditions = array_merge($msgConditions, $alertConditions); } if ($error == 'true') { $msgConditions[] = 'logs.msg_type IN (4, 5)'; } if ($msgConditions !== []) { $whereClauses[] = '(' . implode(' OR ', $msgConditions) . ')'; } // Host and service filters $hostServiceConditions = []; // Check if the filter is on services $service_filter = str_contains($openid, 'HS'); $tab_id = explode(',', $openid); $tab_host_ids = []; $tab_svc = []; foreach ($tab_id as $openidItem) { $tab_tmp = explode('_', $openidItem); $id = $tab_tmp[2] ?? $tab_tmp[1] ?? ''; $hostId = ! empty($tab_tmp[2]) ? $tab_tmp[1] : ''; if ($id == '') { continue; } $type = $tab_tmp[0]; if (! $service_filter && $type == 'HG' && (isset($lca['LcaHostGroup'][$id]) || $is_admin)) { // Get hosts from host groups $hosts = getMyHostGroupHosts($id); foreach ($hosts as $h_id) { if (isset($lca['LcaHost'][$h_id])) { $tab_host_ids[] = $h_id; $tab_svc[$h_id] = $lca['LcaHost'][$h_id]; } } } elseif (! $service_filter && $type == 'SG' && (isset($lca['LcaSG'][$id]) || $is_admin)) { // Get services from service groups $services = getMyServiceGroupServices($id); foreach ($services as $svc_id => $svc_name) { $svc_parts = explode('_', $svc_id); $tmp_host_id = $svc_parts[0]; $tmp_service_id = $svc_parts[1]; if (isset($lca['LcaHost'][$tmp_host_id][$tmp_service_id])) { $tab_svc[$tmp_host_id][$tmp_service_id] = $lca['LcaHost'][$tmp_host_id][$tmp_service_id]; } } } elseif (! $service_filter && $type == 'HH' && isset($lca['LcaHost'][$id])) { $tab_host_ids[] = $id; $tab_svc[$id] = $lca['LcaHost'][$id]; } elseif ($type == 'HS' && isset($lca['LcaHost'][$hostId][$id])) { $tab_svc[$hostId][$id] = $lca['LcaHost'][$hostId][$id]; } elseif ($type == 'MS') { $tab_svc['_Module_Meta'][$id] = 'meta_' . $id; } } if (in_array('true', [$up, $down, $unreachable, $ok, $warning, $critical, $unknown, $acknowledgement])) { if ($tab_host_ids !== []) { [$bindValues, $bindQuery] = createMultipleBindQuery($tab_host_ids, ':tab_host_ids_', PDO::PARAM_INT); $hostServiceConditions[] = "(logs.host_id IN ({$bindQuery}) AND (logs.service_id IS NULL OR logs.service_id = 0))"; $queryValues = array_merge($queryValues, $bindValues); } if ($tab_svc !== []) { $serviceConditions = []; foreach ($tab_svc as $hostIndex => $services) { $hostParam = ':hostId' . $hostIndex; $queryValues[$hostParam] = [$hostIndex, PDO::PARAM_INT]; $servicePlaceholders = []; foreach ($services as $svcIndex => $svcId) { $paramName = ':serviceId' . $hostIndex . '_' . $svcIndex; $servicePlaceholders[] = $paramName; $queryValues[$paramName] = [$svcIndex, PDO::PARAM_INT]; } $servicePlaceholdersString = implode(', ', $servicePlaceholders); $serviceConditions[] = "(logs.host_id = {$hostParam} AND logs.service_id IN ({$servicePlaceholdersString}))"; } if ($serviceConditions !== []) { $hostServiceConditions[] = '(' . implode(' OR ', $serviceConditions) . ')'; } } if ($hostServiceConditions !== []) { $whereClauses[] = '(' . implode(' OR ', $hostServiceConditions) . ')'; } } // Exclude BAM modules if necessary if ($engine == 'false' && $tab_host_ids === [] && $tab_svc === []) { $whereClauses[] = 'logs.msg_type NOT IN (4, 5)'; $whereClauses[] = "logs.host_name NOT LIKE '_Module_BAM%'"; } // Apply host and service search filters if (! empty($search_host)) { $whereClauses[] = 'logs.host_name LIKE :searchHost'; $queryValues[':searchHost'] = ['%' . $search_host . '%', PDO::PARAM_STR]; } if (! empty($search_service)) { $whereClauses[] = 'logs.service_description LIKE :searchService'; $queryValues[':searchService'] = ['%' . $search_service . '%', PDO::PARAM_STR]; } // Build the select fields without including SQL_CALC_FOUND_ROWS and DISTINCT $selectFields = [ '1 AS REALTIME', 'logs.ctime', 'logs.host_id', 'logs.host_name', 'logs.service_id', 'logs.service_description', 'logs.msg_type', 'logs.notification_cmd', 'logs.notification_contact', 'logs.output', 'logs.retry', 'logs.status', 'logs.type', 'logs.instance_name', ]; // Start building the SELECT clause $selectClause = 'SELECT '; // Add DISTINCT if the user is not an admin if (! $is_admin) { $selectClause .= 'DISTINCT '; } // Add the select fields $selectClause .= implode(', ', $selectFields); $fromClause = 'FROM logs'; $joinClauses = []; if ($engine == 'true' && ! empty($openid)) { $pollerIds = array_filter(explode(',', $openid), 'is_numeric'); if ($pollerIds !== []) { [$bindValues, $bindQuery] = createMultipleBindQuery($pollerIds, ':pollerIds_', PDO::PARAM_INT); $joinClauses[] = " INNER JOIN instances i ON i.name = logs.instance_name AND i.instance_id IN ({$bindQuery}) "; $queryValues = array_merge($queryValues, $bindValues); } if ($str_unitH != '') { $str_unitH = "(logs.host_id IN ({$str_unitH}) AND (logs.service_id IS NULL OR logs.service_id = 0))"; if (isset($search_host) && $search_host != '') { $host_search_sql = " AND logs.host_name LIKE '%" . $pearDBO->escapeString($search_host) . "%' "; } } } if (! $is_admin) { $joinClauses[] = ' INNER JOIN centreon_acl acl ON ( logs.host_id = acl.host_id AND (acl.service_id IS NULL OR acl.service_id = logs.service_id) ) '; $whereClauses[] = 'acl.group_id IN (' . $access->getAccessGroupsString() . ')'; } $whereClause = 'WHERE ' . implode(' AND ', $whereClauses); $orderClause = 'ORDER BY logs.ctime DESC'; $limitClause = ''; if (! $export) { $offset = (($num - 1) * $limit); $queryValues[':offset'] = [$offset > 0 ? $offset : 0, PDO::PARAM_INT]; $queryValues[':limit'] = [$limit, PDO::PARAM_INT]; $limitClause = 'LIMIT :limit OFFSET :offset'; } $sqlQuery = " {$selectClause} {$fromClause} " . implode(' ', $joinClauses) . " {$whereClause} {$orderClause} {$limitClause} "; $countQuery = " SELECT COUNT(*) {$fromClause} " . implode(' ', $joinClauses) . " {$whereClause} "; $paginator = new Paginator((int) $num, (int) $limit); try { // Execute the count query $countqueryValues = $queryValues; unset($countqueryValues[':limit'], $countqueryValues[':offset']); $countStatement = $pearDBO->prepareQuery($countQuery); $pearDBO->executePreparedQuery($countStatement, $countqueryValues, true); $totalRows = $pearDBO->fetchColumn($countStatement); $paginator = $paginator->withTotalRecordCount((int) $totalRows); $pearDBO->closeQuery($countStatement); // Prepare and execute the query using CentreonDB methods $statement = $pearDBO->prepareQuery($sqlQuery); $pearDBO->executePreparedQuery($statement, $queryValues, true); $rows = $statement->rowCount(); // If the current page is out of bounds, adjust it if (! $export && $rows === 0 && $paginator->isOutOfUpperBound()) { // Update the offset in both $queryValues and $flatQueryValues $newOffset = $paginator->getOffsetMaximum(); $queryValues[':offset'] = [$newOffset, PDO::PARAM_INT]; // Re-prepare and execute the query with the updated offset $statement = $pearDBO->prepareQuery($sqlQuery); $pearDBO->executePreparedQuery($statement, $queryValues, true); } $logs = $pearDBO->fetchAll($statement); $pearDBO->closeQuery($statement); } catch (CentreonDbException $e) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Error while fetching logs', $e->getContext() ); } // Render XML output $buffer->startElement('selectLimit'); foreach ([10, 20, 30, 40, 50, 60, 70, 80, 90, 100] as $i) { $buffer->writeElement('limitValue', $i); } $buffer->writeElement('limit', $limit); $buffer->endElement(); // add generated pages into xml $paginationRenderer = new PaginationRenderer($buffer); $paginationRenderer->render($paginator); // Display logs $cpts = 0; // The query retrieves more than $limit results, but only the first $limit elements should be displayed foreach (array_slice($logs, 0, $limit) as $log) { $buffer->startElement('line'); $buffer->writeElement('msg_type', $log['msg_type']); /** * For an ACK there is no point to display RETRY and TYPE columns */ $displayType = ''; if ( $log['msg_type'] != HOST_ACKNOWLEDGEMENT_MSG_TYPE && $log['msg_type'] != SERVICE_ACKNOWLEDGEMENT_MSG_TYPE ) { $displayType = $log['type']; if (isset($tab_type[$log['type']])) { $displayType = $tab_type[$log['type']]; } $log['msg_type'] > 1 ? $buffer->writeElement('retry', '') : $buffer->writeElement('retry', $log['retry']); $log['msg_type'] == 2 || $log['msg_type'] == 3 ? $buffer->writeElement('type', 'NOTIF') : $buffer->writeElement('type', $displayType); } /* * Color initialisation for services and hosts status * For ACK message types, display a badge 'ACK' in Yellow */ $color = ''; if ( $log['msg_type'] == HOST_ACKNOWLEDGEMENT_MSG_TYPE || $log['msg_type'] == SERVICE_ACKNOWLEDGEMENT_MSG_TYPE ) { $color = $acknowlegementMessageType['badgeColor']; } elseif (isset($log['status'])) { if ( isset($tab_color_service[$log['status']]) && ! empty($log['service_description']) ) { $color = $tab_color_service[$log['status']]; } elseif (isset($tab_color_host[$log['status']])) { $color = $tab_color_host[$log['status']]; } } // Variable initialisation to color "INITIAL STATE" on event logs if ($log['output'] == '' && $log['status'] != '') { $log['output'] = 'INITIAL STATE'; } $buffer->startElement('status'); $buffer->writeAttribute('color', $color); $displayStatus = $log['status']; if ( $log['msg_type'] == HOST_ACKNOWLEDGEMENT_MSG_TYPE || $log['msg_type'] == SERVICE_ACKNOWLEDGEMENT_MSG_TYPE ) { $displayStatus = $acknowlegementMessageType['badgeText']; } elseif ($log['service_description'] && isset($tab_status_service[$log['status']])) { $displayStatus = $tab_status_service[$log['status']]; } elseif (isset($tab_status_host[$log['status']])) { $displayStatus = $tab_status_host[$log['status']]; } $buffer->text($displayStatus); $buffer->endElement(); if (! strncmp($log['host_name'], '_Module_Meta', strlen('_Module_Meta'))) { if (preg_match('/meta_([0-9]*)/', $log['service_description'], $matches)) { try { $statement = $pearDB->prepareQuery( <<<'SQL' SELECT meta_name FROM meta_service WHERE meta_id = :meta_id SQL ); $pearDB->executePreparedQuery($statement, [':meta_id' => [$matches[1], PDO::PARAM_INT]], true); $meta = $pearDB->fetch($statement); $pearDB->closeQuery($statement); $buffer->writeElement('host_name', 'Meta', false); $buffer->writeElement('real_service_name', $log['service_description'], false); $buffer->writeElement('service_description', $meta['meta_name'], false); unset($meta); } catch (CentreonDbException $e) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Error while fetching meta_services', $e->getContext() ); } } else { // Log case where meta pattern is not found in service description CentreonLog::create()->info( CentreonLog::TYPE_BUSINESS_LOG, 'No meta pattern found in service_description: ' . $log['service_description'] ); // Default output when meta pattern is missing $buffer->writeElement('host_name', $log['host_name'], false); if ($export) { $buffer->writeElement('address', $HostCache[$log['host_name']], false); } $buffer->writeElement('service_description', $log['service_description'], false); $buffer->writeElement('real_service_name', $log['service_description'], false); } } else { $buffer->writeElement('host_name', $log['host_name'], false); if ($export) { $buffer->writeElement('address', $HostCache[$log['host_name']], false); } $buffer->writeElement('service_description', $log['service_description'], false); $buffer->writeElement('real_service_name', $log['service_description'], false); $serviceTimelineRedirectionUri = $useDeprecatedPages ? 'main.php?p=20201&amp;o=svcd&amp;host_name=' . $log['host_name'] . '&amp;service_description=' . $log['service_description'] : $resourceController->buildServiceUri( $log['host_id'], $log['service_id'], $resourceController::TAB_TIMELINE_NAME ); $buffer->writeElement( 's_timeline_uri', $serviceTimelineRedirectionUri ); } $buffer->writeElement('real_name', $log['host_name'], false); $hostTimelineRedirectionUri = $useDeprecatedPages ? 'main.php?p=20202&amp;o=hd&amp;host_name=' . $log['host_name'] : $resourceController->buildHostUri($log['host_id'], $resourceController::TAB_TIMELINE_NAME); $buffer->writeElement( 'h_timeline_uri', $hostTimelineRedirectionUri ); $buffer->writeElement('class', $tab_class[$cpts % 2]); $buffer->writeElement('poller', $log['instance_name']); $buffer->writeElement('date', $log['ctime']); $buffer->writeElement('time', $log['ctime']); $buffer->writeElement('output', $log['output']); $buffer->writeElement('contact', $log['notification_contact'], false); $buffer->writeElement('contact_cmd', $log['notification_cmd'], false); $buffer->endElement(); $cpts++; } // Translation for tables. $buffer->startElement('lang'); $buffer->writeElement('d', _('Day'), 0); $buffer->writeElement('t', _('Time'), 0); $buffer->writeElement('O', _('Object name'), 0); $buffer->writeElement('T', _('Type'), 0); $buffer->writeElement('R', _('Retry'), 0); $buffer->writeElement('o', _('Output'), 0); $buffer->writeElement('c', _('Contact'), 0); $buffer->writeElement('C', _('Command'), 0); $buffer->writeElement('P', _('Poller'), 0); $buffer->endElement(); $buffer->endElement(); // XML tag stristr($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') ? header('Content-type: application/xhtml+xml') : header('Content-type: text/xml'); header('Content-Disposition: attachment; filename="eventLogs-' . time() . '.xml"'); $buffer->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/eventLogs/xml/PaginationRenderer.php
centreon/www/include/eventLogs/xml/PaginationRenderer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); include_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php'; class PaginationRenderer { public function __construct(private CentreonXML $buffer) { } /** * Renders navigation pages as xml nodes. * * @param Paginator $paginator */ public function render(Paginator $paginator): void { if ($paginator->totalPagesCount <= 1) { return; } $this->addNavigation('prev', $paginator->getPageNumberPrevious()); foreach ($paginator as $page) { $this->addPage($paginator, $page); } $this->addNavigation('next', $paginator->getPageNumberNext()); } /** * Adds next or previous page into the xml as a new node. * * @param string $elName * @param ?int $pageNb */ private function addNavigation(string $elName, ?int $pageNb): void { $this->buffer->startElement($elName); if (is_int($pageNb)) { $this->buffer->writeAttribute('show', 'true'); $this->buffer->text((string) $pageNb); } else { $this->buffer->writeAttribute('show', 'false'); $this->buffer->text('none'); } $this->buffer->endElement(); } /** * Adds navigation page into the xml as a new node. * * @param Paginator $paginator * @param int $pageNb */ private function addPage(Paginator $paginator, int $pageNb): void { $active = $paginator->isActive($pageNb); $url = $paginator->getUrl($pageNb); $this->buffer->startElement('page'); $this->buffer->writeElement('selected', $active ? '1' : '0'); $this->buffer->writeElement('num', (string) $pageNb); $this->buffer->writeElement('url_page', $url); $this->buffer->writeElement('label_page', (string) $pageNb); $this->buffer->endElement(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/export/Request.php
centreon/www/include/eventLogs/export/Request.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Centreon\Legacy\EventLogs\Export; require_once realpath(__DIR__ . '/../../../../www/class') . '/HtmlAnalyzer.php'; class Request { private const STATUS_UP = 0; private const STATUS_DOWN = 1; private const STATUS_UNREACHABLE = 2; private const STATUS_OK = 0; private const STATUS_WARNING = 1; private const STATUS_CRITICAL = 2; private const STATUS_UNKNOWN = 3; private const STATUS_ACKNOWLEDGEMENT = 5; private ?int $is_admin = null; /** @var array<string,mixed> */ private array $lca = []; private ?string $lang = null; private ?string $id = null; private ?int $limit = null; private ?string $startDate = null; private ?string $startTime = null; private ?string $endDate = null; private ?string $endTime = null; private ?int $period = null; private string $engine = 'false'; private string $up = 'true'; private string $down = 'true'; private string $unreachable = 'true'; private string $ok = 'true'; private string $warning = 'true'; private string $critical = 'true'; private string $unknown = 'true'; private string $notification = 'false'; private string $acknowledgement = 'true'; private string $alert = 'true'; private string $oh = 'false'; private string $error = 'false'; private string $output = ''; private string $searchH = 'VIDE'; private string $searchS = 'VIDE'; private string $searchHost = ''; private string $searchService = ''; private string $export = '0'; /** @var array<int, string> */ private array $hostMsgStatusSet = []; /** @var array<int, string> */ private array $svcMsgStatusSet = []; /** @var array<int, string> */ private array $tabHostIds = []; /** @var mixed[] */ private array $tabSvc = []; public function __construct() { $this->populateClassPropertiesFromRequestParameters(); } /** * @param int|null $is_admin * @return void */ public function setIsAdmin(?int $is_admin): void { $this->is_admin = $is_admin; } /** * @param array<string,mixed> $lca * @return void */ public function setLca(array $lca): void { $this->lca = $lca; } /** * @return string|null */ public function getLang(): ?string { return $this->lang; } /** * @return string|null */ public function getId(): ?string { return $this->id; } /** * @return string */ public function getOpenid(): string { return \HtmlAnalyzer::sanitizeAndRemoveTags($this->getId() ?? '-1'); } /** * @return int|null */ public function getLimit(): ?int { return $this->limit; } /** * Retrieves timestamp for start date * @return int */ public function getStart(): int { $start = 0; if ($this->startDate != '') { $startDateTime = sprintf('%s %s', $this->startDate, $this->startTime); $start = $this->dateStringToTimestamp($startDateTime); } // setting the startDate/Time using the user's chosen period // and checking if the start date/time was set by the user, // to avoid to display/export the whole data since 1/1/1970 if ($this->getPeriod() > 0 || $start === 0) { $start = time() - $this->getPeriod(); } return $start; } /** * * Retrieves timestamp for end date * @return int */ public function getEnd(): int { $end = time(); if ($this->endDate != '') { $endDateTime = sprintf('%s %s', $this->endDate, $this->endTime); $end = $this->dateStringToTimestamp($endDateTime); } return $end; } /** * @return string|null */ public function getEndDate(): ?string { return $this->endDate; } /** * @return string|null */ public function getStartTime(): ?string { return $this->startTime; } /** * @return int|null */ public function getPeriod(): ?int { return $this->period ?? 0; } /** * @return string */ public function getEngine(): string { return htmlentities($this->engine); } /** * @return string */ public function getUp(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->up); } /** * @return string */ public function getDown(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->down); } /** * @return string */ public function getUnreachable(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->unreachable); } /** * @return string */ public function getOk(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->ok); } /** * @return string */ public function getWarning(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->warning); } /** * @return string */ public function getCritical(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->critical); } /** * @return string */ public function getAcknowledgement(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->acknowledgement); } /** * @return string */ public function getUnknown(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->unknown); } /** * @return string */ public function getNotification(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->notification); } /** * @return string */ public function getAlert(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->alert); } /** * @return string */ public function getOh(): string { if ($this->getEngine() === 'true') { return 'false'; } return htmlentities($this->oh); } /** * @return string */ public function getError(): string { return $this->error; } /** * @return string */ public function getOutput(): string { return urldecode($this->output); } /** * @return string|null */ public function getSearchS(): ?string { return $this->searchS; } /** * @return string */ public function getSearchHost(): string { return $this->charsToHtmlEntities($this->searchHost); } /** * @return string */ public function getSearchService(): string { return$this->charsToHtmlEntities($this->searchService); } /** * @return string */ public function getExport(): string { return $this->charsToHtmlEntities($this->export); } /** * Retrieves list of host message statuses depending on request parameters * @return string[] */ public function getHostMsgStatusSet(): array { if ($this->getUp() === 'true') { $this->hostMsgStatusSet[] = sprintf("'%s'", self::STATUS_UP); } if ($this->getDown() === 'true') { $this->hostMsgStatusSet[] = sprintf("'%s'", self::STATUS_DOWN); } if ($this->getUnreachable() === 'true') { $this->hostMsgStatusSet[] = sprintf("'%s'", self::STATUS_UNREACHABLE); } return $this->hostMsgStatusSet; } /** * Retrieves list of service message statuses depending on request parameters * @return string[] */ public function getSvcMsgStatusSet(): array { if ($this->getOk() === 'true') { $this->svcMsgStatusSet[] = sprintf("'%s'", self::STATUS_OK); } if ($this->getWarning() === 'true') { $this->svcMsgStatusSet[] = sprintf("'%s'", self::STATUS_WARNING); } if ($this->getCritical() === 'true') { $this->svcMsgStatusSet[] = sprintf("'%s'", self::STATUS_CRITICAL); } if ($this->getUnknown() === 'true') { $this->svcMsgStatusSet[] = sprintf("'%s'", self::STATUS_UNKNOWN); } if ($this->getAcknowledgement() === 'true') { $this->svcMsgStatusSet[] = sprintf("'%s'", self::STATUS_ACKNOWLEDGEMENT); } return $this->svcMsgStatusSet; } /** * Retrieves host ids depending on open id parameter * @return mixed[] */ public function getTabHostIds(): array { $tab_id = preg_split("/\,/", $this->getOpenid()); if ($tab_id === false) { throw new \InvalidArgumentException('Unable to parse open ID'); } foreach ($tab_id as $openid) { $openIdChunks = $this->splitOpenId($openid); $id = $openIdChunks['id']; $type = $openIdChunks['type']; if ($id === '') { continue; } if ($type == 'HG' && (isset($this->lca['LcaHostGroup'][$id]) || $this->is_admin)) { // Get hosts from hostgroups $hosts = getMyHostGroupHosts($id); if (count($hosts) == 0) { $this->tabHostIds[] = '-1'; } else { foreach ($hosts as $h_id) { if (isset($this->lca['LcaHost'][$h_id])) { $this->tabHostIds[] = $h_id; } } } } elseif ($type == 'HH' && isset($this->lca['LcaHost'][$id])) { $this->tabHostIds[] = $id; } } return $this->tabHostIds; } /** * Retrieves service ids depending on open id parameter * @return array<mixed> */ public function getTabSvc(): array { $tab_id = preg_split("/\,/", $this->getOpenid()); foreach ($tab_id as $openid) { $openIdChunks = $this->splitOpenId($openid); $id = $openIdChunks['id']; $type = $openIdChunks['type']; $hostId = $openIdChunks['hostId']; if ($id === '') { continue; } if ($type == 'HG' && (isset($this->lca['LcaHostGroup'][$id]) || $this->is_admin)) { // Get hosts from hostgroups $hosts = getMyHostGroupHosts($id); if (count($hosts) !== 0) { foreach ($hosts as $h_id) { if (isset($this->lca['LcaHost'][$h_id])) { $this->tabSvc[$h_id] = $this->lca['LcaHost'][$h_id]; } } } } elseif ($type == 'SG' && (isset($this->lca['LcaSG'][$id]) || $this->is_admin)) { $services = getMyServiceGroupServices($id); if (count($services) == 0) { $this->tabSvc[] = '-1'; } else { foreach ($services as $svc_id => $svc_name) { $tab_tmp = preg_split("/\_/", $svc_id); $tmp_host_id = $tab_tmp[0]; $tmp_service_id = $tab_tmp[1]; if (isset($this->lca['LcaHost'][$tmp_host_id][$tmp_service_id])) { $this->tabSvc[$tmp_host_id][$tmp_service_id] = $this->lca['LcaHost'][$tmp_host_id][$tmp_service_id]; } } } } elseif ($type == 'HH' && isset($this->lca['LcaHost'][$id])) { $this->tabSvc[$id] = $this->lca['LcaHost'][$id]; } elseif ($type == 'HS' && isset($this->lca['LcaHost'][$hostId][$id])) { $this->tabSvc[$hostId][$id] = $this->lca['LcaHost'][$hostId][$id]; } elseif ($type == 'MS') { $this->tabSvc['_Module_Meta'][$id] = 'meta_' . $id; } } return $this->tabSvc; } /** * Converts date string to timestamp * Expected format of date string : 06/22/2022 00:00 * * @param string $dateString * @return int */ private function dateStringToTimestamp(string $dateString): int { preg_match("/^([0-9]*)\/([0-9]*)\/([0-9]*)/", $dateString, $matchesD); preg_match('/([0-9]*):([0-9]*)/', $dateString, $matchesT); $hour = array_key_exists(1, $matchesT) ? (int) $matchesT[1] : 0; $minute = array_key_exists(2, $matchesT) ? (int) $matchesT[2] : 0; $tmstp = mktime( $hour, $minute, 0, (int) $matchesD[1], (int) $matchesD[2], (int) $matchesD[3] ); if ($tmstp === false) { throw new \InvalidArgumentException('Unable to convert string to timestamp'); } return $tmstp; } /** * Splits open id string into associative array of id, hostId and type * * @param string $openid * @return array<string, string> */ private function splitOpenId(string $openid): array { $chunks = preg_split("/\_/", $openid); if (! is_array($chunks)) { return ['id' => '', 'hostId' => '', 'type' => '']; } $id = ''; $hostId = ''; if (isset($chunks[2])) { $hostId = $chunks[1]; $id = $chunks[2]; } elseif (isset($chunks[1])) { $id = $chunks[1]; } return ['id' => $id, 'hostId' => $hostId, 'type' => $chunks[0]]; } /** * Populates class properties from request. * Request arguments are matched against property name. Request values are used as property values. * @return void */ private function populateClassPropertiesFromRequestParameters(): void { $inputGet = [ 'lang' => $this->sanitizeGetParameter('lang'), 'id' => $this->sanitizeGetParameter('id'), 'num' => filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]), 'limit' => filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 30]]), 'StartDate' => $this->sanitizeGetParameter('StartDate'), 'EndDate' => $this->sanitizeGetParameter('EndDate'), 'StartTime' => $this->sanitizeGetParameter('StartTime'), 'EndTime' => $this->sanitizeGetParameter('EndTime'), 'period' => filter_input(INPUT_GET, 'period', FILTER_VALIDATE_INT), 'engine' => $this->sanitizeGetParameter('engine'), 'up' => $this->sanitizeGetParameter('up'), 'down' => $this->sanitizeGetParameter('down'), 'unreachable' => $this->sanitizeGetParameter('unreachable'), 'ok' => $this->sanitizeGetParameter('ok'), 'warning' => $this->sanitizeGetParameter('warning'), 'critical' => $this->sanitizeGetParameter('critical'), 'acknowledgement' => $this->sanitizeGetParameter('acknowledgement'), 'unknown' => $this->sanitizeGetParameter('unknown'), 'notification' => $this->sanitizeGetParameter('notification'), 'alert' => $this->sanitizeGetParameter('alert'), 'oh' => $this->sanitizeGetParameter('oh'), 'error' => $this->sanitizeGetParameter('error'), 'output' => $this->sanitizeGetParameter('output'), 'search_H' => $this->sanitizeGetParameter('search_H'), 'search_S' => $this->sanitizeGetParameter('search_S'), 'search_host' => $this->sanitizeGetParameter('search_host'), 'search_service' => $this->sanitizeGetParameter('search_service'), 'export' => $this->sanitizeGetParameter('export'), ]; $inputPost = [ 'lang' => $this->sanitizePostParameter('lang'), 'id' => $this->sanitizePostParameter('id'), 'num' => filter_input(INPUT_POST, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]), 'limit' => filter_input(INPUT_POST, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 30]]), 'StartDate' => $this->sanitizePostParameter('StartDate'), 'EndDate' => $this->sanitizePostParameter('EndDate'), 'StartTime' => $this->sanitizePostParameter('StartTime'), 'EndTime' => $this->sanitizePostParameter('EndTime'), 'period' => filter_input(INPUT_POST, 'period', FILTER_VALIDATE_INT), 'engine' => $this->sanitizePostParameter('engine'), 'up' => $this->sanitizePostParameter('up'), 'down' => $this->sanitizePostParameter('down'), 'unreachable' => $this->sanitizePostParameter('unreachable'), 'ok' => $this->sanitizePostParameter('ok'), 'warning' => $this->sanitizePostParameter('warning'), 'critical' => $this->sanitizePostParameter('critical'), 'acknowledgement' => $this->sanitizePostParameter('acknowledgement'), 'unknown' => $this->sanitizePostParameter('unknown'), 'notification' => $this->sanitizePostParameter('notification'), 'alert' => $this->sanitizePostParameter('alert'), 'oh' => $this->sanitizePostParameter('oh'), 'error' => $this->sanitizePostParameter('error'), 'output' => $this->sanitizePostParameter('output'), 'search_H' => $this->sanitizePostParameter('search_H'), 'search_S' => $this->sanitizePostParameter('search_S'), 'search_host' => $this->sanitizePostParameter('search_host'), 'search_service' => $this->sanitizePostParameter('search_service'), 'export' => $this->sanitizePostParameter('export'), ]; foreach (array_keys($inputGet) as $argumentName) { if (array_key_exists($argumentName, $inputGet) && ! empty($inputGet[$argumentName])) { $this->populateClassPropertyWithRequestArgument($argumentName, $inputGet[$argumentName]); } elseif (array_key_exists($argumentName, $inputPost) && ! empty($inputPost[$argumentName])) { $this->populateClassPropertyWithRequestArgument($argumentName, $inputPost[$argumentName]); } } } private function sanitizeGetParameter(string $parameterName): ?string { return isset($_GET[$parameterName]) ? \HtmlAnalyzer::sanitizeAndRemoveTags($_GET[$parameterName]) : null; } private function sanitizePostParameter(string $parameterName): ?string { return isset($_POST[$parameterName]) ? \HtmlAnalyzer::sanitizeAndRemoveTags($_POST[$parameterName]) : null; } /** * Populates class properties from request. * Arguments are matched against property name. Values as property values. * @param mixed $argumentName * @param mixed $propertyValue * @return void */ private function populateClassPropertyWithRequestArgument(mixed $argumentName, mixed $propertyValue): void { $propertyName = $this->stringToCamelCase($argumentName); if (property_exists($this, $propertyName)) { $this->{$propertyName} = $propertyValue; } } /** * Converts string to camelCase literal * @param string $string * @return string */ private function stringToCamelCase(string $string): string { $str = str_replace('_', '', ucwords($string, '_')); return lcfirst($str); } /** * Convert string to HTML entities in order to secure against XSS vulnerabilities * @param string $string * @return string */ private function charsToHtmlEntities(string $string): string { return htmlentities($string, ENT_QUOTES, 'UTF-8'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/export/Presenter.php
centreon/www/include/eventLogs/export/Presenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Centreon\Legacy\EventLogs\Export; class Presenter { private const DELIMITER = ';'; /** @var string[] */ private array $heads = []; /** @var \Iterator<string[]> */ private iterable $logs; /** @var mixed[] */ private array $metaData; /** * @param string[] $heads * @return void */ public function setHeads(array $heads): void { $this->heads = $heads; } /** * @param mixed[] $metaData * @return void */ public function setMetaData(array $metaData): void { $this->metaData = $metaData; } /** * @param \Iterator<string[]> $logs * @return void */ public function setLogs(iterable $logs): void { $this->logs = $logs; } /** * Renders metadata and formatted records as CSV file * @return void */ public function render(): void { header('Content-Disposition: attachment;filename="EventLogs.csv";'); header('Content-Type: application/csv; charset=UTF-8'); header('Pragma: no-cache'); $f = fopen('php://output', 'w'); if ($f === false) { throw new \RuntimeException('Unable to write content in output'); } // print meta data foreach ($this->metaData as $metaData) { fputcsv($f, $metaData, self::DELIMITER); } // print heads fputcsv($f, $this->heads, self::DELIMITER); // print data foreach ($this->logs as $log) { fputcsv($f, $log, self::DELIMITER); } fclose($f); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/export/QueryGenerator.php
centreon/www/include/eventLogs/export/QueryGenerator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Centreon\Legacy\EventLogs\Export; use CentreonACL; use CentreonDB; use PDOStatement; class QueryGenerator { /** @var array<array<int,mixed>> */ private array $queryValues = []; private ?int $is_admin = null; private string $openid = ''; private string $output = ''; private CentreonACL $access; private int $start; private int $end; private string $up; private string $down; private string $unreachable; private string $ok; private string $warning; private string $critical; private string $unknown; private string $acknowledgement; private string $notification; private string $alert; private string $error; private string $oh; /** @var string[] */ private array $hostMsgStatusSet = []; /** @var string[] */ private array $svcMsgStatusSet = []; /** @var string[] */ private array $tabHostIds = []; private string $searchHost = ''; /** @var array<mixed> */ private array $tabSvc; private string $searchService = ''; private string $engine; private string|int $export; private int $num = 0; private ?int $limit = null; public function __construct(private CentreonDB $pearDBO) { } /** * @param string $up * @return void */ public function setUp(string $up): void { $this->up = $up; } /** * @param int|null $is_admin * @return void */ public function setIsAdmin(?int $is_admin): void { $this->is_admin = $is_admin; } /** * @param string $openId * @return void */ public function setOpenId(string $openId): void { $this->openid = $openId; } /** * @param string $output * @return void */ public function setOutput(string $output): void { $this->output = $output; } /** * @param CentreonACL $access * @return void */ public function setAccess(CentreonACL $access): void { $this->access = $access; } /** * @param int $start * @return void */ public function setStart(int $start): void { $this->start = $start; } /** * @param int $end * @return void */ public function setEnd(int $end): void { $this->end = $end; } /** * @param string $down * @return void */ public function setDown(string $down): void { $this->down = $down; } /** * @param string $unreachable * @return void */ public function setUnreachable(string $unreachable): void { $this->unreachable = $unreachable; } /** * @param string $ok * @return void */ public function setOk(string $ok): void { $this->ok = $ok; } /** * @param string $warning * @return void */ public function setWarning(string $warning): void { $this->warning = $warning; } /** * @param string $critical * @return void */ public function setCritical(string $critical): void { $this->critical = $critical; } /** * @param string $unknown * @return void */ public function setUnknown(string $unknown): void { $this->unknown = $unknown; } /** * @param string $notification * @return void */ public function setNotification(string $notification): void { $this->notification = $notification; } /** * @param string $alert * @return void */ public function setAlert(string $alert): void { $this->alert = $alert; } /** * @param string $error * @return void */ public function setError(string $error): void { $this->error = $error; } /** * @param string $oh * @return void */ public function setOh(string $oh): void { $this->oh = $oh; } /** * @param string[] $hostMsgStatusSet * @return void */ public function setHostMsgStatusSet(array $hostMsgStatusSet): void { $this->hostMsgStatusSet = $hostMsgStatusSet; } /*** * @param String[] $svcMsgStatusSet * @return void */ public function setSvcMsgStatusSet(array $svcMsgStatusSet): void { $this->svcMsgStatusSet = $svcMsgStatusSet; } /** * @param string[] $tabHostIds * @return void */ public function setTabHostIds(array $tabHostIds): void { $this->tabHostIds = $tabHostIds; } /** * @param string $searchHost * @return void */ public function setSearchHost(string $searchHost): void { $this->searchHost = $searchHost; } /** * @param string[] $tabSvc * @return void */ public function setTabSvc(array $tabSvc): void { $this->tabSvc = $tabSvc; } /** * @param string $searchService * @return void */ public function setSearchService(string $searchService): void { $this->searchService = $searchService; } /** * @param string $engine * @return void */ public function setEngine(string $engine): void { $this->engine = $engine; } /** * @param int|string $export * @return void */ public function setExport(int|string $export): void { $this->export = $export; } /** * @param int $num * @return void */ public function setNum(int $num): void { $this->num = $num; } /** * @param int|null $limit * @return void */ public function setLimit(?int $limit): void { $this->limit = $limit; } /** * @param string $acknowledgement */ public function setAcknowledgement(string $acknowledgement): void { $this->acknowledgement = $acknowledgement; } /** * Generates executable PROStatement for all database records * @return PDOStatement */ public function getStatement(): PDOStatement { $req = $this->generateQuery(); $stmt = $this->pearDBO->prepare($req); foreach ($this->queryValues as $bindId => $bindData) { foreach ($bindData as $bindType => $bindValue) { $stmt->bindValue($bindId, $bindValue, $bindType); } } return $stmt; } /** * Generates SQL statement with placeholders for all database records * @return string */ private function generateQuery(): string { $whereOutput = $this->generateWhere(); $msg_req = $this->generateMsgHost(); // Build final request $req = 'SELECT SQL_CALC_FOUND_ROWS ' . (! $this->is_admin ? 'DISTINCT' : '') . ' 1 AS REALTIME, logs.ctime, logs.host_id, logs.host_name, logs.service_id, logs.service_description, logs.msg_type, logs.notification_cmd, logs.notification_contact, logs.output, logs.retry, logs.status, logs.type, logs.instance_name FROM logs ' . $this->generateInnerJoinQuery() . ( ! $this->is_admin ? ' INNER JOIN centreon_acl acl ON (logs.host_id = acl.host_id AND (acl.service_id IS NULL OR ' . ' acl.service_id = logs.service_id)) ' . ' WHERE acl.group_id IN (' . $this->access->getAccessGroupsString() . ') AND ' : 'WHERE ' ) . " logs.ctime > '{$this->start}' AND logs.ctime <= '{$this->end}' {$whereOutput} {$msg_req}"; // Add Host $str_unitH = ''; $str_unitH_append = ''; $host_search_sql = ''; if (count($this->tabHostIds) == 0 && count($this->tabSvc) == 0) { if ($this->engine == 'false') { $req .= " AND `msg_type` NOT IN ('4','5') "; $req .= " AND logs.host_name NOT LIKE '\\_Module\\_BAM%' "; } } else { foreach ($this->tabHostIds as $host_id) { if ($host_id != '') { $str_unitH .= $str_unitH_append . "'{$host_id}'"; $str_unitH_append = ', '; } } if ($str_unitH != '') { $str_unitH = "(logs.host_id IN ({$str_unitH}) AND (logs.service_id IS NULL OR logs.service_id = 0))"; if (isset($this->searchHost) && $this->searchHost != '') { $host_search_sql = " AND logs.host_name LIKE '%" . $this->pearDBO->escape($this->searchHost) . "%' "; } } // Add services $flag = 0; $str_unitSVC = ''; $service_search_sql = ''; if ( (count($this->tabSvc) || count($this->tabHostIds)) && ( $this->up == 'true' || $this->down == 'true' || $this->unreachable == 'true' || $this->ok == 'true' || $this->warning == 'true' || $this->critical == 'true' || $this->unknown == 'true' || $this->acknowledgement == 'true' ) ) { $req_append = ''; foreach ($this->tabSvc as $host_id => $services) { $str = ''; $str_append = ''; foreach ($services as $svc_id => $svc_name) { if ($svc_id != '') { $str .= $str_append . $svc_id; $str_append = ', '; } } if ($str != '') { if ($host_id === '_Module_Meta') { $str_unitSVC .= $req_append . " (logs.host_name = '" . $host_id . "' " . 'AND logs.service_id IN (' . $str . ')) '; } else { $str_unitSVC .= $req_append . " (logs.host_id = '" . $host_id . "' AND logs.service_id IN ({$str})) "; } $req_append = ' OR'; } } if (isset($this->searchService) && $this->searchService != '') { $service_search_sql = " AND logs.service_description LIKE '%" . $this->pearDBO->escape($this->searchService) . "%' "; } if ($str_unitH != '' && $str_unitSVC != '') { $str_unitSVC = ' OR ' . $str_unitSVC; } if ($str_unitH != '' || $str_unitSVC != '') { $req .= ' AND (' . $str_unitH . $str_unitSVC . ')'; } } else { $req .= 'AND 0 '; } $req .= " AND logs.host_name NOT LIKE '\\_Module\\_BAM%' "; $req .= $host_search_sql . $service_search_sql; } $limit = ($this->export !== '1' && $this->num) ? $this->generateLimit() : ''; $req .= ' ORDER BY ctime DESC ' . $limit; return $req; } /** * Generates limit statement * @return string */ private function generateLimit(): string { if ($this->num < 0) { $this->num = 0; } $offset = $this->num * $this->limit; $this->queryValues['offset'] = [\PDO::PARAM_INT => $offset]; $this->queryValues['limit'] = [\PDO::PARAM_INT => $this->limit]; return ' LIMIT :offset, :limit'; } /** * Creates join statement with instances and filters on poller IDs * @return string */ private function generateInnerJoinQuery(): string { $innerJoinEngineLog = ''; if ($this->engine == 'true' && isset($this->openid) && $this->openid != '') { // filtering poller ids and keeping only real ids $pollerIds = explode(',', $this->openid); $filteredIds = array_filter($pollerIds, function ($id) { return is_numeric($id); }); if ($filteredIds !== []) { foreach ($filteredIds as $index => $filteredId) { $key = ':pollerId' . $index; $this->queryValues[$key] = [\PDO::PARAM_INT => $filteredId]; $pollerIds[] = $key; } $innerJoinEngineLog = ' INNER JOIN instances i ON i.name = logs.instance_name' . ' AND i.instance_id IN ( ' . implode(',', array_values($pollerIds)) . ')'; } } return $innerJoinEngineLog; } /** * Generates Where statement * @return string */ private function generateWhere(): string { $whereOutput = ''; if (isset($this->output) && $this->output != '') { $this->queryValues[':output'] = [\PDO::PARAM_STR => '%' . $this->output . '%']; $whereOutput = ' AND logs.output like :output '; } return $whereOutput; } /** * Generates sub request with filters * @return string */ private function generateMsgHost(): string { $msg_req = ''; $flag_begin = 0; if ($this->notification == 'true') { if ($this->hostMsgStatusSet !== []) { $msg_req .= '('; $flag_begin = 1; $msg_req .= " (`msg_type` = '3' "; $msg_req .= ' AND `status` IN (' . implode(',', $this->hostMsgStatusSet) . '))'; $msg_req .= ') '; } if ($this->svcMsgStatusSet !== []) { if ($flag_begin == 0) { $msg_req .= '('; } else { $msg_req .= ' OR '; } $msg_req .= " (`msg_type` = '2' "; $msg_req .= ' AND `status` IN (' . implode(',', $this->svcMsgStatusSet) . '))'; if ($flag_begin == 0) { $msg_req .= ') '; } $flag_begin = 1; } } if ($this->alert == 'true') { if ($this->hostMsgStatusSet !== []) { if ($flag_begin) { $msg_req .= ' OR '; } if ($this->oh == true) { $msg_req .= ' ( '; $flag_oh = true; } $flag_begin = 1; $msg_req .= " ((`msg_type` IN ('1', '10', '11') "; $msg_req .= ' AND `status` IN (' . implode(',', $this->hostMsgStatusSet) . ')) '; $msg_req .= ') '; } if ($this->svcMsgStatusSet !== []) { if ($flag_begin) { $msg_req .= ' OR '; } if ($this->oh == true && ! isset($flag_oh)) { $msg_req .= ' ( '; } $flag_begin = 1; $msg_req .= " ((`msg_type` IN ('0', '10', '11') "; $msg_req .= ' AND `status` IN (' . implode(',', $this->svcMsgStatusSet) . ')) '; $msg_req .= ') '; } if ($flag_begin) { $msg_req .= ')'; } if ((count($this->hostMsgStatusSet) || count($this->svcMsgStatusSet)) && $this->oh == 'true') { $msg_req .= ' AND '; } if ($this->oh == 'true') { $flag_begin = 1; $msg_req .= " `type` = '1' "; } } // Error filter is only used in the engine log page. if ($this->error == 'true') { if ($flag_begin == 0) { $msg_req .= 'AND '; } else { $msg_req .= ' OR '; } $msg_req .= " `msg_type` IN ('4','5') "; } if ($flag_begin) { $msg_req = ' AND (' . $msg_req . ') '; } return $msg_req; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/export/Formatter.php
centreon/www/include/eventLogs/export/Formatter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace Centreon\Legacy\EventLogs\Export; class Formatter { private const DATE_FORMAT = 'Y/m/d'; private const TIME_FORMAT = 'H:i:s'; private const DATE_TIME_FORMAT = 'Y/m/d (H:i:s)'; private const SERVICE_ACKNOWLEDGEMENT_MSG_TYPE = 10; private const HOST_ACKNOWLEDGEMENT_MSG_TYPE = 11; private const ACKNOWLEDGMENT_MESSAGE_TYPE = 'ACK'; private const INITIAL_STATE_VALUE = 'INITIAL STATE'; private const NOTIFICATION_TYPE_VALUE = 'NOTIF'; /** @var string[] */ private array $hosts = []; /** @var string[] */ private array $serviceStatuses = ['0' => 'OK', '1' => 'WARNING', '2' => 'CRITICAL', '3' => 'UNKNOWN', '5' => 'ACKNOWLEDGEMENT']; /** @var string[] */ private array $hostStatuses = ['0' => 'UP', '1' => 'DOWN', '2' => 'UNREACHABLE']; /** @var string[] */ private array $notificationTypes = ['1' => 'HARD', '0' => 'SOFT']; private int $start = 0; private int $end = 0; private string $notification = ''; private string $alert = ''; private string $error = ''; private string $up = ''; private string $down = ''; private string $unreachable = ''; private string $ok = ''; private string $warning = ''; private string $critical = ''; private string $unknown = ''; private string $acknowledgement = ''; /** * @param string $up * @return void */ public function setUp(string $up): void { $this->up = $up; } /** * @param int $start * @return void */ public function setStart(int $start): void { $this->start = $start; } /** * @param int $end * @return void */ public function setEnd(int $end): void { $this->end = $end; } /** * @param string $notification * @return void */ public function setNotification(string $notification): void { $this->notification = $notification; } /** * @param string $alert * @return void */ public function setAlert(string $alert): void { $this->alert = $alert; } /** * @param string $error * @return void */ public function setError(string $error): void { $this->error = $error; } /** * @param string $down * @return void */ public function setDown(string $down): void { $this->down = $down; } /** * @param string $unreachable * @return void */ public function setUnreachable(string $unreachable): void { $this->unreachable = $unreachable; } /** * @param string $ok * @return void */ public function setOk(string $ok): void { $this->ok = $ok; } /** * @param string $warning * @return void */ public function setWarning(string $warning): void { $this->warning = $warning; } /** * @param string $critical * @return void */ public function setCritical(string $critical): void { $this->critical = $critical; } /** * @param string $unknown * @return void */ public function setUnknown(string $unknown): void { $this->unknown = $unknown; } /** * @param string $acknowledgement * @return void */ public function setAcknowledgement(string $acknowledgement): void { $this->acknowledgement = $acknowledgement; } /** * @param string[] $hosts * @return void */ public function setHosts(array $hosts): void { $this->hosts = $hosts; } /** * Generates an array with metadata (filter values from http request) * @return mixed[] */ public function formatMetaData(): array { return [ ['Begin date', 'End date'], [$this->formatStart(), $this->formatEnd()], [], ['Type', 'Notification', 'Alert', 'error'], ['', $this->notification, $this->alert, $this->error], [], ['Host', 'Up', 'Down', 'Unreachable'], ['', $this->up, $this->down, $this->unreachable], [], ['Service', 'Ok', 'Warning', 'Critical', 'Unknown', 'Acknowledgement'], ['', $this->ok, $this->warning, $this->critical, $this->unknown, $this->acknowledgement], [], ]; } /** * Column names for CSV data table * @return string[] */ public function getLogHeads(): array { return ['Day', 'Time', 'Host', 'Address', 'Service', 'Status', 'Type', 'Retry', 'Output', 'Contact', 'Cmd']; } /** * Generates formatted CSV data * @param \PDOStatement $logs * @return \Iterator<string[]> */ public function formatLogs(iterable $logs): iterable { foreach ($logs as $log) { yield $this->formatLog($log); } } /** * Formats individual log data for CSV * @param string[] $log * @return string[] */ private function formatLog(array $log): array { return [ 'Day' => $this->dateFromTimestamp((int) $log['ctime']), 'Time' => $this->timeFromTimestamp((int) $log['ctime']), 'Host' => $log['host_name'], 'Address' => $this->formatAddress($log['host_name']), 'Service' => $log['service_description'], 'Status' => $this->formatStatus($log['status'], $log['msg_type'], $log['service_description']), 'Type' => $this->formatType($log['type'], $log['msg_type']), 'Retry' => $this->formatRetry($log['retry'], $log['msg_type']), 'Output' => $this->formatOutput($log['output'], $log['status']), 'Contact' => $log['notification_contact'], 'Cmd' => $log['notification_cmd'], ]; } /** * Formats timestamp to date string * @param int $timestamp * @return string */ private function dateFromTimestamp(int $timestamp): string { return date(self::DATE_FORMAT, $timestamp); } /** * Formats timestamp to time string * @param int $timestamp * @return string */ private function timeFromTimestamp(int $timestamp): string { return date(self::TIME_FORMAT, $timestamp); } /** * Formats output value * * @param string $output * @param string $status * @return string */ private function formatOutput(string $output, string $status): string { if ($output === '' && $status !== '') { return self::INITIAL_STATE_VALUE; } return $output; } /** * Formats host name to IP address * @param string $hostName * @return string */ private function formatAddress(string $hostName): string { if (array_key_exists($hostName, $this->hosts)) { return (string) $this->hosts[$hostName]; } return ''; } /** * Formats status value query parameter to CSV data * @param string $status * @param string $msgType * @param string $serviceDescription * @return string */ private function formatStatus(string $status, string $msgType, string $serviceDescription): string { if ($this->msgTypeIsAcknowledged($msgType)) { return self::ACKNOWLEDGMENT_MESSAGE_TYPE; } if ($serviceDescription && array_key_exists($status, $this->serviceStatuses)) { return $this->serviceStatuses[$status]; } if (array_key_exists($status, $this->hostStatuses)) { return $this->hostStatuses[$status]; } return $status; } /** * Checks that message type is one from the available list * @param string $msgType * @return bool */ private function msgTypeIsAcknowledged(string $msgType): bool { return in_array($msgType, [self::HOST_ACKNOWLEDGEMENT_MSG_TYPE, self::SERVICE_ACKNOWLEDGEMENT_MSG_TYPE]); } /** * Formats type for CSV data * @param string $type * @param string $msgType * @return string */ private function formatType(string $type, string $msgType): string { // For an ACK there is no point to display TYPE column if ($this->msgTypeIsAcknowledged($msgType)) { return ''; } if (array_key_exists($type, $this->notificationTypes)) { return $this->notificationTypes[$type]; } if ($this->typeIsNotification($type)) { return self::NOTIFICATION_TYPE_VALUE; } return $type; } /** * Checks that type is one of allowed one * @param string $type * @return bool */ private function typeIsNotification(string $type): bool { return in_array($type, ['2', '3']); } /** * Formats retry query argument * @param string $retry * @param string $msgType * @return string */ private function formatRetry(string $retry, string $msgType): string { // For an ACK there is no point to display RETRY column if ($this->msgTypeIsAcknowledged($msgType)) { return ''; } if ((int) $msgType > 1) { return ''; } return $retry; } /** * Converts end date to datetime format * @return string */ private function formatEnd(): string { return $this->formatDateTime($this->end); } /** * Converts start date to datetime format * * @return string */ private function formatStart(): string { return $this->formatDateTime($this->start); } /** * Formats timestamp to datetime string * @param int $date * @return string */ private function formatDateTime(int $date): string { if ($date <= 0) { return ''; } return date(self::DATE_TIME_FORMAT, $date); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/eventLogs/export/data.php
centreon/www/include/eventLogs/export/data.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'); // Include configuration require_once realpath(__DIR__ . '/../../../../config/centreon.config.php'); // Include Classes / Methods require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreon.class.php'; // Connect MySQL DB $pearDB = new CentreonDB(); $pearDBO = new CentreonDB('centstorage'); $pearDBO->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); // Security check CentreonSession::start(1); $sessionId = session_id(); if (! CentreonSession::checkSession((string) $sessionId, $pearDB)) { echo 'Bad Session'; exit(); } $centreon = $_SESSION['centreon']; // Language informations init $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'); $sid = $sessionId === false ? '-1' : $sessionId; $contact_id = check_session($sid, $pearDB); $is_admin = isUserAdmin($sid); $access = new CentreonACL($contact_id, $is_admin); $lca = [ 'LcaHost' => $access->getHostsServices($pearDBO, true), 'LcaHostGroup' => $access->getHostGroups(), 'LcaSG' => $access->getServiceGroups(), ]; require_once realpath(__DIR__ . DIRECTORY_SEPARATOR . 'Request.php'); $requestHandler = new Centreon\Legacy\EventLogs\Export\Request(); $requestHandler->setIsAdmin($is_admin); $requestHandler->setLca($lca); require_once realpath(__DIR__ . DIRECTORY_SEPARATOR . 'QueryGenerator.php'); $queryGenerator = new Centreon\Legacy\EventLogs\Export\QueryGenerator($pearDBO); $queryGenerator->setIsAdmin($is_admin); $queryGenerator->setEngine($requestHandler->getEngine()); $queryGenerator->setOpenid($requestHandler->getOpenid()); $queryGenerator->setOutput($requestHandler->getOutput()); $queryGenerator->setAccess($access); $queryGenerator->setStart($requestHandler->getStart()); $queryGenerator->setEnd($requestHandler->getEnd()); $queryGenerator->setUp($requestHandler->getUp()); $queryGenerator->setDown($requestHandler->getDown()); $queryGenerator->setUnreachable($requestHandler->getUnreachable()); $queryGenerator->setOk($requestHandler->getOk()); $queryGenerator->setWarning($requestHandler->getWarning()); $queryGenerator->setCritical($requestHandler->getCritical()); $queryGenerator->setUnreachable($requestHandler->getUnreachable()); $queryGenerator->setNotification($requestHandler->getNotification()); $queryGenerator->setAlert($requestHandler->getAlert()); $queryGenerator->setError($requestHandler->getError()); $queryGenerator->setOh($requestHandler->getOh()); $queryGenerator->setHostMsgStatusSet($requestHandler->getHostMsgStatusSet()); $queryGenerator->setSvcMsgStatusSet($requestHandler->getSvcMsgStatusSet()); $queryGenerator->setTabHostIds($requestHandler->getTabHostIds()); $queryGenerator->setSearchHost($requestHandler->getSearchHost()); $queryGenerator->setTabSvc($requestHandler->getTabSvc()); $queryGenerator->setSearchService($requestHandler->getSearchService()); $queryGenerator->setExport($requestHandler->getExport()); $queryGenerator->setAcknowledgement($requestHandler->getAcknowledgement()); $stmt = $queryGenerator->getStatement(); unset($queryGenerator); $stmt->execute(); $HostCache = []; $dbResult = $pearDB->query("SELECT host_name, host_address FROM host WHERE host_register = '1'"); if (! $dbResult instanceof PDOStatement) { throw new RuntimeException('An error occurred. Hosts could not be found'); } while ($h = $dbResult->fetch()) { $HostCache[$h['host_name']] = $h['host_address']; } $dbResult->closeCursor(); require_once realpath(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter.php'); $formatter = new Centreon\Legacy\EventLogs\Export\Formatter(); $formatter->setHosts($HostCache); $formatter->setStart($requestHandler->getStart()); $formatter->setEnd($requestHandler->getEnd()); $formatter->setNotification($requestHandler->getNotification()); $formatter->setAlert($requestHandler->getAlert()); $formatter->setError($requestHandler->getError()); $formatter->setUp($requestHandler->getUp()); $formatter->setDown($requestHandler->getDown()); $formatter->setUnreachable($requestHandler->getUnreachable()); $formatter->setOk($requestHandler->getOk()); $formatter->setWarning($requestHandler->getWarning()); $formatter->setCritical($requestHandler->getCritical()); $formatter->setUnknown($requestHandler->getUnknown()); $formatter->setAcknowledgement($requestHandler->getAcknowledgement()); $formattedLogs = $formatter->formatLogs($stmt); $logHeads = $formatter->getLogHeads(); $metaData = $formatter->formatMetaData(); unset($formatter); require_once realpath(__DIR__ . DIRECTORY_SEPARATOR . 'Presenter.php'); $presenter = new Centreon\Legacy\EventLogs\Export\Presenter(); $presenter->setMetaData($metaData); $presenter->setHeads($logHeads); $presenter->setLogs($formattedLogs); $presenter->render(); $stmt->closeCursor(); unset($presenter, $stmt);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/common-Func.php
centreon/www/include/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 * */ use enshrined\svgSanitize\Sanitizer; /** * Displays the SVG file in HTML. * * @param string $svgPath SVG file path from _CENTREON_PATH_ * @param string $color Color to be used in SVG image * @param float $height Height of image * @param float $width Width of image * @example <?php displaySvg('www/img/centreon.svg', '#000', 50, 50); ?> */ function displaySvg(string $svgPath, string $color, float $height, float $width): void { $path = pathinfo($svgPath); $svgPath = str_replace('.', '', $path['dirname']) . DIRECTORY_SEPARATOR . $path['basename']; $path = _CENTREON_PATH_ . DIRECTORY_SEPARATOR . $svgPath; if (file_exists($path)) { $sanitizer = new Sanitizer(); $svg = file_get_contents($path); if ($svg === false) { echo 'Unable to get content of file: ' . $path; } else { $cleanSvg = str_replace('"', "'", $sanitizer->sanitize($svg)); $cleanSvg = str_replace("\n", '', $cleanSvg); $cleanSvg = str_replace('<svg ', "<svg height='{$height}' width='{$width}' ", $cleanSvg); echo "<span style='fill:{$color}; vertical-align: middle'>" . $cleanSvg . '</span>'; } } else { echo 'SVG file not found: ' . $svgPath; } } /** * Return the SVG file. * * @param string $svgPath SVG file path from _CENTREON_PATH_ * @param string $color Color to be used in SVG image * @param float $height Height of image * @param float $width Width of image * @example <?php returnSvg('www/img/centreon.svg', '#000', 50, 50); ?> */ function returnSvg(string $svgPath, string $color, float $height, float $width): string { $path = pathinfo($svgPath); $svgPath = str_replace('.', '', $path['dirname']) . DIRECTORY_SEPARATOR . $path['basename']; $path = _CENTREON_PATH_ . DIRECTORY_SEPARATOR . $svgPath; if (file_exists($path)) { $data = file_get_contents($path); $data = str_replace('<svg ', "<svg height='{$height}' width='{$width}' ", $data); return "<span style='fill:{$color} ; vertical-align: middle'>" . $data . '</span>'; } return 'SVG file not found: ' . $svgPath; } // Form Rules function slash($elem = null) { if ($elem) { return rtrim($elem, '/') . '/'; } } /* * function table_not_exists() * - This function test if a table exist in database. * * @param string $table_name (the name of the table to test) * @return int 0 (return 0 if the table exists) */ function isUserAdmin($sid = null) { global $pearDB; if (! isset($sid)) { return; } $DBRESULT = $pearDB->prepare( <<<'SQL' SELECT contact_admin, contact_id FROM session, contact WHERE session.session_id = ? AND contact.contact_id = session.user_id SQL ); $DBRESULT->execute([CentreonDB::escape($sid)]); $admin = $DBRESULT->fetchRow(); $DBRESULT->closeCursor(); if ($admin['contact_admin']) { return 1; } return 0; } function myDecode($data) { if (is_string($data)) { $data = html_entity_decode($data, ENT_QUOTES, 'UTF-8'); } return $data; } function myEncode($data) { if (is_string($data)) { $data = htmlentities($data); } return $data; } function isPositiveInteger($value) { return preg_match('/^\d+$/', $value); } function getStatusColor($pearDB) { $colors = []; $DBRESULT = $pearDB->query("SELECT * FROM `options` WHERE `key` LIKE 'color%'"); while ($c = $DBRESULT->fetchRow()) { $colors[$c['key']] = myDecode($c['value']); } $DBRESULT->closeCursor(); return $colors; } function tidySearchKey($search, $advanced_search) { if ($advanced_search == 1) { if (isset($search) && ! strstr($search, '*') && ! strstr($search, '%')) { $search = "'" . $search . "'"; } elseif ( isset($search, $search[0], $search[strlen($search) - 1]) && $search[0] == '%' && $search[strlen($search) - 1] == '%' ) { $search = str_replace('%', '', $search); } elseif (strpos($search, '%')) { $search = str_replace('%', '*', $search); } } return $search; } // // # SMARTY /** * NOT REMOVE THIS FUNCTION - Used in centreon-modules * * Allows to load Smarty's configuration in relation to a path * * @param string|null $path [$path=null] Path to the default template directory * @param object|null $tpl [$tpl=null] A Smarty instance * @param string|null $subDir [$subDir=null] A subdirectory of path * * @throws SmartyException * @return SmartyBC * * @deprecated Instead use {@see SmartyBC::createSmartyTemplate()} * @see SmartyBC::createSmartyTemplate() */ function initSmartyTpl(?string $path = null, ?object &$tpl = null, ?string $subDir = null): SmartyBC { return SmartyBC::createSmartyTemplate($path, $subDir); } /** * NOT REMOVE THIS FUNCTION - Used in centreon-modules * * This function is mainly used in widgets * * @param string|null $path * @param object|null $tpl * @param string|null $subDir * @param string|null $centreonPath * * @throws SmartyException * @return SmartyBC * * @deprecated Instead use {@see SmartyBC::createSmartyTemplate()} * @see SmartyBC::createSmartyTemplate() */ function initSmartyTplForPopup(?string $path = null, ?object $tpl = null, ?string $subDir = null, ?string $centreonPath = null): SmartyBC { return SmartyBC::createSmartyTemplate($path, $subDir); } // FORM VALIDATION function myTrim($str) { global $form; $str = rtrim($str, '\\'); return trim($str); } /** * @param string $value * @return string */ function limitNotesLength(string $value): string { return substr($value, 0, 512); } /** * @param string $value * @return string */ function limitUrlLength(string $value): string { return substr($value, 0, 2048); } function getMyHostName($host_id = null) { global $pearDB; if (! $host_id) { return; } $query = 'SELECT host_name FROM host WHERE host_id = :host_id LIMIT 1'; $statement = $pearDB->prepare($query); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['host_name']) { return $row['host_name']; } } function getMyHostField($host_id, $field) { if (! $host_id) { return; } global $pearDB; $query = 'SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = :host_id ORDER BY `order` ASC'; $statement = $pearDB->prepare($query); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $hostStatement = $pearDB->prepare('SELECT `' . $field . '` FROM host WHERE host_id = :host_tpl_id'); while ($row = $statement->fetchRow()) { $hostStatement->bindValue(':host_tpl_id', (int) $row['host_tpl_id'], PDO::PARAM_INT); $hostStatement->execute(); while ($row2 = $hostStatement->fetchRow()) { if (isset($row2[$field]) && $row2[$field]) { return $row2[$field]; } if ($tmp = getMyHostField($row['host_tpl_id'], $field)) { return $tmp; } } } return null; } // This functions is called recursively until it finds an ehi field function getMyHostExtendedInfoFieldFromMultiTemplates($host_id, $field) { if (! $host_id) { return null; } global $pearDB; $rq = 'SELECT host_tpl_id ' . 'FROM host_template_relation ' . 'WHERE host_host_id = :host_host_id ' . 'ORDER BY `order`'; $statement = $pearDB->prepare($rq); $statement->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $rq2 = 'SELECT ehi.`' . $field . '` ' . ' FROM extended_host_information ehi ' . 'WHERE ehi.host_host_id = :host_host_id LIMIT 1'; $statement2 = $pearDB->prepare($rq2); while ($row = $statement->fetchRow()) { $statement2->bindValue(':host_host_id', (int) $row['host_tpl_id'], PDO::PARAM_INT); $statement2->execute(); $row2 = $statement2->fetchRow(); if (isset($row2[$field]) && $row2[$field]) { return $row2[$field]; } if ($result_field = getMyHostExtendedInfoFieldFromMultiTemplates($row['host_tpl_id'], $field)) { return $result_field; } } return null; } function getMyHostMacroFromMultiTemplates($host_id, $field) { if (! $host_id) { return null; } global $pearDB; $statement = $pearDB->prepare('SELECT host_tpl_id ' . 'FROM host_template_relation ' . 'WHERE host_host_id = :host_host_id ' . 'ORDER BY `order`'); $statement->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $statement2 = $pearDB->prepare('SELECT macro.host_macro_value ' . 'FROM on_demand_macro_host macro ' . 'WHERE macro.host_host_id = :host_host_id AND macro.host_macro_name = :field LIMIT 1'); while ($row = $statement->fetchRow()) { $statement2->bindValue(':host_host_id', (int) $row['host_tpl_id'], PDO::PARAM_INT); $statement2->bindValue(':field', '$_HOST' . $field . '$', PDO::PARAM_STR); $statement2->execute(); $row2 = $statement2->fetchRow(); if (isset($row2['host_macro_value']) && $row2['host_macro_value']) { $macroValue = str_replace('#S#', '/', $row2['host_macro_value']); $macroValue = str_replace('#BS#', '\\', $macroValue); return $macroValue; } if ($result_field = getMyHostMacroFromMultiTemplates($row['host_tpl_id'], $field)) { $macroValue = str_replace('#S#', '/', $result_field); $macroValue = str_replace('#BS#', '\\', $macroValue); return $macroValue; } } return null; } function getMyServiceCategories($service_id = null) { global $pearDB, $oreon; if (! $service_id) { return; } $tab = []; while (1) { $statement = $pearDB->prepare('SELECT sc.sc_id FROM service_categories_relation scr, service_categories sc ' . "WHERE scr.service_service_id = :service_id AND sc.sc_id = scr.sc_id AND sc.sc_activate = '1'"); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); if ($statement->rowCount()) { $tabSC = []; while ($row = $statement->fetchRow()) { $tabSC[$row['sc_id']] = $row['sc_id']; } return $tabSC; } $statement = $pearDB->prepare('SELECT service_template_model_stm_id ' . ' FROM service WHERE service_id = :service_id'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { return []; } } } function getMyCategorieName($sc_id = null) { if (! $sc_id) { return; } global $pearDB, $oreon; $statement = $pearDB->prepare('SELECT sc_name FROM service_categories WHERE sc_id = :sc_id'); $statement->bindValue(':sc_id', (int) $sc_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); return $row['sc_name']; } function getMyServiceMacro($service_id, $field) { if (! $service_id) { return; } global $pearDB; $query = 'SELECT macro.svc_macro_value ' . 'FROM on_demand_macro_service macro ' . 'WHERE macro.svc_svc_id = :svc_svc_id AND macro.svc_macro_name = :svc_macro_name LIMIT 1'; $statement = $pearDB->prepare($query); $statement->bindValue(':svc_svc_id', (int) $service_id, PDO::PARAM_INT); $statement->bindValue(':svc_macro_name', '$_SERVICE' . $field . '$', PDO::PARAM_STR); $statement->execute(); $row = $statement->fetch(PDO::FETCH_ASSOC); if (isset($row['svc_macro_value']) && $row['svc_macro_value']) { $macroValue = str_replace('#S#', '/', $row['svc_macro_value']); $macroValue = str_replace('#BS#', '\\', $macroValue); return $macroValue; } $service_id = getMyServiceField($service_id, 'service_template_model_stm_id'); return getMyServiceMacro($service_id, $field); } function getMyHostExtendedInfoField($host_id, $field) { if (! $host_id) { return; } global $pearDB, $oreon; $rq = 'SELECT ehi.`' . $field . '` ' . 'FROM extended_host_information ehi ' . 'WHERE ehi.host_host_id = :host_id LIMIT 1'; $statement = $pearDB->prepare($rq); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if (isset($row[$field]) && $row[$field]) { return $row[$field]; } return getMyHostExtendedInfoFieldFromMultiTemplates($host_id, $field); } function getMyHostExtendedInfoImage($host_id, $field, $flag1stLevel = null, $antiLoop = null) { global $pearDB, $oreon; if (! $host_id) { return; } if (isset($flag1stLevel) && $flag1stLevel) { $rq = 'SELECT ehi.`' . $field . '` ' . 'FROM extended_host_information ehi ' . 'WHERE ehi.host_host_id = :host_host_id LIMIT 1'; $statement = $pearDB->prepare($rq); $statement->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetch(PDO::FETCH_ASSOC); if (isset($row[$field]) && $row[$field]) { $query = 'SELECT img_path, dir_alias FROM view_img vi, view_img_dir vid, view_img_dir_relation vidr ' . 'WHERE vi.img_id = :img_id AND vidr.img_img_id = vi.img_id AND vid.dir_id = vidr.dir_dir_parent_id LIMIT 1'; $statement = $pearDB->prepare($query); $statement->bindValue(':img_id', (int) $row[$field], PDO::PARAM_INT); $statement->execute(); $row2 = $statement->fetch(PDO::FETCH_ASSOC); if (isset($row2['dir_alias'], $row2['img_path']) && $row2['dir_alias'] && $row2['img_path']) { return $row2['dir_alias'] . '/' . $row2['img_path']; } } elseif ($result_field = getMyHostExtendedInfoImage($host_id, $field)) { return $result_field; } return null; } $rq = 'SELECT host_tpl_id ' . 'FROM host_template_relation ' . 'WHERE host_host_id = :host_host_id ' . 'ORDER BY `order`'; $htStatement = $pearDB->prepare($rq); $htStatement->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $htStatement->execute(); $rq2 = 'SELECT `' . $field . '` ' . 'FROM extended_host_information ehi ' . 'WHERE ehi.host_host_id = :host_host_id LIMIT 1'; $ehiStatement = $pearDB->prepare($rq2); $query = 'SELECT img_path, dir_alias FROM view_img vi, view_img_dir vid, view_img_dir_relation vidr ' . 'WHERE vi.img_id = :img_id AND vidr.img_img_id = vi.img_id AND vid.dir_id = vidr.dir_dir_parent_id LIMIT 1'; $imgStatement = $pearDB->prepare($query); while ($row = $htStatement->fetch(PDO::FETCH_ASSOC)) { $ehiStatement->bindValue(':host_host_id', (int) $row['host_tpl_id'], PDO::PARAM_INT); $ehiStatement->execute(); $row2 = $ehiStatement->fetch(PDO::FETCH_ASSOC); if (isset($row2[$field]) && $row2[$field]) { $imgStatement->bindValue(':img_id', (int) $row2[$field], PDO::PARAM_INT); $imgStatement->execute(); $row3 = $imgStatement->fetch(PDO::FETCH_ASSOC); if (isset($row3['dir_alias'], $row3['img_path']) && $row3['dir_alias'] && $row3['img_path']) { return $row3['dir_alias'] . '/' . $row3['img_path']; } } elseif (isset($antiLoop) && $antiLoop) { if ($antiLoop != $row['host_tpl_id']) { if ($result_field = getMyHostExtendedInfoImage($row['host_tpl_id'], $field, null, $antiLoop)) { return $result_field; } } } elseif ($result_field = getMyHostExtendedInfoImage( $row['host_tpl_id'], $field, null, $row['host_tpl_id'] )) { return $result_field; } } return null; } function getMyHostMultipleTemplateModels($host_id = null) { if (! $host_id) { return []; } global $pearDB; $tplArr = []; $query = 'SELECT host_tpl_id FROM `host_template_relation` WHERE host_host_id = :host_id ORDER BY `order`'; $statement0 = $pearDB->prepare($query); $statement0->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement0->execute(); $statement = $pearDB->prepare('SELECT host_name FROM host WHERE host_id = :host_id LIMIT 1'); while ($row = $statement0->fetchRow()) { $statement->bindValue(':host_id', (int) $row['host_tpl_id'], PDO::PARAM_INT); $statement->execute(); $hTpl = $statement->fetch(PDO::FETCH_ASSOC); $tplArr[$row['host_tpl_id']] = html_entity_decode($hTpl['host_name'], ENT_QUOTES, 'UTF-8'); } return $tplArr; } // // # HOST GROUP function getMyHostGroupName($hg_id = null) { if (! $hg_id) { return; } global $pearDB; $query = 'SELECT hg_name FROM hostgroup WHERE hg_id = :hg_id LIMIT 1'; $statement = $pearDB->prepare($query); $statement->bindValue(':hg_id', (int) $hg_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['hg_name']) { return html_entity_decode($row['hg_name'], ENT_QUOTES, 'UTF-8'); } return null; } /* * ****************************** * Get all host for a specific hostgroup * * @var hostgroup id * @var search string * * @return list of host */ function getMyHostGroupHosts($hg_id = null, $searchHost = null, $level = 1) { global $pearDB; if (! $hg_id) { return; } $searchSTR = ''; if (isset($searchHost) && $searchHost != '') { $searchSTR = " AND h.host_name LIKE '%" . CentreonDB::escape($searchHost) . "%' "; } $hosts = []; $statement = $pearDB->prepare('SELECT hgr.host_host_id ' . 'FROM hostgroup_relation hgr, host h ' . 'WHERE hgr.hostgroup_hg_id = :hostgroup_hg_id ' . "AND h.host_id = hgr.host_host_id {$searchSTR} " . 'ORDER by h.host_name'); $statement->bindValue(':hostgroup_hg_id', (int) $hg_id, PDO::PARAM_INT); $statement->execute(); while ($elem = $statement->fetch(PDO::FETCH_ASSOC)) { $hosts[$elem['host_host_id']] = $elem['host_host_id']; } $statement->closeCursor(); unset($elem); if ($level) { $hgHgCache = setHgHgCache($pearDB); $hostgroups = getMyHostGroupHostGroups($hg_id); if (isset($hostgroups) && count($hostgroups)) { foreach ($hostgroups as $hg_id2) { $tmp = getMyHostGroupHosts($hg_id2, '', 1); foreach ($tmp as $id) { $hosts[$id] = $id; } unset($tmp); } } } return $hosts; } function setHgHgCache($pearDB) { $hgHgCache = []; $DBRESULT = $pearDB->query('SELECT /* SQL_CACHE */ hg_parent_id, hg_child_id FROM hostgroup_hg_relation'); while ($data = $DBRESULT->fetchRow()) { if (! isset($hgHgCache[$data['hg_parent_id']])) { $hgHgCache[$data['hg_parent_id']] = []; } $hgHgCache[$data['hg_parent_id']][$data['hg_child_id']] = 1; } $DBRESULT->closeCursor(); unset($data); return $hgHgCache; } function getMyHostGroupHostGroups($hg_id = null) { global $pearDB; if (! $hg_id) { return; } $hosts = []; $statement = $pearDB->prepare('SELECT hg_child_id ' . 'FROM hostgroup_hg_relation, hostgroup ' . 'WHERE hostgroup_hg_relation.hg_parent_id = :hg_parent_id ' . 'AND hostgroup.hg_id = hostgroup_hg_relation.hg_child_id ' . 'ORDER BY hostgroup.hg_name'); $statement->bindValue(':hg_parent_id', (int) $hg_id, PDO::PARAM_INT); $statement->execute(); while ($elem = $statement->fetch(PDO::FETCH_ASSOC)) { $hosts[$elem['hg_child_id']] = $elem['hg_child_id']; } $statement->closeCursor(); unset($elem); return $hosts; } // // # SERVICE GROUP function getMyServiceGroupServices($sg_id = null) { global $pearDB; if (! $sg_id) { return; } // ServiceGroups by host $svs = []; $statement = $pearDB->prepare('SELECT service_description, service_id, host_host_id, host_name ' . 'FROM servicegroup_relation, service, host ' . 'WHERE servicegroup_sg_id = :sg_id ' . 'AND servicegroup_relation.servicegroup_sg_id = servicegroup_sg_id ' . 'AND service.service_id = servicegroup_relation.service_service_id ' . 'AND servicegroup_relation.host_host_id = host.host_id ' . 'AND servicegroup_relation.host_host_id IS NOT NULL'); $statement->bindValue(':sg_id', (int) $sg_id, PDO::PARAM_INT); $statement->execute(); while ($elem = $statement->fetchRow()) { $svs[$elem['host_host_id'] . '_' . $elem['service_id']] = db2str($elem['service_description']) . ':::' . $elem['host_name']; } // ServiceGroups by hostGroups $statement1 = $pearDB->prepare('SELECT service_description, service_id, hostgroup_hg_id, hg_name ' . 'FROM servicegroup_relation, service, hostgroup ' . 'WHERE servicegroup_sg_id = :sg_id ' . 'AND servicegroup_relation.servicegroup_sg_id = servicegroup_sg_id ' . 'AND service.service_id = servicegroup_relation.service_service_id ' . 'AND servicegroup_relation.hostgroup_hg_id = hostgroup.hg_id ' . 'AND servicegroup_relation.hostgroup_hg_id IS NOT NULL'); $statement1->bindValue(':sg_id', (int) $sg_id, PDO::PARAM_INT); $statement1->execute(); while ($elem = $statement1->fetchRow()) { $hosts = getMyHostGroupHosts($elem['hostgroup_hg_id']); foreach ($hosts as $key => $value) { $svs[$key . '_' . $elem['service_id']] = db2str($elem['service_description']) . ':::' . $value; } } $statement1->closeCursor(); return $svs; } // // # SERVICE function getMyServiceField($service_id, $field) { if (! $service_id) { return; } global $pearDB; $tab = []; while (1) { $statement = $pearDB->prepare('SELECT `' . $field . '` , service_template_model_stm_id ' . 'FROM service WHERE service_id = :service_id LIMIT 1'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row[$field]) { return $row[$field]; } if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { break; } } } function getMyServiceExtendedInfoField($service_id, $field) { if (! $service_id) { return; } global $pearDB; $tab = []; while (1) { $statement = $pearDB->prepare('SELECT `extended_service_information`.`' . $field . '` ,' . ' `service`.`service_template_model_stm_id` ' . 'FROM `service`, `extended_service_information` ' . 'WHERE `extended_service_information`.`service_service_id` =:service_id ' . 'AND `service`.`service_id` = :service_id LIMIT 1'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch()) { if ($row[$field]) { return $row[$field]; } if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { break; } } else { break; } } } function getMyServiceName($service_id = null) { if (! $service_id) { return; } global $pearDB; $tab = []; while (1) { $statement = $pearDB->prepare('SELECT service_description, service_template_model_stm_id FROM service ' . ' WHERE service_id = :service_id LIMIT 1'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['service_description']) { return html_entity_decode(db2str($row['service_description']), ENT_QUOTES, 'UTF-8'); } if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { break; } } } function getMyServiceAlias($service_id = null) { if (! $service_id) { return; } global $pearDB; $tab = []; while (1) { $statement = $pearDB->prepare('SELECT service_alias, service_template_model_stm_id FROM service ' . 'WHERE service_id = :service_id LIMIT 1'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['service_alias']) { return html_entity_decode(db2str($row['service_alias']), ENT_QUOTES, 'UTF-8'); } if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { break; } } } function getMyServiceGraphID($service_id = null) { if (! $service_id) { return; } global $pearDB; $tab = []; while (1) { $statement = $pearDB->prepare('SELECT esi.graph_id, service_template_model_stm_id' . ' FROM service, extended_service_information esi ' . 'WHERE service_id = :service_id AND esi.service_service_id = service_id LIMIT 1'); $statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['graph_id']) { return $row['graph_id']; } if ($row['service_template_model_stm_id']) { if (isset($tab[$row['service_template_model_stm_id']])) { break; } $service_id = $row['service_template_model_stm_id']; $tab[$service_id] = 1; } else { break; } } return null; } function getMyServiceIDStorage($service_description, $host_id) { $dbb = new CentreonDB('centstorage'); $statement = $dbb->prepare('SELECT s.service_id FROM services s ' . ' WHERE (s.description = :service_description OR s.description = :utf8_uncoded_service_description ) ' . ' AND s.host_id = :host_id LIMIT 1'); $statement->bindValue(':service_description', $service_description, PDO::PARAM_STR); $statement->bindValue(':utf8_uncoded_service_description', mb_convert_encoding($service_description, 'UTF-8', 'ISO-8859-1'), PDO::PARAM_STR); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetchRow(); if ($row['service_id']) { return $row['service_id']; } } function getMyServiceID($service_description = null, $host_id = null, $hg_id = null) { if (! $service_description && (! $host_id || ! $hg_id)) { return; } global $pearDB; $service_description = str2db($service_description); if ($host_id) { $statement = $pearDB->prepare('SELECT service_id FROM service, host_service_relation hsr ' . 'WHERE hsr.host_host_id = :host_host_id AND hsr.service_service_id = service_id ' . 'AND (service_description = :service_description OR' . ' service_description = :utf8_encoded_service_description ) LIMIT 1'); $statement->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $statement->bindValue(':utf8_encoded_service_description', mb_convert_encoding($service_description, 'UTF-8', 'ISO-8859-1'), PDO::PARAM_STR); $statement->bindValue(':service_description', $service_description, PDO::PARAM_STR); $statement->execute(); $row = $statement->fetchRow(); // Service is directely link to a host, no problem if ($row['service_id']) { return $row['service_id']; } // The Service might be link with a HostGroup $statement1 = $pearDB->prepare('SELECT service_id ' . ' FROM hostgroup_relation hgr, service, host_service_relation hsr' . ' WHERE hgr.host_host_id = :host_host_id AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id' . ' AND service_id = hsr.service_service_id AND service_description = :service_description'); $statement1->bindValue(':host_host_id', (int) $host_id, PDO::PARAM_INT); $statement1->bindValue(':service_description', $service_description, PDO::PARAM_STR); $statement1->execute(); $row = $statement1->fetchRow(); if ($row['service_id']) { return $row['service_id']; } } if ($hg_id) { $statement2 = $pearDB->prepare('SELECT service_id FROM service, host_service_relation hsr ' . 'WHERE hsr.hostgroup_hg_id = :hostgroup_hg_id AND hsr.service_service_id = service_id ' . 'AND service_description = :service_description LIMIT 1'); $statement2->bindValue(':hostgroup_hg_id', (int) $hg_id, PDO::PARAM_INT); $statement2->bindValue(':service_description', $service_description, PDO::PARAM_STR); $statement2->execute(); $row = $statement2->fetchRow(); if ($row['service_id']) { return $row['service_id']; } } return null; } function getMyHostServices($host_id = null, $search = 0) { global $pearDB; if (! $host_id) { return; } $hSvs = []; // Get Services attached to hosts if ($search !== 0) { $statement = $pearDB->prepare('SELECT service_id, service_description' . ' FROM service, host_service_relation hsr ' . 'WHERE hsr.host_host_id = :host_id AND hsr.service_service_id = service_id ' . 'AND service_description LIKE :service_description '); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->bindValue(':service_description', "'%" . $search . "%'", PDO::PARAM_STR); $statement->execute(); } else { $statement = $pearDB->prepare('SELECT service_id, service_description ' . 'FROM service, host_service_relation hsr ' . 'WHERE hsr.host_host_id = :host_id AND hsr.service_service_id = service_id'); $statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT); $statement->execute(); } while ($elem = $statement->fetchRow()) {
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/checkPagination.php
centreon/www/include/common/checkPagination.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 * */ $page_max = ceil($rows / $limit); if ($num >= $page_max && $rows) { $num = $page_max - 1; } if ($rows == 0) { $num = 0; $page_max = 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/common/vault-functions.php
centreon/www/include/common/vault-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 * */ use Centreon\Domain\Log\Logger; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Common\Infrastructure\FeatureFlags; use Core\Common\Infrastructure\Repository\AbstractVaultRepository; use Core\Security\Vault\Domain\Model\VaultConfiguration; use Symfony\Component\Yaml\Yaml; const DEFAULT_SCHEME = 'https'; /** * Get Client Token for Vault. * * @param VaultConfiguration $vaultConfiguration * @param Logger $logger * @param CentreonRestHttp $httpClient * * @throws Exception * * @return string */ function authenticateToVault( VaultConfiguration $vaultConfiguration, Logger $logger, CentreonRestHttp $httpClient, ): string { try { $url = $vaultConfiguration->getAddress() . ':' . $vaultConfiguration->getPort() . '/v1/auth/approle/login'; $url = sprintf('%s://%s', DEFAULT_SCHEME, $url); $body = [ 'role_id' => $vaultConfiguration->getRoleId(), 'secret_id' => $vaultConfiguration->getSecretId(), ]; $logger->info('Authenticating to Vault: ' . $url); $loginResponse = $httpClient->call($url, 'POST', $body); } catch (Exception $ex) { $logger->error($url . ' did not respond with a 2XX status'); throw $ex; } if (! isset($loginResponse['auth']['client_token'])) { $logger->error($url . ' Unable to retrieve client token from Vault'); throw new Exception('Unable to authenticate to Vault'); } return $loginResponse['auth']['client_token']; } /** * Get host secrets data from vault. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param int $hostId * @param string $vaultPath * @param Logger $logger * * @throws Exception * * @return array<string, mixed> */ function getHostSecretsFromVault( ReadVaultRepositoryInterface $readVaultRepository, int $hostId, string $vaultPath, Logger $logger, ): array { try { return $readVaultRepository->findFromPath($vaultPath); } catch (Exception $ex) { $logger->error(sprintf('Unable to get secrets for host : %d', $hostId)); throw $ex; } } /** * Update host table with secrets path on vault. * * @param CentreonDB $pearDB * @param string $hostPath * @param int $hostId * * @throws Throwable */ function updateHostTableWithVaultPath(CentreonDB $pearDB, string $hostPath, int $hostId): void { $statementUpdateHost = $pearDB->prepare( <<<'SQL' UPDATE `host` SET host_snmp_community = :path WHERE host_id = :hostId SQL ); $statementUpdateHost->bindValue(':path', $hostPath, PDO::PARAM_STR); $statementUpdateHost->bindValue(':hostId', $hostId); $statementUpdateHost->execute(); } /** * Duplicate Host Secrets in Vault. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param ?string $snmpCommunity * @param array<int, array<string, string>> $macroPasswords * @param int $duplicatedHostId * @param int $newHostId * * @throws Throwable */ function duplicateHostSecretsInVault( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, ?string $snmpCommunity, array $macroPasswords, int $duplicatedHostId, int $newHostId, ): void { global $pearDB; $vaultPath = null; // Get UUID form Host SNMP Community Path if it is set if (! empty($snmpCommunity)) { if (str_starts_with($snmpCommunity, VaultConfiguration::VAULT_PATH_PATTERN)) { $vaultPath = $snmpCommunity; } // Get UUID from macro password if they match the vault path regex } elseif ($macroPasswords !== []) { foreach ($macroPasswords as $macroInfo) { if (str_starts_with($macroInfo['macroValue'], VaultConfiguration::VAULT_PATH_PATTERN)) { $vaultPath = $macroInfo['macroValue']; break; } } } $hostSecretsFromVault = []; if ($vaultPath !== null) { $hostSecretsFromVault = getHostSecretsFromVault( $readVaultRepository, $duplicatedHostId, // The duplicated host id $vaultPath, $logger ); } if ($hostSecretsFromVault !== []) { $vaultPaths = $writeVaultRepository->upsert(null, $hostSecretsFromVault); // Store vault path for SNMP Community if (array_key_exists(VaultConfiguration::HOST_SNMP_COMMUNITY_KEY, $vaultPaths)) { updateHostTableWithVaultPath($pearDB, $vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY], $newHostId); } // Store vault path for macros if ($macroPasswords !== []) { foreach ($macroPasswords as $macroId => $macroInfo) { $macroPasswords[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } updateOnDemandMacroHostTableWithVaultPath($pearDB, $macroPasswords); } } } /** * Update on_demand_macro_host table with secrets path on vault. * * @param CentreonDB $pearDB * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * * @throws Throwable */ function updateOnDemandMacroHostTableWithVaultPath(CentreonDB $pearDB, array $macros): void { $statementUpdateMacro = $pearDB->prepare( <<<'SQL' UPDATE `on_demand_macro_host` SET host_macro_value = :path WHERE host_macro_id = :macroId AND host_macro_name = :name SQL ); foreach ($macros as $macroId => $macroInfo) { $statementUpdateMacro->bindValue(':path', $macroInfo['macroValue'], PDO::PARAM_STR); $statementUpdateMacro->bindValue(':macroId', $macroId, PDO::PARAM_INT); $statementUpdateMacro->bindValue(':name', '$' . $macroInfo['macroName'] . '$', PDO::PARAM_STR); $statementUpdateMacro->execute(); } } /** * Delete resources from the vault. * * @param WriteVaultRepositoryInterface $writeVaultRepository * @param int[] $hostIds * @param int[] $serviceIds * * @throws Throwable */ function deleteResourceSecretsInVault( WriteVaultRepositoryInterface $writeVaultRepository, array $hostIds, array $serviceIds, ): void { if ($hostIds !== []) { $uuids = retrieveMultipleHostUuidsFromDatabase($hostIds); if (array_key_exists('host', $uuids)) { foreach ($uuids['host'] as $uuid) { $writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH); $writeVaultRepository->delete($uuid); } } // Delete entry in vault for children services if (array_key_exists('service', $uuids)) { foreach ($uuids['service'] as $uuid) { $writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH); $writeVaultRepository->delete($uuid); } } } if ($serviceIds !== []) { $uuids = retrieveMultipleServiceUuidsFromDatabase($serviceIds); foreach ($uuids as $uuid) { $writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH); $writeVaultRepository->delete($uuid); } } } /** * Found Host and Service linked to Host Secrets UUIDs. * * @param non-empty-array<int> $hostIds * * @return array<string,string[]> */ function retrieveMultipleHostUuidsFromDatabase(array $hostIds): array { global $pearDB; $bindParams = []; foreach ($hostIds as $hostId) { $bindParams[':hostId_' . $hostId] = $hostId; } $bindString = implode(', ', array_keys($bindParams)); $statement = $pearDB->prepare( <<<SQL SELECT DISTINCT h.host_snmp_community, odmh.host_macro_value, odms.svc_macro_value FROM host as h LEFT JOIN on_demand_macro_host as odmh ON h.host_id = odmh.host_host_id LEFT JOIN host_service_relation as hsr ON h.host_id = hsr.host_host_id LEFT JOIN on_demand_macro_service as odms ON odms.svc_svc_id = hsr.service_service_id WHERE (h.host_snmp_community LIKE :vaultPath OR odmh.host_macro_value LIKE :vaultPath OR odms.svc_macro_value LIKE :vaultPath) AND h.host_id IN ( {$bindString} ); SQL ); foreach ($bindParams as $token => $hostId) { $statement->bindValue($token, $hostId, PDO::PARAM_INT); } $statement->bindValue(':vaultPath', 'secret::%', PDO::PARAM_STR); $statement->execute(); $uuids = []; while ($result = $statement->fetch(PDO::FETCH_ASSOC)) { if ( ( preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $result['host_snmp_community'], $matches ) || preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $result['host_macro_value'], $matches ) ) && isset($matches[2]) ) { $uuids['host'][] = $matches[2]; } // Add UUID of services linked to host if ( preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $result['svc_macro_value'], $matches ) && isset($matches[2]) ) { $uuids['service'][] = $matches[2]; } } return $uuids; } /** * Found Service Secrets UUIDs. * * @param non-empty-array<int> $serviceIds * * @return string[] */ function retrieveMultipleServiceUuidsFromDatabase(array $serviceIds): array { global $pearDB; $bindParams = []; foreach ($serviceIds as $serviceId) { $bindParams[':serviceId_' . $serviceId] = $serviceId; } $bindString = implode(', ', array_keys($bindParams)); $statement = $pearDB->prepare( <<<SQL SELECT DISTINCT odms.svc_macro_value FROM on_demand_macro_service as odms WHERE odms.svc_macro_value LIKE :vaultPath AND odms.svc_svc_id IN ( {$bindString} ) SQL ); foreach ($bindParams as $token => $serviceId) { $statement->bindValue($token, $serviceId, PDO::PARAM_INT); } $statement->bindValue(':vaultPath', 'secret::%', PDO::PARAM_STR); $statement->execute(); $uuids = []; while ($result = $statement->fetch(PDO::FETCH_ASSOC)) { if ( preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $result['svc_macro_value'], $matches ) && isset($matches[2]) ) { $uuids[] = $matches[2]; } } return $uuids; } /** * Retrieve Vault path of a host. * * @param CentreonDB $pearDB * @param int $hostId * * @throws Throwable * * @return string|null */ function retrieveHostVaultPathFromDatabase(CentreonDB $pearDB, int $hostId): ?string { $statement = $pearDB->prepare( <<<'SQL' SELECT h.host_snmp_community, odm.host_macro_value FROM host as h LEFT JOIN on_demand_macro_host AS odm ON odm.host_host_id = h.host_id WHERE h.host_id= :hostId AND (odm.host_macro_value LIKE :vaultPath OR h.host_snmp_community LIKE :vaultPath) SQL ); $statement->bindValue(':hostId', $hostId, PDO::PARAM_STR); $statement->bindValue(':vaultPath', VaultConfiguration::VAULT_PATH_PATTERN . '%', PDO::PARAM_STR); $statement->execute(); if (($result = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { foreach ($result as $columnValue) { if (str_starts_with($columnValue, VaultConfiguration::VAULT_PATH_PATTERN)) { return $columnValue; } } } return null; } /** * Retrieve Vault path of a service. * * @param CentreonDB $pearDB * @param int $serviceId * * @throws Throwable * * @return string|null */ function retrieveServiceVaultPathFromDatabase(CentreonDB $pearDB, int $serviceId): ?string { $statement = $pearDB->prepare( <<<'SQL' SELECT ods.svc_macro_value FROM on_demand_macro_service AS ods WHERE ods.svc_svc_id= :serviceId AND ods.svc_macro_value LIKE :vaultPath SQL ); $statement->bindValue(':serviceId', $serviceId, PDO::PARAM_STR); $statement->bindValue(':vaultPath', VaultConfiguration::VAULT_PATH_PATTERN . '%', PDO::PARAM_STR); $statement->execute(); if (($result = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { foreach ($result as $columnValue) { if (str_starts_with($columnValue, VaultConfiguration::VAULT_PATH_PATTERN)) { return $columnValue; } } } return null; } /** * Update Host Secrets in Vault while Massive changing. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param string|null $vaultPath * @param int $hostId * @param array<int,array<string,string>> $macros * @param ?string $snmpCommunity * * @throws Throwable $ex */ function updateHostSecretsInVaultFromMC( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, ?string $vaultPath, int $hostId, array $macros, ?string $snmpCommunity, ): void { global $pearDB; $hostSecretsFromVault = []; $uuid = null; if ($vaultPath !== null) { $uuid = preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $vaultPath, $matches ) ? $matches[2] : null; $hostSecretsFromVault = getHostSecretsFromVault( $readVaultRepository, $hostId, $vaultPath, $logger, ); } $updateHostPayload = prepareHostUpdateMCPayload( $snmpCommunity, $macros, $hostSecretsFromVault ); if ($updateHostPayload !== []) { $vaultPaths = $writeVaultRepository->upsert($uuid, $updateHostPayload); foreach ($macros as $macroId => $macroInfo) { $macros[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } // Store vault path for SNMP Community if (array_key_exists(VaultConfiguration::HOST_SNMP_COMMUNITY_KEY, $vaultPaths)) { updateHostTableWithVaultPath($pearDB, $vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY], $hostId); } // Store vault path for macros if ($macros !== []) { updateOnDemandMacroHostTableWithVaultPath($pearDB, $macros); } } } /** * Add new macros and SNMP Community to the write in vault payload. * * @param string|null $hostSNMPCommunity * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * @param array<string,string> $secretsFromVault * * @return array<string,string> */ function prepareHostUpdateMCPayload(?string $hostSNMPCommunity, array $macros, array $secretsFromVault): array { foreach ($macros as $macroInfos) { $secretsFromVault[$macroInfos['macroName']] = $macroInfos['macroValue']; } // Add SNMP Community if a new value has been set if ($hostSNMPCommunity !== null && ! str_starts_with($hostSNMPCommunity, VaultConfiguration::VAULT_PATH_PATTERN)) { $secretsFromVault[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY] = $hostSNMPCommunity; } return $secretsFromVault; } /** * Update Host Secrets in Vault. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param string|null $vaultPath * @param int $hostId * @param array $macros * @param string|null $snmpCommunity * * @throws Throwable */ function updateHostSecretsInVault( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, ?string $vaultPath, int $hostId, array $macros, ?string $snmpCommunity, ): void { global $pearDB; $hostSecretsFromVault = []; $uuid = null; if ($vaultPath !== null) { $uuid = preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $vaultPath, $matches ) ? $matches[2] : null; $hostSecretsFromVault = getHostSecretsFromVault( $readVaultRepository, $hostId, $vaultPath, $logger ); } $updateHostPayload = prepareHostUpdatePayload( $snmpCommunity, $macros, $hostSecretsFromVault ); // If no more fields are password types, we delete the host from the vault has it will not be read. if (empty($updateHostPayload['to_insert']) && $uuid !== null) { $writeVaultRepository->delete($uuid); } else { $vaultPaths = $writeVaultRepository->upsert( $uuid, $updateHostPayload['to_insert'], $updateHostPayload['to_delete'] ); foreach ($macros as $macroId => $macroInfo) { $macros[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } // Store vault path for SNMP Community if (array_key_exists(VaultConfiguration::HOST_SNMP_COMMUNITY_KEY, $vaultPaths)) { updateHostTableWithVaultPath($pearDB, $vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY], $hostId); } // Store vault path for macros if ($macros !== []) { updateOnDemandMacroHostTableWithVaultPath($pearDB, $macros); } } } /** * Prepare the write-in vault payload while updating a host. * * This method will compare the secrets already stored in the vault with the secrets submitted by the form * And return which secrets should be inserted or deleted. * * @param string|null $hostSNMPCommunity * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * @param array<string,string> $secretsFromVault * * @return array{to_insert: array<string,string>, to_delete: array<string,string>} */ function prepareHostUpdatePayload(?string $hostSNMPCommunity, array $macros, array $secretsFromVault): array { $payload = ['to_insert' => [], 'to_delete' => []]; // Unset existing macros on vault if they no more exist while submitting the form foreach (array_keys($secretsFromVault) as $secretKey) { if ($secretKey !== VaultConfiguration::HOST_SNMP_COMMUNITY_KEY) { $macroName = []; foreach ($macros as $macroInfos) { $macroName[] = $macroInfos['macroName']; if (array_key_exists('originalName', $macroInfos) && $secretKey === $macroInfos['originalName']) { $secretsFromVault[$macroInfos['macroName']] = $secretsFromVault[$secretKey]; } } if (! in_array($secretKey, $macroName, true)) { $payload['to_delete'][$secretKey] = $secretsFromVault[$secretKey]; unset($secretsFromVault[$secretKey]); } } } // Add macros to payload if they are password type and their values have changed foreach ($macros as $macroInfos) { if ( $macroInfos['macroPassword'] === '1' && ! str_starts_with($macroInfos['macroValue'], VaultConfiguration::VAULT_PATH_PATTERN) ) { $secretsFromVault[$macroInfos['macroName']] = $macroInfos['macroValue']; } } /** * Unset existing SNMP Community if it no more exists while submitting the form * * A non updated SNMP Community is considered as null * A removed SNMP Community is considered as an empty string */ if ( array_key_exists(VaultConfiguration::HOST_SNMP_COMMUNITY_KEY, $secretsFromVault) && $hostSNMPCommunity === '' ) { $payload['to_delete'][VaultConfiguration::HOST_SNMP_COMMUNITY_KEY] = $secretsFromVault[ VaultConfiguration::HOST_SNMP_COMMUNITY_KEY ]; unset($secretsFromVault[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]); } // Add SNMP Community if a new value has been set if ($hostSNMPCommunity !== null && ! str_starts_with($hostSNMPCommunity, VaultConfiguration::VAULT_PATH_PATTERN)) { $secretsFromVault[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY] = $hostSNMPCommunity; } $payload['to_insert'] = $secretsFromVault; return $payload; } /** * Duplicate Service Secrets in Vault. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param int $duplicatedServiceId * @param array<int, array<string, string> $macroPasswords * * @throws Throwable */ function duplicateServiceSecretsInVault( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, int $duplicatedServiceId, array $macroPasswords, ): void { global $pearDB; $vaultPath = null; foreach ($macroPasswords as $macroInfo) { if (str_starts_with($macroInfo['macroValue'], VaultConfiguration::VAULT_PATH_PATTERN)) { $vaultPath = $macroInfo['macroValue']; break; } } $serviceSecretsFromVault = []; if ($vaultPath !== null) { $serviceSecretsFromVault = getServiceSecretsFromVault( $readVaultRepository, $duplicatedServiceId, // The duplicated service id $vaultPath, $logger, ); } if ($serviceSecretsFromVault !== []) { $vaultPaths = $writeVaultRepository->upsert(null, $serviceSecretsFromVault); // Store vault path for macros if ($macroPasswords !== []) { foreach ($macroPasswords as $macroId => $macroInfo) { $macroPasswords[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } updateOnDemandMacroServiceTableWithVaultPath($pearDB, $macroPasswords); } } } /** * Get service secrets data from vault. * * @param VaultConfiguration $vaultConfiguration * @param int $serviceId * @param string $uuid * @param string $clientToken * @param Logger $logger * @param CentreonRestHttp $httpClient * * @throws Throwable * * @return array<string, mixed> */ function getServiceSecretsFromVault( ReadVaultRepositoryInterface $readVaultRepository, int $serviceId, string $vaultPath, Logger $logger, ): array { try { return $readVaultRepository->findFromPath($vaultPath); } catch (Exception $ex) { $logger->error(sprintf('Unable to get secrets for Service : %d', $serviceId)); throw $ex; } } /** * Update on_demand_macro_service table with secrets path on vault. * * @param CentreonDB $pearDB * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * * @throws Throwable */ function updateOnDemandMacroServiceTableWithVaultPath(CentreonDB $pearDB, array $macros): void { $statementUpdateMacro = $pearDB->prepare( <<<'SQL' UPDATE `on_demand_macro_service` SET svc_macro_value = :path WHERE svc_macro_id = :macroId AND svc_macro_name = :name SQL ); foreach ($macros as $macroId => $macroInfo) { $statementUpdateMacro->bindValue(':path', $macroInfo['macroValue'], PDO::PARAM_STR); $statementUpdateMacro->bindValue(':macroId', $macroId, PDO::PARAM_INT); $statementUpdateMacro->bindValue(':name', '$' . $macroInfo['macroName'] . '$', PDO::PARAM_STR); $statementUpdateMacro->execute(); } } /** * Retrieve UUID of a service. * * @param CentreonDB $pearDB * @param int $serviceId * @param string $vaultConfigurationName * * @throws Throwable * * @return string|null */ function retrieveServiceSecretUuidFromDatabase( CentreonDB $pearDB, int $serviceId, ): ?string { $statement = $pearDB->prepare( <<<'SQL' SELECT ods.svc_macro_value FROM on_demand_macro_service AS ods WHERE ods.svc_svc_id= :serviceId AND ods.svc_macro_value LIKE :vaultPath SQL ); $statement->bindValue(':serviceId', $serviceId, PDO::PARAM_STR); $statement->bindValue(':vaultPath', VaultConfiguration::VAULT_PATH_PATTERN . '%', PDO::PARAM_STR); $statement->execute(); if (($result = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { if ( preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $result['svc_macro_value'], $matches ) && isset($matches[2]) ) { return $matches[2]; } } return null; } /** * Update Service Secrets in Vault after Massive changing. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param string|null $vaultPath * @param int $serviceId * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * * @throws Throwable */ function updateServiceSecretsInVaultFromMC( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, ?string $vaultPath, int $serviceId, array $macros, ): void { global $pearDB; $serviceSecretsFromVault = []; $uuid = null; if ($vaultPath !== null) { $uuid = preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $vaultPath, $matches ) ? $matches[2] : null; $serviceSecretsFromVault = getServiceSecretsFromVault( $readVaultRepository, $serviceId, $vaultPath, $logger ); } $updateServicePayload = prepareServiceUpdateMCPayload( $macros, $serviceSecretsFromVault ); if (! empty($updateServicePayload)) { $vaultPaths = $writeVaultRepository->upsert($uuid, $updateServicePayload); foreach ($macros as $macroId => $macroInfo) { $macros[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } // Store vault path for macros if ($macros !== []) { updateOnDemandMacroServiceTableWithVaultPath($pearDB, $macros); } } } /** * Add new macros to the write in vault payload. * * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * @param array<string,string> $serviceSecretsFromVault * * @return array<string,string> */ function prepareServiceUpdateMCPayload(array $macros, array $serviceSecretsFromVault) { foreach ($macros as $macroInfos) { if ( $macroInfos['macroPassword'] === '1' && ! str_starts_with($macroInfos['macroValue'], VaultConfiguration::VAULT_PATH_PATTERN) ) { $serviceSecretsFromVault[$macroInfos['macroName']] = $macroInfos['macroValue']; } } return $serviceSecretsFromVault; } /** * Update Service Secrest in Vault. * * @param ReadVaultRepositoryInterface $readVaultRepository * @param WriteVaultRepositoryInterface $writeVaultRepository * @param Logger $logger * @param int $serviceId * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * @param string|null $uuid * * @throws Throwable */ function updateServiceSecretsInVault( ReadVaultRepositoryInterface $readVaultRepository, WriteVaultRepositoryInterface $writeVaultRepository, Logger $logger, ?string $vaultPath, int $serviceId, array $macros, ): void { global $pearDB; $serviceSecretsFromVault = []; if ($vaultPath !== null) { $uuid = preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $vaultPath, $matches ) ? $matches[2] : null; $serviceSecretsFromVault = getServiceSecretsFromVault( $readVaultRepository, $serviceId, $vaultPath, $logger ); } $updateServicePayload = prepareServiceUpdatePayload( $macros, $serviceSecretsFromVault ); // If no more fields are password types, we delete the service from the vault has it will not be read. if (empty($updateServicePayload['to_insert']) && $uuid !== null) { $writeVaultRepository->delete($uuid); } else { $vaultPaths = $writeVaultRepository->upsert( $uuid, $updateServicePayload['to_insert'], $updateServicePayload['to_delete'] ); foreach ($macros as $macroId => $macroInfo) { $macros[$macroId]['macroValue'] = $vaultPaths[$macroInfo['macroName']]; } // Store vault path for macros if ($macros !== []) { updateOnDemandMacroServiceTableWithVaultPath($pearDB, $macros); } } } /** * Prepare the write-in vault payload while updating a service. * * This method will compare the secrets already stored in the vault with the secrets submitted by the form * And update their value or delete them if they are no more setted. * * @param array<int,array{ * macroName: string, * macroValue: string, * macroPassword: '0'|'1', * originalName?: string * }> $macros * @param array<string,string> $serviceSecretsFromVault * * @return array{to_insert: array<string,string>, to_delete: array<string,string>} */ function prepareServiceUpdatePayload(array $macros, array $serviceSecretsFromVault): array { $payload = ['to_insert' => [], 'to_delete' => []]; // Unset existing macros on vault if they no more exist while submitting the form foreach (array_keys($serviceSecretsFromVault) as $secretKey) { $macroName = []; foreach ($macros as $macroInfos) { $macroName[] = $macroInfos['macroName']; if (array_key_exists('originalName', $macroInfos) && $secretKey === $macroInfos['originalName']) { $serviceSecretsFromVault[$macroInfos['macroName']] = $serviceSecretsFromVault[$secretKey]; } } if (! in_array($secretKey, $macroName, true)) { $payload['to_delete'][$secretKey] = $serviceSecretsFromVault[$secretKey]; unset($serviceSecretsFromVault[$secretKey]); } } // Add macros to payload if they are password type and their values have changed foreach ($macros as $macroInfos) { if ( $macroInfos['macroPassword'] === '1' && ! str_starts_with($macroInfos['macroValue'], VaultConfiguration::VAULT_PATH_PATTERN) ) { $serviceSecretsFromVault[$macroInfos['macroName']] = $macroInfos['macroValue']; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/sqlCommonFunction.php
centreon/www/include/common/sqlCommonFunction.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); require_once _CENTREON_PATH_ . '/src/Core/Common/Infrastructure/Repository/SqlMultipleBindTrait.php'; use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum; use Adaptation\Database\Connection\ValueObject\QueryParameter; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; /** * @param array<int|string, int|string> $list * @param string $prefix * @param int|null $bindType (optional) * * @return array{ * 0: array<string, int|string|array{0: int|string, 1: int}>, * 1: string * } */ function createMultipleBindQuery(array $list, string $prefix, ?int $bindType = null): array { return (new class () { use SqlMultipleBindTrait { SqlMultipleBindTrait::createMultipleBindQuery as public create; } })->create($list, $prefix, $bindType); } /** * Create multiple bind parameters compatible with QueryParameterTypeEnum * * @param array<int|string, int|string|null> $values Scalar values to bind * @param string $prefix Placeholder prefix (no colon) * @param QueryParameterTypeEnum $paramType Type of binding (INTEGER|STRING) * * @return array{parameters: QueryParameter[], placeholderList: string} */ function createMultipleBindParameters( array $values, string $prefix, QueryParameterTypeEnum $paramType, ): array { return (new class () { use SqlMultipleBindTrait { SqlMultipleBindTrait::createMultipleBindParameters as public create; } })->create($values, $prefix, $paramType); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/mobile_menu.php
centreon/www/include/common/mobile_menu.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 * */ ?> <header class="nav-top"> <span class="hamburger material-icons" id="ham">menu</span> <div class="logo"></div> </header> <nav class="nav-drill"> <ul class="nav-items nav-level-1"> <?php foreach ($treeMenu as $index => $subMenu) { ?> <li class="nav-item <?php if (! empty($subMenu['children'])) { ?>nav-expand<?php } ?>"> <a class="nav-link <?php if (! empty($subMenu['children'])) { ?>nav-expand-link<?php } ?>" href="#"> <?= $subMenu['label']; ?> </a> <?php if (! empty($subMenu['children'])) { ?> <ul class="nav-items nav-expand-content"> <?php foreach ($subMenu['children'] as $index2 => $subMenu2) { ?> <?php if (! empty($subMenu2['children'])) { ?> <li class="nav-item nav-expand"> <a class="nav-link nav-expand-link" href="#"> <?= $subMenu2['label']; ?> </a> <ul class="nav-items nav-expand-content"> <?php foreach ($subMenu2['children'] as $childrens) { ?> <?php foreach ($childrens as $index3 => $subMenu3) { ?> <li class="nav-item"> <a class="nav-link" href="main.php?p=<?= substr($index3, 1) . $subMenu3['options']; ?>"> <?= $subMenu3['label']; ?> </a> </li> <?php } ?> <?php } ?> </ul> </li> <?php } else { ?> <li class="nav-item"> <a class="nav-link" href="main.php?p=<?= substr($index2, 1); ?>"> <?= $subMenu2['label']; ?> </a> </li> <?php } ?> <?php } ?> </ul> <?php } ?> </li> <?php } ?> <li class="nav-item"> <a class="nav-link" href="index.php?disconnect=1"> <?= gettext('Logout'); ?> </a> </li> </ul> </nav>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/pagination.php
centreon/www/include/common/pagination.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 * */ global $centreon; if (! isset($centreon)) { exit(); } global $num, $limit, $search, $url, $pearDB, $search_type_service, $search_type_host, $host_name, $hostgroup, $rows, $p, $gopt, $pagination, $poller, $template, $search_output, $search_service; $type = filter_var( $_POST['type'] ?? $_GET['type'] ?? null, FILTER_VALIDATE_INT ); $type = $type ? '&type=' . $type : ''; $o = $_GET['o'] ?? null; // saving current pagination filter value and current displayed page $centreon->historyPage[$url] = $num; $centreon->historyLastUrl = $url; $num = addslashes($num); $tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc']; if (isset($_GET['search_type_service'])) { $search_type_service = $_GET['search_type_service']; $centreon->search_type_service = $_GET['search_type_service']; } elseif (isset($centreon->search_type_service)) { $search_type_service = $centreon->search_type_service; } else { $search_type_service = null; } if (isset($_GET['search_type_host'])) { $search_type_host = $_GET['search_type_host']; $centreon->search_type_host = $_GET['search_type_host']; } elseif (isset($centreon->search_type_host)) { $search_type_host = $centreon->search_type_host; } else { $search_type_host = null; } if (! isset($_GET['search_type_host']) && ! isset($centreon->search_type_host) && ! isset($_GET['search_type_service']) && ! isset($centreon->search_type_service) ) { $search_type_host = 1; $centreon->search_type_host = 1; $search_type_service = 1; $centreon->search_type_service = 1; } $url_var = ''; if (isset($search_type_service)) { $url_var .= '&search_type_service=' . $search_type_service; } if (isset($search_type_host)) { $url_var .= '&search_type_host=' . $search_type_host; } if (isset($hostgroup)) { $url_var .= '&hostgroup=' . $hostgroup; } if (isset($host_name)) { $url_var .= '&search_host=' . $host_name; } if (isset($search_service)) { $url_var .= '&search_service=' . $search_service; } if (isset($search_output) && $search_output != '') { $url_var .= '&search_output=' . $search_output; } if (isset($_GET['order'])) { $url_var .= '&order=' . $_GET['order']; $order = $_GET['order']; } if (isset($_GET['sort_types'])) { $url_var .= '&sort_types=' . $_GET['sort_types']; $sort_type = $_GET['sort_types']; } // Fix for downtime if (isset($_REQUEST['view_all'])) { $url_var .= '&view_all=' . $_REQUEST['view_all']; } if (isset($_REQUEST['view_downtime_cycle'])) { $url_var .= '&view_downtime_cycle=' . $_REQUEST['view_downtime_cycle']; } if (isset($_REQUEST['search_author'])) { $url_var .= '&search_author=' . $_REQUEST['search_author']; } // Fix for status in service configuration if (isset($_REQUEST['status'])) { $url_var .= '&status=' . $_REQUEST['status']; } // Fix for status in service configuration if (isset($_REQUEST['hostgroups'])) { $url_var .= '&hostgroups=' . $_REQUEST['hostgroups']; } // Start Fix for performance management under administration - parameters if (isset($_REQUEST['searchS'])) { $url_var .= '&searchS=' . $_REQUEST['searchS']; if (isset($_POST['num'])) { $num = 0; } } if (isset($_REQUEST['searchH'])) { $url_var .= '&searchH=' . $_REQUEST['searchH']; if (isset($_POST['num'])) { $num = 0; } } // End Fix for performance management under administration - parameters if (! isset($path)) { $path = null; } // Smarty template initialization $tpl = SmartyBC::createSmartyTemplate($path, './include/common/'); $page_max = ceil($rows / $limit); if ($num >= $page_max && $rows) { $num = $page_max - 1; } $pageArr = []; $iStart = 0; for ($i = 5, $iStart = $num; $iStart && $i > 0; $i--) { $iStart--; } for ($i2 = 0, $iEnd = $num; ($iEnd < ($rows / $limit - 1)) && ($i2 < (5 + $i)); $i2++) { $iEnd++; } if ($rows != 0) { for ($i = $iStart; $i <= $iEnd; $i++) { $urlPage = 'main.php?p=' . $p . '&num=' . $i . $type; $pageArr[$i] = ['url_page' => $urlPage, 'label_page' => '<b>' . ($i + 1) . '</b>', 'num' => $i]; } if ($i > 1) { $tpl->assign('pageArr', $pageArr); } $tpl->assign('num', $num); $tpl->assign('first', _('First page')); $tpl->assign('previous', _('Previous page')); $tpl->assign('next', _('Next page')); $tpl->assign('last', _('Last page')); if (($prev = $num - 1) >= 0) { $tpl->assign( 'pagePrev', ('main.php?p=' . $p . '&num=' . $prev . '&limit=' . $limit . $type) ); } if (($next = $num + 1) < ($rows / $limit)) { $tpl->assign( 'pageNext', ('main.php?p=' . $p . '&num=' . $next . '&limit=' . $limit . $type) ); } $pageNumber = ceil($rows / $limit); if (($rows / $limit) > 0) { $tpl->assign('pageNumber', ($num + 1) . '/' . $pageNumber); } else { $tpl->assign('pageNumber', ($num) . '/' . $pageNumber); } if ($page_max > 5 && $num != 0) { $tpl->assign( 'firstPage', ('main.php?p=' . $p . '&num=0&limit=' . $limit . $type) ); } if ($page_max > 5 && $num != ($pageNumber - 1)) { $tpl->assign( 'lastPage', ('main.php?p=' . $p . '&num=' . ($pageNumber - 1) . '&limit=' . $limit . $type) ); } // Select field to change the number of row on the page for ($i = 10; $i <= 100; $i = $i + 10) { $select[$i] = $i; } if (isset($gopt[$pagination]) && $gopt[$pagination]) { $select[$gopt[$pagination]] = $gopt[$pagination]; } ksort($select); } else { for ($i = 10; $i <= 100; $i = $i + 10) { $select[$i] = $i; } } ?> <script type="text/javascript"> function setL(_this) { var _l = document.getElementsByName('l'); document.forms['form'].elements['limit'].value = _this; _l[0].value = _this; _l[1].value = _this; window.history.replaceState('', '', '?p=<?= $p . $type; ?>'); } </script> <?php $form = new HTML_QuickFormCustom( 'select_form', 'GET', '?p=' . $p . '&search_type_service=' . $search_type_service . '&search_type_host=' . $search_type_host ); $selLim = $form->addElement( 'select', 'l', _('Rows'), $select, ['onChange' => 'setL(this.value); this.form.submit()'] ); $selLim->setSelected($limit); // Element we need when we reload the page $form->addElement('hidden', 'p'); $form->addElement('hidden', 'search'); $form->addElement('hidden', 'num'); $form->addElement('hidden', 'order'); $form->addElement('hidden', 'type'); $form->addElement('hidden', 'sort_types'); $form->setDefaults(['p' => $p, 'search' => $search, 'num' => $num]); // Init QuickForm $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $host_name = $_GET['host_name'] ?? null; $status = $_GET['status'] ?? null; isset($order) ? true : $order = null; $tpl->assign('host_name', $host_name); $tpl->assign('status', $status); $tpl->assign('limite', $limite ?? null); $tpl->assign('begin', $num); $tpl->assign('end', $limit); $tpl->assign('pagin_page', _('Page')); $tpl->assign('order', $order); $tpl->assign('tab_order', $tab_order); $tpl->assign('form', $renderer->toArray()); if (! $tpl->get_template_vars('firstPage')) { $tpl->assign('firstPage', null); } if (! $tpl->get_template_vars('pagePrev')) { $tpl->assign('pagePrev', null); } if (! $tpl->get_template_vars('pageArr')) { $tpl->assign('pageArr', null); } if (! $tpl->get_template_vars('pageNext')) { $tpl->assign('pageNext', null); } if (! $tpl->get_template_vars('lastPage')) { $tpl->assign('lastPage', null); } $tpl->display('pagination.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/common/userTimezone.php
centreon/www/include/common/userTimezone.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__ . '/../../../config/centreon.config.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/centreonXML.class.php'; require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php'; $pearDB = new CentreonDB(); $buffer = new CentreonXML(); $buffer->startElement('entry'); session_start(); session_write_close(); $sid = session_id(); $centreon = null; if (isset($_SESSION['centreon'])) { $centreon = $_SESSION['centreon']; $currentTime = $centreon->CentreonGMT->getCurrentTime(time(), $centreon->user->getMyGMT()); $stmt = $pearDB->prepare('SELECT user_id FROM session WHERE session_id = ?'); $stmt->execute([$sid]); if ($stmt->rowCount()) { $buffer->writeElement('state', 'ok'); } else { $buffer->writeElement('state', 'nok'); } } else { $currentTime = date_format(date_create(), '%c'); $buffer->writeElement('state', 'nok'); } $buffer->writeElement('time', $currentTime); $buffer->writeElement( 'timezone', $centreon !== null ? $centreon->CentreonGMT->getActiveTimezone($centreon->user->getMyGMT()) : date_default_timezone_get() ); $buffer->endElement(); header('Content-Type: text/xml'); header('Pragma: no-cache'); header('Expires: 0'); header('Cache-Control: no-cache, must-revalidate'); $buffer->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/common/getHiddenImage.php
centreon/www/include/common/getHiddenImage.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__ . '/../../../config/centreon.config.php'; require_once __DIR__ . '/../../class/centreonSession.class.php'; require_once __DIR__ . '/../../class/centreon.class.php'; require_once __DIR__ . '/../../class/centreonDB.class.php'; CentreonSession::start(); $pearDB = new CentreonDB(); $session = $pearDB->query("SELECT * FROM `session` WHERE `session_id` = '" . session_id() . "'"); if (! $session->rowCount()) { exit; } $logos_path = '../../img/media/'; if (isset($_GET['id']) && $_GET['id'] && is_numeric($_GET['id'])) { $query = 'SELECT dir_name, img_path FROM view_img_dir, view_img, view_img_dir_relation vidr ' . 'WHERE view_img_dir.dir_id = vidr.dir_dir_parent_id AND vidr.img_img_id = img_id AND img_id = :img_id'; $statement = $pearDB->prepare($query); $statement->bindValue(':img_id', $_GET['id'], PDO::PARAM_INT); $statement->execute(); while ($img = $statement->fetch(PDO::FETCH_ASSOC)) { $imgDirName = basename($img['dir_name']); $imgName = basename($img['img_path']); $imgPath = $logos_path . $imgDirName . '/' . $imgName; if (! is_file($imgPath)) { $imgPath = _CENTREON_PATH_ . 'www/img/media/' . $imgDirName . '/' . $imgName; } if (is_file($imgPath)) { $mimeType = finfo_file(finfo_open(), $imgPath, FILEINFO_MIME_TYPE); $fileExtension = substr($imgName, strrpos($imgName, '.') + 1); try { switch ($mimeType) { case 'image/jpeg': /** * use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log */ $image = @imagecreatefromjpeg($imgPath); if (! $image || ! imagejpeg($image)) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Unable to validate image, your image may be corrupted', [ 'mime_type' => $mimeType, 'filename' => $imgName, 'extension' => $fileExtension, ] ); throw new Exception('Failed to create image from JPEG'); } break; case 'image/png': /** * use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log */ $image = @imagecreatefrompng($imgPath); if (! $image || ! imagepng($image)) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Unable to validate image, your image may be corrupted', [ 'mime_type' => $mimeType, 'filename' => $imgName, 'extension' => $fileExtension, ] ); throw new Exception('Failed to create image from PNG'); } break; case 'image/gif': /** * use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log */ $image = @imagecreatefromgif($imgPath); if (! $image || ! imagegif($image)) { CentreonLog::create()->error( CentreonLog::TYPE_BUSINESS_LOG, 'Unable to validate image, your image may be corrupted', [ 'mime_type' => $mimeType, 'filename' => $imgName, 'extension' => $fileExtension, ] ); throw new Exception('Failed to create image from GIF'); } break; case 'image/svg+xml': $image = file_get_contents($imgPath); header('Content-Type: image/svg+xml'); echo $image; break; default: throw new Exception("Unsupported image type: {$mimeType}"); break; } } catch (Throwable $e) { echo $e->getMessage(); } } else { echo 'File not found'; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/autoNumLimit.php
centreon/www/include/common/autoNumLimit.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(); } $limitNotInRequestParameter = ! isset($_POST['limit']) && ! isset($_GET['limit']); $historyLimitNotDefault = isset($centreon->historyLimit[$url]) && $centreon->historyLimit[$url] !== 30; $sessionLimitKey = "results_limit_{$url}"; // Setting the limit filter if (isset($_POST['limit']) && $_POST['limit']) { $limit = filter_input(INPUT_POST, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); } elseif (isset($_GET['limit'])) { $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]); } elseif ($limitNotInRequestParameter && $historyLimitNotDefault) { $limit = $centreon->historyLimit[$url]; } elseif (isset($_SESSION[$sessionLimitKey])) { $limit = $_SESSION[$sessionLimitKey]; } else { if (($p >= 200 && $p < 300) || ($p >= 20000 && $p < 30000)) { $dbResult = $pearDB->query("SELECT * FROM `options` WHERE `key` = 'maxViewMonitoring'"); } else { $dbResult = $pearDB->query("SELECT * FROM `options` WHERE `key` = 'maxViewConfiguration'"); } $gopt = $dbResult->fetch(); $limit = (int) $gopt['value'] ?: 30; } $_SESSION[$sessionLimitKey] = $limit; // Setting the pagination filter if (isset($_POST['num'], $_POST['search']) || (isset($centreon->historyLastUrl) && $centreon->historyLastUrl !== $url) ) { // Checking if the current page and the last displayed page are the same and resetting the filters $num = 0; } elseif (isset($_REQUEST['num'])) { // Checking if a pagination filter has been sent in the http request $num = filter_var( $_GET['num'] ?? $_POST['num'] ?? 0, FILTER_VALIDATE_INT ); } else { // Resetting the pagination filter $num = $centreon->historyPage[$url] ?? 0; } // Cast limit and num to avoid sql error on prepared statement (PDO::PARAM_INT) $limit = (int) $limit; $num = (int) $num; global $search;
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/csvFunctions.php
centreon/www/include/common/csvFunctions.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 string $text * @param string $delimiter (default ';') * * @return Generator */ function readCsvLine(string &$text, string $delimiter = ';'): Generator { $handle = @fopen('php://memory', 'r+'); if ($handle === false) { throw new RuntimeException('Failed to create memory stream'); } if (fwrite($handle, $text) === false) { fclose($handle); throw new RuntimeException('Failed to write to memory stream'); } rewind($handle); while ($data = fgetcsv($handle, null, $delimiter, '"', '')) { yield $data; } fclose($handle); } /** * @param $text * @param bool $useCsvHeaderAsKey If true, the first line will be used as headers * @param string $delimiter The delimiter used in the CSV file * * @return array */ function csvToArray(&$text, bool $useCsvHeaderAsKey, string $delimiter = ';'): array { $lineNumber = 0; $delimiterNumber = 0; $data = []; $headers = []; foreach (readCsvLine($text, $delimiter) as $record) { if ($lineNumber++ === 0) { $headers = $record; $delimiterNumber = count($headers); if (! $useCsvHeaderAsKey) { $data[] = $headers; } continue; } $record = explode($delimiter, implode($delimiter, $record), $delimiterNumber); if ($useCsvHeaderAsKey) { if (count($record) !== count($headers)) { throw new RuntimeException( sprintf( 'CSV record on line %d has %d fields, expected %d', $lineNumber, count($record), count($headers) ) ); } $data[] = array_combine($headers, $record); } else { $data[] = $record; } } return $data; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/common/webServices/rest/internal.php
centreon/www/include/common/webServices/rest/internal.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 '../../../../api/internal.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/common/webServices/rest/index.php
centreon/www/include/common/webServices/rest/index.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 '../../../../api/index.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/common/javascript/color_picker.php
centreon/www/include/common/javascript/color_picker.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__ . '/../../../class/HtmlAnalyzer.php'; $n = ''; $name = ''; $title = ''; $hcolor = '000000'; function filter_get($str) { if (preg_match("/([a-zA-Z0-9\_\-\%\ ]*)/", $str, $matches)) { return $matches[1]; } return null; } if (function_exists('filter_var')) { $n = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['n']); $name = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['name']); $title = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['title']); if (isset($_GET['hcolor'])) { $hcolor = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hcolor']); } } else { $n = filter_get($_GET['n']); $name = filter_get($_GET['name']); $title = filter_get($_GET['title']); if (isset($_GET['hcolor'])) { $hcolor = filter_get($_GET['hcolor']); } } $n = htmlspecialchars($n, ENT_QUOTES, 'UTF-8'); $name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); $title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); $hcolor = htmlspecialchars($hcolor, ENT_QUOTES, 'UTF-8'); $name1 = $n . ''; $name2 = $n . '_color'; ?> <html> <head> <title>Color Picker</title> <style type="text/css"> body { font-size: 12px; font-family: Verdana, Sans-Serif; text-align:center; background-color:#FFFFFF; color:navy;} td { font-size: 12px; font-family: Verdana, Sans-Serif; text-align:center; background-color:#FFFFFF} .table_black_border {border-style:solid; border-width:1px; border-color:#000000;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> // Déposé par Frosty sur www.toutjavascript.com // 27/5/2003 - Ajout compatibilité IE5 sur MacOS // 5/6/2003 - Ajout compatibilité Mozilla // 5/9/2005 - Correction d'un bug (clic sur la bordure de la palette principale) // 6/9/2005 - Ajout de la possibilité de sélectionner une couleur en déplaçant la souris // sur les palettes (bouton gauche enfoncé) /***************************************************************** * Script Color Picker écrit par Frosty (Maxime Pacary) - Mai 2003 ******************************************************************/ // var. globale var detail = 50; // nombre de nuances de couleurs dans la barre de droite // ne pas modifier var strhex = "0123456789ABCDEF"; var i; var is_mouse_down = false; var is_mouse_over = false; // conversion decimal (0-255) => hexa function dechex(n) { return strhex.charAt(Math.floor(n/16)) + strhex.charAt(n%16); } // détection d'un clic/mouvement souris sur la "palette" (à gauche) function compute_color(e) { x = e.offsetX ? e.offsetX : (e.target ? e.clientX-e.target.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY-e.target.y : 0); // calcul de la couleur à partir des coordonnées du clic var part_width = document.all ? document.all.color_picker.width/6 : document.getElementById('color_picker').width/6; var im_height = document.all ? document.all.color_picker.height : document.getElementById('color_picker').height; var red = (x >= 0)*(x < part_width)*255 + (x >= part_width)*(x < 2*part_width)*(2*255 - x * 255 / part_width) + (x >= 4*part_width)*(x < 5*part_width)*(-4*255 + x * 255 / part_width) + (x >= 5*part_width)*(x < 6*part_width)*255; var blue = (x >= 2*part_width)*(x < 3*part_width)*(-2*255 + x * 255 / part_width) + (x >= 3*part_width)*(x < 5*part_width)*255 + (x >= 5*part_width)*(x < 6*part_width)*(6*255 - x * 255 / part_width); var green = (x >= 0)*(x < part_width)*(x * 255 / part_width) + (x >= part_width)*(x < 3*part_width)*255 + (x >= 3*part_width)*(x < 4*part_width)*(4*255 - x * 255 / part_width); var coef = (im_height-y)/im_height; // composantes de la couleur choisie sur la "palette" red = 128+(red-128)*coef; green = 128+(green-128)*coef; blue = 128+(blue-128)*coef; // mise à jour de la couleur finale changeFinalColor('#' + dechex(red) + dechex(green) + dechex(blue)); // mise à jour de la barre de droite en fonction de cette couleur UpdateGradBarColor(red, green, blue); } // pour afficher la couleur finale choisie function changeFinalColor(color) { document.forms['colpick_form'].elements['btn_choose_color'].style.backgroundColor = color; document.forms['colpick_form'].elements['btn_choose_color'].style.borderColor = color; } function UpdateGradBarColor(red, green, blue) { if (red == null) red=00; if (green == null) green=00; if (blue == null) blue=00; var part_detail = detail/2; for(i = 0; i < detail; i++) { if ((i >= 0) && (i < part_detail)) { var final_coef = i/part_detail ; var final_red = dechex(255 - (255 - red) * final_coef); var final_green = dechex(255 - (255 - green) * final_coef); var final_blue = dechex(255 - (255 - blue) * final_coef); } else { var final_coef = 2 - i/part_detail ; var final_red = dechex(red * final_coef); var final_green = dechex(green * final_coef); var final_blue = dechex(blue * final_coef); } color = final_red + final_green + final_blue ; document.all ? document.all('gs'+i).style.backgroundColor = '#'+color : document.getElementById('gs'+i).style.backgroundColor = '#'+color; } } // "renvoyer" la couleur en cliquant sur OK function send_color() { if (window.opener) { var new_color = document.forms['colpick_form'].elements['btn_choose_color'].style.backgroundColor; exp_rgb = new RegExp("rgb","g"); if (exp_rgb.test(new_color)) { exp_extract = new RegExp("[0-9]+","g"); var tab_rgb = new_color.match(exp_extract); new_color = '#'+dechex(parseInt(tab_rgb[0]))+dechex(parseInt(tab_rgb[1]))+dechex(parseInt(tab_rgb[2])); } window.opener.document.forms['Form'].elements['<?php echo $name1; ?>'].value = new_color; window.opener.document.forms['Form'].elements['<?php echo $name2; ?>'].style.borderColor = new_color; window.opener.document.forms['Form'].elements['<?php echo $name2; ?>'].style.backgroundColor = new_color; window.opener.focus(); window.close(); } } window.focus(); </script> </head> <body> <form name="colpick_form" action="#" method="post"> <h2><?php echo $title; ?></h2> <h3><?php echo $name; ?></h3> <table border="0" cellspacing="0" cellpadding="0" align="center"> <tr> <td> <table border="1" cellspacing="0" cellpadding="0" class="table_black_border"> <tr> <td style="padding:0px; border-width:0px; border-style:none;"> <img id="color_picker" src="colpick.jpg" onclick="compute_color(event)" onmousedown="is_mouse_down = true; return false;" onmouseup="is_mouse_down = false;" onmousemove="if (is_mouse_down && is_mouse_over) compute_color(event); return false;" onmouseover="is_mouse_over = true;" onmouseout="is_mouse_over = false;" style="cursor:crosshair;" /></td> </td> </tr> </table> </td> <td style="background-color:#ffffff; width:20px; height:2px; padding:0px;"></td> <td> <table border="1" cellspacing="0" cellpadding="0" class="table_black_border" style="cursor:crosshair"> <script type="text/javascript"> for(i = 0; i < detail; i++) { document.write('<tr><td id="gs'+i+'" style="background-color:#000000; width:20px; height:3px; border-style:none; border-width:0px;"' + ' onclick="changeFinalColor(this.style.backgroundColor)"' + ' onmousedown="is_mouse_down = true; return false;"' + ' onmouseup="is_mouse_down = false;"' + ' onmousemove="if (is_mouse_down && is_mouse_over) changeFinalColor(this.style.backgroundColor); return false;"' + ' onmouseover="is_mouse_over = true;"' + ' onmouseout="is_mouse_over = false;"' + '></td></tr>'); } </script> </table> </td> </tr> </table> <br /> <table align="center"> <tr valign="center"> <td><input type="button" name="btn_choose_color" value="&nbsp;" style="background-color:#000000; border-color:#000000; width:100px; height:35px;"></td> <td><input type="button" name="btn_ok" value="Ok" style="width:70px" onclick="send_color();"></td> </tr> </table> </form> </body> <script type="text/javascript"> changeFinalColor('#<?php echo $hcolor; ?>'); UpdateGradBarColor('<?php echo hexdec(substr($hcolor, 0, 2)); ?>','<?php echo hexdec(substr($hcolor, 2, 2)); ?>','<?php echo hexdec(substr($hcolor, 4, 2)); ?>'); </script> </html>
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false