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/lib/Centreon/Object/Relation/Service/Group/Host/Group/Service.php | centreon/lib/Centreon/Object/Relation/Service/Group/Host/Group/Service.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once 'Centreon/Object/Relation/Relation.php';
class Centreon_Object_Relation_Service_Group_Host_Group_Service extends Centreon_Object_Relation
{
protected $relationTable = 'servicegroup_relation';
protected $firstKey = 'servicegroup_sg_id';
protected $secondKey = 'service_service_id';
/**
* This call will directly throw an exception
*
* @param string $name
* @param array $arg
* @throws Exception
*/
public function __call($name, $arg = [])
{
throw new Exception('Unknown method');
}
/**
* Used for inserting relation into database
* @param int $fkey
* @param null $key
*/
public function insert($fkey, $key = null): void
{
$hgId = $key['hostId'];
$serviceId = $key['serviceId'];
$sql = "INSERT INTO {$this->relationTable} ({$this->firstKey}, hostgroup_hg_id, {$this->secondKey}) VALUES (?, ?, ?)";
$this->db->query($sql, [$fkey, $hgId, $serviceId]);
}
/**
* Used for deleting relation from database
*
* @param int $fkey
* @param int $hgId
* @param int $serviceId
* @return void
*/
public function delete($fkey, $hgId = null, $serviceId = null): void
{
if (isset($fkey, $hgId, $serviceId)) {
$sql = "DELETE FROM {$this->relationTable} WHERE {$this->firstKey} = ? AND hostgroup_hg_id = ? AND {$this->secondKey} = ?";
$args = [$fkey, $hgId, $serviceId];
} elseif (isset($hgId, $serviceId)) {
$sql = "DELETE FROM {$this->relationTable} WHERE hostgroup_hg_id = ? AND {$this->secondKey} = ?";
$args = [$hgId, $serviceId];
} else {
$sql = "DELETE FROM {$this->relationTable} WHERE {$this->firstKey} = ?";
$args = [$fkey];
}
$this->db->query($sql, $args);
}
/**
* Get service group id from host id, service id
*
* @param int $hgId
* @param int $serviceId
* @return array
*/
public function getServicegroupIdFromHostIdServiceId($hgId, $serviceId)
{
$sql = "SELECT {$this->firstKey} FROM {$this->relationTable} WHERE hostgroup_hg_id = ? AND {$this->secondKey} = ?";
$result = $this->getResult($sql, [$hgId, $serviceId]);
$tab = [];
foreach ($result as $rez) {
$tab[] = $rez[$this->firstKey];
}
return $tab;
}
/**
* Get Host id service id from service group id
*
* @param int $servicegroupId
* @return array multidimentional array with hostgroup_id and service_id indexes
*/
public function getHostGroupIdServiceIdFromServicegroupId($servicegroupId)
{
$sql = "SELECT hostgroup_hg_id, {$this->secondKey} FROM {$this->relationTable} WHERE {$this->firstKey} = ?";
$result = $this->getResult($sql, [$servicegroupId]);
$tab = [];
$i = 0;
foreach ($result as $rez) {
$tab[$i]['hostgroup_id'] = $rez['hostgroup_hg_id'];
$tab[$i]['service_id'] = $rez[$this->secondKey];
$i++;
}
return $tab;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Engine/Engine_Broker_Module.php | centreon/lib/Centreon/Object/Engine/Engine_Broker_Module.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with Engine Broker Module
*
* @author kevin duret <kduret@centreon.com>
*/
class Centreon_Object_Engine_Broker_Module extends Centreon_Object
{
protected $table = 'cfg_nagios_broker_module';
protected $primaryKey = 'bk_mod_id';
protected $uniqueLabelField = 'bk_mod_id';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Engine/Engine.php | centreon/lib/Centreon/Object/Engine/Engine.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with Engine
*
* @author sylvestre
*/
class Centreon_Object_Engine extends Centreon_Object
{
protected $table = 'cfg_nagios';
protected $primaryKey = 'nagios_id';
protected $uniqueLabelField = 'nagios_name';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Media/Media.php | centreon/lib/Centreon/Object/Media/Media.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with media
*
* @author Mathieu Parent
*/
class Centreon_Object_Media extends Centreon_Object
{
protected $table = 'view_img';
protected $primaryKey = 'img_id';
protected $uniqueLabelField = 'img_path';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Extended.php | centreon/lib/Centreon/Object/Service/Extended.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with Service extended information
*
* @author sylvestre
*/
class Centreon_Object_Service_Extended extends Centreon_Object
{
protected $table = 'extended_service_information';
protected $primaryKey = 'service_service_id';
protected $uniqueLabelField = 'service_service_id';
/**
* Used for inserting object into database
*
* @param array $params
* @return int
*/
public function insert($params = [])
{
$sql = "INSERT INTO {$this->table} ";
$sqlFields = '';
$sqlValues = '';
$sqlParams = [];
foreach ($params as $key => $value) {
if ($sqlFields != '') {
$sqlFields .= ',';
}
if ($sqlValues != '') {
$sqlValues .= ',';
}
$sqlFields .= $key;
$sqlValues .= '?';
$sqlParams[] = $value;
}
if ($sqlFields && $sqlValues) {
$sql .= '(' . $sqlFields . ') VALUES (' . $sqlValues . ')';
$this->db->query($sql, $sqlParams);
return $this->db->lastInsertId();
}
return null;
}
/**
* Get object parameters
*
* @param int $objectId
* @param mixed $parameterNames
* @return array
*/
public function getParameters($objectId, $parameterNames)
{
$params = parent::getParameters($objectId, $parameterNames);
$params_image = ['esi_icon_image'];
if (! is_array($params)) {
return [];
}
foreach ($params_image as $image) {
if (array_key_exists($image, $params)) {
$sql = 'SELECT dir_name, img_path
FROM view_img vi
LEFT JOIN view_img_dir_relation vidr ON vi.img_id = vidr.img_img_id
LEFT JOIN view_img_dir vid ON vid.dir_id = vidr.dir_dir_parent_id
WHERE img_id = ?';
$res = $this->getResult($sql, [$params[$image]], 'fetch');
if (is_array($res)) {
$params[$image] = $res['dir_name'] . '/' . $res['img_path'];
}
}
}
return $params;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Category.php | centreon/lib/Centreon/Object/Service/Category.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with service categories
*
* @author sylvestre
*/
class Centreon_Object_Service_Category extends Centreon_Object
{
protected $table = 'service_categories';
protected $primaryKey = 'sc_id';
protected $uniqueLabelField = 'sc_name';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Template.php | centreon/lib/Centreon/Object/Service/Template.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with hosts
*
* @author Toufik MECHOUET
*/
class Centreon_Object_Service_Template extends Centreon_Object
{
protected $table = 'service';
protected $primaryKey = 'service_id';
protected $uniqueLabelField = 'service_description';
/**
* Generic method that allows to retrieve object ids
* from another object parameter
*
* @param string $paramName
* @param array $paramValues
* @return array
*/
public function getIdByParameter($paramName, $paramValues = [])
{
$sql = "SELECT {$this->primaryKey} FROM {$this->table} WHERE ";
$condition = '';
if (! is_array($paramValues)) {
$paramValues = [$paramValues];
}
foreach ($paramValues as $val) {
if ($condition != '') {
$condition .= ' OR ';
}
$condition .= $paramName . ' = ? ';
}
if ($condition) {
$sql .= $condition;
$sql .= ' AND ' . $this->table . ".service_register = '0' ";
$rows = $this->getResult($sql, $paramValues, 'fetchAll');
$tab = [];
foreach ($rows as $val) {
$tab[] = $val[$this->primaryKey];
}
return $tab;
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Service.php | centreon/lib/Centreon/Object/Service/Service.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once 'Centreon/Object/Object.php';
/**
* Used for interacting with services
*
* @author sylvestre
*/
class Centreon_Object_Service extends Centreon_Object
{
protected $table = 'service';
protected $primaryKey = 'service_id';
protected $uniqueLabelField = 'service_description';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Group.php | centreon/lib/Centreon/Object/Service/Group.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with servicegroups
*
* @author sylvestre
*/
class Centreon_Object_Service_Group extends Centreon_Object
{
protected $table = 'servicegroup';
protected $primaryKey = 'sg_id';
protected $uniqueLabelField = 'sg_name';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Service/Macro/Custom.php | centreon/lib/Centreon/Object/Service/Macro/Custom.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Used for interacting with service custom macros
*
* @author sylvestre
*/
class Centreon_Object_Service_Macro_Custom extends Centreon_Object
{
protected $table = 'on_demand_macro_service';
protected $primaryKey = 'svc_macro_id';
protected $uniqueLabelField = 'svc_macro_name';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/lib/Centreon/Object/Command/Command.php | centreon/lib/Centreon/Object/Command/Command.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/Object/Object.php';
/**
* Class
*
* @class Centreon_Object_Command
*/
class Centreon_Object_Command extends Centreon_Object
{
/** @var string */
protected $table = 'command';
/** @var string */
protected $primaryKey = 'command_id';
/** @var string */
protected $uniqueLabelField = 'command_name';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/preload.php | centreon/config.new/preload.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
if (file_exists(dirname(__DIR__) . '/var/cache/prod/App_Shared_Infrastructure_Symfony_KernelProdContainer.preload.php')) {
require_once dirname(__DIR__) . '/var/cache/prod/App_Shared_Infrastructure_Symfony_KernelProdContainer.preload.php';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/bundles.php | centreon/config.new/bundles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
return [
ApiPlatform\Symfony\Bundle\ApiPlatformBundle::class => ['all' => true],
DAMA\DoctrineTestBundle\DAMADoctrineTestBundle::class => ['test' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/bootstrap.php | centreon/config.new/bootstrap.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
use Symfony\Component\Dotenv\Dotenv;
(new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');
$constants = [];
$conf_centreon = [];
require_once dirname(__DIR__) . '/config/centreon.config.php';
require_once dirname(__DIR__) . '/container.php';
(new Dotenv())->populate($constants);
(new Dotenv())->populate($conf_centreon);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/services/shared.php | centreon/config.new/services/shared.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->defaults()
->autowire()
->autoconfigure();
$services->load('App\\Shared\\', __DIR__ . '/../../src/App/Shared')
->exclude([__DIR__ . '/../../src/App/Shared/Infrastructure/Symfony/Kernel.php']);
};
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/services/activity_logging.php | centreon/config.new/services/activity_logging.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->defaults()
->autowire()
->autoconfigure();
$services->load('App\\ActivityLogging\\', __DIR__ . '/../../src/App/ActivityLogging');
};
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config.new/services/monitoring_configuration.php | centreon/config.new/services/monitoring_configuration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->defaults()
->autowire()
->autoconfigure();
$services->load('App\\MonitoringConfiguration\\', __DIR__ . '/../../src/App/MonitoringConfiguration');
};
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config/centreon-statistics.config.php | centreon/config/centreon-statistics.config.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Url where the stats are sent.
const CENTREON_STATS_URL = 'https://statistics.centreon.com';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config/bundles.php | centreon/config/bundles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
FOS\RestBundle\FOSRestBundle::class => ['all' => true],
JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/config/bootstrap.php | centreon/config/bootstrap.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__) . '/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
(new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] ??= $_ENV['APP_DEBUG'] ?? $_SERVER['APP_ENV'] !== 'prod';
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG']
= (int) $_SERVER['APP_DEBUG']
|| filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
if (! isset($GLOBALS['constants']) && ! isset($GLOBALS['conf_centreon'])) {
$constants = [];
$conf_centreon = [];
include_once dirname(__DIR__) . '/config/centreon.config.php';
(new Dotenv())->populate($constants);
(new Dotenv())->populate($conf_centreon);
} else {
(new Dotenv())->populate($GLOBALS['constants']);
(new Dotenv())->populate($GLOBALS['conf_centreon']);
}
include_once dirname(__DIR__) . '/container.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/libinstall/check_pear.php | centreon/libinstall/check_pear.php | #!@PHP_BIN@
<?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Error Level
error_reporting(E_ERROR | E_PARSE);
function usage()
{
echo $argv[0] . " check|install [file]\n";
echo "\tcheck\tcheck if the package list is installed\n";
echo "\tupgrade\tupgrade the packages\n";
echo "\tinstall\tinstall the packages\n";
}
function check_file($file)
{
if (! file_exists($file)) {
fwrite(STDERR, "The file with the list of packages does not exist\n");
exit(2);
}
if (! is_readable($file)) {
fwrite(STDERR, "The file with the list of packages cannot be read\n");
exit(2);
}
}
function get_list($file)
{
$packages = [];
$fd = fopen($file, 'r');
while ($line = fgets($fd)) {
[$name, $version, $status] = preg_split('/::/', trim($line));
$package = ['name' => $name, 'version' => $version];
if ($status) {
$package['status'] = $status;
}
$packages[] = $package;
}
fclose($fd);
return $packages;
}
function check($packages)
{
$config = & PEAR_Config::singleton();
$reg = & $config->getRegistry();
$ret = 0;
foreach ($packages as $package) {
// echo "\033[s\033[1;37m" . $package['name'] . "\033[0m\033[33G\033[0;37m" . $package['version'] . "\033[0m\033[45G";
echo "\033[s" . $package['name'] . "\033[0m\033[33G" . $package['version'] . "\033[0m\033[45G";
$package_info = & $reg->getPackage($package['name']);
if (is_null($package_info)) {
$ret = 1;
echo "\033[u\033[60G\033[1;31mNOK\033[0m\n";
} else {
$version = $package_info->getVersion();
echo $version;
if (version_compare($package['version'], $version, '<=')) {
echo "\033[u\033[60G\033[1;32mOK\033[0m\n";
} else {
$ret = 1;
echo "\033[u\033[60G\033[1;31mNOK\033[0m\n";
}
}
}
return $ret;
}
function install($packages)
{
$config = & PEAR_Config::singleton();
$reg = & $config->getRegistry();
PEAR_Command::setFrontendType('CLI');
$cmd = PEAR_Command::factory('install', $config);
$ret = 0;
foreach ($packages as $package) {
if (! $reg->packageExists($package['name'])) {
echo "\033[s" . $package['name'] . "\033[0m\033[33G" . $package['version'] . "\033[0m\033[45G";
$name = $package['name'];
if (isset($package['status'])) {
$name .= '-' . $package['status'];
}
ob_start();
$ok = $cmd->run('install', ['soft' => true, 'onlyreqdeps' => true], [$name]);
ob_end_clean();
$package_info = & $reg->getPackage($package['name']);
if (! is_null($package_info)) {
echo $package_info->getVersion();
echo "\033[u\033[60G\033[1;32mOK\033[0m\n";
} else {
$ret = 1;
echo "\033[u\033[60G\033[1;31mNOK\033[0m\n";
}
}
}
return $ret;
}
function upgrade($packages)
{
$config = & PEAR_Config::singleton();
$reg = & $config->getRegistry();
PEAR_Command::setFrontendType('CLI');
$cmd = PEAR_Command::factory('install', $config);
$ret = 0;
foreach ($packages as $package) {
$package_info = & $reg->getPackage($package['name']);
if (is_null($package_info)) {
continue;
}
if ($package['name'] == 'PEAR') {
ob_start();
$ok = $cmd->run('install', ['soft' => true, 'nodeps' => true, 'force' => true], [$package['name']]);
ob_end_clean();
}
$installed_version = $package_info->getVersion();
if (version_compare($package['version'], $installed_version, '>')) {
echo "\033[s" . $package['name'] . "\033[0m\033[33G" . $package['version'] . "\033[0m\033[45G" . $installed_version . "\t";
$name = $package['name'];
if (isset($package['status'])) {
$name .= '-' . $package['status'];
}
ob_start();
$ok = $cmd->run('install', ['soft' => true, 'onlyreqdeps' => true, 'upgrade' => true], [$name]);
ob_end_clean();
$package_info = & $reg->getPackage($package['name']);
if (! is_null($package_info)) {
echo $package_info->getVersion();
echo "\033[u\033[60G\033[1;32mOK\033[0m\n";
} else {
$ret = 1;
echo "\033[u\033[60G\033[1;31mNOK\033[0m\n";
}
}
}
}
if (count($argv) < 2 || count($argv) > 3) {
fwrite(STDERR, "Incorrect number of arguments\n");
usage();
exit(2);
}
$file = count($argv) == 3 ? $argv[2] : 'pear.lst';
check_file($file);
$packages = get_list($file);
require_once 'PEAR.php';
require_once 'PEAR/Config.php';
require_once 'PEAR/Command.php';
$ret = 0;
switch ($argv[1]) {
case 'check':
$ret = check($packages);
break;
case 'install':
$ret = install($packages);
break;
case 'upgrade':
$ret = upgrade($packages);
break;
default:
fwrite(STDERR, "Incorrect argument\n");
usage();
exit(2);
}
exit($ret);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/libinstall/clean_session.php | centreon/libinstall/clean_session.php | #!@PHP_BIN@
<?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Error Level
error_reporting(E_ERROR | E_PARSE);
function usage($command)
{
echo $command . " centreon_etc_path\n";
echo "\tcentreon_etc_path\tThe path to Centreon configuration default (/etc/centreon)\n";
}
if (count($argv) != 2) {
fwrite(STDERR, "Incorrect number of arguments\n");
usage($argv[0]);
exit(1);
}
$centreon_etc = realpath($argv[1]);
if (! file_exists($centreon_etc . '/centreon.conf.php')) {
fwrite(STDERR, "Centreon configuration file doesn't exists\n");
usage($argv[0]);
exit(1);
}
require_once $centreon_etc . '/centreon.conf.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
$dbconn = new CentreonDB();
try {
$queryCleanSession = 'DELETE FROM session';
} catch (PDOException $e) {
fwrite(STDERR, "Error in purge sessions\n");
exit(1);
}
exit(0);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/main.php | centreon/www/main.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
use CentreonLegacy\Core\Menu\Menu;
// Set logging options
if (defined('E_DEPRECATED')) {
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
} else {
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT);
}
// Purge Values
foreach ($_GET as $key => $value) {
if (! is_array($value)) {
$_GET[$key] = HtmlAnalyzer::sanitizeAndRemoveTags($value);
}
}
$inputGet = [
'p' => filter_input(INPUT_GET, 'p', FILTER_SANITIZE_NUMBER_INT),
'num' => filter_input(INPUT_GET, 'num', FILTER_SANITIZE_NUMBER_INT),
'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o'] ?? ''),
'min' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['min'] ?? ''),
'type' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['type'] ?? ''),
'search' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search'] ?? ''),
'limit' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['limit'] ?? ''),
];
$inputPost = [
'p' => filter_input(INPUT_POST, 'p', FILTER_SANITIZE_NUMBER_INT),
'num' => filter_input(INPUT_POST, 'num', FILTER_SANITIZE_NUMBER_INT),
'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['o'] ?? ''),
'min' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['min'] ?? ''),
'type' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['type'] ?? ''),
'search' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['search'] ?? ''),
'limit' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['limit'] ?? ''),
];
$inputs = [];
foreach ($inputGet as $argumentName => $argumentValue) {
if (! empty($inputGet[$argumentName]) && trim($inputGet[$argumentName]) != '') {
$inputs[$argumentName] = $inputGet[$argumentName];
} elseif (! empty($inputPost[$argumentName]) && trim($inputPost[$argumentName]) != '') {
$inputs[$argumentName] = $inputPost[$argumentName];
} else {
$inputs[$argumentName] = null;
}
}
$p = $inputs['p'];
$o = $inputs['o'];
$min = $inputs['min'];
$type = $inputs['type'];
$search = $inputs['search'];
$limit = $inputs['limit'];
$num = $inputs['num'];
// Include all func
include_once './include/common/common-Func.php';
include_once './include/core/header/header.php';
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$isMobile = str_contains($userAgent, 'Mobil');
if ($isMobile) {
$db = $dependencyInjector['configuration_db'];
$menu = new Menu($db, $_SESSION['centreon']->user);
$treeMenu = $menu->getMenu();
require_once 'main.get.php';
} else {
include './index.html';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/main.get.php | centreon/www/main.get.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
// Set logging options
if (defined('E_DEPRECATED')) {
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
} else {
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT);
}
// Purge Values
foreach ($_GET as $key => $value) {
if (! is_array($value)) {
$_GET[$key] = HtmlAnalyzer::sanitizeAndRemoveTags($value);
}
}
$inputGet = [
'p' => filter_input(INPUT_GET, 'p', FILTER_SANITIZE_NUMBER_INT),
'num' => filter_input(INPUT_GET, 'num', FILTER_SANITIZE_NUMBER_INT),
'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o'] ?? ''),
'min' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['min'] ?? ''),
'type' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['type'] ?? ''),
'search' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search'] ?? ''),
'limit' => HtmlAnalyzer::sanitizeAndRemoveTags($_GET['limit'] ?? ''),
];
$inputPost = [
'p' => filter_input(INPUT_POST, 'p', FILTER_SANITIZE_NUMBER_INT),
'num' => filter_input(INPUT_POST, 'num', FILTER_SANITIZE_NUMBER_INT),
'o' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['o'] ?? ''),
'min' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['min'] ?? ''),
'type' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['type'] ?? ''),
'search' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['search'] ?? ''),
'limit' => HtmlAnalyzer::sanitizeAndRemoveTags($_POST['limit'] ?? ''),
];
$inputs = [];
foreach ($inputGet as $argumentName => $argumentValue) {
if (! empty($inputGet[$argumentName]) && trim($inputGet[$argumentName]) !== '') {
$inputs[$argumentName] = $inputGet[$argumentName];
} elseif (! empty($inputPost[$argumentName]) && trim($inputPost[$argumentName]) !== '') {
$inputs[$argumentName] = $inputPost[$argumentName];
} else {
$inputs[$argumentName] = null;
}
}
if (empty($p)) {
$p = $inputs['p'];
}
$o = $inputs['o'];
$min = $inputs['min'];
$type = $inputs['type'];
$search = $inputs['search'];
$limit = $inputs['limit'];
$num = $inputs['num'];
// Include all func
include_once './include/common/common-Func.php';
include_once './include/core/header/header.php';
$centreon->user->setCurrentPage($p);
// LCA Init Common Var
global $is_admin;
$is_admin = $centreon->user->admin;
/**
* @param int $page
*
* @return array{
* topology_id: int,
* topology_parent: int|null,
* topology_page: int|null,
* topology_name: string,
* topology_url: string|null,
* topology_url_substitute: string|null,
* }
*/
$loadTopology = function (int $page): mixed {
global $pearDB;
$query = <<<'SQL'
SELECT topology_parent, topology_name, topology_id, topology_url, topology_page, topology_url_substitute
FROM topology
WHERE topology_page = :page
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':page', $page, PDO::PARAM_INT);
$statement->execute();
return $statement->fetch(PDO::FETCH_ASSOC);
};
$getTopologyUrl = function (mixed $data): ?string {
if (! is_array($data)) {
return null;
}
return $data['topology_url_substitute'] ?? $data['topology_url'];
};
$redirect = $loadTopology((int) $p);
/**
* Is server a remote ?
*/
global $isRemote;
$isRemote = false;
$result = $pearDB->query("SELECT `value` FROM `informations` WHERE `key` = 'isRemote'");
if ($row = $result->fetch()) {
$isRemote = $row['value'] === 'yes';
}
// Disable the page if not enabled.
if (! is_enabled_feature_flag($redirect['topology_feature_flag'] ?? null)) {
$redirect = false;
}
// Init URL
$url = '';
$acl_page = $centreon->user->access->page($p, true);
if (
$redirect !== false
&& ($acl_page == CentreonACL::ACL_ACCESS_READ_WRITE || $acl_page == CentreonACL::ACL_ACCESS_READ_ONLY)
) {
if ($redirect['topology_page'] < 100) {
$ret = get_child($redirect['topology_page'], $centreon->user->access->topologyStr);
if ($ret === false || ! $ret['topology_page']) {
if (($url = $getTopologyUrl($redirect)) && file_exists($url)) {
reset_search_page($url);
} else {
$url = './include/core/errors/alt_error.php';
}
} else {
$ret2 = get_child($ret['topology_page'], $centreon->user->access->topologyStr);
if ($ret2 === false || $ret2['topology_url_opt']) {
if (! $o) {
$tab = preg_split("/\=/", $ret2['topology_url_opt']);
$o = $tab[1];
}
$p = $ret2['topology_page'];
}
if (($url = $getTopologyUrl($ret2)) && file_exists($url)) {
reset_search_page($url);
if ($ret2['topology_url_opt']) {
$tab = preg_split("/\=/", $ret2['topology_url_opt']);
$o = $tab[1];
}
} elseif ($url = $getTopologyUrl($ret)) {
if ($ret['is_react'] === '1') {
// workaround to update react page without refreshing whole page
echo '<script>'
. 'window.top.history.pushState("", "", ".' . $url . '");'
. 'window.top.history.pushState("", "", ".' . $url . '");'
. 'window.top.history.go(-1);'
. '</script>';
exit();
}
} else {
$url = './include/core/errors/alt_error.php';
}
}
} elseif ($redirect['topology_page'] >= 100 && $redirect['topology_page'] < 1000) {
$ret = get_child($redirect['topology_page'], $centreon->user->access->topologyStr);
if ($ret === false || ! $ret['topology_page']) {
if (($url = $getTopologyUrl($redirect)) && file_exists($url)) {
reset_search_page($url);
} else {
$url = './include/core/errors/alt_error.php';
}
} else {
if ($ret['topology_url_opt']) {
if (! $o) {
$tab = preg_split("/\=/", $ret['topology_url_opt']);
$o = $tab[1];
}
$p = $ret['topology_page'];
}
$url = $getTopologyUrl($ret);
if ($url && file_exists($url)) {
reset_search_page($url);
} else {
$url = './include/core/errors/alt_error.php';
}
}
} elseif ($redirect['topology_page'] >= 1000) {
$ret = get_child($redirect['topology_page'], $centreon->user->access->topologyStr);
$url = $getTopologyUrl($redirect);
if ($ret === false || ! $ret['topology_page']) {
if ($url && file_exists($url)) {
reset_search_page($url);
} else {
$url = './include/core/errors/alt_error.php';
}
} elseif ($url && file_exists($url) && $ret['topology_page']) {
reset_search_page($url);
} else {
$url = './include/core/errors/alt_error.php';
}
}
if (isset($o) && $acl_page == CentreonACL::ACL_ACCESS_READ_ONLY) {
if ($o == 'c') {
$o = 'w';
} elseif ($o == 'a') {
$url = './include/core/errors/alt_error.php';
}
}
} else {
$url = './include/core/errors/alt_error.php';
}
// Header HTML
include_once './include/core/header/htmlHeader.php';
?>
<div id="centreonMsg" class="react-centreon-message"></div>
<script type='text/javascript'>
//saving the user locale
localStorage.setItem('locale', '<?php echo $centreon->user->get_lang(); ?>');
</script>
<?php
if (! $centreon->user->showDiv('header')) {
?>
<script type="text/javascript">
new Effect.toggle('header', 'appear', {
duration: 0, afterFinish: function () {
setQuickSearchPosition();
}
});
</script> <?php
}
if (! $centreon->user->showDiv('menu_3')) {
?>
<script type="text/javascript">
new Effect.toggle('menu_3', 'appear', {duration: 0});
</script> <?php
}
if (! $centreon->user->showDiv('menu_2')) {
?>
<script type="text/javascript">
new Effect.toggle('menu_2', 'appear', {duration: 0});
</script> <?php
}
?>
<section class="main section-expand" style="padding-top: 4px;">
<?php
// Display PathWay
if ($min != 1) {
include_once './include/core/pathway/pathway.php';
}
if (isset($url) && $url) {
include_once $url;
}
if (! isset($centreon->historyPage)) {
$centreon->createHistory();
}
// Keep in memory all informations about pagination, keyword for search...
$inputArguments = ['num' => FILTER_SANITIZE_NUMBER_INT, 'limit' => FILTER_SANITIZE_NUMBER_INT];
$inputGet = filter_input_array(
INPUT_GET,
$inputArguments
);
$inputPost = filter_input_array(
INPUT_POST,
$inputArguments
);
if (isset($url) && $url) {
foreach ($inputArguments as $argumentName => $argumentFlag) {
if ($argumentName === 'limit') {
if (! empty($inputGet[$argumentName])) {
$centreon->historyLimit[$url] = $inputGet[$argumentName];
} elseif (! empty($inputPost[$argumentName])) {
$centreon->historyLimit[$url] = $inputPost[$argumentName];
} else {
$centreon->historyLimit[$url] = 30;
}
}
}
}
// Display Footer
if (! $min) {
echo "\t\t\t</td>\t\t</tr>\t</table>\n</div>";
}
?>
</section>
<?php
// Include Footer
include_once './include/core/footer/footerPart.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/index.php | centreon/www/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 __DIR__ . '/../bootstrap.php';
require_once __DIR__ . '/class/centreonSession.class.php';
require_once __DIR__ . '/class/centreonAuth.class.php';
require_once __DIR__ . '/class/centreonLog.class.php';
require_once __DIR__ . '/class/centreonDB.class.php';
const AUTOLOGIN_FIELDS = ['autologin', 'useralias', 'token'];
updateCentreonBaseUri();
include __DIR__ . '/index.html';
CentreonSession::start();
// Already connected
if (isset($_SESSION['centreon'])) {
$pearDB = new CentreonDB();
manageRedirection($_SESSION['centreon'], $pearDB);
return;
}
/*
* Check PHP version
*
* Centreon >= 24.10 doesn't support PHP < 8.2
*
*/
if (version_compare(phpversion(), '8.2') < 0) {
echo "<div class='msg'> PHP version is < 8.2. Please Upgrade PHP</div>";
return;
}
if (isset($_GET['autologin']) && $_GET['autologin']) {
global $pearDB;
$pearDB = new CentreonDB();
$dbResult = $pearDB->query("SELECT `value` FROM `options` WHERE `key` = 'enable_autologin'");
if (($row = $dbResult->fetch()) && $row['value'] !== '1') {
return;
}
// Init log class
$centreonLog = new CentreonUserLog(-1, $pearDB);
// Check first for Autologin or Get Authentication
$autologin = $_GET['autologin'] ?? CentreonAuth::AUTOLOGIN_DISABLE;
$useralias = $_GET['useralias'] ?? null;
$password = $passwordG ?? null;
$token = $_REQUEST['token'] ?? '';
$centreonAuth = new CentreonAuth(
$dependencyInjector,
$useralias,
$password,
$autologin,
$pearDB,
$centreonLog,
CentreonAuth::ENCRYPT_MD5,
$token,
);
if ($centreonAuth->passwdOk == 1) {
$centreon = new Centreon($centreonAuth->userInfos);
// security fix - regenerate the sid after the login to prevent session fixation
session_regenerate_id(true);
$_SESSION['centreon'] = $centreon;
// saving session data in the DB
$query = 'INSERT INTO `session` (`session_id` , `user_id` , `current_page` , `last_reload`, `ip_address`) '
. 'VALUES (?, ?, ?, ?, ?)';
$dbResult = $pearDB->prepare($query);
$pearDB->execute(
$dbResult,
[session_id(), $centreon->user->user_id, '1', time(), $_SERVER['REMOTE_ADDR']]
);
// saving session token in security_token
$expirationSessionDelay = 120;
$delayStatement = $pearDB->prepare("SELECT value FROM options WHERE `key` = 'session_expire'");
$delayStatement->execute();
if (($result = $delayStatement->fetch(PDO::FETCH_ASSOC)) !== false) {
$expirationSessionDelay = $result['value'];
}
$securityTokenStatement = $pearDB->prepare(
'INSERT INTO security_token (`token`, `creation_date`, `expiration_date`) '
. 'VALUES (:token, :createdAt, :expireAt)'
);
$securityTokenStatement->bindValue(':token', session_id(), PDO::PARAM_STR);
$securityTokenStatement->bindValue(':createdAt', (new DateTime())->getTimestamp(), PDO::PARAM_INT);
$securityTokenStatement->bindValue(
':expireAt',
(new DateTime())->add(new DateInterval('PT' . $expirationSessionDelay . 'M'))->getTimestamp(),
PDO::PARAM_INT
);
$securityTokenStatement->execute();
// saving session in security_authentication_tokens
$providerTokenId = (int) $pearDB->lastInsertId();
$configurationStatement = $pearDB->query("SELECT id from provider_configuration WHERE name='local'");
if (($result = $configurationStatement->fetch(PDO::FETCH_ASSOC)) !== false) {
$configurationId = (int) $result['id'];
} else {
throw new Exception('No local provider found');
}
$securityAuthenticationTokenStatement = $pearDB->prepare(
'INSERT INTO security_authentication_tokens '
. '(`token`, `provider_token_id`, `provider_configuration_id`, `user_id`) VALUES '
. '(:token, :providerTokenId, :providerConfigurationId, :userId)'
);
$securityAuthenticationTokenStatement->bindValue(':token', session_id(), PDO::PARAM_STR);
$securityAuthenticationTokenStatement->bindValue(':providerTokenId', $providerTokenId, PDO::PARAM_INT);
$securityAuthenticationTokenStatement->bindValue(
':providerConfigurationId',
$configurationId,
PDO::PARAM_INT
);
$securityAuthenticationTokenStatement->bindValue(':userId', $centreon->user->user_id, PDO::PARAM_INT);
$securityAuthenticationTokenStatement->execute();
manageRedirection($centreon, $pearDB);
return;
}
}
/**
* Update centreon base uri in index.html
*/
function updateCentreonBaseUri(): void
{
$requestUri = htmlspecialchars($_SERVER['REQUEST_URI']) ?: '/centreon/';
// Regular expression pattern to match the string between slashes
$pattern = "/\/([^\/]+)\//";
preg_match($pattern, $requestUri, $matches);
$basePath = isset($matches[0]) && $matches[0] !== '' ? str_replace('//', '/', $matches[0]) : '/centreon/';
$indexHtmlPath = './index.html';
$indexHtmlContent = file_get_contents($indexHtmlPath);
// update base path only if it has changed
if (! preg_match('/.*<base\shref="' . preg_quote($basePath, '/') . '">/', $indexHtmlContent)) {
$indexHtmlContent = preg_replace(
'/(^.*<base\shref=")\S+(">.*$)/s',
'${1}' . $basePath . '${2}',
$indexHtmlContent
);
file_put_contents($indexHtmlPath, $indexHtmlContent, LOCK_EX);
}
}
/**
* Redirect to user default page
*
* @param Centreon $centreon
* @param CentreonDB $pearDB
*/
function manageRedirection(Centreon $centreon, CentreonDB $pearDB): void
{
$headerRedirection = './main.php';
$argP = filter_var(
$_POST['p'] ?? $_GET['p'] ?? null,
FILTER_VALIDATE_INT
);
if ($argP !== false) {
$headerRedirection .= '?p=' . $argP;
foreach ($_GET as $parameter => $value) {
if (! in_array($parameter, AUTOLOGIN_FIELDS)) {
$sanitizeParameter = htmlspecialchars($parameter);
$sanitizeValue = filter_input(INPUT_GET, $parameter);
if (! empty($sanitizeParameter) && $sanitizeValue !== false) {
$headerRedirection .= '&' . $parameter . '=' . $value;
}
}
}
} elseif (isset($centreon->user->default_page) && $centreon->user->default_page !== '') {
// get more details about the default page
$stmt = $pearDB->prepare(
'SELECT topology_url, is_react FROM topology WHERE topology_page = ? LIMIT 0, 1'
);
$pearDB->execute($stmt, [$centreon->user->default_page]);
if ($stmt->rowCount() && ($topologyData = $stmt->fetch()) && $topologyData['is_react']) {
// redirect to the react path
$headerRedirection = '.' . $topologyData['topology_url'];
} else {
$headerRedirection .= '?p=' . $centreon->user->default_page;
$argMin = $_POST['min'] ?? $_GET['min'] ?? null;
if ($argMin === '1') {
$headerRedirection .= '&min=1';
}
}
}
header('Location: ' . $headerRedirection);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/db/viewDBInfos.php | centreon/www/include/options/db/viewDBInfos.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './class/centreonDB.class.php';
require_once './class/centreon-partition/partEngine.class.php';
require_once './class/centreon-partition/config.class.php';
require_once './class/centreon-partition/mysqlTable.class.php';
require_once './class/centreon-partition/options.class.php';
// Get Properties
$dataCentreon = $pearDB->getProperties();
$dataCentstorage = $pearDBO->getProperties();
// Get partitioning informations
$partEngine = new PartEngine();
$tables = ['data_bin', 'logs', 'log_archive_host', 'log_archive_service'];
$partitioningInfos = [];
foreach ($tables as $table) {
$mysqlTable = new MysqlTable($pearDBO, $table, $conf_centreon['dbcstg']);
$partitioningInfos[$table] = $partEngine->listParts($mysqlTable, $pearDBO, false);
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate('./include/options/db/');
$tpl->assign('conf_centreon', $conf_centreon);
$tpl->assign('dataCentreon', $dataCentreon);
$tpl->assign('dataCentstorage', $dataCentstorage);
$tpl->assign('partitioning', $partitioningInfos);
$tpl->display('viewDBInfos.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/options/session/connected_user.php | centreon/www/include/options/session/connected_user.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
/**
* Kick a logged user
*/
const KICK_USER = 'k';
$path = './include/options/session/';
require_once './include/common/common-Func.php';
require_once './class/centreonMsg.class.php';
$action = HtmlSanitizer::createFromString($_GET['o'] ?? '')
->removeTags()
->sanitize()
->getString();
$selectedUserId = filter_var(
$_GET['user'] ?? null,
FILTER_VALIDATE_INT
);
$currentPage = filter_var(
$_GET['p'] ?? $_POST['p'] ?? 0,
FILTER_VALIDATE_INT
);
if ($selectedUserId) {
$msg = new CentreonMsg();
$msg->setTextStyle('bold');
$msg->setTimeOut('3');
switch ($action) {
// logout action
case KICK_USER:
// check if the user is allowed to kick this user
if ($centreon->user->admin == 0) {
$msg->setText(_('You are not allowed to disconnect this user'));
break;
}
$stmt = $pearDB->prepare('DELETE FROM session WHERE user_id = :userId');
$stmt->bindValue(':userId', $selectedUserId, PDO::PARAM_INT);
$stmt->execute();
$msg->setText(_('User disconnected'));
break;
}
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$session_data = [];
$res = $pearDB->query(
'SELECT session.*, contact_name, contact_admin, contact_auth_type, `contact_ldap_last_sync`
FROM session, contact
WHERE contact_id = user_id ORDER BY contact_name, contact_admin'
);
for ($cpt = 0; $r = $res->fetch(); $cpt++) {
$session_data[$cpt] = [];
$session_data[$cpt]['class'] = $cpt % 2 ? 'list_one' : 'list_two';
$session_data[$cpt]['user_id'] = $r['user_id'];
$session_data[$cpt]['user_alias'] = $r['contact_name'];
$session_data[$cpt]['admin'] = $r['contact_admin'];
$session_data[$cpt]['ip_address'] = $r['ip_address'];
$session_data[$cpt]['last_reload'] = $r['last_reload'];
$session_data[$cpt]['ldapContact'] = $r['contact_auth_type'];
$resCP = $pearDB->prepare(
'SELECT topology_name, topology_page, topology_url_opt FROM topology '
. 'WHERE topology_page = :topologyPage'
);
$resCP->bindValue(':topologyPage', $r['current_page'], PDO::PARAM_INT);
$resCP->execute();
$rCP = $resCP->fetch();
// getting the current users' position in the IHM
$session_data[$cpt]['current_page'] = $r['current_page'] . $rCP['topology_url_opt'];
$session_data[$cpt]['topology_name'] = $rCP['topology_name'] != '' ? _($rCP['topology_name']) : $rCP['topology_name'];
// $centreon->user->admin is a string '1' or '0'
if ($centreon->user->admin == 1) {
// adding the link to be able to kick the user
$session_data[$cpt]['actions']
= "<a href='./main.php?p=" . $p . '&o=k&user=' . $r['user_id'] . "'>"
. "<span title='" . _('Disconnect user') . "'>"
. returnSvg('www/img/icons/delete.svg', 'var(--icons-fill-color)', 22, 22)
. '</span>'
. '</a>';
// checking if the user account is linked to an LDAP
if ($r['contact_auth_type'] === 'ldap') {
// adding the last synchronization time
if ($r['contact_ldap_last_sync'] > 0) {
$session_data[$cpt]['last_sync'] = (int) $r['contact_ldap_last_sync'];
} elseif ($r['contact_ldap_last_sync'] === 0 || $r['contact_ldap_last_sync'] === null) {
$session_data[$cpt]['last_sync'] = '-';
}
$session_data[$cpt]['synchronize']
= "<a href='#'>"
. "<span onclick='submitSync(" . $currentPage . ', "' . $r['user_id'] . "\")'
title='" . _('Synchronize LDAP') . "'>"
. returnSvg('www/img/icons/refresh.svg', 'var(--icons-fill-color)', 18, 18)
. '</span>'
. '</a>';
} else {
// hiding the synchronization option and details
$session_data[$cpt]['last_sync'] = '';
$session_data[$cpt]['synchronize'] = '';
}
// adding the column titles
$tpl->assign('wi_last_sync', _('Last LDAP sync'));
$tpl->assign('wi_syncLdap', _('Refresh LDAP'));
$tpl->assign('wi_logoutUser', _('Logout user'));
}
}
if (isset($msg)) {
$tpl->assign('msg', $msg);
}
$tpl->assign('session_data', $session_data);
$tpl->assign('isAdmin', $centreon->user->admin);
$tpl->assign('wi_user', _('Users'));
$tpl->assign('wi_where', _('Position'));
$tpl->assign('wi_last_req', _('Last request'));
$tpl->assign('distant_location', _('IP Address'));
$tpl->assign('adminIcon', returnSvg('www/img/icons/admin.svg', 'var(--icons-fill-color)', 17, 17));
$tpl->assign('userIcon', returnSvg('www/img/icons/user.svg', 'var(--icons-fill-color)', 17, 17));
$tpl->display('connected_user.ihtml');
?>
<script>
//formatting the tags containing a class isTimestamp
formatDateMoment();
// ask for confirmation when requesting to resynchronize contact data from the LDAP
function submitSync(p, contactId) {
// msg = localized message to be displayed in the confirmation popup
let msg = "<?= _('All this contact sessions will be closed. Are you sure you want to request a '
. 'synchronization at the next login of this Contact ?'); ?>";
// then executing the request and refreshing the page
if (confirm(msg)) {
$.ajax({
url: './api/internal.php?object=centreon_ldap_synchro&action=requestLdapSynchro',
type: 'POST',
async: false,
data: {contactId: contactId},
success: function(data) {
if (data === true) {
window.location.href = "?p=" + p;
}
}
});
}
}
</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/options/media/images/images.php | centreon/www/include/options/media/images/images.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
const IMAGE_ADD = 'a';
const IMAGE_WATCH = 'w';
const IMAGE_MODIFY = 'ci';
const IMAGE_MODIFY_DIRECTORY = 'cd';
const IMAGE_MOVE = 'm';
const IMAGE_DELETE = 'd';
const IMAGE_SYNC_DIR = 'sd';
$imageId = filter_var(
$_GET['img_id'] ?? $_POST['img_id'] ?? null,
FILTER_VALIDATE_INT
);
$directoryId = filter_var(
$_GET['dir_id'] ?? $_POST['dir_id'] ?? null,
FILTER_VALIDATE_INT
);
// Path to the cities dir
$path = './include/options/media/images/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
switch ($o) {
case IMAGE_MODIFY:
case IMAGE_ADD:
require_once $path . 'formImg.php';
break;
case IMAGE_WATCH:
if (is_int($imageId)) {
require_once $path . 'formImg.php';
}
break;
case IMAGE_MOVE:
case IMAGE_MODIFY_DIRECTORY:
require_once $path . 'formDirectory.php';
break;
case IMAGE_DELETE:
// If one data are not correctly typed in array, it will be set to false
$selectIds = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
deleteMultImg($selectIds);
deleteMultDirectory($selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listImg.php';
break;
case IMAGE_SYNC_DIR:
require_once $path . 'syncDir.php';
break;
default:
require_once $path . 'listImg.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/options/media/images/formDirectory.php | centreon/www/include/options/media/images/formDirectory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Directory
//
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
$dir = [];
$list = [];
$selected = [];
$userCanSeeAllFolders = ((int) $centreon->user->admin === 1 || $centreon->user->access->hasAccessToAllImageFolders);
// Change Directory
if ($o == IMAGE_MODIFY_DIRECTORY && $directoryId) {
$directories = $pearDB->fetchAssociative(
<<<'SQL'
SELECT * FROM view_img_dir WHERE dir_id = :directoryId LIMIT 1
SQL,
QueryParameters::create(
[QueryParameter::int('directoryId', $directoryId)]
)
);
$dir = array_map('myDecode', $directories);
// Set Child elements
$childElements = $pearDB->fetchAllAssociative(
<<<'SQL'
SELECT DISTINCT img_img_id FROM view_img_dir_relation WHERE dir_dir_parent_id = :directoryId
SQL,
QueryParameters::create(
[QueryParameter::int('directoryId', $directoryId)]
)
);
foreach ($childElements as $i => $imgs) {
$dir['dir_imgs'][$i] = $imgs['img_img_id'];
}
} elseif ($o == IMAGE_MOVE) {
$selected = [];
if (isset($selectIds) && $selectIds) {
$list = $selectIds;
} elseif (isset($dir_imgs) && $dir_imgs) {
$list = $dir_imgs;
}
foreach ($list as $selector => $status) {
$ids = explode('-', $selector);
if (count($ids) != 2) {
continue;
}
$selected[] = $ids[1];
}
}
//
// # Database retrieve information for differents elements list we need on the page
//
// Images comes from DB -> Store in $imgs Array
try {
$imgs = [];
$queryParameters = [];
$request = <<<'SQL'
SELECT
images.img_id,
CONCAT(directories.dir_alias, '/', images.img_name) AS imagePath
FROM view_img AS images
INNER JOIN view_img_dir_relation vidr
ON vidr.img_img_id = images.img_id
INNER JOIN view_img_dir AS directories
ON directories.dir_id = vidr.dir_dir_parent_id
SQL;
if (! $userCanSeeAllFolders) {
$request .= <<<'SQL'
INNER JOIN acl_resources_image_folder_relations armdr
ON armdr.dir_id = directories.dir_id
INNER JOIN acl_resources ar
ON ar.acl_res_id = armdr.acl_res_id
INNER JOIN acl_res_group_relations argr
ON argr.acl_res_id = ar.acl_res_id
LEFT JOIN acl_group_contacts_relations gcr
ON gcr.acl_group_id = argr.acl_group_id
LEFT JOIN acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = argr.acl_group_id
LEFT JOIN contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND (cgcr.contact_contact_id = :contactId OR gcr.contact_contact_id = :contactId)
SQL;
$queryParameters[] = QueryParameter::int('contactId', $centreon->user->user_id);
}
if ($o == IMAGE_MOVE && $selected !== []) {
[
'parameters' => $bindImageParameters,
'placeholderList' => $bindQuery,
] = createMultipleBindParameters($selected, 'imageId', QueryParameterTypeEnum::INTEGER);
$request .= <<<SQL
WHERE images.img_id IN ({$bindQuery}) AND directories.dir_name NOT IN ('centreon-map', 'ppm', 'dashboards')
SQL;
$queryParameters = array_merge($queryParameters, $bindImageParameters);
}
$request .= ' GROUP BY directories.dir_id, images.img_id ORDER BY directories.dir_alias, images.img_name';
/** @var CentreonDB $pearDB */
$records = $pearDB->iterateAssociative($request, QueryParameters::create($queryParameters));
foreach ($records as $record) {
$imgs[$record['img_id']] = htmlentities($record['imagePath'], ENT_QUOTES, 'utf-8');
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
$exception = new RepositoryException(
message: 'Error while retrieving images from database: ' . $e->getMessage(),
previous: $e
);
ExceptionLogger::create()->log($exception);
throw $exception;
}
try {
$directories = getListDirectory();
} catch (RepositoryException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while retrieving image directories: ' . $e->getMessage(),
exception: $e
);
throw $e;
}
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsSelect = ['size' => '5', 'multiple' => '1', 'cols' => '40', 'required' => 'true'];
$attrsAdvSelect = ['style' => 'width: 250px; height: 250px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == IMAGE_MODIFY_DIRECTORY) {
$form->addElement('header', 'title', _('Modify directory'));
$form->addElement('autocomplete', 'dir_name', _('Directory name'), $directories);
$form->addElement('textarea', 'dir_comment', _('Comments'), $attrsTextarea);
$form->setDefaults($dir);
} elseif ($o == IMAGE_MOVE) {
$form->addElement('header', 'title', _('Move files to directory'));
$userCanSeeAllFolders
? $form->addElement('autocomplete', 'dir_name', _('Destination directory'), $directories)
: $form->addElement('select', 'dir_name', _('Destination Directory'), $directories);
$form->addElement('select', 'dir_imgs', _('Images'), $imgs, $attrsSelect);
}
$tab = [];
$tab[] = $form->createElement('radio', 'action', null, _('List'), '1');
$tab[] = $form->createElement('radio', 'action', null, _('Form'), '0');
$form->addGroup($tab, 'action', _('Action'), ' ');
$form->setDefaults(['action' => '1']);
$form->addElement('hidden', 'dir_id');
$form->addElement('hidden', 'select');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
//
// # Form Rules
//
$form->applyFilter('__ALL__', 'myTrim');
if ($o == IMAGE_MODIFY_DIRECTORY && $directoryId) {
$form->addRule('dir_name', _('Compulsory Name'), 'required');
$form->setRequiredNote(_('Required Field'));
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o == IMAGE_MOVE) {
$subM = $form->addElement('submit', 'submitM', _('Apply'));
$res = $form->addElement(
'button',
'cancel',
_('Cancel'),
['onClick' => "javascript:window.location.href='?p={$p}'"]
);
} elseif ($o == IMAGE_MODIFY_DIRECTORY) {
$confirm = isset($dir['dir_imgs']) ? implode(',', $dir['dir_imgs']) : '';
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement(
'button',
'cancel',
_('Cancel'),
[
'class' => 'btc bt_success',
'onClick' => "javascript:window.location.href='?p={$p}'",
]
);
$form->setDefaults($dir);
}
$valid = false;
if ($form->validate()) {
if ($form->getSubmitValue('submitM')) {
/**
* Move files to new directory
*/
$dir_name = $form->getSubmitValue('dir_name');
$imgs = $form->getSubmitValue('dir_imgs');
moveMultImg($imgs, $dir_name);
$valid = true;
// modify dir
} elseif ($form->getSubmitValue('submitC')
&& ($directoryId = $form->getSubmitValue('dir_id'))
) {
/**
* Update directory name
*/
$dirName = $form->getSubmitValue('dir_name');
$dirCmnt = $form->getSubmitValue('dir_comment');
updateDirectory($directoryId, $dirName, $dirCmnt);
$valid = true;
}
}
if ($valid) {
$o = null;
$form->freeze();
require_once $path . 'listImg.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <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('formDirectory.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/options/media/images/syncDir.php | centreon/www/include/options/media/images/syncDir.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once './class/centreonDB.class.php';
require_once './class/centreonLog.class.php';
$pearDB = new CentreonDB();
$mediaLogInstance = CentreonLog::create();
/**
* Counters
*/
global $regCounter, $gdCounter, $fileRemoved, $dirCreated;
$sid = session_id();
if ($sid === false) {
exit;
}
if (isset($sid)) {
$DBRESULT = $pearDB->query("SELECT * FROM session WHERE session_id = '" . $pearDB->escape($sid) . "'");
if ($DBRESULT->rowCount() === 0) {
exit();
}
}
$dir = './img/media/';
$rejectedDir = ['.' => 1, '..' => 1];
$dirCreated = 0;
$regCounter = 0;
$gdCounter = 0;
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($subdir = readdir($dh)) !== false) {
if (! isset($rejectedDir[$subdir]) && filetype($dir . $subdir) === 'dir') {
try {
$dir_id = checkDirectory($subdir, $pearDB);
} catch (Exception $ex) {
$mediaLogInstance->error(
CentreonLog::TYPE_BUSINESS_LOG,
$ex->getMessage(),
[],
$ex
);
continue;
}
if ($dh2 = opendir($dir . $subdir)) {
while (($picture = readdir($dh2)) !== false) {
if (! isset($rejectedDir[$picture])) {
try {
checkPicture($picture, $dir . $subdir, $dir_id, $pearDB);
} catch (Exception $ex) {
$mediaLogInstance->error(
CentreonLog::TYPE_BUSINESS_LOG,
$ex->getMessage(),
[],
$ex
);
}
}
}
closedir($dh2);
}
}
}
closedir($dh);
}
}
$fileRemoved = deleteOldPictures($pearDB);
// Display Stats
?>
<script type="text/javascript">
jQuery('body').css('overflow-x', 'hidden');
function reloadAndClose() {
window.opener.location.reload();
window.close();
}
</script>
<br>
<?php
echo '<b> ' . _('Media Detection') . '</b>';
?>
<br><br>
<div style="width:250px;height:50px;margin-left:5px;padding:20px;background-color:#FFFFFF;border:1px #CDCDCD solid;-moz-border-radius:4px;">
<div style='float:left;width:270px;text-align:left;'>
<p>
<?php
echo _('Bad picture alias detected :') . " {$fileRemoved}<br>";
echo _('New directory added :') . " {$dirCreated}<br>";
echo _('New images added :') . " {$regCounter}<br>";
echo _('Convert gd2 -> png :') . " {$gdCounter}<br><br><br>";
?>
</p>
<br><br><br>
<center><a href='javascript:window.opener.location.reload();javascript:window.close();'>
<?php echo _('Close'); ?>
</a></center>
</div>
<br>
<?php
// recreates local centreon directories as defined in DB
/**
* Recreates local centreon directories as defined in DB.
*
* @param string $directory
* @param CentreonDB $db
*
* @throws CentreonDbException
* @return int Id of the directory
*/
function checkDirectory(string $directory, CentreonDB $db): int
{
global $dirCreated;
$statement = $db->prepareQuery(
'SELECT dir_id FROM view_img_dir WHERE dir_alias = :directory'
);
$db->executePreparedQuery($statement, [':directory' => $directory]);
$directoryId = $db->fetchColumn($statement);
if ($directoryId === false) {
$statement = $db->prepareQuery(
<<<'SQL'
INSERT INTO view_img_dir (`dir_name`, `dir_alias`)
VALUES (:directory, :directory)
SQL
);
$db->executePreparedQuery($statement, [':directory' => $directory]);
$directoryId = $db->lastInsertId();
@mkdir("./img/media/{$directory}");
$dirCreated++;
}
return $directoryId;
}
/**
* Inserts $dir_id/$picture into DB if not registered yet
*
* @param string $imagePath
* @param string $directoryPath
* @param int $directoryId
* @param CentreonDB $pearDB
*
* @throws CentreonDbException
* @return void
*/
function checkPicture(
string $imagePath,
string $directoryPath,
int $directoryId,
CentreonDB $pearDB,
): void {
global $regCounter, $gdCounter;
$mimeTypeFileExtensionConcordance = [
'svg' => 'image/svg+xml',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'gd2' => '',
];
[$filename, $extension] = extractFileInfo($imagePath);
if ($filename === '') {
return;
}
if (! array_key_exists(strtolower($extension), $mimeTypeFileExtensionConcordance)) {
return;
}
if ($extension === 'gd2' && ! is_file($filename . '.png')) {
convertGd2ToPng($directoryPath, $imagePath);
$gdCounter++;
}
$mimeType = mime_content_type($directoryPath . '/' . $imagePath);
if (! preg_match('/^image\/(jpg|jpeg|svg\+xml|gif|png)$/', $mimeType)) {
return;
}
if ($mimeType === 'image/svg+xml') {
sanitizeSvg($directoryPath, $imagePath);
}
$statement = $pearDB->prepareQuery(
<<<'SQL'
SELECT 1
FROM view_img
INNER JOIN view_img_dir_relation idr
ON idr.img_img_id = img_id
WHERE img_path = :img_path
AND idr.dir_dir_parent_id = :parent_id
SQL
);
$pearDB->executePreparedQuery(
$statement,
[
':img_path' => $filename . '.' . $extension,
':parent_id' => $directoryId,
]
);
if (! $statement->rowCount()) {
$pearDB->beginTransaction();
try {
$pearDB->executePreparedQuery(
$pearDB->prepareQuery(
'INSERT INTO view_img (`img_name`, `img_path`) VALUES (:img_name, :img_path)'
),
[
':img_name' => $filename,
':img_path' => $imagePath,
]
);
$imageId = $pearDB->lastInsertId();
$statement = $pearDB->prepareQuery(
<<<'SQL'
INSERT INTO view_img_dir_relation (`dir_dir_parent_id`, `img_img_id`)
VALUES (:parent_id, :img_id)
SQL
);
$pearDB->executePreparedQuery(
$statement,
[
':parent_id' => $directoryId,
':img_id' => $imageId,
]
);
$pearDB->commit();
$regCounter++;
} catch (Exception $ex) {
$pearDB->rollBack();
throw $ex;
}
}
}
/**
* @param string $directoryPath
* @param string $picture
*/
function sanitizeSvg(string $directoryPath, string $picture): void
{
$sanitizer = new Sanitizer();
$svgFile = file_get_contents($directoryPath . '/' . $picture);
$cleanSVG = $sanitizer->sanitize($svgFile);
file_put_contents($directoryPath . '/' . $picture, $cleanSVG);
}
/**
* Extracts file info from a picture
*
* @param string $picture
* @return array{0: string, 1: string} [filename, extension]
*/
function extractFileInfo(string $picture): array
{
$fileInfo = pathinfo($picture);
if (! isset($fileInfo['filename'])) {
$basenameDetails = explode('.', $fileInfo['basename']);
$fileInfo['filename'] = $basenameDetails[0];
}
return [
$fileInfo['filename'],
$fileInfo['extension'],
];
}
function convertGd2ToPng(string $directoryPath, string $picture): void
{
$gdImage = imagecreatefromgd2($directoryPath . '/' . $picture);
if (! $gdImage) {
return;
}
[$filename] = extractFileInfo($picture);
imagepng($gdImage, $directoryPath . '/' . $filename . '.png');
imagedestroy($gdImage);
}
/**
* Removes obsolete files from DB if not on filesystem.
*
* @param CentreonDB $pearDB
*
* @return int Number of files removed
*/
function deleteOldPictures(CentreonDB $pearDB): int
{
$fileRemoved = 0;
$DBRESULT = $pearDB->query(
'SELECT img_id, img_path, dir_alias FROM view_img vi, '
. 'view_img_dir vid, view_img_dir_relation vidr '
. 'WHERE vidr.img_img_id = vi.img_id AND vid.dir_id = vidr.dir_dir_parent_id'
);
$statement = $pearDB->prepare('DELETE FROM view_img WHERE img_id = :img_id');
while ($row2 = $DBRESULT->fetchRow()) {
if (! file_exists('./img/media/' . $row2['dir_alias'] . '/' . $row2['img_path'])) {
$statement->bindValue(':img_id', (int) $row2['img_id'], PDO::PARAM_INT);
$statement->execute();
$fileRemoved++;
}
}
$DBRESULT->closeCursor();
return $fileRemoved;
}
?>
</div>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/media/images/help.php | centreon/www/include/options/media/images/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['img_name'] = dgettext('help', 'Enter a new name for the image.');
$help['img_dir'] = dgettext(
'help',
'Enter an already existing or a new directory to add the uploads '
. 'to it. A non-existent directory name will be created first.'
);
$help['img_file'] = dgettext(
'help',
'Select a local file to upload. You can upload jpg, png, gif and '
. 'gd2 files. Multiple images can be uploaded together inside '
. 'archives like zip, tar, tar.gz or tar.bz2.'
);
/**
* formDirectory.ihtml
*/
$help['tip_destination_directory'] = dgettext('help', 'Destination directory.');
$help['tip_images'] = dgettext('help', 'Images.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/media/images/listImg.php | centreon/www/include/options/media/images/listImg.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
if (! isset($centreon)) {
exit();
}
include './include/common/autoNumLimit.php';
include_once './class/centreonUtils.class.php';
$search = null;
if (isset($_POST['searchM'])) {
$centreon->historySearch[$url] = CentreonUtils::escapeSecure(
$_POST['searchM'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
);
$search = $centreon->historySearch[$url];
} elseif (isset($_GET['searchM'])) {
$centreon->historySearch[$url] = CentreonUtils::escapeSecure(
$_GET['searchM'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
);
$search = $centreon->historySearch[$url];
} elseif (isset($centreon->historySearch[$url])) {
$search = $centreon->historySearch[$url];
}
try {
$queryParameters = [];
$selectQuery = <<<'SQL'
SELECT
images.*,
directories.*
SQL;
if (
$centreon->user->admin === '1'
|| $centreon->user->access->hasAccessToAllImageFolders
) {
$bodyQuery = <<<'SQL'
FROM view_img_dir AS `directories`
LEFT JOIN view_img_dir_relation AS `vidr`
ON vidr.dir_dir_parent_id = directories.dir_id
LEFT JOIN view_img AS `images`
ON images.img_id = vidr.img_img_id
SQL;
} else {
$bodyQuery = <<<'SQL'
FROM view_img_dir AS `directories`
LEFT JOIN view_img_dir_relation AS `vidr`
ON vidr.dir_dir_parent_id = directories.dir_id
LEFT JOIN view_img AS `images`
ON images.img_id = vidr.img_img_id
INNER JOIN acl_resources_image_folder_relations armdr
ON armdr.dir_id = vidr.dir_dir_parent_id
INNER JOIN acl_resources ar
ON ar.acl_res_id = armdr.acl_res_id
INNER JOIN acl_res_group_relations argr
ON argr.acl_res_id = ar.acl_res_id
LEFT JOIN acl_group_contacts_relations gcr
ON gcr.acl_group_id = argr.acl_group_id
LEFT JOIN acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = argr.acl_group_id
LEFT JOIN contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND (cgcr.contact_contact_id = :contactId OR gcr.contact_contact_id = :contactId)
SQL;
$queryParameters[] = QueryParameter::int('contactId', $centreon->user->user_id);
}
if ($search) {
$queryParameters[] = QueryParameter::string(
'search',
'%' . HtmlSanitizer::createFromString($search)->getString() . '%',
);
$bodyQuery .= <<<'SQL'
WHERE (images.img_name LIKE :search OR directories.dir_name LIKE :search) AND directories.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')
SQL;
} else {
$bodyQuery .= <<<'SQL'
WHERE directories.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')
SQL;
}
$rows = $pearDB->fetchOne(
sprintf(
<<<'SQL'
SELECT COUNT(DISTINCT images.img_id, directories.dir_id) AS nb
%s
SQL,
$bodyQuery,
),
QueryParameters::create($queryParameters),
);
$bodyQuery .= ' GROUP BY images.img_id, directories.dir_id';
$bodyQuery .= ' ORDER BY dir_alias, img_name LIMIT :offset, :limit';
$query = $selectQuery . ' ' . $bodyQuery;
$queryParameters[] = QueryParameter::int('offset', $num * $limit);
$queryParameters[] = QueryParameter::int('limit', $limit);
/** @var CentreonDB $pearDB */
$res = $pearDB->fetchAllAssociative($query, QueryParameters::create($queryParameters));
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
$exception = new RepositoryException(
message: 'Unable to retrieve images and directories',
context: ['search' => $search, 'contactId' => $centreon->user->user_id],
previous: $e
);
ExceptionLogger::create()->log($exception);
throw $exception;
}
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Directory'));
$tpl->assign('headerMenu_img', _('Image'));
$tpl->assign('headerMenu_comment', _('Comment'));
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p);
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
foreach ($res as $i => $elem) {
if (isset($elem['dir_id']) && ! isset($elemArr[$elem['dir_id']])) {
$selectedDirElem = $form->addElement('checkbox', 'select[' . $elem['dir_id'] . ']');
$selectedDirElem->setAttribute('onclick', "setSubNodes(this, 'select[" . $elem['dir_id'] . "-')");
$rowOpt = ['RowMenu_select' => $selectedDirElem->toHtml(), 'RowMenu_DirLink' => 'main.php?p=' . $p . '&o=cd&dir_id=' . $elem['dir_id'], 'RowMenu_dir' => CentreonUtils::escapeSecure(
$elem['dir_name'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_dir_cmnt' => CentreonUtils::escapeSecure(
$elem['dir_comment'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_empty' => _('Empty directory'), 'counter' => 0];
$elemArr[$elem['dir_id']] = ['head' => $rowOpt, 'elem' => []];
}
if ($elem['img_id']) {
$searchOpt = isset($search) && $search ? '&search=' . $search : '';
$selectedImgElem = $form->addElement(
'checkbox',
'select[' . $elem['dir_id'] . '-' . $elem['img_id'] . ']'
);
$rowOpt = ['RowMenu_select' => $selectedImgElem->toHtml(), 'RowMenu_ImgLink' => "main.php?p={$p}&o=ci&img_id={$elem['img_id']}", 'RowMenu_DirLink' => "main.php?p={$p}&o=cd&dir_id={$elem['dir_id']}", 'RowMenu_dir' => CentreonUtils::escapeSecure(
$elem['dir_name'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_img' => CentreonUtils::escapeSecure(
html_entity_decode($elem['dir_alias'] . '/' . $elem['img_path'], ENT_QUOTES, 'UTF-8'),
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_name' => CentreonUtils::escapeSecure(
html_entity_decode($elem['img_name'], ENT_QUOTES, 'UTF-8'),
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_comment' => CentreonUtils::escapeSecure(
html_entity_decode($elem['img_comment'], ENT_QUOTES, 'UTF-8'),
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
)];
$elemArr[$elem['dir_id']]['elem'][$i] = $rowOpt;
$elemArr[$elem['dir_id']]['head']['counter']++;
}
}
$tpl->assign('elemArr', $elemArr);
// Calculate available disk's space
$bytes = disk_free_space(CentreonMedia::CENTREON_MEDIA_PATH);
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$class = min((int) log($bytes, 1024), count($units) - 1);
$availiableSpace = sprintf('%1.2f', $bytes / pow(1024, $class)) . ' ' . $units[$class];
$tpl->assign('availiableSpace', $availiableSpace);
$tpl->assign('Available', _('Available'));
// 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 openPopup(pageNumber) {
window.open(
'./main.get.php?p=' + pageNumber + '&o=sd&min=1',
'',
'toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,' +
'width=350,height=250'
)
}
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
function submitO(_i) {
if (document.forms['form'].elements[_i].selectedIndex == 1 &&
confirm('<?php echo _('Do you confirm the deletion ?'); ?>')
) {
setO(document.forms['form'].elements[_i].value);
document.forms['form'].submit();
} else if (document.forms['form'].elements[_i].selectedIndex == 2) {
setO(document.forms['form'].elements[_i].value);
document.forms['form'].submit();
}
document.forms['form'].elements[_i].selectedIndex = 0;
}
function setSubNodes(theElement, like) {
var theForm = theElement.form;
var z = 0;
for (z = 0; z < theForm.length; z++) {
if (theForm[z].type == 'checkbox' && theForm[z].disabled == '0' && theForm[z].name.indexOf(like) >= 0) {
if (theElement.checked && !theForm[z].checked) {
theForm[z].checked = true;
if (typeof(_selectedElem) != 'undefined') {
putInSelectedElem(theForm[z].id);
}
} else if (!theElement.checked && theForm[z].checked) {
theForm[z].checked = false;
if (typeof(_selectedElem) != 'undefined') {
removeFromSelectedElem(theForm[z].id);
}
}
}
}
}
</script>
<?php
$actions = [null => _('More actions'), IMAGE_DELETE => _('Delete'), IMAGE_MOVE => _('Move images')];
$form->addElement('select', 'o1', null, $actions, ['onchange' => "javascript:submitO('o1');"]);
$form->addElement('select', 'o2', null, $actions, ['onchange' => "javascript:submitO('o2');"]);
if ($centreon->user->admin === '1') {
$form->addElement(
'button',
'syncDir',
_('Synchronize Media Directory'),
['onClick' => "openPopup({$p})", 'class' => 'btc bt_info ml-2 mr-1'],
);
}
$form->setDefaults(['o1' => null]);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('p', $p);
$tpl->assign('session_id', session_id());
$tpl->assign('searchM', $search);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listImg.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/options/media/images/DB-Func.php | centreon/www/include/options/media/images/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use enshrined\svgSanitize\Sanitizer;
if (! isset($oreon)) {
exit();
}
function sanitizeFilename($filename)
{
return str_replace(
[' ', '/', '\\'],
'_',
$filename
);
}
function sanitizePath($path)
{
return str_replace(
['#', '/', '\\'],
'_',
$path
);
}
function extractDir($zipfile, $path)
{
if (file_exists($zipfile)) {
$files = [];
$zip = new ZipArchive();
if ($zip->open($zipfile) === true) {
return (bool) ($zip->extractTo($path) === true);
$zip->close();
} else {
return false;
}
} else {
return false;
}
}
function isValidImage($filename)
{
if (! $filename) {
return false;
}
$imginfo = getimagesize($filename);
if (isset($imginfo) && $imginfo !== false) {
return true;
}
return is_gd2($filename);
return false;
}
function is_gd2($filename)
{
if (getimagesize($filename) !== false) {
return false;
}
$gd_res = imagecreatefromgd2($filename);
if ($gd_res) {
imagedestroy($gd_res);
return true;
}
return false;
}
function insertImg($src_dir, $src_file, $dst_dir, $dst_file, $img_comment = '')
{
global $pearDB;
$mediadir = './img/media/';
if (! ($dir_id = testDirectoryExistence($dst_dir))) {
$dir_id = insertDirectory($dst_dir);
}
$dst_file = sanitizeFilename($dst_file);
$dst = $mediadir . $dst_dir . '/' . $dst_file;
if (is_file($dst)) {
return false;
} // file exists
if (! rename($src_dir . $src_file, $dst)) {
return false;
} // access denied, path error
$img_parts = explode('.', $dst_file);
$img_name = $img_parts[0];
$prepare = $pearDB->prepare(
'INSERT INTO view_img (img_name, img_path, img_comment) VALUES '
. '(:image_name, :image_path, :image_comment)'
);
$prepare->bindValue(':image_name', $img_name, PDO::PARAM_STR);
$prepare->bindValue(':image_path', $dst_file, PDO::PARAM_STR);
$prepare->bindValue(':image_comment', $img_comment, PDO::PARAM_STR);
$prepare->execute();
$image_id = $pearDB->lastInsertId();
$prepare2 = $pearDB->prepare(
'INSERT INTO view_img_dir_relation (dir_dir_parent_id, img_img_id) '
. 'VALUES (:dir_id, :image_id)'
);
$prepare2->bindValue(':dir_id', $dir_id, PDO::PARAM_INT);
$prepare2->bindValue(':image_id', $image_id, PDO::PARAM_INT);
$prepare2->execute();
return $image_id;
}
function deleteMultImg($images = [])
{
foreach (array_keys($images) as $selector) {
$id = explode('-', $selector);
if (count($id) != 2) {
continue;
}
deleteImg($id[1]);
}
}
function deleteImg($imageId)
{
if (! isset($imageId)) {
return;
}
$imageId = (int) $imageId;
global $pearDB;
$mediadir = './img/media/';
$query = <<<'SQL'
SELECT dir.dir_alias, img.img_path
FROM view_img img
INNER JOIN view_img_dir_relation rel ON img.img_id = rel.img_img_id
INNER JOIN view_img_dir dir ON rel.dir_dir_parent_id = dir.dir_id
WHERE img.img_id = :imageId
SQL;
$dbResult = $pearDB->prepare($query);
$dbResult->bindValue(':imageId', $imageId, PDO::PARAM_INT);
$dbResult->execute();
foreach ($dbResult->fetchAll(PDO::FETCH_ASSOC) as $imagePath) {
$fullpath = $mediadir . basename($imagePath['dir_alias']) . '/' . basename($imagePath['img_path']);
if (is_file($fullpath)) {
unlink($fullpath);
}
}
$pearDB->beginTransaction();
try {
$deleteStatement = $pearDB->prepare('DELETE FROM view_img WHERE img_id = :imageId');
$deleteStatement->bindValue(':imageId', $imageId, PDO::PARAM_INT);
$deleteStatement->execute();
$deleteRelationStatement = $pearDB->prepare('DELETE FROM view_img_dir_relation WHERE img_img_id = :imageId');
$deleteRelationStatement->bindValue(':imageId', $imageId, PDO::PARAM_INT);
$deleteRelationStatement->execute();
$pearDB->commit();
} catch (PDOException $e) {
$pearDB->rollBack();
throw $e;
}
}
function moveMultImg($images, $dirName)
{
if (count($images) > 0) {
foreach ($images as $id) {
moveImg($id, $dirName);
}
}
}
function moveImg($img_id, $dir_alias)
{
if (! $img_id) {
return;
}
global $pearDB;
$mediadir = './img/media/';
$prepare = $pearDB->prepare(
'SELECT dir_id, dir_alias, img_path, img_comment '
. 'FROM view_img, view_img_dir, view_img_dir_relation '
. 'WHERE img_id = :image_id AND img_id = img_img_id '
. 'AND dir_dir_parent_id = dir_id'
);
$prepare->bindValue(':image_id', $img_id, PDO::PARAM_INT);
if (! $prepare->execute()) {
return;
}
$img_info = $prepare->fetch(PDO::FETCH_ASSOC);
$image_info_path = basename($img_info['img_path']);
$image_info_dir_alias = basename($img_info['dir_alias']);
$dir_alias = $dir_alias ? sanitizePath($dir_alias) : $image_info_dir_alias;
if ($dir_alias != $img_info['dir_alias']) {
$oldpath = $mediadir . $image_info_dir_alias . '/' . $image_info_path;
$newpath = $mediadir . $dir_alias . '/' . $image_info_path;
if (! file_exists($newpath)) {
/**
* Only if file doesn't already exist in the destination
*/
if (! testDirectoryExistence($dir_alias)) {
$dir_id = insertDirectory($dir_alias);
} else {
$prepare2 = $pearDB->prepare(
'SELECT dir_id FROM view_img_dir WHERE dir_alias = :dir_alias'
);
$prepare2->bindValue(':dir_alias', $dir_alias, PDO::PARAM_STR);
if (! $prepare2->execute()) {
return;
}
$dir_info = $prepare2->fetch();
$dir_id = $dir_info['dir_id'];
}
if (rename($oldpath, $newpath)) {
$prepare2 = $pearDB->prepare(
'UPDATE view_img_dir_relation SET dir_dir_parent_id = :dir_id '
. ' WHERE img_img_id = :image_id'
);
$prepare2->bindValue(':dir_id', $dir_id, PDO::PARAM_INT);
$prepare2->bindValue(':image_id', $img_id, PDO::PARAM_INT);
$prepare2->execute();
}
}
}
}
function testDirectoryCallback($name)
{
return testDirectoryExistence($name) == 0;
}
function testDirectoryExistence($name)
{
global $pearDB;
$dir_id = 0;
$prepare = $pearDB->prepare(
'SELECT dir_name, dir_id FROM view_img_dir WHERE dir_name = :dir_name'
);
$prepare->bindValue(':dir_name', $name, PDO::PARAM_STR);
$prepare->execute();
$result = $prepare->fetch(PDO::FETCH_ASSOC);
if (isset($result['dir_id'])) {
$dir_id = $result['dir_id'];
}
return $dir_id;
}
function testDirectoryIsEmpty($directoryId)
{
if (! $directoryId) {
return true;
}
global $pearDB;
$statement = $pearDB->prepare('SELECT img_img_id FROM view_img_dir_relation WHERE dir_dir_parent_id = :directoryId');
$statement->bindValue(':directoryId', $directoryId, PDO::PARAM_INT);
$statement->execute();
$empty = ($statement->fetchColumn() > 0) ? false : true;
$statement->closeCursor();
return $empty;
}
function insertDirectory($dir_alias, $dir_comment = '')
{
global $pearDB;
$mediadir = './img/media/';
$dir_alias_safe = basename($dir_alias);
@mkdir($mediadir . $dir_alias_safe);
if (is_dir($mediadir . $dir_alias_safe)) {
touch($mediadir . $dir_alias_safe . '/index.html');
$prepare = $pearDB->prepare(
'INSERT INTO view_img_dir (dir_name, dir_alias, dir_comment) VALUES '
. '(:dir_alias, :dir_alias, :dir_comment)'
);
$prepare->bindValue(':dir_alias', $dir_alias_safe, PDO::PARAM_STR);
$prepare->bindValue(':dir_comment', $dir_comment, PDO::PARAM_STR);
$prepare->execute();
$dir_id = $pearDB->lastInsertId();
return $dir_id;
}
return '';
}
function deleteMultDirectory($dirs = [])
{
foreach (array_keys($dirs) as $selector) {
$id = explode('-', $selector);
if (count($id) != 1) {
continue;
}
deleteDirectory($id[0]);
}
}
function deleteDirectory($directoryId)
{
global $pearDB;
$mediadir = './img/media/';
$directoryId = (int) $directoryId;
// Purge images of the directory
$statement1 = $pearDB->prepare('SELECT img_img_id FROM view_img_dir_relation WHERE dir_dir_parent_id = :directoryId');
$statement1->bindValue(':directoryId', $directoryId, PDO::PARAM_INT);
$statement1->execute();
while ($img = $statement1->fetch()) {
deleteImg($img['img_img_id']);
}
$statement1->closeCursor();
// Delete directory
$statement2 = $pearDB->prepare('SELECT dir_alias FROM view_img_dir WHERE dir_id = :directoryId');
$statement2->bindValue(':directoryId', $directoryId, PDO::PARAM_INT);
$statement2->execute();
$dirAlias = $statement2->fetch();
$statement2->closeCursor();
$safeDirAlias = basename($dirAlias['dir_alias']);
$filenames = scandir($mediadir . $safeDirAlias);
foreach ($filenames as $fileName) {
if (is_file($mediadir . $safeDirAlias . '/' . $fileName)) {
unlink($mediadir . $safeDirAlias . '/' . $fileName);
}
}
rmdir($mediadir . $safeDirAlias);
if (! is_dir($mediadir . $safeDirAlias)) {
$statement3 = $pearDB->prepare('DELETE FROM view_img_dir WHERE dir_id = :directoryId');
$statement3->bindValue(':directoryId', $directoryId, PDO::PARAM_INT);
$statement3->execute();
}
}
function updateDirectory($dir_id, $dir_alias, $dir_comment = '')
{
if (! $dir_id) {
return;
}
global $pearDB;
$mediadir = './img/media/';
$prepare = $pearDB->prepare('SELECT dir_alias FROM view_img_dir WHERE dir_id = :dir_id ');
$prepare->bindValue(':dir_id', $dir_id, PDO::PARAM_INT);
$prepare->execute();
$old_dir = $prepare->fetch(PDO::FETCH_ASSOC);
$dir_alias = sanitizePath($dir_alias);
if (! is_dir($mediadir . $old_dir['dir_alias'])) {
mkdir($mediadir . $dir_alias);
} else {
rename($mediadir . $old_dir['dir_alias'], $mediadir . $dir_alias);
}
if (is_dir($mediadir . $dir_alias)) {
$prepare = $pearDB->prepare(
'UPDATE view_img_dir SET dir_name = :dir_name, '
. 'dir_alias = :dir_alias, dir_comment = :dir_comment '
. 'WHERE dir_id = :dir_id'
);
$prepare->bindValue(':dir_name', $dir_alias, PDO::PARAM_STR);
$prepare->bindValue(':dir_alias', $dir_alias, PDO::PARAM_STR);
$prepare->bindValue(':dir_comment', $dir_comment, PDO::PARAM_STR);
$prepare->bindValue(':dir_id', $dir_id, PDO::PARAM_INT);
$prepare->execute();
}
}
/**
* @param null|mixed $filter
*
* @throws RepositoryException
* @return array<int|string,mixed>
*/
function getListDirectory($filter = null): array
{
global $pearDB, $centreon;
try {
$queryParameters = [];
if (
$centreon->user->admin === '1'
|| $centreon->user->access->hasAccessToAllImageFolders
) {
$query = <<<'SQL'
SELECT
directories.dir_id,
directories.dir_name
FROM view_img_dir AS `directories`
SQL;
} else {
$query = <<<'SQL'
SELECT
directories.dir_id,
directories.dir_name
FROM view_img_dir AS `directories`
INNER JOIN acl_resources_image_folder_relations armdr
ON armdr.dir_id = directories.dir_id
INNER JOIN acl_resources ar
ON ar.acl_res_id = armdr.acl_res_id
INNER JOIN acl_res_group_relations argr
ON argr.acl_res_id = ar.acl_res_id
LEFT JOIN acl_group_contacts_relations gcr
ON gcr.acl_group_id = argr.acl_group_id
LEFT JOIN acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = argr.acl_group_id
LEFT JOIN contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND (cgcr.contact_contact_id = :contactId OR gcr.contact_contact_id = :contactId)
SQL;
$queryParameters[] = QueryParameter::int('contactId', $centreon->user->user_id);
}
// Handling a potential filter even though I do not know where it comes from (no BC break).
if ($filter !== null && $filter !== '') {
$query .= <<<'SQL'
WHERE directories.dir_name LIKE :filter AND directories.dir_name NOT IN ('centreon-map', 'ppm', 'dashboards')
SQL;
$queryParameters[] = QueryParameter::string('filter', '%' . $filter . '%');
} else {
$query .= <<<'SQL'
WHERE directories.dir_name NOT IN ('centreon-map', 'ppm', 'dashboards')
SQL;
}
$query .= ' GROUP BY directories.dir_id ORDER BY directories.dir_name';
return $pearDB->fetchAllKeyValue($query, QueryParameters::create($queryParameters));
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to retrieve the list of directories',
context: ['filter' => $filter],
previous: $e
);
}
}
/**
* Check MIME Type of file
*
* @param array $file
* @return bool
*/
function isCorrectMIMEType(array $file): bool
{
$mimeTypeFileExtensionConcordance = [
'svg' => 'image/svg+xml',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'zip' => 'application/zip',
'gzip' => 'application/x-gzip',
];
$fileExtension = end(explode('.', $file['name']));
if (! array_key_exists($fileExtension, $mimeTypeFileExtensionConcordance)) {
return false;
}
$mimeType = mime_content_type($file['tmp_name']);
if (
! preg_match('/(^image\/(jpg|jpeg|svg\+xml|gif|png)$)|(^application(\/zip)|(\/x-gzip)$)/', $mimeType)
|| (preg_match('/^image\//', $mimeType) && $mimeType !== $mimeTypeFileExtensionConcordance[$fileExtension])
) {
return false;
}
$dir = sys_get_temp_dir() . '/pendingMedia';
switch ($mimeType) {
// .zip archive
case 'application/zip':
$zip = new ZipArchive();
if (isValidMIMETypeFromArchive($dir, $file['tmp_name'], $zip) === true) {
return true;
}
// remove the pending images from tmp
removeRecursiveTempDirectory($dir);
return false;
break;
// .tgz archive
case 'application/x-gzip':
// Append an extension to temp file to be able to instanciate a PharData object
$archiveNewName = $file['tmp_name'] . '.tgz';
rename($file['tmp_name'], $archiveNewName);
$tar = new PharData($archiveNewName);
if (isValidMIMETypeFromArchive($dir, null, null, $tar) === true) {
// remove the .tgz from tmp
unlink($archiveNewName);
return true;
}
// remove the .tgz and the pending images from tmp
unlink($archiveNewName);
removeRecursiveTempDirectory($dir);
return false;
break;
// single image
case 'image/svg+xml':
$sanitizer = new Sanitizer();
$uploadedSVG = file_get_contents($file['tmp_name']);
$cleanSVG = $sanitizer->sanitize($uploadedSVG);
file_put_contents($file['tmp_name'], $cleanSVG);
return true;
break;
case 'image/jpeg':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefromjpeg($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'mime_type' => $mimeType,
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
return true;
break;
case 'image/png':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefrompng($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'mime_type' => $mimeType,
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
return true;
break;
case 'image/gif':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefromgif($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'mime_type' => $mimeType,
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
return true;
break;
default:
return true;
}
}
/**
* Remove a directory and its content
*
* @param string $dir
* @return void
*/
function removeRecursiveTempDirectory(string $dir): void
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object !== '.' && $object !== '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && ! is_link($dir . DIRECTORY_SEPARATOR . $object)) {
removeRecursiveTempDirectory($dir . DIRECTORY_SEPARATOR . $object);
} else {
unlink($dir . DIRECTORY_SEPARATOR . $object);
}
}
}
rmdir($dir);
}
}
/**
* Extract an archive and check the MIME Type of every files
*
* @param string $dir
* @param string $filename
* @param ZipArchive $zip
* @param PharData $tar
* @return bool
*/
function isValidMIMETypeFromArchive(
string $dir,
?string $filename = null,
?ZipArchive $zip = null,
?PharData $tar = null,
): bool {
$files = [];
/**
* Remove Pending images directory to avoid images duplication problems.
*/
if (file_exists($dir)) {
removeRecursiveTempDirectory($dir);
}
$files = [];
if (isset($zip)) {
if ($zip->open($filename) === true && $zip->extractTo($dir) === true) {
$files = array_diff(scandir($dir), ['..', '.']);
} else {
return false;
}
} elseif (isset($tar)) {
if ($tar->extractTo($dir) === true) {
$files = array_diff(scandir($dir), ['..', '.']);
} else {
return false;
}
}
$mimeTypeFileExtensionConcordance = [
'svg' => 'image/svg+xml',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'zip' => 'application/zip',
'gzip' => 'application/x-gzip',
];
foreach ($files as $file) {
$fileExtension = end(explode('.', $file));
if (! array_key_exists($fileExtension, $mimeTypeFileExtensionConcordance)) {
return false;
}
$mimeType = mime_content_type($dir . '/' . $file);
if (
! preg_match('/(^image\/(jpg|jpeg|svg\+xml|gif|png)$)/', $mimeType)
|| (preg_match('/^image\//', $mimeType) && $mimeType !== $mimeTypeFileExtensionConcordance[$fileExtension])
) {
return false;
}
switch ($mimeType) {
case 'image/svg+xml':
$sanitizer = new Sanitizer();
$uploadedSVG = file_get_contents($file['tmp_name']);
$cleanSVG = $sanitizer->sanitize($uploadedSVG);
file_put_contents($file['tmp_name'], $cleanSVG);
break;
case 'image/jpeg':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefromjpeg($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
break;
case 'image/png':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefrompng($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
break;
case 'image/gif':
/**
* use @ to avoid PHP Warning log and instead log a more suitable error in centreon-web.log
*/
$image = @imagecreatefromgif($file['tmp_name']);
if (! $image) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'Unable to validate image, your image may be corrupted',
[
'filename' => $file['name'],
'extension' => $fileExtension,
]
);
return false;
}
break;
default:
return true;
}
}
return true;
}
/**
* Format all the pending images as an array usable by CentreonImageManager
*
* @param string $tempDirectory
* @return array
*/
function getFilesFromTempDirectory(string $tempDirectory): array
{
$directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempDirectory;
$filesInfo = [];
if (is_dir($directory)) {
$files = array_diff(scandir($directory), ['..', '.']);
foreach ($files as $file) {
$filesInfo[] = [
'filename' => [
'name' => $file,
'tmp_name' => $file,
'size' => filesize($directory . DIRECTORY_SEPARATOR . $file),
],
];
}
}
return $filesInfo;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/media/images/formImg.php | centreon/www/include/options/media/images/formImg.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
require_once _CENTREON_PATH_ . 'www/class/centreonImageManager.php';
require_once __DIR__ . '/../../../../../bootstrap.php';
const BASE_CENTREON_IMG_DIRECTORY = './img/media';
/** @var Centreon $centreon */
if (! isset($centreon)) {
exit();
}
$userCanSeeAllFolders = ((int) $centreon->user->admin === 1 || $centreon->user->access->hasAccessToAllImageFolders);
// Database retrieve information
$img = ['img_path' => null];
if ($o == IMAGE_MODIFY || $o == IMAGE_WATCH) {
try {
$query = <<<'SQL'
SELECT
image.img_id,
image.img_name,
image.img_path,
image.img_comment,
directory.dir_id,
directory.dir_name AS `directories`,
directory.dir_alias
FROM view_img AS image
INNER JOIN view_img_dir_relation AS vidr
ON vidr.img_img_id = image.img_id
INNER JOIN view_img_dir AS directory
ON directory.dir_id = vidr.dir_dir_parent_id
WHERE image.img_id = :imageId
LIMIT 1
SQL;
$queryParameters = QueryParameters::create([QueryParameter::int('imageId', $imageId)]);
$img = $pearDB->fetchAssociative($query, $queryParameters);
$img_path = sprintf('%s/%s/%s', BASE_CENTREON_IMG_DIRECTORY, $img['dir_alias'], $img['img_path']);
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
$exception = new RepositoryException(
message: 'Error while retrieving image information',
context: ['imageId' => $imageId],
previous: $e
);
ExceptionLogger::create()->log($exception);
throw $exception;
}
}
// Get Directories
try {
$directoryIds = getListDirectory();
} catch (RepositoryException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while retrieving image directories: ' . $e->getMessage(),
exception: $e
);
throw $e;
}
$directoryListForSelect = $directoryIds;
$directoryListForSelect[0] = '';
asort($directoryListForSelect);
// Styles
$attrsText = ['size' => '35'];
$attrsAdvSelect = ['style' => 'width: 200px; height: 100px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '80'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == IMAGE_ADD) {
$form->addElement('header', 'title', _('Add Image(s)'));
$form->addElement(
'autocomplete',
'directories',
$userCanSeeAllFolders ? _('Existing or new directory') : _('Existing directory'),
$directoryIds,
[
'id' => 'directories',
'style' => $userCanSeeAllFolders ? '' : 'display:none;',
]
);
$form->addElement(
'select',
'list_dir',
'',
$directoryListForSelect,
['onchange' => 'document.getElementById("directories").value = this.options[this.selectedIndex].text;']
);
$form->addElement('file', 'filename', _('Image or archive'));
$subA = $form->addElement(
'submit',
'submitA',
_('Save'),
['class' => 'btc bt_success']
);
$form->registerRule('isCorrectMIMEType', 'callback', 'isCorrectMIMEType');
$form->addRule('filename', _('Invalid Image Format.'), 'isCorrectMIMEType');
} elseif ($o == IMAGE_MODIFY) {
$form->addElement('header', 'title', _('Modify Image'));
$form->addElement('text', 'img_name', _('Image Name'), $attrsText);
// Small hack for user with not enough rights to see all folders and avoid creation of a directory that user will not see
// post creation. Pure cosmetic
$form->addElement(
'autocomplete',
'directories',
$userCanSeeAllFolders ? _('Existing or new directory') : _('Existing directory'),
$directoryIds,
[
'id' => 'directories',
'style' => $userCanSeeAllFolders ? '' : 'display:none;',
]
);
$directorySelect = $form->addElement(
'select',
'list_dir',
' ',
$directoryListForSelect,
['onchange' => 'document.getElementById("directories").value = this.options[this.selectedIndex].text;']
);
$directorySelect->setSelected($img['dir_id']);
$form->addElement('file', 'filename', _('Image'));
$subC = $form->addElement(
'submit',
'submitC',
_('Save'),
['class' => 'btc bt_success']
);
$form->setDefaults($img);
$form->addRule('img_name', _('Compulsory image name'), 'required');
$form->registerRule('isCorrectMIMEType', 'callback', 'isCorrectMIMEType');
$form->addRule('filename', _('Invalid Image Format.'), 'isCorrectMIMEType');
} elseif ($o == IMAGE_WATCH) {
$form->addElement('header', 'title', _('View Image'));
$form->addElement('text', 'img_name', _('Image Name'), $attrsText);
$form->addElement('text', 'img_path', $img_path, null);
$form->addElement(
'autocomplete',
'directories',
_('Directory'),
$directoryIds,
['id', 'directories']
);
$form->addElement('file', 'filename', _('Image'));
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p={$p}&o=ci&img_id={$imageId}'"],
['class' => 'btc bt_success']
);
$form->setDefaults($img);
}
$form->addElement(
'button',
'cancel',
_('Cancel'),
[
'onClick' => "javascript:window.location.href='?p={$p}'",
'class' => 'btc bt_default',
]
);
$form->addElement('textarea', 'img_comment', _('Comments'), $attrsTextarea);
$tab = [];
$tab[] = $form->createElement('radio', 'action', null, _('Return to list'), '1');
$tab[] = $form->createElement('radio', 'action', null, _('Review form after save'), '0');
$form->addGroup($tab, 'action', _('Action'), ' ');
$form->setDefaults(['action' => '1']);
$form->addElement('hidden', 'img_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('directories', _('Required Field'), 'required');
$form->setRequiredNote(_('Required Field'));
// watch/view
if ($o == IMAGE_WATCH) {
$form->freeze();
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$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()) {
$imgId = $form->getElement('img_id')->getValue();
$imgPath = $form->getElement('directories')->getValue();
$imgComment = $form->getElement('img_comment')->getValue();
/**
* Check if an archive has been extracted into pendingMedia folder
*/
$filesToUpload = getFilesFromTempDirectory('pendingMedia');
/**
* If a single image is uploaded
*/
if ($filesToUpload === []) {
$oImageUploader = new CentreonImageManager(
$dependencyInjector,
$_FILES,
'./img/media/',
$imgPath,
$imgComment
);
if ($form->getSubmitValue('submitA')) {
$valid = $oImageUploader->upload();
} elseif ($form->getSubmitValue('submitC')) {
$imgName = $form->getElement('img_name')->getValue();
$valid = $oImageUploader->update($imgId, $imgName);
}
$form->freeze();
if ($valid === false) {
$form->setElementError('filename', 'An image is not uploaded.');
}
/**
* If an archive .zip or .tgz is uploaded
*/
} else {
foreach ($filesToUpload as $file) {
$oImageUploader = new CentreonImageManager(
$dependencyInjector,
$file,
'./img/media/',
$imgPath,
$imgComment
);
if ($form->getSubmitValue('submitA')) {
$valid = $oImageUploader->uploadFromDirectory('pendingMedia');
} elseif ($form->getSubmitValue('submitC')) {
$imgName = $form->getElement('img_name')->getValue();
$valid = $oImageUploader->update($imgId, $imgName);
}
$form->freeze();
if ($valid === false) {
$form->setElementError('filename', 'Images already uploaded.');
}
}
/**
* Remove the folder after upload complete
*/
removeRecursiveTempDirectory(sys_get_temp_dir() . '/pendingMedia');
}
}
$action = $form->getSubmitValue('action');
if ($valid) {
require_once 'listImg.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <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('max_uploader_file', ini_get('upload_max_filesize'));
$tpl->assign('o', $o);
$tpl->display('formImg.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/options/accessLists/resourcesACL/resourcesAccess.php | centreon/www/include/options/accessLists/resourcesACL/resourcesAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
const RESOURCE_ACCESS_ADD = 'a';
const RESOURCE_ACCESS_WATCH = 'w';
const RESOURCE_ACCESS_MODIFY = 'c';
const RESOURCE_ACCESS_MASSIVE_CHANGE = 'mc';
const RESOURCE_ACCESS_ACTIVATION = 's';
const RESOURCE_ACCESS_MASSIVE_ACTIVATION = 'ms';
const RESOURCE_ACCESS_DEACTIVATION = 'u';
const RESOURCE_ACCESS_MASSIVE_DEACTIVATION = 'mu';
const RESOURCE_ACCESS_DUPLICATION = 'm';
const RESOURCE_ACCESS_DELETION = 'd';
if (! isset($centreon)) {
exit();
}
$aclId = filter_var(
$_GET['acl_res_id'] ?? $_POST['acl_res_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';
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] != '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] != '') {
$o = $_POST['o2'];
}
}
switch ($o) {
case RESOURCE_ACCESS_ADD:
require_once __DIR__ . '/formResourcesAccess.php';
break; // Add a LCA
case RESOURCE_ACCESS_WATCH:
require_once __DIR__ . '/formResourcesAccess.php';
break; // Watch a LCA
case RESOURCE_ACCESS_MODIFY:
require_once __DIR__ . '/formResourcesAccess.php';
break; // Modify a LCA
case RESOURCE_ACCESS_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableLCAInDB($aclId);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Activate a LCA
case RESOURCE_ACCESS_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableLCAInDB(null, $select);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Activate n LCA
case RESOURCE_ACCESS_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableLCAInDB($aclId);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Desactivate a LCA
case RESOURCE_ACCESS_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableLCAInDB(null, $select);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Desactivate n LCA
case RESOURCE_ACCESS_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleLCAInDB($select, $dupNbr);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Duplicate n LCAs
case RESOURCE_ACCESS_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteLCAInDB($select);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsResourcesAccess.php';
break; // Delete n LCAs
default:
require_once __DIR__ . '/listsResourcesAccess.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/options/accessLists/resourcesACL/help.php | centreon/www/include/options/accessLists/resourcesACL/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_access_list_name'] = dgettext('help', 'Name of resource rule.');
$help['tip_description'] = dgettext('help', 'Description of resource rule.');
/**
* People linked to this Access list
*/
$help['tip_linked_groups'] = dgettext('help', 'Implied ACL groups.');
/**
* Additional Information
*/
$help['tip_status'] = dgettext('help', 'Enable or disable the ACL resource rule.');
$help['tip_comments'] = dgettext('help', 'Comments regarding this resource rule.');
/**
* Shared Host Resouces
*/
$help['tip_hosts'] = dgettext(
'help',
'Hosts that will be displayed to users. Services that belong to these hosts will also be visible.'
);
$help['tip_host_groups'] = dgettext(
'help',
'Host groups that will be displayed to users. Hosts that belong to these host groups will also be visible.'
);
$help['tip_exclude_hosts_from_selected_host_groups'] = dgettext(
'help',
'Excluding hosts from the selected host groups will hide them from users.'
);
/**
* Shared Service Resouces
*/
$help['tip_service_groups'] = dgettext(
'help',
'Service groups that will be displayed to users. '
. 'Services that belong to these service groups will also be visible.'
);
/**
* Shared Meta Services Resouces
*/
$help['tip_meta_services'] = dgettext('help', 'Meta services that will be displayed to users.');
/**
* Filters
*/
$help['tip_poller_filter'] = dgettext(
'help',
'Will only display resources that are monitored by these pollers. When blank, no filter is applied.'
);
$help['tip_host_category_filter'] = dgettext(
'help',
'Will only display hosts that belong to these host categories. When blank, no filter is applied.'
);
$help['tip_service_category_filter'] = dgettext(
'help',
'Will only display services that belong to these service categories. When blank, no filter is applied.'
);
/**
* Shared Service Resouces
*/
$help['tip_image_folder'] = dgettext(
'help',
'Image folders that will be displayed to users. Images that belong to these folders will be visible.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/resourcesACL/formResourcesAccess.php | centreon/www/include/options/accessLists/resourcesACL/formResourcesAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
if (! isset($centreon)) {
exit();
}
// Database retrieve information for LCA
if ($o === RESOURCE_ACCESS_MODIFY || $o === RESOURCE_ACCESS_WATCH) {
try {
$queryParameters = new QueryParameters([
QueryParameter::int('resourceAccessId', $aclId),
]);
$aclResourceInformation = $pearDB->fetchAssociative(
'SELECT * FROM acl_resources WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
$acl = array_map('myDecode', $aclResourceInformation);
// poller relations
$acl['acl_pollers'] = $pearDB->fetchFirstColumn(
'SELECT poller_id FROM acl_resources_poller_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// host relations
$acl['acl_hosts'] = $pearDB->fetchFirstColumn(
'SELECT host_host_id FROM acl_resources_host_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// host exclusions
$acl['acl_hostexclude'] = $pearDB->fetchFirstColumn(
'SELECT host_host_id FROM acl_resources_hostex_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// host groups relations
$acl['acl_hostgroup'] = $pearDB->fetchFirstColumn(
'SELECT hg_hg_id FROM acl_resources_hg_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// ACL Groups relations
$acl['acl_groups'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT acl_group_id FROM acl_res_group_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// Service categories relations
$acl['acl_sc'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT sc_id FROM acl_resources_sc_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// Host categories relations
$acl['acl_hc'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT hc_id FROM acl_resources_hc_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// Service groups relations
$acl['acl_sg'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT sg_id FROM acl_resources_sg_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// Meta services relations
$acl['acl_meta'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT meta_id FROM acl_resources_meta_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
// Image folder relations
$acl['acl_image_folder'] = $pearDB->fetchFirstColumn(
'SELECT DISTINCT dir_id FROM acl_resources_image_folder_relations WHERE acl_res_id = :resourceAccessId',
$queryParameters
);
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
$exception = new RepositoryException(
message: 'Error while retrieving ACL information',
context: ['aclId' => $aclId],
previous: $e
);
ExceptionLogger::create()->log($exception);
throw $exception;
}
}
// GET ALL data that will fill the selectors
try {
$groups = [];
$accessGroups = $pearDB->fetchAllAssociative('SELECT acl_group_id, acl_group_name FROM acl_groups ORDER BY acl_group_name');
foreach ($accessGroups as $accessGroup) {
$groups[$accessGroup['acl_group_id']] = HtmlSanitizer::createfromstring($accessGroup['acl_group_name'])->getstring();
}
$pollers = [];
$monitoringServers = $pearDB->fetchAllAssociative('SELECT id, name FROM nagios_server ORDER BY name');
foreach ($monitoringServers as $monitoringServer) {
$pollers[$monitoringServer['id']] = HtmlSanitizer::createfromstring($monitoringServer['name'])->getstring();
}
$hosts = $pearDB->fetchAllKeyValue("SELECT host_id, host_name FROM host WHERE host_register = '1' ORDER BY host_name");
$hostsToExclude = $hosts;
$hostGroups = $pearDB->fetchAllKeyValue('SELECT hg_id, hg_name FROM hostgroup ORDER BY hg_name');
$serviceCategories = $pearDB->fetchAllKeyValue('SELECT sc_id, sc_name FROM service_categories ORDER BY sc_name');
$hostCategories = $pearDB->fetchAllKeyValue('SELECT hc_id, hc_name FROM hostcategories ORDER BY hc_name');
$serviceGroups = $pearDB->fetchAllKeyValue('SELECT sg_id, sg_name FROM servicegroup ORDER BY sg_name');
$metaServices = $pearDB->fetchAllKeyValue('SELECT meta_id, meta_name FROM meta_service ORDER BY meta_name');
$imageFolders = $pearDB->fetchAllKeyValue("SELECT dir_id, dir_name FROM view_img_dir WHERE dir_name NOT IN ('dashboards', 'ppm', 'centreon-map') ORDER BY dir_name");
} catch (ConnectionException $e) {
$exception = new RepositoryException(
message: 'Error while retrieving data to fill the selectors for ACL form',
previous: $e
);
ExceptionLogger::create()->log($exception);
throw $exception;
}
// Var information to format the element
$attrsText = [
'size' => '30',
];
$attrsText2 = [
'size' => '60',
];
$attrsAdvSelect = [
'style' => 'width: 300px; height: 220px;',
];
$attrsTextarea = [
'rows' => '3',
'cols' => '80',
];
$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 begin
$form = new HTML_QuickFormCustom('Form', 'POST', '?p=' . $p);
if ($o == RESOURCE_ACCESS_ADD) {
$form->addElement('header', 'title', _('Add an ACL'));
} elseif ($o == RESOURCE_ACCESS_MODIFY) {
$form->addElement('header', 'title', _('Modify an ACL'));
} elseif ($o == RESOURCE_ACCESS_WATCH) {
$form->addElement('header', 'title', _('View an ACL'));
}
// LCA basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('header', 'hostgroups', _('Host Groups Shared'));
$form->addElement('header', 'services', _('Filters'));
$form->addElement('text', 'acl_res_name', _('Access list name'), $attrsText);
$form->addElement('text', 'acl_res_alias', _('Description'), $attrsText2);
$tab = [];
$tab[] = $form->createElement('radio', 'acl_res_activate', null, _('Enabled'), '1');
$tab[] = $form->createElement('radio', 'acl_res_activate', null, _('Disabled'), '0');
$form->addGroup($tab, 'acl_res_activate', _('Status'), ' ');
$form->setDefaults(['acl_res_activate' => '1']);
// All hosts checkbox definition
$allHosts[] = $form->createElement(
'checkbox',
'all_hosts',
' ',
'',
['id' => 'all_hosts', 'onClick' => 'toggleTableDeps(this)']
);
$form->addGroup($allHosts, 'all_hosts', _('Include all hosts'), ' ');
// All host groups checkbox definition
$allHostgroups[] = $form->createElement(
'checkbox',
'all_hostgroups',
' ',
'',
['id' => 'all_hostgroups', 'onClick' => 'toggleTableDeps(this)']
);
$form->addGroup($allHostgroups, 'all_hostgroups', _('Include all hostgroups'), ' ');
// All service groups checkbox definition
$allServiceGroups[] = $form->createElement(
'checkbox',
'all_servicegroups',
' ',
'',
['id' => 'all_servicegroups', 'onClick' => 'toggleTableDeps(this)']
);
$form->addGroup($allServiceGroups, 'all_servicegroups', _('Include all servicegroups'), ' ');
// All directories (medias) checkbox definition
$allImageFolders[] = $form->createElement(
'checkbox',
'all_image_folders',
' ',
'',
['id' => 'all_image_folders', 'onClick' => 'toggleTableDeps(this)', 'checked' => true]
);
$form->addGroup($allImageFolders, 'all_image_folders', _('Include all image folders'), ' ');
// Contact implied
$form->addElement('header', 'contacts_infos', _('People linked to this Access list'));
$ams1 = $form->addElement(
'advmultiselect',
'acl_groups',
[_('Linked Groups'), _('Available'), _('Selected')],
$groups,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$form->addElement('header', 'Host_infos', _('Shared Resources'));
$form->addElement('header', 'Image_Folder_info', _('Shared image folders'));
$form->addElement('header', 'help', _('Help'));
$form->addElement(
'header',
'HSharedExplain',
_('<b><i>Help :</i></b> Select hosts and hostgroups that can be seen by associated users. '
. 'You also have the possibility to exclude host(s) from selected hostgroup(s).')
);
$form->addElement(
'header',
'SSharedExplain',
_('<b><i>Help :</i></b> Select services that can be seen by associated users.')
);
$form->addElement(
'header',
'MSSharedExplain',
_('<b><i>Help :</i></b> Select meta services that can be seen by associated users.')
);
$form->addElement(
'header',
'ImageFoldersSharedExplain',
_('<b><i>Help :</i></b> Select image folders that can be seen by associated users.')
);
$form->addElement(
'header',
'FilterExplain',
_('<b><i>Help :</i></b> Select the filter(s) you want to apply to the '
. 'resource definition for a more restrictive view.')
);
// Pollers
$ams0 = $form->addElement(
'advmultiselect',
'acl_pollers',
[_('Poller Filter'), _('Available'), _('Selected')],
$pollers,
$attrsAdvSelect,
SORT_ASC
);
$ams0->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams0->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams0->setElementTemplate($eTemplate);
echo $ams0->getElementJs(false);
// Hosts
$attrsAdvSelect['id'] = 'hostAdvancedSelect';
$ams2 = $form->addElement(
'advmultiselect',
'acl_hosts',
[_('Hosts'), _('Available'), _('Selected')],
$hosts,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Host Groups
$attrsAdvSelect['id'] = 'hostgroupAdvancedSelect';
$ams2 = $form->addElement(
'advmultiselect',
'acl_hostgroup',
[_('Host Groups'), _('Available'), _('Selected')],
$hostGroups,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
unset($attrsAdvSelect['id']);
$ams2 = $form->addElement(
'advmultiselect',
'acl_hostexclude',
[_('Exclude hosts from selected host groups'), _('Available'), _('Selected')],
$hostsToExclude,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Service Filters
$ams2 = $form->addElement(
'advmultiselect',
'acl_sc',
[_('Service Category Filter'), _('Available'), _('Selected')],
$serviceCategories,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Host Filters
$ams2 = $form->addElement(
'advmultiselect',
'acl_hc',
[_('Host Category Filter'), _('Available'), _('Selected')],
$hostCategories,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Service Groups Add
$attrsAdvSelect['id'] = 'servicegroupAdvancedSelect';
$ams2 = $form->addElement(
'advmultiselect',
'acl_sg',
[_('Service Groups'), _('Available'), _('Selected')],
$serviceGroups,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
unset($attrsAdvSelect['id']);
// Meta Services
$ams2 = $form->addElement(
'advmultiselect',
'acl_meta',
[_('Meta Services'), _('Available'), _('Selected')],
$metaServices,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Images
$attrsAdvSelect['id'] = 'imageFolderAdvancedSelect';
$ams2 = $form->addElement(
'advmultiselect',
'acl_image_folder',
[_('Image folders'), _('Available'), _('Selected')],
$imageFolders,
$attrsAdvSelect,
SORT_ASC
);
$ams2->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams2->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams2->setElementTemplate($eTemplate);
echo $ams2->getElementJs(false);
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$form->addElement('textarea', 'acl_res_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'acl_res_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('acl_res_name', _('Required'), 'required');
$form->registerRule('exist', 'callback', 'testExistence');
if (
$o === RESOURCE_ACCESS_ADD
|| $o === RESOURCE_ACCESS_MODIFY
) {
$form->addRule('acl_res_name', _('Already exists'), 'exist');
}
$form->setRequiredNote(_('Required field'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
$formDefaults = $acl ?? [];
$formDefaults['all_hosts[all_hosts]'] = $formDefaults['all_hosts'] ?? '0';
$formDefaults['all_hostgroups[all_hostgroups]'] = $formDefaults['all_hostgroups'] ?? '0';
$formDefaults['all_servicegroups[all_servicegroups]'] = $formDefaults['all_servicegroups'] ?? '0';
// By default we want this to be checked
$formDefaults['all_image_folders[all_image_folders]'] = $formDefaults['all_image_folders'] ?? '1';
if ($o === RESOURCE_ACCESS_WATCH) {
$form->addElement('button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&acl_id=' . $aclId . "'", 'class' => 'btc bt_success']);
$form->setDefaults($formDefaults);
$form->freeze();
} elseif ($o === RESOURCE_ACCESS_MODIFY) {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Delete'), ['class' => 'btc bt_danger']);
$form->setDefaults($formDefaults);
} elseif ($o === RESOURCE_ACCESS_ADD) {
$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&lca_id=' . $aclId, 'changeT' => _('Modify')]);
// 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()) {
$aclObj = $form->getElement('acl_res_id');
if ($form->getSubmitValue('submitA')) {
try {
$aclObj->setValue(insertLCAInDB());
} catch (RepositoryException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while inserting ACL: ' . $e->getMessage(),
exception: $e,
);
throw $e;
}
} elseif ($form->getSubmitValue('submitC')) {
try {
updateLCAInDB($aclObj->getValue());
} catch (RepositoryException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while updating ACL: ' . $e->getMessage(),
customContext: ['aclId' => $aclObj->getValue()],
exception: $e,
);
throw $e;
}
}
require_once 'listsResourcesAccess.php';
} else {
$action = $form->getSubmitValue('action');
if ($valid && $action['action']) {
require_once 'listsResourcesAccess.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <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', _('General Information'));
$tpl->assign('sort2', _('Host Resources'));
$tpl->assign('sort3', _('Service Resources'));
$tpl->assign('sort4', _('Meta Services'));
$tpl->assign('sort5', _('Filters'));
$tpl->assign('sort6', _('Image folders'));
$tpl->display('formResourcesAccess.ihtml');
}
}
?>
<script type='text/javascript'>
function toggleTableDeps(element) {
jQuery(element).parents('td.FormRowValue:first').children('table').toggle(
!jQuery(element).is(':checked')
);
}
jQuery(() => {
toggleTableDeps(jQuery('#all_hosts'));
toggleTableDeps(jQuery('#all_hostgroups'));
toggleTableDeps(jQuery('#all_servicegroups'));
toggleTableDeps(jQuery('#all_image_folders'));
});
</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/options/accessLists/resourcesACL/listsResourcesAccess.php | centreon/www/include/options/accessLists/resourcesACL/listsResourcesAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
$searchStr = '';
$search = null;
if (isset($_POST['searchACLR'])) {
$search = HtmlSanitizer::createFromString($_POST['searchACLR'])
->removeTags()
->getString();
$centreon->historySearch[$url] = $search;
} elseif (isset($_GET['searchACLR'])) {
$search = HtmlSanitizer::createFromString($_GET['searchACLR'])
->removeTags()
->getString();
$centreon->historySearch[$url] = $search;
} elseif (isset($centreon->historySearch[$url])) {
$search = $centreon->historySearch[$url];
}
if ($search) {
$searchStr = 'AND (acl_res_name LIKE :search OR acl_res_alias LIKE :search)';
}
$rq = "
SELECT SQL_CALC_FOUND_ROWS acl_res_id, acl_res_name, acl_res_alias, all_hosts, all_hostgroups,
all_servicegroups, all_image_folders, acl_res_activate FROM acl_resources
WHERE locked = 0 AND cloud_specific = 0 {$searchStr}
ORDER BY acl_res_name
LIMIT :num, :limit
";
$statement = $pearDB->prepare($rq);
if ($search) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->bindValue(':num', $num * $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_alias', _('Description'));
$tpl->assign('headerMenu_contacts', _('Contacts'));
$tpl->assign('headerMenu_allH', _('All Hosts'));
$tpl->assign('headerMenu_allHG', _('All Hostgroups'));
$tpl->assign('headerMenu_allSG', _('All Servicegroups'));
$tpl->assign('headerMenu_allImageFolders', _('All image folders'));
$tpl->assign('headerMenu_status', _('Status'));
$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';
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $resources = $statement->fetchRow(); $i++) {
$selectedElements = $form->addElement('checkbox', 'select[' . $resources['acl_res_id'] . ']');
if ($resources['acl_res_activate']) {
$moptions = "<a href='main.php?p=" . $p . '&acl_res_id=' . $resources['acl_res_id']
. '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $search . '¢reon_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 . '&acl_res_id=' . $resources['acl_res_id']
. '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$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["
. $resources['acl_res_id'] . "]'></input>";
$allHostgroups = (isset($resources['all_hostgroups']) && $resources['all_hostgroups'] == 1 ? _('Yes') : _('No'));
$allServicegroups = (isset($resources['all_servicegroups']) && $resources['all_servicegroups'] == 1
? _('Yes')
: _('No'));
$allImageFolders = (isset($resources['all_image_folders']) && $resources['all_image_folders'] == 1 ? _('Yes') : _('No'));
$elemArr[$i] = [
'MenuClass' => 'list_' . $style,
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => $resources['acl_res_name'],
'RowMenu_alias' => myDecode($resources['acl_res_alias']),
'RowMenu_all_hosts' => (isset($resources['all_hosts']) && $resources['all_hosts'] == 1 ? _('Yes') : _('No')),
'RowMenu_all_hostgroups' => $allHostgroups,
'RowMenu_all_servicegroups' => $allServicegroups,
'RowMenu_all_image_folders' => $allImageFolders,
'RowMenu_link' => 'main.php?p=' . $p . '&o=c&acl_res_id=' . $resources['acl_res_id'],
'RowMenu_status' => $resources['acl_res_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $resources['acl_res_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) {
$attrs1 = ['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 || "
. "this.form.elements['{$option}'].selectedIndex == 4) {"
. "setO(this.form.elements['{$option}'].value); submit();}"];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs1
);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchACLR', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listsResourcesAccess.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/options/accessLists/resourcesACL/DB-Func.php | centreon/www/include/options/accessLists/resourcesACL/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
/**
* @param null $name
* @return bool
*/
function testExistence($name = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('acl_res_id');
}
$name = HtmlAnalyzer::sanitizeAndRemoveTags($name);
$statement = $pearDB->prepare('SELECT acl_res_name, acl_res_id FROM `acl_resources` WHERE acl_res_name = :name');
$statement->bindValue(':name', $name, PDO::PARAM_STR);
$statement->execute();
return ! (($lca = $statement->fetch()) && $lca['acl_res_id'] != $id);
}
/**
* @param null $aclResId
* @param array $acls
*/
function enableLCAInDB($aclResId = null, $acls = [])
{
global $pearDB, $centreon;
if (! $aclResId && ! count($acls)) {
return;
}
if ($aclResId) {
$acls = [$aclResId => '1'];
}
foreach ($acls as $key => $value) {
$query = "UPDATE `acl_groups` SET `acl_group_changed` = '1' "
. "WHERE acl_group_id IN (SELECT acl_group_id FROM acl_res_group_relations WHERE acl_res_id = '{$key}')";
$pearDB->query($query);
$query = "UPDATE `acl_resources` SET acl_res_activate = '1', `changed` = '1' "
. "WHERE `acl_res_id` = '" . $key . "'";
$pearDB->query($query);
$query = "SELECT acl_res_name FROM `acl_resources` WHERE acl_res_id = '" . (int) $key . "' LIMIT 1";
$dbResult = $pearDB->query($query);
$row = $dbResult->fetch();
$centreon->CentreonLogAction->insertLog('resource access', $key, $row['acl_res_name'], 'enable');
}
}
/**
* @param null $aclResId
* @param array $acls
*/
function disableLCAInDB($aclResId = null, $acls = [])
{
global $pearDB, $centreon;
if (! $aclResId && ! count($acls)) {
return;
}
if ($aclResId) {
$acls = [$aclResId => '1'];
}
foreach ($acls as $key => $value) {
$query = "UPDATE `acl_groups` SET `acl_group_changed` = '1' "
. "WHERE acl_group_id IN (SELECT acl_group_id FROM acl_res_group_relations WHERE acl_res_id = '{$key}')";
$pearDB->query($query);
$query = "UPDATE `acl_resources` SET acl_res_activate = '0', `changed` = '1' "
. "WHERE `acl_res_id` = '" . $key . "'";
$pearDB->query($query);
$query = "SELECT acl_res_name FROM `acl_resources` WHERE acl_res_id = '" . (int) $key . "' LIMIT 1";
$dbResult = $pearDB->query($query);
$row = $dbResult->fetch();
$centreon->CentreonLogAction->insertLog('resource access', $key, $row['acl_res_name'], 'disable');
}
}
/**
* Delete ACL entry in DB
* @param $acls
*/
function deleteLCAInDB($acls = [])
{
global $pearDB, $centreon;
foreach ($acls as $key => $value) {
$query = "SELECT acl_res_name FROM `acl_resources` WHERE acl_res_id = '" . (int) $key . "' LIMIT 1";
$dbResult = $pearDB->query($query);
$row = $dbResult->fetch();
$query = "UPDATE `acl_groups` SET `acl_group_changed` = '1' "
. "WHERE acl_group_id IN (SELECT acl_group_id FROM acl_res_group_relations WHERE acl_res_id = '{$key}')";
$pearDB->query($query);
$pearDB->query("DELETE FROM `acl_resources` WHERE acl_res_id = '" . $key . "'");
$centreon->CentreonLogAction->insertLog('resource access', $key, $row['acl_res_name'], 'd');
}
}
/**
* Duplicate Resources ACL
* @param $lcas
* @param $nbrDup
*/
function multipleLCAInDB($lcas = [], $nbrDup = [])
{
global $pearDB, $centreon;
foreach ($lcas as $key => $value) {
$dbResult = $pearDB->query("SELECT * FROM `acl_resources` WHERE acl_res_id = '" . $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['acl_res_id'] = '';
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$values = [];
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'acl_res_name') {
$acl_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$values[] = $value2 != null
? "'" . $value2 . "'"
: 'NULL';
if ($key2 != 'acl_res_id') {
$fields[$key2] = $value2;
}
if (isset($acl_res_name)) {
$fields['acl_res_name'] = $acl_res_name;
}
}
if (testExistence($acl_name)) {
if ($values !== []) {
$pearDB->query('INSERT INTO acl_resources VALUES (' . implode(',', $values) . ')');
}
$dbResult = $pearDB->query('SELECT MAX(acl_res_id) FROM acl_resources');
$maxId = $dbResult->fetch();
$dbResult->closeCursor();
if (isset($maxId['MAX(acl_res_id)'])) {
duplicateGroups($key, $maxId['MAX(acl_res_id)'], $pearDB);
$centreon->CentreonLogAction->insertLog(
'resource access',
$maxId['MAX(acl_res_id)'],
$acl_name,
'a',
$fields
);
}
}
}
}
}
/**
* @param $idTD
* @param $acl_id
* @param $pearDB
*/
function duplicateGroups($idTD, $acl_id, $pearDB)
{
$query = 'INSERT INTO acl_res_group_relations (acl_res_id, acl_group_id) '
. 'SELECT :acl_id AS acl_res_id, acl_group_id FROM acl_res_group_relations WHERE acl_res_id = :acl_res_id';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// host categories
$query = 'INSERT INTO acl_resources_hc_relations (acl_res_id, hc_id) '
. '(SELECT :acl_id, hc_id FROM acl_resources_hc_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// hostgroups
$query = 'INSERT INTO acl_resources_hg_relations (acl_res_id, hg_hg_id) '
. '(SELECT :acl_id, hg_hg_id FROM acl_resources_hg_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// host exceptions
$query = 'INSERT INTO acl_resources_hostex_relations (acl_res_id, host_host_id) '
. '(SELECT :acl_id, host_host_id FROM acl_resources_hostex_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// hosts
$query = 'INSERT INTO acl_resources_host_relations (acl_res_id, host_host_id) '
. '(SELECT :acl_id, host_host_id FROM acl_resources_host_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// meta
$query = 'INSERT INTO acl_resources_meta_relations (acl_res_id, meta_id) '
. '(SELECT :acl_id, meta_id FROM acl_resources_meta_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// poller
$query = 'INSERT INTO acl_resources_poller_relations (acl_res_id, poller_id) '
. '(SELECT :acl_id, poller_id FROM acl_resources_poller_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// service categories
$query = 'INSERT INTO acl_resources_sc_relations (acl_res_id, sc_id) '
. '(SELECT :acl_id, sc_id FROM acl_resources_sc_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
// service groups
$query = 'INSERT INTO acl_resources_sg_relations (acl_res_id, sg_id) '
. '(SELECT :acl_id, sg_id FROM acl_resources_sg_relations WHERE acl_res_id = :acl_res_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':acl_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_res_id', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* @param $idTD
* @param $acl_id
* @param $pearDB
*/
function duplicateContactGroups($idTD, $acl_id, $pearDB)
{
$query = 'INSERT INTO acl_res_group_relations (acl_res_id, acl_group_id) '
. "SELECT acl_res_id, '{$acl_id}' AS acl_group_id FROM acl_res_group_relations WHERE acl_group_id = '{$idTD}'";
$pearDB->query($query);
}
/**
* Update ACL entry
*
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateLCAInDB($aclId = null): void
{
global $form, $centreon;
if (! $aclId) {
return;
}
updateLCA($aclId);
updateGroups($aclId);
updateHosts($aclId);
updateHostGroups($aclId);
updateHostexcludes($aclId);
updateServiceCategories($aclId);
updateHostCategories($aclId);
updateServiceGroups($aclId);
updateMetaServices($aclId);
updateImageFolders($aclId);
updatePollers($aclId);
$submittedValues = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($submittedValues);
$centreon->CentreonLogAction->insertLog(
'resource access',
$aclId,
$submittedValues['acl_res_name'],
'c',
$fields,
);
}
/**
* Insert ACL entry
*
* @throws RepositoryException
* @return int
*/
function insertLCAInDB(): int
{
global $form, $centreon;
$aclId = insertLCA();
updateGroups($aclId);
updateHosts($aclId);
updateHostGroups($aclId);
updateHostexcludes($aclId);
updateServiceCategories($aclId);
updateHostCategories($aclId);
updateServiceGroups($aclId);
updateMetaServices($aclId);
updateImageFolders($aclId);
updatePollers($aclId);
$submittedValues = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($submittedValues);
$centreon->CentreonLogAction->insertLog(
'resource access',
$aclId,
$submittedValues['acl_res_name'],
'a',
$fields,
);
return $aclId;
}
/**
* Insert LCA in DB
*
* @throws RepositoryException
*/
function insertLCA(): int
{
global $form, $pearDB;
$submittedValues = $form->getSubmitValues();
$resourceValues = sanitizeResourceParameters($submittedValues);
try {
$queryParameters = QueryParameters::create(
[
QueryParameter::string('aclResourceName', $resourceValues['acl_res_name']),
QueryParameter::string('aclResourceAlias', $resourceValues['acl_res_alias']),
QueryParameter::string('allHosts', $resourceValues['all_hosts']),
QueryParameter::string('allHostGroups', $resourceValues['all_hostgroups']),
QueryParameter::string('allServiceGroups', $resourceValues['all_servicegroups']),
QueryParameter::string('allImageFolders', $resourceValues['all_image_folders']),
QueryParameter::string('aclResourceActivate', $resourceValues['acl_res_activate']),
QueryParameter::string('aclResourceComment', $resourceValues['acl_res_comment']),
]
);
$pearDB->insert(
<<<'SQL'
INSERT INTO `acl_resources`
(
acl_res_name,
acl_res_alias,
all_hosts,
all_hostgroups,
all_servicegroups,
all_image_folders,
acl_res_activate,
changed,
acl_res_comment
)
VALUES
(
:aclResourceName,
:aclResourceAlias,
:allHosts,
:allHostGroups,
:allServiceGroups,
:allImageFolders,
:aclResourceActivate,
1,
:aclResourceComment
)
SQL,
$queryParameters
);
return (int) $pearDB->getLastInsertId();
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to insert ACL resource in database',
context: ['submitted_values' => $resourceValues],
previous: $e
);
}
}
/**
* Update resource ACL in DB
*
* @param int|null $aclId
*
* @throws RepositoryException
*/
function updateLCA(?int $aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
$submittedValues = $form->getSubmitValues();
$resourceValues = sanitizeResourceParameters($submittedValues);
try {
$pearDB->update(
<<<'SQL'
UPDATE `acl_resources`
SET
acl_res_name = :aclResourceName,
acl_res_alias = :aclResourceAlias,
all_hosts = :allHosts,
all_hostgroups = :allHostGroups,
all_servicegroups = :allServiceGroups,
all_image_folders = :allImageFolders,
acl_res_activate = :aclResourceActivate,
acl_res_comment = :aclResourceComment,
changed = 1
WHERE acl_res_id = :aclResourceId
SQL,
QueryParameters::create(
[
QueryParameter::string('aclResourceName', $resourceValues['acl_res_name']),
QueryParameter::string('aclResourceAlias', $resourceValues['acl_res_alias']),
QueryParameter::string('allHosts', $resourceValues['all_hosts']),
QueryParameter::string('allHostGroups', $resourceValues['all_hostgroups']),
QueryParameter::string('allServiceGroups', $resourceValues['all_servicegroups']),
QueryParameter::string('allImageFolders', $resourceValues['all_image_folders']),
QueryParameter::string('aclResourceActivate', $resourceValues['acl_res_activate']),
QueryParameter::string('aclResourceComment', $resourceValues['acl_res_comment']),
QueryParameter::int('aclResourceId', $aclId),
]
)
);
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL resource in database',
context: ['submitted_values' => $resourceValues],
previous: $e
);
}
}
/** ****************
*
* @param int|null $aclId
*
* @throws RepositoryException
* @return void
*/
function updateGroups($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_res_group_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$aclGroupsSubmitted = $form->getSubmitValue('acl_groups');
$insertParameters = [];
if (is_array($aclGroupsSubmitted) && $aclGroupsSubmitted !== []) {
foreach ($aclGroupsSubmitted as $index => $aclGroupId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('acl_group' . $index, (int) $aclGroupId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_res_group_relations',
columns: [
'acl_res_id',
'acl_group_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL groups in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateHosts($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_host_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$hostsSubmitted = $form->getSubmitValue('acl_hosts');
$insertParameters = [];
if (is_array($hostsSubmitted) && $hostsSubmitted !== []) {
foreach ($hostsSubmitted as $index => $hostId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('host_host_id' . $index, (int) $hostId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_host_relations',
columns: [
'acl_res_id',
'host_host_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL hosts in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* @param int|null $aclId
*
* @throws RepositoryException
* @return void
*/
function updateImageFolders($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$insertParameters = [];
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_image_folder_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$imageFoldersSubmitted = $form->getSubmitValue('acl_image_folder');
// Find directory IDs for system directories that are dashboards, centreon-map, ppm
$systemDirectoryIds = $pearDB->fetchFirstColumn(
"SELECT dir_id FROM view_img_dir WHERE dir_name IN ('centreon-map', 'dashboards', 'ppm')"
);
foreach ($systemDirectoryIds as $systemDirectoryId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('directory_id' . $systemDirectoryId, (int) $systemDirectoryId),
]);
}
if (is_array($imageFoldersSubmitted) && $imageFoldersSubmitted !== []) {
foreach ($imageFoldersSubmitted as $imageFolderId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('directory_id' . $imageFolderId, (int) $imageFolderId),
]);
}
}
if ($insertParameters !== []) {
$pearDB->batchInsert(
tableName: 'acl_resources_image_folder_relations',
columns: [
'acl_res_id',
'dir_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL image folders in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updatePollers($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_poller_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$pollersSubmitted = $form->getSubmitValue('acl_pollers');
$insertParameters = [];
if (is_array($pollersSubmitted) && $pollersSubmitted !== []) {
foreach ($pollersSubmitted as $index => $pollerId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('poller_id' . $index, (int) $pollerId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_poller_relations',
columns: [
'acl_res_id',
'poller_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL pollers in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateHostexcludes($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_hostex_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$hostsToExcludeSubmitted = $form->getSubmitValue('acl_hostexclude');
$insertParameters = [];
if (is_array($hostsToExcludeSubmitted) && $hostsToExcludeSubmitted !== []) {
foreach ($hostsToExcludeSubmitted as $index => $hostId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('host_host_id' . $index, (int) $hostId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_hostex_relations',
columns: [
'acl_res_id',
'host_host_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL host excludes in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateHostGroups($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_hg_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$hostGroupsSubmitted = $form->getSubmitValue('acl_hostgroup');
$insertParameters = [];
if (is_array($hostGroupsSubmitted) && $hostGroupsSubmitted !== []) {
foreach ($hostGroupsSubmitted as $index => $hostGroupId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('hg_hg_id' . $index, (int) $hostGroupId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_hg_relations',
columns: [
'acl_res_id',
'hg_hg_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL host groups in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* Update Service categories entries in DB
*
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateServiceCategories($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_sc_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$serviceCategoriesSubmitted = $form->getSubmitValue('acl_sc');
$insertParameters = [];
if (is_array($serviceCategoriesSubmitted) && $serviceCategoriesSubmitted !== []) {
foreach ($serviceCategoriesSubmitted as $index => $serviceCategoryId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('sc_id' . $index, (int) $serviceCategoryId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_sc_relations',
columns: [
'acl_res_id',
'sc_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL service categories in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* Update HC entries in DB
*
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateHostCategories($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_hc_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$hostCategoriesSubmitted = $form->getSubmitValue('acl_hc');
$insertParameters = [];
if (is_array($hostCategoriesSubmitted) && $hostCategoriesSubmitted !== []) {
foreach ($hostCategoriesSubmitted as $index => $hostCategoryId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('hc_id' . $index, (int) $hostCategoryId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_hc_relations',
columns: [
'acl_res_id',
'hc_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL host categories in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* Update Service groups entries in DB
*
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateServiceGroups($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_sg_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$serviceGroupsSubmitted = $form->getSubmitValue('acl_sg');
$insertParameters = [];
if (is_array($serviceGroupsSubmitted) && $serviceGroupsSubmitted !== []) {
foreach ($serviceGroupsSubmitted as $index => $serviceGroupId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('sg_id' . $index, (int) $serviceGroupId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_sg_relations',
columns: [
'acl_res_id',
'sg_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
message: 'Unable to update ACL service groups in database',
context: ['acl_id' => $aclId],
previous: $e
);
}
}
/**
* Update Meta services entries in DB
*
* @param null|int $aclId
*
* @throws RepositoryException
* @return void
*/
function updateMetaServices($aclId = null): void
{
global $form, $pearDB;
if (! $aclId) {
return;
}
try {
$aclResourceId = QueryParameter::int('aclResourceId', $aclId);
$pearDB->delete(
'DELETE FROM acl_resources_meta_relations WHERE acl_res_id = :aclResourceId',
QueryParameters::create([$aclResourceId]),
);
$metaServicesSubmitted = $form->getSubmitValue('acl_meta');
$insertParameters = [];
if (is_array($metaServicesSubmitted) && $metaServicesSubmitted !== []) {
foreach ($metaServicesSubmitted as $index => $metaServiceId) {
$insertParameters[] = QueryParameters::create([
$aclResourceId,
QueryParameter::int('meta_id' . $index, (int) $metaServiceId),
]);
}
$pearDB->batchInsert(
tableName: 'acl_resources_meta_relations',
columns: [
'acl_res_id',
'meta_id',
],
batchInsertParameters: BatchInsertParameters::create($insertParameters),
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/groupsACL/groupsConfig.php | centreon/www/include/options/accessLists/groupsACL/groupsConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/options/accessLists/groupsACL/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
function sanitize_input_array(array $inputArray): array
{
$sanitizedArray = [];
foreach ($inputArray as $key => $value) {
$key = filter_var($key, FILTER_VALIDATE_INT);
$value = filter_var($value, FILTER_VALIDATE_INT);
if ($key !== false && $value !== false) {
$sanitizedArray[$key] = $value;
}
}
return $sanitizedArray;
}
$dupNbr = $_GET['dupNbr'] ?? $_POST['dupNbr'] ?? null;
$dupNbr = is_array($dupNbr) ? sanitize_input_array($dupNbr) : [];
$select = $_GET['select'] ?? $_POST['select'] ?? null;
$select = is_array($select) ? sanitize_input_array($select) : [];
$acl_group_id = filter_var($_GET['acl_group_id'] ?? $_POST['acl_group_id'] ?? null, FILTER_VALIDATE_INT) ?? null;
// Caution $o may already be set from the GET or from the POST.
$postO = filter_var(
$_POST['o1'] ?? $_POST['o2'] ?? $o ?? null,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => '/^(a|c|d|m|s|u|w)$/']]
);
if ($postO !== false) {
$o = $postO;
}
switch ($o) {
case 'a':
// Add an access group
case 'w':
// Watch an access group
case 'c':
// Modify an access group
require_once $path . 'formGroupConfig.php';
break;
case 's':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableGroupInDB($acl_group_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Activate a contactgroup
case 'ms':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableGroupInDB(null, $select);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Activate n access group
case 'u':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableGroupInDB($acl_group_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Desactivate a contactgroup
case 'mu':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableGroupInDB(null, $select);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Desactivate n access group
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleGroupInDB($select, $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Duplicate n access group
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteGroupInDB($select);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroupConfig.php';
break; // Delete n access group
default:
require_once $path . 'listGroupConfig.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/options/accessLists/groupsACL/formGroupConfig.php | centreon/www/include/options/accessLists/groupsACL/formGroupConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
// Retrieve information
$group = [];
if (($o == 'c' || $o == 'w') && $acl_group_id) {
$DBRESULT = $pearDB->prepare('SELECT * FROM acl_groups WHERE acl_group_id = :aclGroupId LIMIT 1');
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$group = $DBRESULT->fetchRow();
// Set Contact Childs
$query = "SELECT DISTINCT contact_contact_id
FROM acl_group_contacts_relations
WHERE acl_group_id = :aclGroupId
AND contact_contact_id NOT IN
(SELECT contact_id FROM contact WHERE contact_admin = '1')";
$DBRESULT = $pearDB->prepare($query);
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
for ($i = 0; $contacts = $DBRESULT->fetchRow(); $i++) {
$group['cg_contacts'][$i] = $contacts['contact_contact_id'];
}
$DBRESULT->closeCursor();
// Set ContactGroup Childs
$query = 'SELECT DISTINCT cg_cg_id
FROM acl_group_contactgroups_relations
WHERE acl_group_id = :aclGroupId';
$DBRESULT = $pearDB->prepare($query);
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
for ($i = 0; $contactgroups = $DBRESULT->fetchRow(); $i++) {
$group['cg_contactGroups'][$i] = $contactgroups['cg_cg_id'];
}
$DBRESULT->closeCursor();
// Set Menu link List
$query = 'SELECT DISTINCT acl_topology_id
FROM acl_group_topology_relations
WHERE acl_group_id = :aclGroupId';
$DBRESULT = $pearDB->prepare($query);
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
$group['menuAccess'][$i] = $data['acl_topology_id'];
}
$DBRESULT->closeCursor();
// Set resources List
$query = 'SELECT DISTINCT argr.acl_res_id
FROM acl_res_group_relations argr, acl_resources ar
WHERE argr.acl_res_id = ar.acl_res_id
AND ar.locked = 0
AND argr.acl_group_id = :aclGroupId';
$DBRESULT = $pearDB->prepare($query);
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
$group['resourceAccess'][$i] = $data['acl_res_id'];
}
$DBRESULT->closeCursor();
// Set Action List
$query = 'SELECT DISTINCT acl_action_id
FROM acl_group_actions_relations
WHERE acl_group_id = :aclGroupId';
$DBRESULT = $pearDB->prepare($query);
$DBRESULT->bindValue('aclGroupId', $acl_group_id, PDO::PARAM_INT);
$DBRESULT->execute();
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
$group['actionAccess'][$i] = $data['acl_action_id'];
}
$DBRESULT->closeCursor();
}
// Database retrieve information for differents elements list we need on the page
// Contacts comes from DB -> Store in $contacts Array
$contacts = [];
$query = 'SELECT contact_id, contact_name '
. "FROM contact WHERE contact_admin = '0' "
. 'AND contact_register = 1 '
. 'ORDER BY contact_name';
$DBRESULT = $pearDB->query($query);
while ($contact = $DBRESULT->fetchRow()) {
$contacts[$contact['contact_id']] = CentreonUtils::escapeAll(
$contact['contact_name']
);
}
unset($contact);
$DBRESULT->closeCursor();
$cg = new CentreonContactgroup($pearDB);
$contactGroups = $cg->getListContactgroup(true);
// topology comes from DB -> Store in $contacts Array
$menus = [];
$DBRESULT = $pearDB->query('SELECT acl_topo_id, acl_topo_name FROM acl_topology ORDER BY acl_topo_name');
while ($topo = $DBRESULT->fetchRow()) {
$menus[$topo['acl_topo_id']] = CentreonUtils::escapeAll(
$topo['acl_topo_name']
);
}
unset($topo);
$DBRESULT->closeCursor();
// Action comes from DB -> Store in $contacts Array
$action = [];
$DBRESULT = $pearDB->query('SELECT acl_action_id, acl_action_name FROM acl_actions ORDER BY acl_action_name');
while ($data = $DBRESULT->fetchRow()) {
$action[$data['acl_action_id']] = CentreonUtils::escapeAll(
$data['acl_action_name']
);
}
unset($data);
$DBRESULT->closeCursor();
// Resources comes from DB -> Store in $contacts Array
$resources = [];
$query = 'SELECT acl_res_id, acl_res_name '
. 'FROM acl_resources '
. 'WHERE locked = 0 '
. 'ORDER BY acl_res_name';
$DBRESULT = $pearDB->query($query);
while ($res = $DBRESULT->fetchRow()) {
$resources[$res['acl_res_id']] = CentreonUtils::escapeAll(
$res['acl_res_name']
);
}
unset($res);
$DBRESULT->closeCursor();
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 130px;'];
$attrsTextarea = ['rows' => '6', 'cols' => '150'];
$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=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Group'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Group'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Group'));
}
// Contact basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'acl_group_name', _('Group Name'), $attrsText);
$form->addElement('text', 'acl_group_alias', _('Alias'), $attrsText);
// Contacts Selection
$form->addElement('header', 'notification', _('Relations'));
$form->addElement('header', 'menu', _('Menu access list link'));
$form->addElement('header', 'resource', _('Resources access list link'));
$form->addElement('header', 'actions', _('Action access list link'));
$ams1 = $form->addElement(
'advmultiselect',
'cg_contacts',
[_('Linked Contacts'), _('Available'), _('Selected')],
$contacts,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$ams1 = $form->addElement(
'advmultiselect',
'cg_contactGroups',
[_('Linked Contact Groups'), _('Available'), _('Selected')],
$contactGroups,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$ams1 = $form->addElement(
'advmultiselect',
'menuAccess',
[_('Menu access'), _('Available'), _('Selected')],
$menus,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$ams1 = $form->addElement(
'advmultiselect',
'actionAccess',
[_('Actions access'), _('Available'), _('Selected')],
$action,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$ams1 = $form->addElement(
'advmultiselect',
'resourceAccess',
[_('Resources access'), _('Available'), _('Selected')],
$resources,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$groupActivation[] = $form->createElement('radio', 'acl_group_activate', null, _('Enabled'), '1');
$groupActivation[] = $form->createElement('radio', 'acl_group_activate', null, _('Disabled'), '0');
$form->addGroup($groupActivation, 'acl_group_activate', _('Status'), ' ');
$form->setDefaults(['acl_group_activate' => '1']);
$tab = [];
$tab[] = $form->createElement('radio', 'action', null, _('List'), '1');
$tab[] = $form->createElement('radio', 'action', null, _('Form'), '0');
$form->addGroup($tab, 'action', _('Post Validation'), ' ');
$form->setDefaults(['action' => '1']);
$form->addElement('hidden', 'acl_group_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['acl_group_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('acl_group_name', 'myReplace');
$form->addRule('acl_group_name', _('Compulsory Name'), 'required');
$form->addRule('acl_group_alias', _('Compulsory Alias'), 'required');
$form->registerRule('exist', 'callback', 'testGroupExistence');
$form->addRule('acl_group_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->registerRule('cg_group_exists', 'callback', 'testCg');
$form->addRule(
'cg_contactGroups',
_(
'Contactgroups exists. If you try to use a LDAP contactgroup, '
. 'please verified if a Centreon contactgroup has the same name.'
),
'cg_group_exists'
);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Define tab title
$tpl->assign('sort1', _('Group Information'));
$tpl->assign('sort2', _('Authorizations information'));
// 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);
// Just watch a Contact Group information
if ($o == 'w') {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&cg_id=' . $group_id . "'"]
);
$form->setDefaults($group);
$form->freeze();
} elseif ($o == 'c') {
// Modify a Contact Group information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($group);
} elseif ($o == 'a') {
// Add a Contact Group 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()) {
$groupObj = $form->getElement('acl_group_id');
if ($form->getSubmitValue('submitA')) {
$groupObj->setValue(insertGroupInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateGroupInDB($groupObj->getValue());
}
$o = null;
$valid = true;
}
$action = $form->getSubmitValue('action');
if ($valid) {
require_once $path . 'listGroupConfig.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <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('formGroupConfig.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/options/accessLists/groupsACL/listGroupConfig.php | centreon/www/include/options/accessLists/groupsACL/listGroupConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
$searchStr = '';
$search = null;
if (isset($_POST['searchACLG'])) {
$search = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchACLG']);
$centreon->historySearch[$url] = $search;
} elseif (isset($_GET['searchACLG'])) {
$search = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['searchACLG']);
$centreon->historySearch[$url] = $search;
} elseif (isset($centreon->historySearch[$url])) {
$search = $centreon->historySearch[$url];
}
if ($search) {
$searchStr .= 'AND (acl_group_name LIKE :search OR acl_group_alias LIKE :search)';
}
$rq = "
SELECT SQL_CALC_FOUND_ROWS acl_group_id, acl_group_name, acl_group_alias, acl_group_activate
FROM acl_groups
WHERE cloud_specific = 0 {$searchStr}
ORDER BY acl_group_name LIMIT :num, :limit
";
$statement = $pearDB->prepare($rq);
if ($search) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->bindValue(':num', $num * $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$search = tidySearchKey($search, $advanced_search);
$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_contacts', _('Contacts'));
$tpl->assign('headerMenu_contactgroups', _('Contact Groups'));
$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';
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $group = $statement->fetchRow(); $i++) {
$selectedElements = $form->addElement('checkbox', 'select[' . $group['acl_group_id'] . ']');
if ($group['acl_group_activate']) {
$moptions = "<a href='main.php?p=" . $p . '&acl_group_id=' . $group['acl_group_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_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 . '&acl_group_id=' . $group['acl_group_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$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["
. $group['acl_group_id'] . "]' />";
// Contacts
$ctNbr = [];
$rq2 = 'SELECT COUNT(*) AS nbr FROM acl_group_contacts_relations WHERE acl_group_id = :aclGroupId ';
$dbResult2 = $pearDB->prepare($rq2);
$dbResult2->bindValue(':aclGroupId', $group['acl_group_id'], PDO::PARAM_INT);
$dbResult2->execute();
$ctNbr = $dbResult2->fetchRow();
$dbResult2->closeCursor();
$cgNbr = [];
$rq3 = 'SELECT COUNT(*) AS nbr FROM acl_group_contactgroups_relations WHERE acl_group_id = :aclGroupId ';
$dbResult3 = $pearDB->prepare($rq3);
$dbResult3->bindValue('aclGroupId', $group['acl_group_id'], PDO::PARAM_INT);
$dbResult3->execute();
$cgNbr = $dbResult3->fetchRow();
$dbResult3->closeCursor();
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeAll(
$group['acl_group_name']
), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&acl_group_id=' . $group['acl_group_id'], 'RowMenu_desc' => CentreonUtils::escapeAll(
$group['acl_group_alias']
), 'RowMenu_contacts' => $ctNbr['nbr'], 'RowMenu_contactgroups' => $cgNbr['nbr'], 'RowMenu_status' => $group['acl_group_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $group['acl_group_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 ?')]
);
// Toolbar select lgd_more_actions
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['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 || "
. "this.form.elements['{$option}'].selectedIndex == 4) {"
. "setO(this.form.elements['{$option}'].value); submit();}"];
$form->addElement('select', $option, null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')], $attrs1);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchACLG', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listGroupConfig.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/options/accessLists/groupsACL/help.php | centreon/www/include/options/accessLists/groupsACL/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_group_name'] = dgettext('help', 'Name of access group.');
$help['tip_alias'] = dgettext('help', 'Alias of access group.');
/**
* Relations
*/
$help['tip_linked_contacts'] = dgettext('help', 'Implied users.');
$help['tip_linked_contact_groups'] = dgettext('help', 'Implied user groups.');
/**
* Additional Information
*/
$help['tip_status'] = dgettext('help', 'Enable or disable the access group.');
/**
* Resources access list link
*/
$help['tip_resources_access'] = dgettext('help', 'ACL resource rules that are linked to the access group.');
/**
* Menu access list link
*/
$help['tip_menu_access'] = dgettext('help', 'ACL menu rules that are linked to the access group.');
/**
* Action access list link
*/
$help['tip_actions_access'] = dgettext('help', 'ACL action rules that are linked to the access group.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/groupsACL/DB-Func.php | centreon/www/include/options/accessLists/groupsACL/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();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
/**
* Set the Acl group changed flag to 1
*
* @param $db CentreonDB
* @param $aclGroupId int
*/
function setAclGroupChanged($db, $aclGroupId)
{
$prepare = $db->prepare(
"UPDATE acl_groups SET acl_group_changed = '1' WHERE acl_group_id = :id"
);
$prepare->bindValue(':id', $aclGroupId, PDO::PARAM_INT);
$prepare->execute();
}
/**
* Test if group exists
*
* @param null $name
* @return bool
*/
function testGroupExistence($name = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('acl_group_id');
}
$query = 'SELECT acl_group_id, acl_group_name '
. 'FROM acl_groups '
. "WHERE acl_group_name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "' ";
$dbResult = $pearDB->query($query);
$cg = $dbResult->fetch();
if ($dbResult->rowCount() >= 1 && $cg['acl_group_id'] == $id) {
return true;
}
return ! ($dbResult->rowCount() >= 1 && $cg['acl_group_id'] != $id);
// Duplicate entry
}
/**
* @param null $acl_group_id
* @param array $groups
*/
function enableGroupInDB($acl_group_id = null, $groups = [])
{
global $pearDB, $centreon;
if (! $acl_group_id && ! count($groups)) {
return;
}
if ($acl_group_id) {
$groups = [$acl_group_id => '1'];
}
foreach ($groups as $key => $value) {
$dbResult = $pearDB->prepare(
<<<'SQL'
UPDATE acl_groups
SET acl_group_activate = '1',
acl_group_changed = '1'
WHERE acl_group_id = :aclGroupId
SQL
);
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$dbResult = $pearDB->prepare(
'SELECT acl_group_name FROM `acl_groups`
WHERE acl_group_id = :aclGroupId LIMIT 1'
);
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$row = $dbResult->fetch();
$centreon->CentreonLogAction->insertLog('access group', (int) $key, $row['acl_group_name'], 'enable');
}
}
/**
* @param null $acl_group_id
* @param array $groups
*/
function disableGroupInDB($acl_group_id = null, $groups = [])
{
global $pearDB, $centreon;
if (! $acl_group_id && ! count($groups)) {
return;
}
if ($acl_group_id) {
$groups = [$acl_group_id => '1'];
}
foreach ($groups as $key => $value) {
$dbResult = $pearDB->prepare(
"UPDATE acl_groups SET acl_group_activate = '0' WHERE acl_group_id = :aclGroupId"
);
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$dbResult = $pearDB->prepare(
'SELECT acl_group_name FROM `acl_groups` WHERE acl_group_id = :aclGroupId LIMIT 1'
);
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$row = $dbResult->fetch();
$centreon->CentreonLogAction->insertLog('access group', (int) $key, $row['acl_group_name'], 'disable');
}
}
/**
* Delete the selected group in DB
* @param $groups
*/
function deleteGroupInDB($groups = [])
{
global $pearDB, $centreon;
foreach ($groups as $key => $value) {
$dbResult = $pearDB->prepare(
'SELECT acl_group_name FROM `acl_groups` WHERE acl_group_id = :aclGroupId LIMIT 1'
);
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$row = $dbResult->fetch();
$dbResult = $pearDB->prepare('DELETE FROM acl_groups WHERE acl_group_id = :aclGroupId');
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$centreon->CentreonLogAction->insertLog('access group', (int) $key, $row['acl_group_name'], 'd');
}
}
/**
* Duplicate the selected group
* @param $groups
* @param $nbrDup
*/
function multipleGroupInDB($groups = [], $nbrDup = [])
{
global $pearDB, $centreon;
foreach ($groups as $key => $value) {
$dbResult = $pearDB->prepare('SELECT * FROM acl_groups WHERE acl_group_id = :aclGroupId LIMIT 1');
$dbResult->bindValue('aclGroupId', $key, PDO::PARAM_INT);
$dbResult->execute();
$row = $dbResult->fetch();
$row['acl_group_id'] = '';
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'acl_group_name') {
$acl_group_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'acl_group_id') {
$fields[$key2] = $value2;
}
if (isset($acl_group_name)) {
$fields['acl_group_name'] = $acl_group_name;
}
}
if (testGroupExistence($acl_group_name)) {
$rq = $val ? 'INSERT INTO acl_groups VALUES (' . $val . ')' : null;
$pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(acl_group_id) FROM acl_groups');
$maxId = $dbResult->fetch();
$dbResult->closeCursor();
// Duplicate Links
duplicateContacts($key, $maxId['MAX(acl_group_id)'], $pearDB);
duplicateContactGroups($key, $maxId['MAX(acl_group_id)'], $pearDB);
duplicateResources($key, $maxId['MAX(acl_group_id)'], $pearDB);
duplicateActions($key, $maxId['MAX(acl_group_id)'], $pearDB);
duplicateMenus($key, $maxId['MAX(acl_group_id)'], $pearDB);
$centreon->CentreonLogAction->insertLog(
'access group',
$maxId['MAX(acl_group_id)'],
$acl_group_name,
'a',
$fields
);
}
}
}
}
/**
* Insert group in DB
* @param $ret
*/
function insertGroupInDB($ret = [])
{
global $form, $centreon;
$acl_group_id = insertGroup($ret);
updateGroupContacts($acl_group_id, $ret);
updateGroupContactGroups($acl_group_id);
updateGroupActions($acl_group_id);
updateGroupResources($acl_group_id);
updateGroupMenus($acl_group_id);
$ret = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('access group', $acl_group_id, $ret['acl_group_name'], 'a', $fields);
return $acl_group_id;
}
/**
* Insert a new access group
*
* @param $groupInfos Array containing group's informations
* @global $form HTML_QuickFormCustom
* @global $pearDB CentreonDB
* @return int Return id of the new access group
*/
function insertGroup($groupInfos)
{
global $form, $pearDB;
if (! count($groupInfos)) {
$groupInfos = $form->getSubmitValues();
}
$isAclGroupActivate = false;
if (isset($groupInfos['acl_group_activate'], $groupInfos['acl_group_activate']['acl_group_activate'])
&& $groupInfos['acl_group_activate']['acl_group_activate'] == '1'
) {
$isAclGroupActivate = true;
}
$request = 'INSERT INTO acl_groups '
. '(acl_group_name, acl_group_alias, acl_group_activate) '
. 'VALUES (:group_name, :group_alias, :is_activate)';
$prepare = $pearDB->prepare($request);
$prepare->bindValue(
':group_name',
$groupInfos['acl_group_name'],
PDO::PARAM_STR
);
$prepare->bindValue(
':group_alias',
$groupInfos['acl_group_alias'],
PDO::PARAM_STR
);
$prepare->bindValue(
':group_alias',
$groupInfos['acl_group_alias'],
PDO::PARAM_STR
);
$prepare->bindValue(
':is_activate',
($isAclGroupActivate ? '1' : '0'),
PDO::PARAM_STR
);
return $prepare->execute()
? $pearDB->lastInsertId()
: null;
}
/**
* Update Group in DB
* @param $acl_group_id
*/
function updateGroupInDB($acl_group_id = null)
{
if (! $acl_group_id) {
return;
}
global $form, $centreon;
updateGroup($acl_group_id);
updateGroupContacts($acl_group_id);
updateGroupContactGroups($acl_group_id);
updateGroupActions($acl_group_id);
updateGroupResources($acl_group_id);
updateGroupMenus($acl_group_id);
$ret = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('access group', $acl_group_id, $ret['acl_group_name'], 'c', $fields);
}
/**
* Update the selected group
*
* @param int $acl_group_id
* @param null|mixed $aclGroupId
* @global $form HTML_QuickFormCustom
* @global $pearDB CentreonDB
*/
function updateGroup($aclGroupId = null)
{
global $form, $pearDB;
if (is_null($aclGroupId)) {
return;
}
$groupInfos = $form->getSubmitValues();
$isAclGroupActivate = false;
if (isset($groupInfos['acl_group_activate'], $groupInfos['acl_group_activate']['acl_group_activate'])
&& $groupInfos['acl_group_activate']['acl_group_activate'] == '1'
) {
$isAclGroupActivate = true;
}
$request = 'UPDATE acl_groups '
. 'SET acl_group_name = :acl_group_name, '
. 'acl_group_alias = :acl_group_alias, '
. 'acl_group_activate = :is_activate '
. 'WHERE acl_group_id = :acl_group_id';
$prepare = $pearDB->prepare($request);
$prepare->bindValue(
':acl_group_name',
$groupInfos['acl_group_name'],
PDO::PARAM_STR
);
$prepare->bindValue(
':acl_group_alias',
$groupInfos['acl_group_alias'],
PDO::PARAM_STR
);
$prepare->bindValue(
':is_activate',
($isAclGroupActivate ? '1' : '0'),
PDO::PARAM_STR
);
$prepare->bindValue(
':acl_group_id',
$aclGroupId,
PDO::PARAM_INT
);
$prepare->execute();
setAclGroupChanged($pearDB, $aclGroupId);
}
/**
* Update Contacts lists
* @param $acl_group_id
* @param $ret
*/
function updateGroupContacts($acl_group_id, $ret = [])
{
global $form, $pearDB;
if (! $acl_group_id) {
return;
}
$rq = "DELETE FROM acl_group_contacts_relations WHERE acl_group_id = '" . $acl_group_id . "'";
$dbResult = $pearDB->query($rq);
if (isset($_POST['cg_contacts'])) {
foreach ($_POST['cg_contacts'] as $id) {
$rq = 'INSERT INTO acl_group_contacts_relations ';
$rq .= '(contact_contact_id, acl_group_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $acl_group_id . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* Update contact group list
* @param $acl_group_id
* @param $ret
*/
function updateGroupContactGroups($acl_group_id, $ret = [])
{
global $form, $pearDB;
if (! $acl_group_id) {
return;
}
$rq = "DELETE FROM acl_group_contactgroups_relations WHERE acl_group_id = '" . $acl_group_id . "'";
$dbResult = $pearDB->query($rq);
if (isset($_POST['cg_contactGroups'])) {
$cg = new CentreonContactgroup($pearDB);
foreach ($_POST['cg_contactGroups'] as $id) {
if (! is_numeric($id)) {
$res = $cg->insertLdapGroup($id);
if ($res != 0) {
$id = $res;
} else {
continue;
}
}
$rq = 'INSERT INTO acl_group_contactgroups_relations ';
$rq .= '(cg_cg_id, acl_group_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $acl_group_id . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* Update Group actions
* @param $acl_group_id
* @param $ret
*/
function updateGroupActions($acl_group_id, $ret = [])
{
global $form, $pearDB;
if (! $acl_group_id) {
return;
}
$rq = "DELETE FROM acl_group_actions_relations WHERE acl_group_id = '" . $acl_group_id . "'";
$dbResult = $pearDB->query($rq);
if (isset($_POST['actionAccess'])) {
foreach ($_POST['actionAccess'] as $id) {
$rq = 'INSERT INTO acl_group_actions_relations ';
$rq .= '(acl_action_id, acl_group_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $acl_group_id . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* Update Menu Access
* @param $acl_group_id
* @param $ret
*/
function updateGroupMenus($acl_group_id, $ret = [])
{
global $form, $pearDB;
if (! $acl_group_id) {
return;
}
$rq = "DELETE FROM acl_group_topology_relations WHERE acl_group_id = '" . $acl_group_id . "'";
$dbResult = $pearDB->query($rq);
if (isset($_POST['menuAccess'])) {
foreach ($_POST['menuAccess'] as $id) {
$rq = 'INSERT INTO acl_group_topology_relations ';
$rq .= '(acl_topology_id, acl_group_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $acl_group_id . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* Update Group ressources
* @param $acl_group_id
* @param $ret
*/
function updateGroupResources($acl_group_id, $ret = [])
{
global $form, $pearDB;
if (! $acl_group_id) {
return;
}
$query = 'DELETE argr '
. 'FROM acl_res_group_relations argr '
. 'JOIN acl_resources ar ON argr.acl_res_id = ar.acl_res_id '
. 'WHERE argr.acl_group_id = ' . $acl_group_id . ' '
. 'AND ar.locked = 0 ';
$pearDB->query($query);
if (isset($_POST['resourceAccess'])) {
foreach ($_POST['resourceAccess'] as $id) {
$rq = 'INSERT INTO acl_res_group_relations ';
$rq .= '(acl_res_id, acl_group_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $acl_group_id . "')";
$pearDB->query($rq);
}
}
}
/**
* Duplicate Contacts lists
* @param $acl_group_id
* @param $ret
* @param mixed $idTD
* @param mixed $acl_id
* @param mixed $pearDB
*/
function duplicateContacts($idTD, $acl_id, $pearDB)
{
$request = 'INSERT INTO acl_group_contacts_relations (contact_contact_id, acl_group_id) '
. 'SELECT contact_contact_id, :acl_group_id AS acl_group_id '
. 'FROM acl_group_contacts_relations '
. 'WHERE acl_group_id = :acl_group_id_td';
$statement = $pearDB->prepare($request);
$statement->bindValue(':acl_group_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_group_id_td', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* Duplicate Contactgroups lists
* @param $acl_group_id
* @param $ret
* @param mixed $idTD
* @param mixed $acl_id
* @param mixed $pearDB
*/
function duplicateContactGroups($idTD, $acl_id, $pearDB)
{
$request = 'INSERT INTO acl_group_contactgroups_relations (cg_cg_id, acl_group_id) '
. 'SELECT cg_cg_id, :acl_group_id AS acl_group_id '
. 'FROM acl_group_contactgroups_relations '
. 'WHERE acl_group_id = :acl_group_id_td';
$statement = $pearDB->prepare($request);
$statement->bindValue(':acl_group_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_group_id_td', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* Duplicate Resources lists
* @param $acl_group_id
* @param $ret
* @param mixed $idTD
* @param mixed $acl_id
* @param mixed $pearDB
*/
function duplicateResources($idTD, $acl_id, $pearDB)
{
$request = 'INSERT INTO acl_res_group_relations (acl_res_id, acl_group_id) '
. 'SELECT acl_res_id, :acl_group_id AS acl_group_id '
. 'FROM acl_res_group_relations '
. 'WHERE acl_group_id = :acl_group_id_td';
$statement = $pearDB->prepare($request);
$statement->bindValue(':acl_group_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_group_id_td', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* Duplicate Actions lists
* @param $acl_group_id
* @param $ret
* @param mixed $idTD
* @param mixed $acl_id
* @param mixed $pearDB
*/
function duplicateActions($idTD, $acl_id, $pearDB)
{
$request = 'INSERT INTO acl_group_actions_relations (acl_action_id, acl_group_id) '
. 'SELECT acl_action_id, :acl_group_id AS acl_group_id '
. 'FROM acl_group_actions_relations '
. 'WHERE acl_group_id = :acl_group_id_td';
$statement = $pearDB->prepare($request);
$statement->bindValue(':acl_group_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_group_id_td', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* Duplicate Menu lists
* @param $acl_group_id
* @param $ret
* @param mixed $idTD
* @param mixed $acl_id
* @param mixed $pearDB
*/
function duplicateMenus($idTD, $acl_id, $pearDB)
{
$request = 'INSERT INTO acl_group_topology_relations (acl_topology_id, acl_group_id) '
. 'SELECT acl_topology_id, :acl_group_id AS acl_group_id '
. 'FROM acl_group_topology_relations '
. 'WHERE acl_group_id = :acl_group_id_td';
$statement = $pearDB->prepare($request);
$statement->bindValue(':acl_group_id', (int) $acl_id, PDO::PARAM_INT);
$statement->bindValue(':acl_group_id_td', (int) $idTD, PDO::PARAM_INT);
$statement->execute();
}
/**
* Rule for test if a ldap contactgroup name already exists
*
* @param array $listCgs The list of contactgroups to validate
* @param mixed $list
* @return bool
*/
function testCg($list)
{
return CentreonContactgroup::verifiedExists($list);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/actionsACL/formActionsAccess.php | centreon/www/include/options/accessLists/actionsACL/formActionsAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
$informationsService = $dependencyInjector['centreon_remote.informations_service'];
$serverIsMaster = $informationsService->serverIsMaster();
// Database retrieve information for Modify a present "Action Access"
if (($o === ACL_ACTION_MODIFY) && $aclActionId) {
// 1. Get "Actions Rule" id selected by user
$statement = $pearDB->prepare(
'SELECT * FROM acl_actions WHERE acl_action_id = :aclActionId LIMIT 1'
);
$statement->bindValue(':aclActionId', $aclActionId, PDO::PARAM_INT);
$statement->execute();
$action_infos = [];
$action_infos = array_map('myDecode', $statement->fetch());
// 2. Get "Groups" id linked with the selected Rule in order to initialize the form
$statement = $pearDB->prepare(
'SELECT DISTINCT acl_group_id FROM acl_group_actions_relations '
. 'WHERE acl_action_id = :aclActionId'
);
$statement->bindValue(':aclActionId', $aclActionId, PDO::PARAM_INT);
$statement->execute();
$selected = [];
while ($contacts = $statement->fetch()) {
$selected[] = $contacts['acl_group_id'];
}
$action_infos['acl_groups'] = $selected;
$statement = $pearDB->prepare(
'SELECT acl_action_name FROM `acl_actions_rules` '
. 'WHERE `acl_action_rule_id` = :aclActionId'
);
$statement->bindValue(':aclActionId', $aclActionId, PDO::PARAM_INT);
$statement->execute();
$selected_actions = [];
while ($act = $statement->fetch()) {
$selected_actions[$act['acl_action_name']] = 1;
}
$statement->closeCursor();
}
// Database retrieve information for differents elements list we need on the page
// Groups list comes from Database and stores in $groups Array
$groups = [];
$DBRESULT = $pearDB->query('SELECT acl_group_id,acl_group_name FROM acl_groups ORDER BY acl_group_name');
while ($group = $DBRESULT->fetchRow()) {
$groups[$group['acl_group_id']] = CentreonUtils::escapeSecure(
$group['acl_group_name'],
CentreonUtils::ESCAPE_ALL
);
}
$DBRESULT->closeCursor();
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 220px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '60'];
$eTemplate = "<table style='border:0px;'><tr><td>{unselected}</td><td align='center'>{add}<br /><br /><br />"
. '{remove}</td><td>{selected}</td></tr></table>';
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === ACL_ACTION_ADD) {
$form->addElement('header', 'title', _('Add an Action'));
} elseif ($o === ACL_ACTION_MODIFY) {
$form->addElement('header', 'title', _('Modify an Action'));
} elseif ($o === ACL_ACTION_WATCH) {
$form->addElement('header', 'title', _('View an Action'));
}
// Basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'acl_action_name', _('Action Name'), $attrsText);
$form->addElement('text', 'acl_action_description', _('Description'), $attrsText);
// Services
if ($serverIsMaster) {
$form->addElement('checkbox', 'service_checks', _('Enable/Disable Checks for a service'));
$form->addElement('checkbox', 'service_notifications', _('Enable/Disable Notifications for a service'));
}
$form->addElement('checkbox', 'service_acknowledgement', _('Acknowledge a service'));
$form->addElement('checkbox', 'service_disacknowledgement', _('Disacknowledge a service'));
$form->addElement('checkbox', 'service_schedule_check', _('Re-schedule the next check for a service'));
$form->addElement('checkbox', 'service_schedule_forced_check', _('Re-schedule the next check for a service (Forced)'));
$form->addElement('checkbox', 'service_schedule_downtime', _('Schedule downtime for a service'));
$form->addElement('checkbox', 'service_comment', _('Add/Delete a comment for a service'));
if ($serverIsMaster) {
$form->addElement('checkbox', 'service_event_handler', _('Enable/Disable Event Handler for a service'));
$form->addElement('checkbox', 'service_flap_detection', _('Enable/Disable Flap Detection of a service'));
$form->addElement('checkbox', 'service_passive_checks', _('Enable/Disable passive checks of a service'));
}
$form->addElement('checkbox', 'service_submit_result', _('Submit result for a service'));
$form->addElement('checkbox', 'service_display_command', _('Display executed command by monitoring engine'));
// Hosts
if ($serverIsMaster) {
$form->addElement('checkbox', 'host_checks', _('Enable/Disable Checks for a host'));
$form->addElement('checkbox', 'host_notifications', _('Enable/Disable Notifications for a host'));
}
$form->addElement('checkbox', 'host_acknowledgement', _('Acknowledge a host'));
$form->addElement('checkbox', 'host_disacknowledgement', _('Disaknowledge a host'));
$form->addElement('checkbox', 'host_schedule_check', _('Schedule the check for a host'));
$form->addElement('checkbox', 'host_schedule_forced_check', _('Schedule the check for a host (Forced)'));
$form->addElement('checkbox', 'host_schedule_downtime', _('Schedule downtime for a host'));
$form->addElement('checkbox', 'host_comment', _('Add/Delete a comment for a host'));
if ($serverIsMaster) {
$form->addElement('checkbox', 'host_event_handler', _('Enable/Disable Event Handler for a host'));
$form->addElement('checkbox', 'host_flap_detection', _('Enable/Disable Flap Detection for a host'));
$form->addElement('checkbox', 'host_notifications_for_services', _('Enable/Disable Notifications services of a host'));
$form->addElement('checkbox', 'host_checks_for_services', _('Enable/Disable Checks services of a host'));
}
$form->addElement('checkbox', 'host_submit_result', _('Submit result for a host'));
// Global Nagios External Commands
$form->addElement('checkbox', 'global_shutdown', _('Shutdown Monitoring Engine'));
$form->addElement('checkbox', 'global_restart', _('Restart Monitoring Engine'));
$form->addElement('checkbox', 'global_notifications', _('Enable/Disable notifications'));
$form->addElement('checkbox', 'global_service_checks', _('Enable/Disable service checks'));
$form->addElement('checkbox', 'global_service_passive_checks', _('Enable/Disable passive service checks'));
$form->addElement('checkbox', 'global_host_checks', _('Enable/Disable host checks'));
$form->addElement('checkbox', 'global_host_passive_checks', _('Enable/Disable passive host checks'));
$form->addElement('checkbox', 'global_event_handler', _('Enable/Disable Event Handlers'));
$form->addElement('checkbox', 'global_flap_detection', _('Enable/Disable Flap Detection'));
$form->addElement('checkbox', 'global_service_obsess', _('Enable/Disable Obsessive service checks'));
$form->addElement('checkbox', 'global_host_obsess', _('Enable/Disable Obsessive host checks'));
$form->addElement('checkbox', 'global_perf_data', _('Enable/Disable Performance Data'));
// Global Functionnalities
$form->addElement('checkbox', 'top_counter', _('Display Top Counter'));
$form->addElement('checkbox', 'poller_stats', _('Display Top Counter pollers statistics'));
$form->addElement('checkbox', 'poller_listing', _('Display Poller Listing'));
// Configuration Actions
$form->addElement('checkbox', 'create_edit_poller_cfg', _('Create and edit pollers'));
$form->addElement('checkbox', 'delete_poller_cfg', _('Delete pollers'));
$form->addElement('checkbox', 'generate_cfg', _('Deploy configuration'));
$form->addElement('checkbox', 'generate_trap', _('Generate SNMP Trap configuration'));
$form->addElement('checkbox', 'all_service', '');
$form->addElement('checkbox', 'all_host', '');
$form->addElement('checkbox', 'all_engine', '');
$form->setDefaults(['hostComment' => 1]);
// Contacts Selection
$form->addElement('header', 'notification', _('Relations'));
$form->addElement('header', 'service_actions', _('Services Actions Access'));
$form->addElement('header', 'host_actions', _('Hosts Actions Access'));
$form->addElement('header', 'global_actions', _('Global Monitoring Engine Actions (External Process Commands)'));
$form->addElement('header', 'global_access', _('Global Functionalities Access'));
$form->addElement('header', 'poller_cfg_access', _('Poller Configuration Actions / Poller Management'));
$ams1 = $form->addElement('advmultiselect', 'acl_groups', _('Linked Groups'), $groups, $attrsAdvSelect, SORT_ASC);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
// Administration section
$form->addElement('header', 'administration', _('Administration'));
$form->addElement('checkbox', 'manage_tokens', _('Manage API tokens'));
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$groupActivation[] = $form->createElement('radio', 'acl_action_activate', null, _('Enabled'), '1');
$groupActivation[] = $form->createElement('radio', 'acl_action_activate', null, _('Disabled'), '0');
$form->addGroup($groupActivation, 'acl_action_activate', _('Status'), ' ');
$form->setDefaults(['acl_action_activate' => '1']);
$form->addElement('hidden', 'acl_action_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['acl_action_name']);
}
// Controls
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('acl_group_name', 'myReplace');
$form->addRule('acl_action_name', _('Compulsory Name'), 'required');
$form->addRule('acl_action_description', _('Compulsory Alias'), 'required');
$form->addRule('acl_groups', _('Compulsory Groups'), 'required');
$form->registerRule('exist', 'callback', 'testActionExistence');
$form->addRule('acl_action_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// End of form definition
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
// Modify an Action Group
if ($o === ACL_ACTION_MODIFY && isset($selected_actions, $action_infos)) {
$form->setDefaults($selected_actions);
$form->setDefaults($action_infos);
}
// Add an Action Group
if ($o === ACL_ACTION_ADD) {
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
} else {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate()) {
$groupObj = $form->getElement('acl_action_id');
if ($form->getSubmitValue('submitA')) {
$groupObj->setValue(insertActionInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateActionInDB($groupObj->getValue());
updateRulesActions($groupObj->getValue());
}
$o = null;
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&c_id=' . $groupObj->getValue() . "'"]
);
$form->freeze();
$valid = true;
}
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$tpl->assign('serverIsMaster', $serverIsMaster);
$action = $form->getSubmitValue('action');
if ($valid) {
require_once __DIR__ . '/listsActionsAccess.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <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('formActionsAccess.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/options/accessLists/actionsACL/listsActionsAccess.php | centreon/www/include/options/accessLists/actionsACL/listsActionsAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
$SearchStr = '';
$search = null;
if (isset($_POST['searchACLA'])) {
$search = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['searchACLA']);
$centreon->historySearch[$url] = $search;
} elseif (isset($_GET['searchACLA'])) {
$search = HtmlAnalyzer::sanitizeAndRemoveTags($_GET['searchACLA']);
$centreon->historySearch[$url] = $search;
} elseif (isset($centreon->historySearch[$url])) {
$search = $centreon->historySearch[$url];
}
if ($search) {
$SearchStr .= ' WHERE (acl_action_name LIKE :search OR acl_action_description LIKE :search)';
}
$rq = "
SELECT SQL_CALC_FOUND_ROWS acl_action_id, acl_action_name, acl_action_description, acl_action_activate
FROM acl_actions
{$SearchStr}
ORDER BY acl_action_name LIMIT :num, :limit
";
$statement = $pearDB->prepare($rq);
if ($search) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->bindValue(':num', $num * $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_alias', _('Description'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// end header menu
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $topo = $statement->fetchRow(); $i++) {
$selectedElements = $form->addElement('checkbox', 'select[' . $topo['acl_action_id'] . ']');
if ($topo['acl_action_activate']) {
$moptions = "<a href='main.php?p=" . $p . '&acl_action_id=' . $topo['acl_action_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_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 . '&acl_action_id=' . $topo['acl_action_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$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["
. $topo['acl_action_id'] . "]' />";
// Contacts
$elemArr[$i] = [
'MenuClass' => 'list_' . $style,
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => $topo['acl_action_name'],
'RowMenu_link' => 'main.php?p=' . $p . '&o=c&acl_action_id=' . $topo['acl_action_id'],
'RowMenu_alias' => $topo['acl_action_description'],
'RowMenu_status' => $topo['acl_action_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $topo['acl_action_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 ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['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 || "
. "this.form.elements['{$option}'].selectedIndex == 4) {"
. "setO(this.form.elements['{$option}'].value); submit();}"];
$form->addElement('select', $option, null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')], $attrs1);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchACLA', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listsActionsAccess.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/options/accessLists/actionsACL/help.php | centreon/www/include/options/accessLists/actionsACL/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_action_name'] = dgettext('help', 'Name of action rule.');
$help['tip_description'] = dgettext('help', 'Description of action rule.');
/**
* Relations
*/
$help['tip_linked_groups'] = dgettext('help', 'Implied ACL groups.');
/**
* Global Functionalities Access
*/
$help['tip_display_top_counter'] = dgettext(
'help',
'The monitoring overview will be displayed at the top of all pages.'
);
$help['tip_display_top_counter_pollers_statistics'] = dgettext(
'help',
'The monitoring poller status overview will be displayed at the top of all pages.'
);
$help['tip_display_poller_listing'] = dgettext(
'help',
'The poller filter will be available to users in the monitoring consoles.'
);
/**
* Poller configuration - Generation of configuration files
*/
$help['create_edit_pollers'] = dgettext(
'help',
'Allows user to perform “Add”, “Add (advanced)” and “Duplicate” actions on pollers.'
);
$help['delete_pollers'] = dgettext(
'help',
'Allows user to delete pollers.'
);
$help['deploy_pollers'] = dgettext(
'help',
'Allows user to deploy configuration.'
);
$help['tip_display_generate_trap'] = dgettext(
'help',
'Allows user to generate and export configuration, and restart centreontrapd process.'
);
/**
* Global Nagios Actions (External Process Commands)
*/
$help['tip_shutdown_nagios'] = dgettext('help', 'Allows users to stop the monitoring systems.');
$help['tip_restart_nagios'] = dgettext('help', 'Allows users to restart the monitoring systems.');
$help['tip_enable_disable_notifications'] = dgettext('help', 'Allows users to enable or disable notifications.');
$help['tip_enable_service_checks'] = dgettext('help', 'Allows users to enable or disable service checks.');
$help['tip_enable_passive_service_checks'] = dgettext(
'help',
'Allows users to enable or disable passive service checks.'
);
$help['tip_enable_host_checks'] = dgettext('help', 'Allows users to enable or disable host checks.');
$help['tip_enable_passive_host_checks'] = dgettext('help', 'Allows users to enable or disable passive host checks.');
$help['tip_enable_event_handlers'] = dgettext('help', 'Allows users to enable or disable event handlers.');
$help['tip_enable_flap_detection'] = dgettext('help', 'Allows users to enable or disable flap detection.');
$help['tip_enable_obsessive_service_checks'] = dgettext(
'help',
'Allows users to enable or disable obsessive service checks.'
);
$help['tip_enable_obsessive_host_checks'] = dgettext(
'help',
'Allows users to enable or disable obsessive host checks.'
);
$help['tip_enable_performance_data'] = dgettext(
'help',
'Allows users to enable or disable performance data processing.'
);
/**
* Services Actions Access
*/
$help['tip_enable_disable_checks_for_a_service'] = dgettext(
'help',
'Allows users to enable or disable checks of a service.'
);
$help['tip_enable_disable_notifications_for_a_service'] = dgettext(
'help',
'Allows users to enable or disable notifications of a service.'
);
$help['tip_acknowledge_a_service'] = dgettext('help', 'Allows users to acknowledge a service.');
$help['tip_disacknowledge_a_service'] = dgettext('help', 'Allows users to remove an acknowledgement from a service.');
$help['tip_re_schedule_the_next_check_for_a_service'] = dgettext(
'help',
'Allows users to re-schedule next check of a service.'
);
$help['tip_re_schedule_the_next_check_for_a_service_forced'] = dgettext(
'help',
'Allows users to re-schedule next check of a service by placing its priority to the top.'
);
$help['tip_schedule_downtime_for_a_service'] = dgettext('help', 'Allows users to schedule downtime on a service.');
$help['tip_add_delete_a_comment_for_a_service'] = dgettext(
'help',
'Allows users to add or delete a comment of a service.'
);
$help['tip_enable_disable_event_handler_for_a_service'] = dgettext(
'help',
'Allows users to enable or disable the event handler processing of a service.'
);
$help['tip_enable_disable_flap_detection_of_a_service'] = dgettext(
'help',
'Allows users to enable or disable flap detection of a service.'
);
$help['tip_enable_disable_passive_checks_of_a_service'] = dgettext(
'help',
'Allows users to enable or disable passive checks of a service.'
);
$help['tip_submit_result_for_a_service'] = dgettext('help', 'Allows users to submit result to a service.');
/**
* Hosts Actions Access
*/
$help['tip_enable_disable_checks_for_a_host'] = dgettext('help', 'Allows users to enable or disable checks of a host.');
$help['tip_enable_disable_notifications_for_a_host'] = dgettext(
'help',
'Allows users to enable or disable notifications of a host.'
);
$help['tip_acknowledge_a_host'] = dgettext('help', 'Allows users to acknowledge a host.');
$help['tip_disacknowledge_a_host'] = dgettext('help', 'Allows users to remove an acknowledgement from a host.');
$help['tip_schedule_the_check_for_a_host'] = dgettext('help', 'Allows users to re-schedule next check of a host.');
$help['tip_schedule_the_check_for_a_host_forced'] = dgettext(
'help',
'Allows users to re-schedule next check of a host by placing its priority to the top.'
);
$help['tip_schedule_downtime_for_a_host'] = dgettext('help', 'Allows users to schedule downtime on a host.');
$help['tip_add_delete_a_comment_for_a_host'] = dgettext('help', 'Allows users to add or delete a comment of a host.');
$help['tip_enable_disable_event_handler_for_a_host'] = dgettext(
'help',
'Allows users to enable or disable the event handler processing of a host.'
);
$help['tip_enable_disable_flap_detection_for_a_host'] = dgettext(
'help',
'Allows users to enable or disable flap detection of a host.'
);
$help['tip_enable_disable_checks_services_of_a_host'] = dgettext(
'help',
'Allows users to enable or disable all service checks of a host.'
);
$help['tip_enable_disable_notifications_services_of_a_host'] = dgettext(
'help',
'Allows users to enable or disable service notifications of a host.'
);
$help['tip_submit_result_for_a_host'] = dgettext('help', 'Allows users to submit result to a host.');
/**
* Additional Information
*/
$help['tip_status'] = dgettext('help', 'Enable or disable the ACL action rule.');
$help['tip_manage_tokens'] = dgettext('help', 'Provided that the user can access the API Tokens menu, this action will allow them to not only list, create and delete tokens for themselves, but also manage tokens for other users.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/actionsACL/actionsConfig.php | centreon/www/include/options/accessLists/actionsACL/actionsConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
$aclActionId = filter_var(
$_GET['acl_action_id'] ?? $_POST['acl_action_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';
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] != '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] != '') {
$o = $_POST['o2'];
}
}
const ACL_ACTION_ADD = 'a';
const ACL_ACTION_WATCH = 'w';
const ACL_ACTION_MODIFY = 'c';
const ACL_ACTION_ACTIVATION = 's';
const ACL_ACTION_MASSIVE_ACTIVATION = 'ms';
const ACL_ACTION_DEACTIVATION = 'u';
const ACL_ACTION_MASSIVE_DEACTIVATION = 'mu';
const ACL_ACTION_DUPLICATION = 'm';
const ACL_ACTION_DELETION = 'd';
switch ($o) {
case ACL_ACTION_ADD:
case ACL_ACTION_WATCH:
case ACL_ACTION_MODIFY:
require_once __DIR__ . '/formActionsAccess.php';
break; // Modify an Actions Access
case ACL_ACTION_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableActionInDB($aclActionId);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Activate an Actions Access
case ACL_ACTION_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableActionInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Activate an Actions Access
case ACL_ACTION_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableActionInDB($aclActionId);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Desactivate an an Actions Access
case ACL_ACTION_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableActionInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Desactivate n Actions Access
case ACL_ACTION_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleActionInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Duplicate n Actions Access
case ACL_ACTION_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteActionInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listsActionsAccess.php';
break; // Delete n Actions Access
default:
require_once __DIR__ . '/listsActionsAccess.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/options/accessLists/actionsACL/DB-Func.php | centreon/www/include/options/accessLists/actionsACL/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface;
if (! isset($centreon)) {
exit();
}
/**
* @param null $name
* @return bool
*/
function testActionExistence($name = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('acl_action_id');
}
$query = 'SELECT acl_action_id, acl_action_name FROM acl_actions '
. "WHERE acl_action_name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'";
$dbResult = $pearDB->query($query);
$action = $dbResult->fetch();
// Modif case
if ($dbResult->rowCount() >= 1 && $action['acl_action_id'] == $id) {
return true;
} // Duplicate entry
return ! ($dbResult->rowCount() >= 1 && $action['acl_action_id'] != $id);
}
/**
* @param null $aclActionId
* @param array $actions
*/
function enableActionInDB($aclActionId = null, $actions = [])
{
if ($aclActionId === null && empty($actions)) {
return;
}
global $pearDB, $centreon;
if ($aclActionId) {
$actions = [$aclActionId => '1'];
}
$queryValues = [];
foreach ($actions as $key => $value) {
$sanitizedAclActionId = filter_var($key, FILTER_VALIDATE_INT);
if ($sanitizedAclActionId === false) {
throw new InvalidArgumentException('Invalid id');
}
$queryValues[':acl_action_id_' . $sanitizedAclActionId] = $sanitizedAclActionId;
$statement = $pearDB->prepare(
"UPDATE acl_actions SET acl_action_activate = '1' WHERE acl_action_id = :acl_action_id_"
. $sanitizedAclActionId
);
$statement->bindValue(
':acl_action_id_' . $sanitizedAclActionId,
$queryValues[':acl_action_id_' . $sanitizedAclActionId],
PDO::PARAM_INT
);
$statement->execute();
$statementSelect = $pearDB->prepare(
'SELECT acl_action_name FROM `acl_actions` WHERE acl_action_id = :acl_action_id_'
. $sanitizedAclActionId . ' LIMIT 1'
);
$statementSelect->bindValue(
':acl_action_id_' . $sanitizedAclActionId,
$queryValues[':acl_action_id_' . $sanitizedAclActionId],
PDO::PARAM_INT
);
$statementSelect->execute();
$row = $statementSelect->fetch();
$centreon->CentreonLogAction->insertLog(
'action access',
$sanitizedAclActionId,
$row['acl_action_name'],
'enable'
);
}
updateACLActionsForAuthentifiedUsers($queryValues);
}
/**
* @param null $aclActionId
* @param array $actions
*/
function disableActionInDB($aclActionId = null, $actions = [])
{
if ($aclActionId === null && empty($actions)) {
return;
}
global $pearDB, $centreon;
if ($aclActionId) {
$actions = [$aclActionId => '1'];
}
$queryValues = [];
foreach ($actions as $key => $value) {
$sanitizedAclActionId = filter_var($key, FILTER_VALIDATE_INT);
if ($sanitizedAclActionId === false) {
throw new InvalidArgumentException('Invalid id');
}
$queryValues[':acl_action_id_' . $sanitizedAclActionId] = $sanitizedAclActionId;
$statement = $pearDB->prepare(
"UPDATE acl_actions SET acl_action_activate = '0' WHERE acl_action_id = :acl_action_id_"
. $sanitizedAclActionId
);
$statement->bindValue(
':acl_action_id_' . $sanitizedAclActionId,
$queryValues[':acl_action_id_' . $sanitizedAclActionId],
PDO::PARAM_INT
);
$statement->execute();
$statementSelect = $pearDB->prepare(
'SELECT acl_action_name FROM `acl_actions` WHERE acl_action_id = :acl_action_id_'
. $sanitizedAclActionId . ' LIMIT 1'
);
$statementSelect->bindValue(
':acl_action_id_' . $sanitizedAclActionId,
$queryValues[':acl_action_id_' . $sanitizedAclActionId],
PDO::PARAM_INT
);
$statementSelect->execute();
$row = $statementSelect->fetch();
$centreon->CentreonLogAction->insertLog(
'action access',
$sanitizedAclActionId,
$row['acl_action_name'],
'disable'
);
}
updateACLActionsForAuthentifiedUsers($queryValues);
}
/**
* delete an action rules
* @param $actions
*/
function deleteActionInDB($actions = [])
{
global $pearDB, $centreon;
$aclGroupIds = [];
foreach ($actions as $key => $value) {
$sanitizedAclActionId = filter_var($key, FILTER_VALIDATE_INT);
if ($sanitizedAclActionId === false) {
throw new InvalidArgumentException('Invalid id');
}
$queryValues[':acl_action_id_' . $sanitizedAclActionId] = $sanitizedAclActionId;
$statement = $pearDB->prepare(
'SELECT acl_action_name FROM `acl_actions`
WHERE acl_action_id = :acl_action_id_' . $sanitizedAclActionId . ' LIMIT 1'
);
$statement->bindValue(
':acl_action_id_' . $sanitizedAclActionId,
$queryValues[':acl_action_id_' . $sanitizedAclActionId],
PDO::PARAM_INT
);
$statement->execute();
$row = $statement->fetch();
$aclActionIdQueryString = '(' . implode(', ', array_keys($queryValues)) . ')';
$statement = $pearDB->prepare(
"SELECT DISTINCT acl_group_id FROM acl_group_actions_relations
WHERE acl_action_id IN {$aclActionIdQueryString}"
);
foreach ($queryValues as $bindParameter => $bindValue) {
$statement->bindValue($bindParameter, $bindValue, PDO::PARAM_INT);
}
$statement->execute();
while ($result = $statement->fetch()) {
$aclGroupIds[] = (int) $result['acl_group_id'];
}
$pearDB->query("DELETE FROM acl_actions WHERE acl_action_id = '" . $key . "'");
$pearDB->query("DELETE FROM acl_actions_rules WHERE acl_action_rule_id = '" . $key . "'");
$pearDB->query("DELETE FROM acl_group_actions_relations WHERE acl_action_id = '" . $key . "'");
$centreon->CentreonLogAction->insertLog('action access', $key, $row['acl_action_name'], 'd');
}
flagUpdatedAclForAuthentifiedUsers($aclGroupIds);
}
/**
* Duplicate an action rules
* @param $actions
* @param $nbrDup
*/
function multipleActionInDB($actions = [], $nbrDup = [])
{
global $pearDB, $centreon;
foreach (array_keys($actions) as $key) {
$dbResult = $pearDB->query("SELECT * FROM acl_actions WHERE acl_action_id = '" . $key . "' LIMIT 1");
$row = $dbResult->fetch();
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$aclActionName = $row['acl_action_name'] . '_' . $i;
if (testActionExistence($aclActionName)) {
$pearDB->executeStatement(
<<<'SQL'
INSERT INTO acl_actions (acl_action_name, acl_action_description, acl_action_activate)
VALUES (:aclActionName, :aclActionDescription, :aclActionActivate)
SQL,
QueryParameters::create([
QueryParameter::string('aclActionName', $aclActionName),
QueryParameter::string(
'aclActionDescription',
$row['acl_action_description']
),
QueryParameter::string(
'aclActionActivate',
$row['acl_action_activate']
),
])
);
$dbResult = $pearDB->query('SELECT MAX(acl_action_id) FROM acl_actions');
$maxId = $dbResult->fetch();
$dbResult->closeCursor();
if (isset($maxId['MAX(acl_action_id)'])) {
$query = 'SELECT DISTINCT acl_group_id,acl_action_id FROM acl_group_actions_relations '
. " WHERE acl_action_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$query = 'INSERT INTO acl_group_actions_relations VALUES (:acl_action_id, :acl_group_id)';
$statement = $pearDB->prepare($query);
while ($cct = $dbResult->fetch()) {
$statement->bindValue(':acl_action_id', (int) $maxId['MAX(acl_action_id)'], PDO::PARAM_INT);
$statement->bindValue(':acl_group_id', (int) $cct['acl_group_id'], PDO::PARAM_INT);
$statement->execute();
}
// Duplicate Actions
$query = 'SELECT acl_action_rule_id,acl_action_name FROM acl_actions_rules '
. "WHERE acl_action_rule_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$query = 'INSERT INTO acl_actions_rules VALUES (NULL, :acl_action_id, :acl_action_name)';
$statement = $pearDB->prepare($query);
while ($acl = $dbResult->fetch()) {
$statement->bindValue(':acl_action_id', (int) $maxId['MAX(acl_action_id)'], PDO::PARAM_INT);
$statement->bindValue(':acl_action_name', $acl['acl_action_name'], PDO::PARAM_STR);
$statement->execute();
}
$dbResult->closeCursor();
$centreon->CentreonLogAction->insertLog(
'action access',
$maxId['MAX(acl_action_id)'],
$aclActionName,
'a',
[
'acl_action_name' => $aclActionName,
'acl_action_description' => $row['acl_action_description'],
'acl_action_activate' => $row['acl_action_activate'],
]
);
}
}
}
}
}
/**
* Insert all information in DB
* @param $ret
*/
function insertActionInDB($ret = [])
{
global $form, $centreon;
$aclActionId = insertAction($ret);
updateGroupActions($aclActionId, $ret);
updateRulesActions($aclActionId, $ret);
$ret = $form->getSubmitValues();
flagUpdatedAclForAuthentifiedUsers($ret['acl_groups']);
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('action access', $aclActionId, $ret['acl_action_name'], 'a', $fields);
return $aclActionId;
}
/**
* Insert actions
* @param $ret
*/
function insertAction($ret)
{
global $form, $pearDB;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$statement = $pearDB->prepare(
'INSERT INTO acl_actions (acl_action_name, acl_action_description, acl_action_activate) '
. 'VALUES (:aclActionName, :aclActionDescription, :aclActionActivate)'
);
$statement->bindValue(
':aclActionName',
htmlentities($ret['acl_action_name'], ENT_QUOTES, 'UTF-8'),
PDO::PARAM_STR
);
$statement->bindValue(
':aclActionDescription',
$ret['acl_action_description'],
PDO::PARAM_STR
);
$statement->bindValue(
':aclActionActivate',
htmlentities(
(
isset($ret['acl_action_activate'])
? $ret['acl_action_activate']['acl_action_activate']
: ''
),
ENT_QUOTES,
'UTF-8'
),
PDO::PARAM_STR
);
$statement->execute();
$dbResult = $pearDB->query('SELECT MAX(acl_action_id) FROM acl_actions');
$cg_id = $dbResult->fetch();
return $cg_id['MAX(acl_action_id)'];
}
/**
* Summary function
* @param $aclActionId
*/
function updateActionInDB($aclActionId = null)
{
global $form, $centreon;
if (! $aclActionId) {
return;
}
updateAction($aclActionId);
updateGroupActions($aclActionId);
$ret = $form->getSubmitValues();
flagUpdatedAclForAuthentifiedUsers($ret['acl_groups']);
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('action access', $aclActionId, $ret['acl_action_name'], 'c', $fields);
}
/**
* Update all Actions
* @param $aclActionId
*/
function updateAction($aclActionId = null)
{
if (! $aclActionId) {
return;
}
global $form, $pearDB;
$ret = $form->getSubmitValues();
$pearDB->executeStatement(
<<<'SQL'
UPDATE acl_actions
SET acl_action_name = :acl_action_name,
acl_action_description = :acl_action_description,
acl_action_activate = :acl_action_activate
WHERE acl_action_id = :acl_action_id
SQL,
QueryParameters::create([
QueryParameter::string('acl_action_name', $ret['acl_action_name']),
QueryParameter::string(
'acl_action_description',
$ret['acl_action_description']
),
QueryParameter::string(
'acl_action_activate',
$ret['acl_action_activate']['acl_action_activate']
),
QueryParameter::int('acl_action_id', $ret['acl_action_id']),
])
);
}
/**
* Update group action information in DB
* @param $aclActionId
* @param $ret
*/
function updateGroupActions($aclActionId, $ret = [])
{
if (! $aclActionId) {
return;
}
global $form, $pearDB;
$rq = 'DELETE FROM acl_group_actions_relations WHERE acl_action_id = :acl_action_id';
$statement = $pearDB->prepare($rq);
$statement->bindValue(':acl_action_id', (int) $aclActionId, PDO::PARAM_INT);
$statement->execute();
if (isset($_POST['acl_groups'])) {
foreach ($_POST['acl_groups'] as $id) {
$rq = 'INSERT INTO acl_group_actions_relations ';
$rq .= '(acl_group_id, acl_action_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $id . "', '" . $aclActionId . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* update all Rules in DB
* @param $aclActionId
* @param $ret
*/
function updateRulesActions($aclActionId, $ret = [])
{
global $form, $pearDB;
if (! $aclActionId) {
return;
}
$rq = 'DELETE FROM acl_actions_rules WHERE acl_action_rule_id = :acl_action_rule_id';
$statement = $pearDB->prepare($rq);
$statement->bindValue(':acl_action_rule_id', (int) $aclActionId, PDO::PARAM_INT);
$statement->execute();
$actions = [];
$actions = listActions();
foreach ($actions as $action) {
if (isset($_POST[$action])) {
$rq = 'INSERT INTO acl_actions_rules ';
$rq .= '(acl_action_rule_id, acl_action_name) ';
$rq .= 'VALUES ';
$rq .= "('" . $aclActionId . "', '" . $action . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* list all actions
*/
function listActions()
{
global $dependencyInjector;
$actions = [];
$informationsService = $dependencyInjector['centreon_remote.informations_service'];
$serverIsMaster = $informationsService->serverIsMaster();
// Global Functionnality access
$actions[] = 'poller_listing';
$actions[] = 'poller_stats';
$actions[] = 'top_counter';
// Services Actions
if ($serverIsMaster) {
$actions[] = 'service_checks';
$actions[] = 'service_notifications';
}
$actions[] = 'service_acknowledgement';
$actions[] = 'service_disacknowledgement';
$actions[] = 'service_schedule_check';
$actions[] = 'service_schedule_forced_check';
$actions[] = 'service_schedule_downtime';
$actions[] = 'service_comment';
if ($serverIsMaster) {
$actions[] = 'service_event_handler';
$actions[] = 'service_flap_detection';
$actions[] = 'service_passive_checks';
}
$actions[] = 'service_submit_result';
$actions[] = 'service_display_command';
// Hosts Actions
if ($serverIsMaster) {
$actions[] = 'host_checks';
$actions[] = 'host_notifications';
}
$actions[] = 'host_acknowledgement';
$actions[] = 'host_disacknowledgement';
$actions[] = 'host_schedule_check';
$actions[] = 'host_schedule_forced_check';
$actions[] = 'host_schedule_downtime';
$actions[] = 'host_comment';
if ($serverIsMaster) {
$actions[] = 'host_event_handler';
$actions[] = 'host_flap_detection';
$actions[] = 'host_checks_for_services';
$actions[] = 'host_notifications_for_services';
}
$actions[] = 'host_submit_result';
// Global Nagios External Commands
$actions[] = 'global_shutdown';
$actions[] = 'global_restart';
$actions[] = 'global_notifications';
$actions[] = 'global_service_checks';
$actions[] = 'global_service_passive_checks';
$actions[] = 'global_host_checks';
$actions[] = 'global_host_passive_checks';
$actions[] = 'global_event_handler';
$actions[] = 'global_flap_detection';
$actions[] = 'global_service_obsess';
$actions[] = 'global_host_obsess';
$actions[] = 'global_perf_data';
$actions[] = 'create_edit_poller_cfg';
$actions[] = 'delete_poller_cfg';
$actions[] = 'generate_cfg';
$actions[] = 'generate_trap';
$actions[] = 'manage_tokens';
return $actions;
}
/**
* Updates ACL actions for an authentified user from ACL Action ID.
* Ex: $queryValue = [':acl_action_id_1' => 1, ..., ':acl_action_id_3' => 3]
*
* @param array<string,string> $queryValues
*/
function updateAclActionsForAuthentifiedUsers(array $queryValues): void
{
$aclGroupIds = getAclGroupIdsByActionIds($queryValues);
flagUpdatedAclForAuthentifiedUsers($aclGroupIds);
}
/**
* This method flags updated ACL for authentified users.
*
* @param int[] $aclGroupIds
*/
function flagUpdatedAclForAuthentifiedUsers(array $aclGroupIds): void
{
global $pearDB;
$userIds = getUsersIdsByAclGroup($aclGroupIds);
$readSessionRepository = getReadSessionRepository();
foreach ($userIds as $userId) {
$sessionIds = $readSessionRepository->findSessionIdsByUserId($userId);
$statement = $pearDB->prepare("UPDATE session SET update_acl = '1' WHERE session_id = :sessionId");
foreach ($sessionIds as $sessionId) {
$statement->bindValue(':sessionId', $sessionId, PDO::PARAM_STR);
$statement->execute();
}
}
}
/**
* This function returns user ids from ACL Group Ids
*
* @param int[] $aclGroupIds
* @return int[]
*/
function getUsersIdsByAclGroup(array $aclGroupIds): array
{
global $pearDB;
$queryValues = [];
foreach ($aclGroupIds as $index => $aclGroupId) {
$sanitizedAclGroupId = filter_var($aclGroupId, FILTER_VALIDATE_INT);
if ($sanitizedAclGroupId !== false) {
$queryValues[':acl_group_id_' . $index] = $sanitizedAclGroupId;
}
}
$aclGroupIdQueryString = '(' . implode(', ', array_keys($queryValues)) . ')';
$statement = $pearDB->prepare(
"SELECT DISTINCT `contact_contact_id` FROM `acl_group_contacts_relations`
WHERE `acl_group_id`
IN {$aclGroupIdQueryString}"
);
foreach ($queryValues as $bindParameter => $bindValue) {
$statement->bindValue($bindParameter, $bindValue, PDO::PARAM_INT);
}
$statement->execute();
$userIds = [];
while ($result = $statement->fetch()) {
$userIds[] = (int) $result['contact_contact_id'];
}
return $userIds;
}
/**
* This method gets SessionRepository from Service container
*
* @return ReadSessionRepositoryInterface
*/
function getReadSessionRepository(): ReadSessionRepositoryInterface
{
$kernel = App\Kernel::createForWeb();
return $kernel->getContainer()->get(
ReadSessionRepositoryInterface::class
);
}
/**
* Returns ACL Group IDs
* Ex: $queryValue = [':acl_action_id_1' => 1, ..., ':acl_action_id_3' => 3]
*
* @param array<string,string> $queryValues
* @return int[]
*/
function getAclGroupIdsByActionIds(array $queryValues): array
{
global $pearDB;
$aclActionIdQueryString = '(' . implode(', ', array_keys($queryValues)) . ')';
$statement = $pearDB->prepare(
"SELECT DISTINCT acl_group_id FROM acl_group_actions_relations
WHERE acl_action_id IN {$aclActionIdQueryString}"
);
foreach ($queryValues as $bindParameter => $bindValue) {
$statement->bindValue($bindParameter, $bindValue, PDO::PARAM_INT);
}
$statement->execute();
$aclGroupIds = [];
while ($result = $statement->fetch()) {
$aclGroupIds[] = (int) $result['acl_group_id'];
}
return $aclGroupIds;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/menusACL/formMenusAccess.php | centreon/www/include/options/accessLists/menusACL/formMenusAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
/** @var string $o */
/** @var string $p */
/** @var string $path */
/** @var CentreonDB $pearDB */
/** @var int|false $aclTopologyId */
/** @var array<int|false> $duplicateNbr */
/** @var array<int|false> $selectIds */
if (! isset($centreon)) {
exit();
}
if ($o === ACL_ADD || $o === ACL_MODIFY) {
/**
* Filtering the topology relation to remove all relations with access right
* that are not equal to 1 (CentreonACL::ACL_ACCESS_READ_WRITE)
* or 2 (CentreonACL::ACL_ACCESS_READ_ONLY)
*/
if (isset($_POST['acl_r_topos']) && is_array($_POST['acl_r_topos'])) {
foreach ($_POST['acl_r_topos'] as $topologyId => $accessRight) {
$topologyId = (int) $topologyId;
$accessRight = (int) $accessRight;
// Only 1 or 2 are allowed
$hasAccessNotAllowed
= $accessRight != CentreonACL::ACL_ACCESS_READ_WRITE
&& $accessRight != CentreonACL::ACL_ACCESS_READ_ONLY;
if ($hasAccessNotAllowed) {
unset($_POST['acl_r_topos'][$topologyId]);
}
}
}
}
// Database retrieve information for LCA
/** @var array{
* acl_topo_id?: int,
* acl_topo_name?: int,
* acl_topo_alias?: int,
* acl_comments?: int,
* acl_topo_activate?: int,
* acl_topos: array<int, int>,
* acl_groups?: list<int>,
* } $acl */
$acl = [
'acl_topos' => [],
];
if ($o === ACL_MODIFY || $o === ACL_WATCH) {
$statementAcl = $pearDB->prepare(
<<<'SQL'
SELECT *
FROM acl_topology
WHERE acl_topo_id = :aclTopologyId LIMIT 1
SQL
);
$statementAcl->bindValue(':aclTopologyId', $aclTopologyId, PDO::PARAM_INT);
$statementAcl->execute();
// Set base value
$acl = array_map('myDecode', $statementAcl->fetchRow() ?: []);
unset($statementAcl);
// Set Topology relations
$statementAclTopoRelations = $pearDB->prepare(
<<<'SQL'
SELECT topology_topology_id, access_right
FROM acl_topology_relations
WHERE acl_topo_id = :aclTopologyId
SQL
);
$statementAclTopoRelations->bindValue(':aclTopologyId', $aclTopologyId, PDO::PARAM_INT);
$statementAclTopoRelations->execute();
foreach ($statementAclTopoRelations as $topo) {
$acl['acl_topos'][$topo['topology_topology_id']] = $topo['access_right'];
}
unset($statementAclTopoRelations);
// Set Contact Groups relations
$statementAclGroupTopoRelations = $pearDB->prepare(
<<<'SQL'
SELECT DISTINCT acl_group_id
FROM acl_group_topology_relations
WHERE acl_topology_id = :aclTopologyId
SQL
);
$statementAclGroupTopoRelations->bindValue(':aclTopologyId', $aclTopologyId, PDO::PARAM_INT);
$statementAclGroupTopoRelations->execute();
foreach ($statementAclGroupTopoRelations as $groups) {
$acl['acl_groups'][] = $groups['acl_group_id'];
}
unset($statementAclGroupTopoRelations);
}
/** @var array<int, string> $groups */
$groups = [];
$statementAclGroups = $pearDB->query(
<<<'SQL'
SELECT acl_group_id, acl_group_name
FROM acl_groups
ORDER BY acl_group_name
SQL
);
foreach ($statementAclGroups as $group) {
$groups[$group['acl_group_id']] = CentreonUtils::escapeAll($group['acl_group_name']);
}
unset($statementAclGroups);
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 180px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '80'];
$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 begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === ACL_ADD) {
$form->addElement('header', 'title', _('Add an ACL'));
} elseif ($o === ACL_MODIFY) {
$form->addElement('header', 'title', _('Modify an ACL'));
} elseif ($o === ACL_WATCH) {
$form->addElement('header', 'title', _('View an ACL'));
}
// LCA basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'acl_topo_name', _('ACL Definition'), $attrsText);
$form->addElement('text', 'acl_topo_alias', _('Alias'), $attrsText);
/** @var HTML_QuickForm_advmultiselect $ams1 */
$ams1 = $form->addElement(
'advmultiselect',
'acl_groups',
[
_('Linked Groups'),
_('Available'),
_('Selected'),
],
$groups,
$attrsAdvSelect,
SORT_ASC
);
$ams1->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$ams1->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$ams1->setElementTemplate($eTemplate);
echo $ams1->getElementJs(false);
$tab = [];
$tab[] = $form->createElement('radio', 'acl_topo_activate', null, _('Enabled'), '1');
$tab[] = $form->createElement('radio', 'acl_topo_activate', null, _('Disabled'), '0');
$form->addGroup($tab, 'acl_topo_activate', _('Status'), ' ');
$form->setDefaults(['acl_topo_activate' => '1']);
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$form->addElement('textarea', 'acl_comments', _('Comments'), $attrsTextarea);
// Create buffer group list for Foorth level.
/** @var array<int, array<int, string>> $groupMenus */
$groupMenus = [];
$statementTopology = $pearDB->query(
<<<'SQL'
SELECT topology_group, topology_name, topology_parent
FROM `topology`
WHERE topology_page IS NULL
ORDER BY topology_group, topology_page
SQL
);
foreach ($statementTopology as $group) {
$groupMenus[$group['topology_group']] ??= [];
$groupMenus[$group['topology_group']][$group['topology_parent']] = $group['topology_name'];
}
unset($statementTopology);
// Topology concerned
$form->addElement('header', 'pages', _('Accessible Pages'));
$statementTopo1 = $pearDB->query(
<<<'SQL'
SELECT topology_id, topology_page, topology_name, topology_parent, readonly, topology_feature_flag
FROM `topology`
WHERE topology_parent IS NULL
ORDER BY topology_order, topology_group
SQL
);
$acl_topos = [];
$acl_topos2 = [];
$a = 0;
foreach ($statementTopo1 as $topo1) {
if (! is_enabled_feature_flag($topo1['topology_feature_flag'] ?? null)) {
continue;
}
$acl_topos2[$a] = [];
$acl_topos2[$a]['name'] = _($topo1['topology_name']);
$acl_topos2[$a]['id'] = $topo1['topology_id'];
$acl_topos2[$a]['access'] = $acl['acl_topos'][$topo1['topology_id']] ?? 0;
$acl_topos2[$a]['c_id'] = $a;
$acl_topos2[$a]['readonly'] = $topo1['readonly'];
$acl_topos2[$a]['childs'] = [];
$acl_topos[] = $form->createElement(
'checkbox',
$topo1['topology_id'],
null,
_($topo1['topology_name']),
['style' => 'margin-top: 5px;', 'id' => $topo1['topology_id']]
);
$b = 0;
$statementTopo2 = $pearDB->prepare(
<<<'SQL'
SELECT topology_id, topology_page, topology_name, topology_parent, readonly, topology_feature_flag
FROM `topology`
WHERE topology_parent = :topology_parent
ORDER BY topology_order
SQL
);
$statementTopo2->bindValue(':topology_parent', (int) $topo1['topology_page'], PDO::PARAM_INT);
$statementTopo2->execute();
foreach ($statementTopo2 as $topo2) {
if (! is_enabled_feature_flag($topo2['topology_feature_flag'] ?? null)) {
continue;
}
$acl_topos2[$a]['childs'][$b] = [];
$acl_topos2[$a]['childs'][$b]['name'] = _($topo2['topology_name']);
$acl_topos2[$a]['childs'][$b]['id'] = $topo2['topology_id'];
$acl_topos2[$a]['childs'][$b]['access'] = $acl['acl_topos'][$topo2['topology_id']] ?? 0;
$acl_topos2[$a]['childs'][$b]['c_id'] = $a . '_' . $b;
$acl_topos2[$a]['childs'][$b]['readonly'] = $topo2['readonly'];
$acl_topos2[$a]['childs'][$b]['childs'] = [];
$acl_topos[] = $form->createElement(
'checkbox',
$topo2['topology_id'],
null,
_($topo2['topology_name']) . '<br />',
['style' => 'margin-top: 5px; margin-left: 20px;']
);
$c = 0;
$statementTopo3 = $pearDB->prepare(
<<<'SQL'
SELECT topology_id, topology_name, topology_parent, topology_page, topology_group, readonly, topology_feature_flag
FROM `topology`
WHERE topology_parent = :topology_parent AND topology_page IS NOT NULL
ORDER BY topology_group, topology_order
SQL
);
$statementTopo3->bindValue(':topology_parent', (int) $topo2['topology_page'], PDO::PARAM_INT);
$statementTopo3->execute();
foreach ($statementTopo3 as $topo3) {
if (! is_enabled_feature_flag($topo3['topology_feature_flag'] ?? null)) {
continue;
}
$acl_topos2[$a]['childs'][$b]['childs'][$c] = [];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['name'] = _($topo3['topology_name']);
if (isset($groupMenus[$topo3['topology_group']][$topo3['topology_parent']])) {
$acl_topos2[$a]['childs'][$b]['childs'][$c]['group'] = $groupMenus[$topo3['topology_group']][$topo3['topology_parent']];
} else {
$acl_topos2[$a]['childs'][$b]['childs'][$c]['group'] = _('Main Menu');
}
$acl_topos2[$a]['childs'][$b]['childs'][$c]['id'] = $topo3['topology_id'];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['access'] = $acl['acl_topos'][$topo3['topology_id']] ?? 0;
$acl_topos2[$a]['childs'][$b]['childs'][$c]['c_id'] = $a . '_' . $b . '_' . $c;
$acl_topos2[$a]['childs'][$b]['childs'][$c]['readonly'] = $topo3['readonly'];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'] = [];
$acl_topos[] = $form->createElement(
'checkbox',
$topo3['topology_id'],
null,
_($topo3['topology_name']) . '<br />',
['style' => 'margin-top: 5px; margin-left: 40px;']
);
$d = 0;
$statementTopo4 = $pearDB->prepare(
<<<'SQL'
SELECT topology_id, topology_name, topology_parent, readonly, topology_feature_flag
FROM `topology`
WHERE topology_parent = :topology_parent AND topology_page IS NOT NULL
ORDER BY topology_order
SQL
);
$statementTopo4->bindValue(':topology_parent', (int) $topo3['topology_page'], PDO::PARAM_INT);
$statementTopo4->execute();
foreach ($statementTopo4 as $topo4) {
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d] = [];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['name'] = _($topo4['topology_name']);
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['id'] = $topo4['topology_id'];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['access'] = $acl['acl_topos'][$topo4['topology_id']] ?? 0;
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['c_id'] = $a . '_' . $b . '_' . $c . '_' . $d;
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['readonly'] = $topo4['readonly'];
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childs'][$d]['childs'] = [];
$d++;
}
unset($statementTopo4);
$acl_topos2[$a]['childs'][$b]['childs'][$c]['childNumber']
= count($acl_topos2[$a]['childs'][$b]['childs'][$c]['childs']);
$c++;
}
unset($statementTopo3);
$acl_topos2[$a]['childs'][$b]['childNumber'] = count($acl_topos2[$a]['childs'][$b]['childs']);
$b++;
}
unset($statementTopo2);
$acl_topos2[$a]['childNumber'] = count($acl_topos2[$a]['childs']);
$a++;
}
unset($statementTopo1);
$form->addGroup($acl_topos, 'acl_topos', _('Visible page'), ' ');
$form->addElement('hidden', 'acl_topo_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('acl_topo_name', _('Required'), 'required');
$form->registerRule('exist', 'callback', 'hasTopologyNameNeverUsed');
if ($o === ACL_ADD) {
$form->addRule('acl_topo_name', _('Already exists'), 'exist');
}
$form->setRequiredNote(_('Required field'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch a LCA information
if ($o === ACL_WATCH) {
$form->addElement('button', 'change', _('Modify'), [
'onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&acl_id=' . $aclTopologyId . "'",
'class' => 'btc bt_success',
]);
$form->setDefaults($acl);
$form->freeze();
} elseif ($o === ACL_MODIFY) { // Modify a LCA information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Delete'), ['class' => 'btc bt_danger']);
$form->setDefaults($acl);
} elseif ($o === ACL_ADD) { // Add a LCA information
$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&lca_id=' . $aclTopologyId, 'changeT' => _('Modify')]);
$tpl->assign('lca_topos2', $acl_topos2);
$tpl->assign('sort1', _('General Information'));
$tpl->assign('sort2', _('Resources'));
$tpl->assign('sort3', _('Topology'));
$tpl->assign('label_none', _('No access'));
$tpl->assign('label_readwrite', _('Read/Write'));
$tpl->assign('label_readonly', _('Read Only'));
// prepare help texts
$helptext = '';
include_once __DIR__ . '/help.php';
/** @var array<string, string> $help */
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()) {
$aclObj = $form->getElement('acl_topo_id');
if ($form->getSubmitValue('submitA')) {
$aclObj->setValue(insertLCAInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateLCAInDB($aclObj->getValue());
}
require_once __DIR__ . '/listsMenusAccess.php';
} else {
$action = $form->getSubmitValue('action');
if ($valid && ! empty($action['action'])) {
require_once __DIR__ . '/listsMenusAccess.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <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('acl_topos2', $acl_topos2);
$tpl->display('formMenusAccess.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/options/accessLists/menusACL/help.php | centreon/www/include/options/accessLists/menusACL/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_acl_definition'] = dgettext('help', 'Name of menu rule.');
$help['tip_alias'] = dgettext('help', 'Alias of menu rule.');
$help['tip_status'] = dgettext('help', 'Enable or disable the ACL menu rule.');
$help['tip_linked_groups'] = dgettext('help', 'Implied ACL groups.');
/**
* Accessible Pages
*/
/**
* Additional Information
*/
$help['tip_comments'] = dgettext('help', 'Comments regarding this menu rule.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/menusACL/listsMenusAccess.php | centreon/www/include/options/accessLists/menusACL/listsMenusAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
include './include/common/autoNumLimit.php';
$searchStr = '';
$search = $_POST['searchACLM'] ?? $_GET['searchACLM'] ?? null;
if (! is_null($search)) {
$centreon->historySearch[$url] = $search;
} elseif (isset($centreon->historySearch[$url])) {
$search = $centreon->historySearch[$url];
}
if (! is_null($search)) {
$search = HtmlSanitizer::createFromString($search)
->removeTags()
->sanitize()
->getString();
}
$rows = 0;
$dataRows = [];
try {
$offset = (int) ($num * $limit);
$max = (int) $limit;
$paramsList = [];
// ---------- COUNT query ----------
$countSql = <<<'SQL'
SELECT COUNT(*) AS total
FROM acl_topology
SQL;
if ($search !== null && $search !== '') {
$countSql .= ' WHERE (acl_topo_name LIKE :searchLike OR acl_topo_alias = :searchAlias)';
$paramsList[] = QueryParameter::string('searchLike', '%' . $search . '%');
$paramsList[] = QueryParameter::string('searchAlias', $search);
}
$countParams = QueryParameters::create($paramsList);
$rows = (int) $pearDB->fetchOne($countSql, $countParams);
// ---------- DATA query ----------
$listSql = <<<'SQL'
SELECT acl_topo_id, acl_topo_name, acl_topo_alias, acl_topo_activate
FROM acl_topology
SQL;
if ($search !== null && $search !== '') {
$listSql .= ' WHERE (acl_topo_name LIKE :searchLike OR acl_topo_alias = :searchAlias)';
}
$listSql .= " ORDER BY acl_topo_name ASC LIMIT {$offset}, {$max}";
$dataParams = QueryParameters::create($paramsList);
$dataRows = $pearDB->fetchAllAssociative($listSql, $dataParams);
} catch (CollectionException|ValueObjectException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while listing ACL topologies: ' . $exception->getMessage(),
[
'search' => $search ?? null,
'limit' => $limit ?? null,
'num' => $num ?? null,
],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('Error while fetching ACL topologies'));
}
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_alias', _('Description'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// end header menu
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
$i = 0;
foreach ($dataRows as $topo) {
$selectedElements = $form->addElement('checkbox', 'select[' . $topo['acl_topo_id'] . ']');
if ($topo['acl_topo_activate']) {
$moptions = "<a href='main.php?p=" . $p . '&acl_topo_id=' . $topo['acl_topo_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_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 . '&acl_topo_id=' . $topo['acl_topo_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$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["
. $topo['acl_topo_id'] . "]' />";
// Contacts
$elemArr[$i++] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(
$topo['acl_topo_name'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&acl_topo_id=' . $topo['acl_topo_id'], 'RowMenu_alias' => CentreonUtils::escapeSecure(
$topo['acl_topo_alias'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_status' => $topo['acl_topo_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $topo['acl_topo_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) {
$attrs1 = ['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 || "
. "this.form.elements['{$option}'].selectedIndex == 4) {"
. "setO(this.form.elements['{$option}'].value); submit();}"];
$form->addElement('select', $option, null, [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')], $attrs1);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchACLM', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listsMenusAccess.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/options/accessLists/menusACL/menusAccess.php | centreon/www/include/options/accessLists/menusACL/menusAccess.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/options/accessLists/menusACL/';
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
define('ACL_ADD', 'a');
define('ACL_WATCH', 'w');
define('ACL_MODIFY', 'c');
define('ACL_ENABLE', 's');
define('ACL_MULTI_ENABLE', 'ms');
define('ACL_DISABLE', 'u');
define('ACL_MULTI_DISABLE', 'mu');
define('ACL_DUPLICATE', 'm');
define('ACL_DELETE', 'd');
$aclTopologyId = filter_var(
$_GET['acl_topo_id'] ?? $_POST['acl_topo_id'] ?? null,
FILTER_VALIDATE_INT
);
$duplicateNbr = filter_var_array(
$_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [],
FILTER_VALIDATE_INT
);
// If one data are not correctly typed in array, it will be set to false
$selectIds = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
$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;
}
switch ($o) {
case ACL_ADD:
require_once $path . 'formMenusAccess.php';
break;
case ACL_WATCH:
if (is_int($aclTopologyId)) {
require_once $path . 'formMenusAccess.php';
} else {
require_once $path . 'listsMenusAccess.php';
}
break;
case ACL_MODIFY:
if (is_int($aclTopologyId)) {
require_once $path . 'formMenusAccess.php';
} else {
require_once $path . 'listsMenusAccess.php';
}
break;
case ACL_ENABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (is_int($aclTopologyId)) {
enableLCAInDB($aclTopologyId);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
case ACL_MULTI_ENABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
enableLCAInDB(null, $selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
case ACL_DISABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (is_int($aclTopologyId)) {
disableLCAInDB($aclTopologyId);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
case ACL_MULTI_DISABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
disableLCAInDB(null, $selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
case ACL_DUPLICATE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds) && ! in_array(false, $duplicateNbr)) {
multipleLCAInDB($selectIds, $duplicateNbr);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
case ACL_DELETE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
deleteLCAInDB($selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listsMenusAccess.php';
break;
default:
require_once $path . 'listsMenusAccess.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/options/accessLists/menusACL/DB-Func.php | centreon/www/include/options/accessLists/menusACL/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();
}
/**
* Indicates if the topology name has already been used
*
* @global \CentreonDB $pearDB
* @global HTML_QuickFormCustom $form
* @param string $topologyName
* @return bool Return false if the topology name has already been used
*/
function hasTopologyNameNeverUsed($topologyName = null)
{
global $pearDB, $form;
$topologyId = null;
if (isset($form)) {
$topologyId = $form->getSubmitValue('lca_id');
}
$prepareSelect = $pearDB->prepare(
'SELECT acl_topo_name, acl_topo_id FROM `acl_topology` '
. 'WHERE acl_topo_name = :topology_name'
);
$prepareSelect->bindValue(
':topology_name',
$topologyName,
PDO::PARAM_STR
);
if ($prepareSelect->execute()) {
$result = $prepareSelect->fetch(PDO::FETCH_ASSOC);
$total = $prepareSelect->rowCount();
if ($total >= 1 && $result['acl_topo_id'] == $topologyId) {
/**
* In case of modification, we need to return true
*/
return true;
}
return ! ($total >= 1 && $result['acl_topo_id'] != $topologyId);
}
}
/**
* Enable an ACL
*
* @global CentreonDB $pearDB
* @global Centreon $centreon
* @param int $aclTopologyId ACL topology id to enable
* @param array $acls Array of ACL topology id to disable
*/
function enableLCAInDB($aclTopologyId = null, $acls = [])
{
global $pearDB, $centreon;
if (! is_int($aclTopologyId) && empty($acls)) {
return;
}
if (is_int($aclTopologyId)) {
$acls = [$aclTopologyId => '1'];
}
foreach (array_keys($acls) as $currentAclTopologyId) {
$prepareUpdate = $pearDB->prepare(
"UPDATE `acl_topology` SET acl_topo_activate = '1' "
. 'WHERE `acl_topo_id` = :topology_id'
);
$prepareUpdate->bindValue(
':topology_id',
$currentAclTopologyId,
PDO::PARAM_INT
);
if (! $prepareUpdate->execute()) {
continue;
}
$prepareSelect = $pearDB->prepare(
'SELECT acl_topo_name FROM `acl_topology` '
. 'WHERE acl_topo_id = :topology_id LIMIT 1'
);
$prepareSelect->bindValue(
':topology_id',
$currentAclTopologyId,
PDO::PARAM_INT
);
if ($prepareSelect->execute()) {
$result = $prepareSelect->fetch(PDO::FETCH_ASSOC);
$centreon->CentreonLogAction->insertLog(
'menu access',
$currentAclTopologyId,
$result['acl_topo_name'],
'enable'
);
}
}
}
/**
* Disable an ACL
*
* @global CentreonDB $pearDB
* @global Centreon $centreon
* @param int $aclTopologyId ACL topology id to disable
* @param array $acls Array of ACL topology id to disable
*/
function disableLCAInDB($aclTopologyId = null, $acls = [])
{
global $pearDB, $centreon;
if (! is_int($aclTopologyId) && empty($acls)) {
return;
}
if (is_int($aclTopologyId)) {
$acls = [$aclTopologyId => '1'];
}
foreach (array_keys($acls) as $currentTopologyId) {
$prepareUpdate = $pearDB->prepare(
"UPDATE `acl_topology` SET acl_topo_activate = '0' "
. 'WHERE `acl_topo_id` = :topology_id'
);
$prepareUpdate->bindValue(
':topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if (! $prepareUpdate->execute()) {
continue;
}
$prepareSelect = $pearDB->prepare(
'SELECT acl_topo_name FROM `acl_topology` '
. 'WHERE acl_topo_id = :topology_id LIMIT 1'
);
$prepareSelect->bindValue(
':topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if ($prepareSelect->execute()) {
$result = $prepareSelect->fetch(PDO::FETCH_ASSOC);
$centreon->CentreonLogAction->insertLog(
'menu access',
$currentTopologyId,
$result['acl_topo_name'],
'disable'
);
}
}
}
/**
* Delete a list of ACL
*
* @global CentreonDB $pearDB
* @global Centreon $centreon
* @param array $acls
*/
function deleteLCAInDB($acls = [])
{
global $pearDB, $centreon;
foreach (array_keys($acls) as $currentTopologyId) {
$prepareSelect = $pearDB->prepare(
'SELECT acl_topo_name FROM `acl_topology` '
. 'WHERE acl_topo_id = :topology_id LIMIT 1'
);
$prepareSelect->bindValue(
':topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if (! $prepareSelect->execute()) {
continue;
}
$result = $prepareSelect->fetch(PDO::FETCH_ASSOC);
$topologyName = $result['acl_topo_name'];
$prepareDelete = $pearDB->prepare(
'DELETE FROM `acl_topology` WHERE acl_topo_id = :topology_id'
);
$prepareDelete->bindValue(
':topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if ($prepareDelete->execute()) {
$centreon->CentreonLogAction->insertLog(
'menu access',
$currentTopologyId,
$topologyName,
'd'
);
}
}
}
/**
* Duplicate a list of ACL
*
* @global CentreonDB $pearDB
* @global Centreon $centreon
* @param array $lcas
* @param array $nbrDup
* @param mixed $acls
* @param mixed $duplicateNbr
*/
function multipleLCAInDB($acls = [], $duplicateNbr = [])
{
global $pearDB, $centreon;
foreach (array_keys($acls) as $currentTopologyId) {
$prepareSelect = $pearDB->prepare(
'SELECT * FROM `acl_topology` WHERE acl_topo_id = :topology_id LIMIT 1'
);
$prepareSelect->bindValue(
':topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if (! $prepareSelect->execute()) {
continue;
}
$topology = $prepareSelect->fetch(PDO::FETCH_ASSOC);
$topology['acl_topo_id'] = '';
for ($newIndex = 1; $newIndex <= $duplicateNbr[$currentTopologyId]; $newIndex++) {
$val = null;
$aclName = null;
$fields = [];
foreach ($topology as $column => $value) {
if ($column === 'acl_topo_name') {
$count = 1;
$aclName = $value . '_' . $count;
while (! hasTopologyNameNeverUsed($aclName)) {
$count++;
$aclName = $value . '_' . $count;
}
$value = $aclName;
$fields['acl_topo_name'] = $aclName;
}
if (is_null($val)) {
$val .= (is_null($value) || empty($value))
? 'NULL'
: "'" . $pearDB->escape($value) . "'";
} else {
$val .= (is_null($value) || empty($value))
? ', NULL'
: ", '" . $pearDB->escape($value) . "'";
}
if ($column !== 'acl_topo_id' && $column !== 'acl_topo_name') {
$fields[$column] = $value;
}
}
if (! is_null($val)) {
$pearDB->query(
"INSERT INTO acl_topology VALUES ({$val})"
);
$newTopologyId = $pearDB->lastInsertId();
$prepareInsertRelation = $pearDB->prepare(
'INSERT INTO acl_topology_relations '
. '(acl_topo_id, topology_topology_id, access_right) '
. '(SELECT :new_topology_id, topology_topology_id, access_right '
. 'FROM acl_topology_relations '
. 'WHERE acl_topo_id = :current_topology_id)'
);
$prepareInsertRelation->bindValue(
':new_topology_id',
$newTopologyId,
PDO::PARAM_INT
);
$prepareInsertRelation->bindValue(
':current_topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if (! $prepareInsertRelation->execute()) {
continue;
}
$prepareInsertGroup = $pearDB->prepare(
'INSERT INTO acl_group_topology_relations '
. '(acl_topology_id, acl_group_id) '
. '(SELECT :new_topology_id, acl_group_id '
. 'FROM acl_group_topology_relations '
. 'WHERE acl_topology_id = :current_topology_id)'
);
$prepareInsertGroup->bindValue(
':new_topology_id',
$newTopologyId,
PDO::PARAM_INT
);
$prepareInsertGroup->bindValue(
':current_topology_id',
$currentTopologyId,
PDO::PARAM_INT
);
if ($prepareInsertGroup->execute()) {
$centreon->CentreonLogAction->insertLog(
'menu access',
$newTopologyId,
$aclName,
'a',
$fields
);
}
}
}
}
}
/**
* Update an ACL
*
* @global HTML_QuickFormCustom $form
* @global Centreon $centreon
* @param int $aclId Acl topology id to update
*/
function updateLCAInDB($aclId = null)
{
global $form, $centreon;
if (! $aclId) {
return;
}
updateLCA($aclId);
updateLCARelation($aclId);
updateGroups($aclId);
$submitedValues = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($submitedValues);
$centreon->CentreonLogAction->insertLog(
'menu access',
$aclId,
$submitedValues['acl_topo_name'],
'c',
$fields
);
}
/**
* Insert an ACL
*
* @global HTML_QuickFormCustom $form
* @global Centreon $centreon
* @return int Id of the new ACL
*/
function insertLCAInDB()
{
global $form, $centreon;
$aclId = insertLCA();
updateLCARelation($aclId);
updateGroups($aclId);
$submitedValues = $form->getSubmitValues();
$fields = CentreonLogAction::prepareChanges($submitedValues);
$centreon->CentreonLogAction->insertLog(
'menu access',
$aclId,
$submitedValues['acl_topo_name'],
'a',
$fields
);
return $aclId;
}
/**
* Insert an ACL
*
* @global HTML_QuickFormCustom $form
* @global CentreonDB $pearDB
* @return int Id of the new ACL topology
*/
function insertLCA()
{
global $form, $pearDB;
$submitedValues = $form->getSubmitValues();
$isAclActivate = false;
if (isset($submitedValues['acl_topo_activate'], $submitedValues['acl_topo_activate']['acl_topo_activate'])
&& $submitedValues['acl_topo_activate']['acl_topo_activate'] == '1'
) {
$isAclActivate = true;
}
$prepare = $pearDB->prepare(
'INSERT INTO `acl_topology` '
. '(acl_topo_name, acl_topo_alias, acl_topo_activate, acl_comments) '
. 'VALUES (:acl_name, :acl_alias, :is_activate, :acl_comment)'
);
$prepare->bindValue(
':acl_name',
$submitedValues['acl_topo_name'],
PDO::PARAM_STR
);
$prepare->bindValue(
':is_activate',
($isAclActivate ? '1' : '0'),
PDO::PARAM_STR
);
$prepare->bindValue(
':acl_alias',
$submitedValues['acl_topo_alias'],
PDO::PARAM_STR
);
$prepare->bindValue(
':acl_comment',
$submitedValues['acl_comments'],
PDO::PARAM_STR
);
return $prepare->execute()
? $pearDB->lastInsertId()
: null;
}
/**
* Update an ACL
*
* @global HTML_QuickFormCustom $form
* @global \CentreonDB $pearDB
* @param int $aclId Acl id to update
*/
function updateLCA($aclId = null)
{
global $form, $pearDB;
if (! $aclId) {
return;
}
$submitedValues = $form->getSubmitValues();
$isAclActivate = false;
if (isset($submitedValues['acl_topo_activate'], $submitedValues['acl_topo_activate']['acl_topo_activate'])
&& $submitedValues['acl_topo_activate']['acl_topo_activate'] == '1'
) {
$isAclActivate = true;
}
$prepareUpdate = $pearDB->prepare(
'UPDATE `acl_topology` '
. 'SET acl_topo_name = :acl_name, '
. 'acl_topo_alias = :acl_alias, '
. 'acl_topo_activate = :is_activate, '
. 'acl_comments = :acl_comment '
. 'WHERE acl_topo_id = :acl_id'
);
$prepareUpdate->bindValue(
':acl_name',
$submitedValues['acl_topo_name'],
PDO::PARAM_STR
);
$prepareUpdate->bindValue(
':acl_alias',
$submitedValues['acl_topo_alias'],
PDO::PARAM_STR
);
$prepareUpdate->bindValue(
':is_activate',
($isAclActivate ? '1' : '0'),
PDO::PARAM_STR
);
$prepareUpdate->bindValue(
':acl_comment',
$submitedValues['acl_comments'],
PDO::PARAM_STR
);
$prepareUpdate->bindValue(':acl_id', $aclId, PDO::PARAM_INT);
$prepareUpdate->execute();
}
/**
* Update all relation of ACL from the global form
*
* @global HTML_QuickFormCustom $form
* @global \CentreonDB $pearDB
* @param type $acl_id
* @param null|mixed $aclId
* @return type
*/
function updateLCARelation($aclId = null)
{
global $form, $pearDB;
if (! $aclId) {
return;
}
$prepareDelete = $pearDB->prepare(
'DELETE FROM acl_topology_relations WHERE acl_topo_id = :acl_id'
);
$prepareDelete->bindValue(':acl_id', $aclId, PDO::PARAM_INT);
if ($prepareDelete->execute()) {
$submitedValues = $form->getSubmitValue('acl_r_topos');
foreach ($submitedValues as $key => $value) {
if (isset($submitedValues) && $key != 0) {
$prepare = $pearDB->prepare(
'INSERT INTO acl_topology_relations (acl_topo_id, topology_topology_id, access_right) '
. 'VALUES (:aclId, :key, :value)'
);
$prepare->bindValue(':aclId', $aclId, PDO::PARAM_INT);
$prepare->bindValue(':key', $key, PDO::PARAM_INT);
$prepare->bindValue(':value', $value, PDO::PARAM_INT);
$prepare->execute();
}
}
}
}
/**
* Update all groups of ACL from the global form
*
* @global HTML_QuickFormCustom $form
* @global \CentreonDB $pearDB
* @param type $acl_id
* @param null|mixed $aclId
* @return type
*/
function updateGroups($aclId = null)
{
global $form, $pearDB;
if (! $aclId) {
return;
}
$prepareDelete = $pearDB->prepare(
'DELETE FROM acl_group_topology_relations WHERE acl_topology_id = :acl_id'
);
$prepareDelete->bindValue(':acl_id', $aclId, PDO::PARAM_INT);
if ($prepareDelete->execute()) {
$submitedValues = $form->getSubmitValue('acl_groups');
if (isset($submitedValues)) {
foreach ($submitedValues as $key => $value) {
if (isset($value)) {
$query = <<<'SQL'
INSERT INTO acl_group_topology_relations
(acl_topology_id, acl_group_id)
VALUES (:aclId, :value)
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':aclId', $aclId, PDO::PARAM_INT);
$statement->bindValue(':value', $value, PDO::PARAM_INT);
$statement->execute();
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/options/accessLists/reloadACL/reloadACL.php | centreon/www/include/options/accessLists/reloadACL/reloadACL.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './include/common/common-Func.php';
require_once './class/centreonMsg.class.php';
if (isset($_GET['o']) && $_GET['o'] === 'r') {
$msg = new CentreonMsg();
$sid = session_id();
try {
$statement = $pearDB->prepareQuery(
<<<'SQL'
UPDATE session SET update_acl = '1' WHERE session_id = :sessionId
SQL
);
$pearDB->executePreparedQuery($statement, ['sessionId' => $sid]);
$pearDB->executeQuery(
<<<'SQL'
UPDATE acl_resources SET changed = '1'
SQL
);
$msg->info(_('ACL reloaded'));
passthru(_CENTREON_PATH_ . '/cron/centAcl.php');
} catch (CentreonDbException|PDOException $e) {
$msg->error(_('An error occurred'));
}
} elseif (isset($_POST['o']) && $_POST['o'] === 'u') {
$msg = new CentreonMsg();
$userIds = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
try {
$pearDB->beginTransaction();
$pearDB->executeQuery(
<<<'SQL'
UPDATE acl_resources SET changed = '1'
SQL
);
$bindParams = [];
// Remove false values from filtered array.
foreach (array_keys(array_filter($userIds)) as $userId) {
$bindParams[':user_' . $userId] = $userId;
}
if ($bindParams !== []) {
$userIdAsString = implode(', ', array_keys($bindParams));
$statement = $pearDB->prepareQuery(
<<<SQL
UPDATE session SET update_acl = '1' WHERE user_id IN ({$userIdAsString})
SQL
);
$pearDB->executePreparedQuery($statement, $bindParams);
}
$pearDB->commit();
$msg->info(_('ACL reloaded'));
passthru(_CENTREON_PATH_ . '/cron/centAcl.php');
} catch (CentreonDbException|PDOException $e) {
$pearDB->rollBack();
$msg->error(_('An error occurred'));
}
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
$res = $pearDB->executeQuery(
<<<'SQL'
SELECT DISTINCT * FROM session
SQL
);
$session_data = [];
$cpt = 0;
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
while ($r = $res->fetch()) {
$statement = $pearDB->prepareQuery(
'SELECT contact_name, contact_admin FROM contact
WHERE contact_id = :contactId'
);
$pearDB->executePreparedQuery($statement, ['contactId' => $r['user_id']]);
$rU = $statement->fetch();
if ($rU['contact_admin'] != '1') {
$session_data[$cpt] = [];
$session_data[$cpt]['class'] = $cpt % 2 ? 'list_one' : 'list_two';
$session_data[$cpt]['user_id'] = $r['user_id'];
$session_data[$cpt]['user_alias'] = $rU['contact_name'];
$session_data[$cpt]['admin'] = $rU['contact_admin'];
/**
* Set current page and topology only if they are not null to avoid invalid array offsets.
*/
$currentPage = null;
$topologyName = null;
if ($r['current_page'] !== null) {
$statement = $pearDB->prepareQuery(
<<<'SQL'
SELECT topology_name, topology_page, topology_url_opt FROM topology
WHERE topology_page = :topologyPage
SQL
);
$pearDB->executePreparedQuery($statement, ['topologyPage' => $r['current_page']]);
$rCP = $statement->fetch();
$currentPage = $rCP['topology_name'] . $rCP['topology_url_opt'];
$topologyName = _($rCP['topology_name']);
}
$session_data[$cpt]['current_page'] = $currentPage;
$session_data[$cpt]['topology_name'] = $topologyName;
$session_data[$cpt]['ip_address'] = $r['ip_address'];
$session_data[$cpt]['actions'] = "<a href='./main.php?p=" . $p . "&o=r'>"
. returnSvg(
'www/img/icons/refresh.svg',
'var(--help-tool-tip-icon-fill-color)',
18,
18
) . '</a>';
$selectedElements = $form->addElement('checkbox', 'select[' . $r['user_id'] . ']');
$session_data[$cpt]['checkbox'] = $selectedElements->toHtml();
$cpt++;
}
}
if (isset($msg)) {
$tpl->assign('msg', $msg);
}
$tpl->assign('session_data', $session_data);
$tpl->assign('wi_user', _('Connected users'));
$tpl->assign('wi_where', _('Position'));
$tpl->assign('actions', _('Reload ACL'));
$tpl->assign('distant_location', _('IP Address'));
?>
<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) "
. "{setO(this.form.elements['" . $option . "'].value); submit();} "
. "this.form.elements['" . $option . "'].selectedIndex = 0"];
$form->addElement('select', $option, null, [null => _('More actions...'), 'u' => _('Reload ACL')], $attrs);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('p', $p);
$tpl->display('reloadACL.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/configWizard/wizard.php | centreon/www/include/configuration/configWizard/wizard.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
// Smarty template Init
// Smarty template initialization
$path = './include/configuration/configWizard/';
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->display('wizard.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/configuration/configServers/listServers.php | centreon/www/include/configuration/configServers/listServers.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
// Init GMT class
$centreonGMT = new CentreonGMT();
$centreonGMT->getMyGMTFromSession(session_id());
$search = $_POST['searchP'] ?? $_GET['searchP'] ?? null;
if (! is_null($search)) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$LCASearch = '';
if (! is_null($search)) {
$search = HtmlSanitizer::createFromString($search)->sanitize()->getString();
$LCASearch .= " name LIKE '%{$search}%'";
}
// Get Authorized Actions
$can_generate = $centreon->user->access->checkAction('generate_cfg');
$can_create_edit = $centreon->user->access->checkAction('create_edit_poller_cfg');
$can_delete = $centreon->user->access->checkAction('delete_poller_cfg');
// nagios servers comes from DB
$nagiosServers = [];
$nagiosRestart = [];
foreach ($serverResult as $nagiosServer) {
$nagiosServers[$nagiosServer['id']] = $nagiosServer['name'];
$nagiosRestart[$nagiosServer['id']] = $nagiosServer['last_restart'];
}
$pollerstring = implode(',', array_keys($nagiosServers));
// Get information info RTM
$nagiosInfo = [];
$dbResult = $pearDBO->query(
'SELECT start_time AS program_start_time, running AS is_currently_running, pid AS process_id, instance_id, '
. 'name AS instance_name , last_alive FROM instances WHERE deleted = 0'
);
while ($info = $dbResult->fetch()) {
$nagiosInfo[$info['instance_id']] = $info;
}
$dbResult->closeCursor();
// Get Scheduler version
$dbResult = $pearDBO->query(
'SELECT DISTINCT instance_id, version AS program_version, engine AS program_name, name AS instance_name '
. 'FROM instances WHERE deleted = 0 '
);
while ($info = $dbResult->fetch()) {
if (isset($nagiosInfo[$info['instance_id']])) {
$nagiosInfo[$info['instance_id']]['version'] = $info['program_name'] . ' ' . $info['program_version'];
}
}
$dbResult->closeCursor();
$query = 'SELECT ip FROM remote_servers';
$dbResult = $pearDB->query($query);
$remotesServerIPs = $dbResult->fetchAll(PDO::FETCH_COLUMN);
$dbResult->closeCursor();
// 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_ip_address', _('Address'));
$tpl->assign('headerMenu_type', _('Server type'));
$tpl->assign('headerMenu_is_running', _('Is running ?'));
$tpl->assign('headerMenu_hasChanged', _('Conf Changed'));
$tpl->assign('headerMenu_pid', _('PID'));
$tpl->assign('headerMenu_version', _('Version'));
$tpl->assign('headerMenu_uptime', _('Uptime'));
$tpl->assign('headerMenu_lastUpdateTime', _('Last Update'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_default', _('Default'));
$tpl->assign('headerMenu_options', _('Options'));
// Poller list
$ACLString = $centreon->user->access->queryBuilder('WHERE', 'id', $pollerstring);
$query = 'SELECT SQL_CALC_FOUND_ROWS id, name, ns_activate, ns_ip_address, localhost, is_default, updated '
. ', gorgone_communication_type FROM `nagios_server` ' . $ACLString . ' '
. ($LCASearch != '' ? ($ACLString != '' ? 'AND ' : 'WHERE ') . $LCASearch : '')
. ' ORDER BY name LIMIT ' . $num * $limit . ', ' . $limit;
$dbResult = $pearDB->query($query);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
$servers = [];
while (($config = $dbResult->fetch())) {
$servers[] = $config;
}
include './include/common/checkPagination.php';
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$i = -1;
$centreonToken = createCSRFToken();
foreach ($servers as $config) {
$i++;
$moptions = '';
$selectedElements = $form->addElement(
'checkbox',
'select[' . $config['id'] . ']',
null,
'',
['id' => 'poller_' . $config['id'], 'onClick' => 'hasPollersSelected();']
);
if (! $isRemote) {
if ($config['ns_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&server_id=' . $config['id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_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 . '&server_id=' . $config['id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a>";
}
}
$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[" . $config['id'] . "]' />";
if (! isset($nagiosInfo[$config['id']]['is_currently_running'])) {
$nagiosInfo[$config['id']]['is_currently_running'] = 0;
}
// Manage flag for changes
$confChangedMessage = _('N/A');
if ($config['ns_activate'] && isset($nagiosRestart[$config['id']])) {
$confChangedMessage = $config['updated'] ? _('Yes') : _('No');
}
// Manage flag for update time
$lastUpdateTimeFlag = 0;
if (! isset($nagiosInfo[$config['id']]['last_alive'])) {
$lastUpdateTimeFlag = 0;
} elseif (time() - $nagiosInfo[$config['id']]['last_alive'] > 10 * 60) {
$lastUpdateTimeFlag = 1;
}
// Get cfg_id
$dbResult2 = $pearDB->query(
'SELECT nagios_id FROM cfg_nagios '
. 'WHERE nagios_server_id = ' . (int) $config['id'] . " AND nagios_activate = '1'"
);
$cfg_id = $dbResult2->rowCount() ? $dbResult2->fetch() : -1;
$uptime = '-';
$isRunning = (isset($nagiosInfo[$config['id']]['is_currently_running'])
&& $nagiosInfo[$config['id']]['is_currently_running'] == 1)
? true
: false;
$version = $nagiosInfo[$config['id']]['version'] ?? _('N/A');
$updateTime = (isset($nagiosInfo[$config['id']]['last_alive'])
&& $nagiosInfo[$config['id']]['last_alive'])
? $nagiosInfo[$config['id']]['last_alive']
: '-';
$serverType = $config['localhost'] ? _('Central') : _('Poller');
$serverType = in_array($config['ns_ip_address'], $remotesServerIPs)
? _('Remote Server')
: $serverType;
if (
isset($nagiosInfo[$config['id']]['is_currently_running'])
&& $nagiosInfo[$config['id']]['is_currently_running'] == 1
) {
$now = new DateTime();
$startDate = (new DateTime())->setTimestamp($nagiosInfo[$config['id']]['program_start_time']);
$interval = date_diff($now, $startDate);
if (intval($interval->format('%a')) >= 2) {
$uptime = $interval->format('%a days');
} elseif (intval($interval->format('%a')) == 1) {
$uptime = $interval->format('%a days %i minutes');
} elseif (intval($interval->format('%a')) < 1 && intval($interval->format('%h')) >= 1) {
$uptime = $interval->format('%h hours %i minutes');
} elseif (intval($interval->format('%h')) < 1) {
$uptime = $interval->format('%i minutes %s seconds');
} else {
$uptime = $interval->format('%a days %h hours %i minutes %s seconds');
}
}
$pollerProcessId = $isRunning
? $nagiosInfo[$config['id']]['process_id']
: '-';
// Manage different styles between each line
$style = ($i % 2) ? 'two' : 'one';
$serverLink = $isRemote
? "main.php?p={$p}&o=w&server_id={$config['id']}"
: "main.php?p={$p}&o=c&server_id={$config['id']}";
$elemArr[$i] = [
'MenuClass' => "list_{$style}",
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => HtmlSanitizer::createFromString($config['name'])->sanitize()->getString(),
'RowMenu_ip_address' => $config['ns_ip_address'],
'RowMenu_server_id' => $config['id'],
'RowMenu_gorgone_protocol' => $config['gorgone_communication_type'],
'RowMenu_link' => $serverLink,
'RowMenu_type' => $serverType,
'RowMenu_is_running' => $isRunning ? _('Yes') : _('No'),
'RowMenu_is_runningFlag' => $nagiosInfo[$config['id']]['is_currently_running'],
'RowMenu_is_default' => $config['is_default'] ? _('Yes') : _('No'),
'RowMenu_hasChanged' => $confChangedMessage,
'RowMenu_pid' => $pollerProcessId,
'RowMenu_hasChangedFlag' => $config['updated'],
'RowMenu_version' => $version,
'RowMenu_uptime' => $uptime,
'RowMenu_lastUpdateTime' => $updateTime,
'RowMenu_lastUpdateTimeFlag' => $lastUpdateTimeFlag,
'RowMenu_status' => $config['ns_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $config['ns_activate'] ? 'service_ok' : 'service_critical',
'RowMenu_statusVal' => $config['ns_activate'],
'RowMenu_cfg_id' => ($cfg_id == -1) ? '' : $cfg_id['nagios_id'],
'RowMenu_options' => $moptions,
];
}
$tpl->assign('elemArr', $elemArr);
$tpl->assign(
'notice',
_('Only services, servicegroups, hosts and hostgroups are taken in '
. 'account in order to calculate this status. If you modify a '
. "template, it won't tell you the configuration had changed.")
);
// Action buttons
if (! $isRemote) {
$tpl->assign(
'wizardAddBtn',
['link' => './poller-wizard/1', 'text' => _('Add'), 'class' => 'btc bt-poller-action bt_success', 'icon' => returnSvg('www/img/icons/add.svg', 'var(--button-icons-fill-color)', 16, 16)]
);
$tpl->assign(
'addBtn',
['link' => 'main.php?p=' . $p . '&o=a', 'text' => _('Add (advanced)'), 'class' => 'btc bt-poller-action bt_success', 'icon' => returnSvg('www/img/icons/add.svg', 'var(--button-icons-fill-color)', 16, 16)]
);
$tpl->assign(
'duplicateBtn',
['text' => _('Duplicate'), 'class' => 'btc bt-poller-action bt_success', 'name' => 'duplicate_action', 'icon' => returnSvg('www/img/icons/duplicate.svg', 'var(--button-icons-fill-color)', 16, 14), 'onClickAction' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (!bChecked) { alert('" . _('Please select one or more items') . "'); return false;} "
. " if (confirm('" . _('Do you confirm the duplication ?') . "')) { setO('m'); submit();} "]
);
$tpl->assign(
'deleteBtn',
['text' => _('Delete'), 'class' => 'btc bt-poller-action bt_danger', 'name' => 'delete_action', 'icon' => returnSvg('www/img/icons/trash.svg', 'var(--button-icons-fill-color)', 16, 16), 'onClickAction' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (!bChecked) { alert('" . _('Please select one or more items') . "'); return false;} "
. " if (confirm('"
. _('You are about to delete one or more pollers.\\nThis action is IRREVERSIBLE.\\n'
. 'Do you confirm the deletion ?')
. "')) { setO('d'); submit();} "]
);
$tpl->assign(
'exportBtn',
[
'link' => 'DYNAMIC_LINK', // Placeholder for dynamic link
'text' => _('Export configuration'),
'class' => 'btc bt-poller-action bt_info',
'icon' => returnSvg('www/img/icons/export.svg', 'var(--button-icons-fill-color)', 14, 14),
'id' => 'exportConfigurationLink',
]
);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchP', $search);
$tpl->assign('can_generate', $can_generate);
$tpl->assign('can_create_edit', $can_create_edit);
$tpl->assign('can_delete', $can_delete);
$tpl->assign('is_admin', $is_admin);
$tpl->assign('isRemote', $isRemote);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listServers.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/configServers/help.php | centreon/www/include/configuration/configServers/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['name'] = dgettext('help', 'Used for identifying the poller');
$help['ns_ip_address'] = dgettext('help', 'Address of the poller');
$help['localhost'] = dgettext('help', 'Whether the poller is local');
$help['is_default'] = dgettext('help', 'Main poller');
$help['remote_id'] = dgettext('help', 'Master Remote Server to which this server will be attached');
$help['remote_additional_id'] = dgettext('help', 'Additional Remote Server to which this server will be attached');
$help['ssh_port'] = dgettext('help', 'SSH legacy port used by Centreon extensions or tools (see Gorgone Information for communication port between monitoring servers)');
$help['gorgone_communication_type'] = dgettext('help', 'Gorgone communication protocol (ZMQ or SSH)');
$help['gorgone_port'] = dgettext('help', 'Gorgone port of the remote poller (5556 or 22)');
$help['engine_start_command'] = dgettext('help', 'Command to start Centreon Engine process');
$help['engine_stop_command'] = dgettext('help', 'Command to stop Centreon Engine process');
$help['engine_restart_command'] = dgettext('help', 'Command to restart Centreon Engine process');
$help['engine_reload_command'] = dgettext('help', 'Command to reload Centreon Engine process');
$help['init_script_centreontrapd'] = dgettext('help', 'Path of init script of centreontrapd');
$help['nagios_bin'] = dgettext('help', 'Path of binary of the scheduler');
$help['nagiostats_bin'] = dgettext('help', 'Path of stats binary of the scheduler');
$help['nagios_perfdata'] = dgettext('help', 'Perfdata script');
$help['broker_reload_command'] = dgettext('help', 'Command to reload Centreon Broker process');
$help['centreonbroker_cfg_path'] = dgettext('help', 'Path of the configuration file for Centreon Broker');
$help['centreonbroker_module_path'] = dgettext('help', 'Path with modules for Centreon Broker');
$help['centreonbroker_logs_path'] = dgettext('help', 'Path of the Centreon Broker log file');
$help['centreonconnector_path'] = dgettext('help', 'Path with Centreon Connector binaries');
$help['ns_activate'] = dgettext('help', 'Enable or disable poller');
$help['centreontrapd_init_script'] = dgettext('help', 'Centreontrapd init script to restart process on poller.');
$help['snmp_trapd_path_conf'] = dgettext(
'help',
'Light databases will be stored in the specified directory. '
. 'They are used for synchronizing trap definitions on pollers.'
);
$help['pollercmd'] = dgettext(
'help',
'Those commands can be executed at the end of the file generation generation/restart process. '
. 'Do not specify macros in the commands, for they will not be replaced. '
. 'Make sure to have sufficient rights for the Apache user to run these commands.'
);
$help['description'] = dgettext('help', 'Short description of the poller');
$help['http_method'] = dgettext(
'help',
'What kind of method is needed to reach the Remote Server, HTTP or HTTPS?'
);
$help['http_port'] = dgettext(
'help',
'On which TCP port is listening the Remote Server?'
);
$help['no_check_certificate'] = dgettext(
'help',
"If checked, it won't check the validity of the SSL certificate of the Remote Server."
);
$help['no_proxy'] = dgettext(
'help',
"If checked, it won't use the proxy configured in 'Administration > Parameters > Centreon UI' "
. 'to connect to the Remote Server.'
);
$help['remote_server_use_as_proxy'] = dgettext(
'help',
'If disabled, the Central server will send configuration and external commands directly to the poller '
. 'and will not use the Remote Server as a proxy.'
);
| 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/configServers/formServers.php | centreon/www/include/configuration/configServers/formServers.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\MonitoringServer\Model\MonitoringServer;
if (! isset($centreon)) {
exit();
}
if (! $centreon->user->access->checkAction('create_edit_poller_cfg')) {
echo "<div class='msg' align='center'>" . _('You are not allowed to reach this page') . '</div>';
exit();
}
require_once _CENTREON_PATH_ . '/www/class/centreon-config/centreonMainCfg.class.php';
$objMain = new CentreonMainCfg();
$monitoring_engines = [];
if (! $centreon->user->admin && $server_id && count($serverResult)) {
if (! isset($serverResult[$server_id])) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this monitoring instance'));
return null;
}
}
// Database retrieve information for Nagios
$nagios = [];
$selectedAdditionnalRS = null;
$serverType = 'poller';
$cfg_server = [];
if (($o == SERVER_MODIFY || $o == SERVER_WATCH) && $server_id) {
$dbResult = $pearDB->query("SELECT * FROM `nagios_server` WHERE `id` = '{$server_id}' LIMIT 1");
$cfg_server = array_map('myDecode', $dbResult->fetch());
$dbResult->closeCursor();
$query = 'SELECT ip FROM remote_servers';
$dbResult = $pearDB->query($query);
$remotesServerIPs = $dbResult->fetchAll(PDO::FETCH_COLUMN);
$dbResult->closeCursor();
if ($cfg_server['localhost']) {
$serverType = 'central';
} elseif (in_array($cfg_server['ns_ip_address'], $remotesServerIPs)) {
$serverType = 'remote';
}
if ($serverType === 'remote') {
$statement = $pearDB->prepare(
'SELECT http_method, http_port, no_check_certificate, no_proxy
FROM `remote_servers`
WHERE `ip` = :ns_ip_address LIMIT 1'
);
$statement->bindParam(':ns_ip_address', $cfg_server['ns_ip_address'], PDO::PARAM_STR);
$statement->execute();
$cfg_server = array_merge($cfg_server, array_map('myDecode', $statement->fetch()));
$statement->closeCursor();
}
if ($serverType === 'poller') {
// Select additional Remote Servers
$statement = $pearDB->prepare(
'SELECT remote_server_id, name
FROM rs_poller_relation AS rspr
LEFT JOIN nagios_server AS ns ON (rspr.remote_server_id = ns.id)
WHERE poller_server_id = :poller_server_id'
);
$statement->bindParam(':poller_server_id', $cfg_server['id'], PDO::PARAM_INT);
$statement->execute();
if ($statement->numRows() > 0) {
while ($row = $statement->fetch()) {
$selectedAdditionnalRS[] = ['id' => $row['remote_server_id'], 'text' => $row['name']];
}
}
$statement->closeCursor();
}
}
// Preset values of misc commands
$cdata = CentreonData::getInstance();
$cmdArray = $instanceObj->getCommandsFromPollerId($server_id ?? null);
$cdata->addJsData('clone-values-pollercmd', htmlspecialchars(
json_encode($cmdArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-pollercmd', count($cmdArray));
// 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();
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '50'];
$attrsText3 = ['size' => '5'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
// Include Poller api
$attrPollers = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_poller&action=list&t=remote', 'multiple' => false, 'linkedObject' => 'centreonInstance'];
$attrPoller1 = $attrPollers;
if (isset($cfg_server['remote_id'])) {
$attrPoller1['defaultDatasetRoute']
= './api/internal.php?object=centreon_configuration_poller&action=defaultValues'
. '&target=resources&field=instance_id&id=' . $cfg_server['remote_id'];
}
$attrPoller2 = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_poller&action=list&t=remote', 'multiple' => true, 'linkedObject' => 'centreonInstance'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == SERVER_ADD) {
$form->addElement('header', 'title', _('Add a poller'));
} elseif ($o == SERVER_MODIFY) {
$form->addElement('header', 'title', _('Modify a poller Configuration'));
} elseif ($o == SERVER_WATCH) {
$form->addElement('header', 'title', _('View a poller Configuration'));
}
// Headers
$form->addElement('header', 'Server_Informations', _('Server Information'));
$form->addElement('header', 'gorgone_Informations', _('Gorgone Information'));
$form->addElement('header', 'Nagios_Informations', _('Monitoring Engine Information'));
$form->addElement('header', 'Misc', _('Miscellaneous'));
$form->addElement('header', 'Centreontrapd', _('Centreon Trap Collector'));
// form for Remote Server
if (strcmp($serverType, 'remote') == 0) {
$form->addElement('header', 'Remote_Configuration', _('Remote Server Configuration'));
$aMethod = ['http' => 'http', 'https' => 'https'];
$form->addElement('select', 'http_method', _('HTTP Method'), $aMethod);
$form->addElement('text', 'http_port', _('HTTP Port'), $attrsText3);
$tab = [];
$tab[] = $form->createElement('radio', 'no_check_certificate', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'no_check_certificate', null, _('No'), '0');
$form->addGroup($tab, 'no_check_certificate', _('Do not check SSL certificate validation'), ' ');
$tab = [];
$tab[] = $form->createElement('radio', 'no_proxy', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'no_proxy', null, _('No'), '0');
$form->addGroup($tab, 'no_proxy', _('Do not use proxy defined in global configuration'), ' ');
}
// Poller Configuration basic information
$form->addElement('header', 'information', _('Satellite configuration'));
$form->addElement('text', 'name', _('Poller Name'), $attrsText);
$form->addElement('text', 'ns_ip_address', _('Address'), $attrsText);
$form->addElement('text', 'engine_start_command', _('Monitoring Engine start command'), $attrsText2);
$form->addElement('text', 'engine_stop_command', _('Monitoring Engine stop command'), $attrsText2);
$form->addElement('text', 'engine_restart_command', _('Monitoring Engine restart command'), $attrsText2);
$form->addElement('text', 'engine_reload_command', _('Monitoring Engine reload command'), $attrsText2);
if (strcmp($serverType, 'poller') == 0) {
$form->addElement(
'select2',
'remote_id',
_('Attach to Master Remote Server'),
[],
$attrPoller1
);
$form->addElement('select2', 'remote_additional_id', _('Attach additional Remote Servers'), [], $attrPoller2);
$tab = [];
$tab[] = $form->createElement('radio', 'remote_server_use_as_proxy', null, _('Enable'), '1');
$tab[] = $form->createElement('radio', 'remote_server_use_as_proxy', null, _('Disable'), '0');
$form->addGroup($tab, 'remote_server_use_as_proxy', _('Use the Remote Server as a proxy'), ' ');
}
$form->addElement('text', 'nagios_bin', _('Monitoring Engine Binary'), $attrsText2);
$form->addElement('text', 'nagiostats_bin', _('Monitoring Engine Statistics Binary'), $attrsText2);
$form->addElement('text', 'nagios_perfdata', _('Perfdata file'), $attrsText2);
$tab = [];
if ($serverType !== 'central') {
$form->addElement('text', 'ssh_port', _('SSH Legacy port'), $attrsText3);
}
$tab[] = $form->createElement('radio', 'gorgone_communication_type', null, _('ZMQ'), ZMQ);
$tab[] = $form->createElement('radio', 'gorgone_communication_type', null, _('SSH'), SSH);
$form->addGroup($tab, 'gorgone_communication_type', _('Gorgone connection protocol'), ' ');
$form->addElement('text', 'gorgone_port', _('Gorgone connection port'), $attrsText3);
$tab = [];
$tab[] = $form->createElement(
'radio',
'localhost',
null,
_('Yes'),
'1',
['onclick' => 'displayGorgoneParam(false);']
);
$tab[] = $form->createElement(
'radio',
'localhost',
null,
_('No'),
'0',
['onclick' => 'displayGorgoneParam(true);']
);
$form->addGroup($tab, 'localhost', _('Localhost ?'), ' ');
$tab = [];
$tab[] = $form->createElement('radio', 'is_default', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'is_default', null, _('No'), '0');
$form->addGroup($tab, 'is_default', _('Is default poller ?'), ' ');
$tab = [];
$tab[] = $form->createElement('radio', 'ns_activate', null, _('Enabled'), '1');
$tab[] = $form->createElement('radio', 'ns_activate', null, _('Disabled'), '0');
$form->addGroup($tab, 'ns_activate', _('Status'), ' ');
// Extra commands
$cmdObj = new CentreonCommand($pearDB);
$cloneSetCmd = [];
$cloneSetCmd[] = $form->addElement(
'select',
'pollercmd[#index#]',
_('Command'),
([null => null] + $cmdObj->getMiscCommands()),
['id' => 'pollercmd_#index#', 'type' => 'select-one']
);
// Centreon Broker
$form->addElement('header', 'CentreonBroker', _('Centreon Broker'));
$form->addElement('text', 'broker_reload_command', _('Centreon Broker reload command'), $attrsText2);
$form->addElement('text', 'centreonbroker_cfg_path', _('Centreon Broker configuration path'), $attrsText2);
$form->addElement('text', 'centreonbroker_module_path', _('Centreon Broker modules path'), $attrsText2);
$form->addElement('text', 'centreonbroker_logs_path', _('Centreon Broker logs path'), $attrsText2);
// Centreon Connector
$form->addElement('header', 'CentreonConnector', _('Centreon Connector'));
$form->addElement('text', 'centreonconnector_path', _('Centreon Connector path'), $attrsText2);
// Centreontrapd
$form->addElement('text', 'init_script_centreontrapd', _('Centreontrapd init script path'), $attrsText2);
$form->addElement('text', 'snmp_trapd_path_conf', _('Directory of light database for traps'), $attrsText2);
// Set Default Values
if (isset($_GET['o']) && $_GET['o'] == SERVER_ADD) {
$monitoring_engines = [
'nagios_bin' => '/usr/sbin/centengine',
'nagiostats_bin' => '/usr/sbin/centenginestats',
'engine_start_command' => MonitoringServer::DEFAULT_ENGINE_START_COMMAND,
'engine_stop_command' => MonitoringServer::DEFAULT_ENGINE_STOP_COMMAND,
'engine_restart_command' => MonitoringServer::DEFAULT_ENGINE_RESTART_COMMAND,
'engine_reload_command' => MonitoringServer::DEFAULT_ENGINE_RELOAD_COMMAND,
'nagios_perfdata' => '/var/log/centreon-engine/service-perfdata',
];
$form->setDefaults(
[
'name' => '',
'localhost' => '0',
'ns_ip_address' => '127.0.0.1',
'description' => '',
'nagios_bin' => $monitoring_engines['nagios_bin'],
'nagiostats_bin' => $monitoring_engines['nagiostats_bin'],
'engine_start_command' => $monitoring_engines['engine_start_command'],
'engine_stop_command' => $monitoring_engines['engine_stop_command'],
'engine_restart_command' => $monitoring_engines['engine_restart_command'],
'engine_reload_command' => $monitoring_engines['engine_reload_command'],
'ns_activate' => '1',
'is_default' => '0',
'ssh_port' => 22,
'gorgone_communication_type' => ZMQ,
'gorgone_port' => 5556,
'nagios_perfdata' => $monitoring_engines['nagios_perfdata'],
'broker_reload_command' => MonitoringServer::DEFAULT_BROKER_RELOAD_COMMAND,
'centreonbroker_cfg_path' => '/etc/centreon-broker',
'centreonbroker_module_path' => '/usr/share/centreon/lib/centreon-broker',
'centreonbroker_logs_path' => '/var/log/centreon-broker',
'init_script_centreontrapd' => 'centreontrapd',
'snmp_trapd_path_conf' => '/etc/snmp/centreon_traps/',
'remote_server_use_as_proxy' => '1',
]
);
} elseif (isset($cfg_server)) {
$form->setDefaults($cfg_server);
}
$form->addElement('hidden', 'id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
$form->registerRule('exist', 'callback', 'testExistence');
$form->registerRule('testAdditionalRemoteServer', 'callback', 'testAdditionalRemoteServer');
$form->registerRule('isValidIpAddress', 'callback', 'isValidIpAddress');
$form->addRule('name', _('Name is already in use'), 'exist');
$form->addRule('name', _('The name of the poller is mandatory'), 'required');
$form->addRule('ns_ip_address', _('Compulsory Name'), 'required');
if ($serverType === 'poller') {
$form->addRule(
['remote_additional_id', 'remote_id'],
_('To use additional Remote Servers a Master Remote Server must be selected.'),
'testAdditionalRemoteServer'
);
}
$form->addRule('ns_ip_address', _('The address is incorrect'), 'isValidIpAddress');
$form->registerRule('isValidStartCommandSyntax', 'callback', 'isValidStartCommandSyntax');
$form->registerRule('isValidStopCommandSyntax', 'callback', 'isValidStopCommandSyntax');
$form->registerRule('isValidRestartCommandSyntax', 'callback', 'isValidRestartCommandSyntax');
$form->registerRule('isValidReloadCommandSyntax', 'callback', 'isValidReloadCommandSyntax');
$form->addRule('engine_start_command', _('The command format is invalid'), 'isValidStartCommandSyntax');
$form->addRule('engine_stop_command', _('The command format is invalid'), 'isValidStopCommandSyntax');
$form->addRule('engine_restart_command', _('The command format is invalid'), 'isValidRestartCommandSyntax');
$form->addRule('engine_reload_command', _('The command format is invalid'), 'isValidReloadCommandSyntax');
$form->addRule('broker_reload_command', _('The command format is invalid'), 'isValidReloadCommandSyntax');
$form->registerRule('isValidPath', 'callback', 'isValidPath');
$form->addRule('nagios_bin', _('The path format is invalid'), 'isValidPath');
$form->addRule('nagiostats_bin', _('The path format is invalid'), 'isValidPath');
$form->addRule('nagios_perfdata', _('The path format is invalid'), 'isValidPath');
$form->addRule('centreonbroker_cfg_path', _('The path format is invalid'), 'isValidPath');
$form->addRule('centreonbroker_module_path', _('The path format is invalid'), 'isValidPath');
$form->addRule('centreonbroker_logs_path', _('The path format is invalid'), 'isValidPath');
$form->addRule('snmp_trapd_path_conf', _('The path format is invalid'), 'isValidPath');
$form->registerRule('isValidTrapInit', 'callback', 'isValidTrapInit');
$form->addRule('init_script_centreontrapd', _('The script path is invalid'), 'isValidTrapInit');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
if ($o == SERVER_WATCH) {
// Just watch a nagios information
if ($centreon->user->access->page($p) != 2 && ! $isRemote) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&id=' . $server_id . "'"]
);
}
$form->setDefaults($nagios);
$form->freeze();
} elseif ($o == SERVER_MODIFY) {
// Modify a nagios information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->registerRule('ipCanBeUpdated', 'callback', 'ipCanBeUpdated');
$form->addRule(
['ns_ip_address', 'id'],
_('The address is already registered on another poller'),
'ipCanBeUpdated'
);
$form->setDefaults($nagios);
} elseif ($o == SERVER_ADD) {
// Add a nagios information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->registerRule('ipCanBeRegistered', 'callback', 'ipCanBeRegistered');
$form->addRule('ns_ip_address', _('The address is already registered'), 'ipCanBeRegistered');
}
$valid = false;
if ($form->validate()) {
$nagiosObj = $form->getElement('id');
if ($form->getSubmitValue('submitA')) {
insertServerInDB($form->getSubmitValues());
} elseif ($form->getSubmitValue('submitC')) {
updateServer(
(int) $nagiosObj->getValue(),
$form->getSubmitValues()
);
}
$o = null;
$valid = true;
}
if ($valid) {
defineLocalPollerToDefault();
require_once $path . 'listServers.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <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('engines', $monitoring_engines);
$tpl->assign('cloneSetCmd', $cloneSetCmd);
$tpl->assign('centreon_path', $centreon->optGen['oreon_path']);
$tpl->assign('isRemote', $isRemote);
include_once 'help.php';
$helptext = '';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$tpl->display('formServers.ihtml');
}
?>
<script type='text/javascript'>
// toggle gorgone port and communication mode fields
function displayGorgoneParam(checkValue) {
if (checkValue === true) {
jQuery('#gorgoneData').fadeIn({duration: 0});
} else {
jQuery('#gorgoneData').fadeOut({duration: 0});
}
}
// init current gorgone fields visibility
displayGorgoneParam(<?= ! isset($cfg_server['localhost']) || ! $cfg_server['localhost'] ? 'true' : 'false'; ?>)
jQuery("#remote_additional_id").centreonSelect2({
select2: {
ajax: {
url: './api/internal.php?object=centreon_configuration_poller&action=list&t=remote',
cache: false
},
multiple: true,
},
allowClear: true,
additionnalFilters: {
e: '#remote_id'
}
});
//check of gorgone_port type
jQuery(function () {
jQuery("input[name='gorgone_port']").change(function () {
if (isNaN(this.value)) {
const msg = "<span id='errMsg'><font style='color: red;'> Need to be a number</font></span>";
jQuery(msg).insertAfter(this);
jQuery("input[type='submit']").prop('disabled', true);
} else {
jQuery('#errMsg').remove();
jQuery("input[type='submit']").prop('disabled', false);
}
});
});
jQuery(function () {
jQuery("#remote_id").change(function () {
var master_remote_id = jQuery("#remote_id").val();
var remote_additional_id = jQuery("#remote_additional_id").val();
jQuery.ajax({
url: "./api/internal.php?object=centreon_configuration_poller&action=list&t=remote&e="
+ master_remote_id,
type: "GET",
dataType: "json",
success: function (json) {
jQuery('#remote_additional_id').val('');
json.items.forEach(function (elem) {
jQuery('#remote_additional_id').empty();
if (jQuery.inArray(elem.id, remote_additional_id) != -1
&& elem.id != master_remote_id && elem.id) {
jQuery('#remote_additional_id').append(
'<option value="' + elem.id + '" selected>' + elem.text + '</option>'
);
}
});
jQuery('#remote_additional_id').trigger('change');
}
});
});
var initAdditionnalRS = '<?php echo json_encode($selectedAdditionnalRS); ?>';
var pollers = JSON.parse(initAdditionnalRS);
if (pollers) {
for (var i = 0; i < pollers.length; i++) {
if (pollers[i].text != null) {
jQuery('#remote_additional_id').append(
'<option value="' + pollers[i].id + '" selected>' + pollers[i].text + '</option>'
);
}
}
jQuery('#remote_additional_id').trigger('change');
}
});
</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/configServers/servers.php | centreon/www/include/configuration/configServers/servers.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
$server_id = filter_var(
$_GET['server_id'] ?? $_POST['server_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
$_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [],
FILTER_VALIDATE_INT
);
// Path to the configuration dir
$path = './include/configuration/configServers/';
// PHP functions
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'];
}
// Build poller listing for ACL
$serverResult
= $centreon->user->access->getPollerAclConf(
[
'fields' => ['id', 'name', 'last_restart'],
'order' => ['name'],
'keys' => ['id'],
]
);
$instanceObj = new CentreonInstance($pearDB);
define('SERVER_ADD', 'a');
define('SERVER_DELETE', 'd');
define('SERVER_DISABLE', 'u');
define('SERVER_DUPLICATE', 'm');
define('SERVER_ENABLE', 's');
define('SERVER_MODIFY', 'c');
define('SERVER_WATCH', 'w');
$action = filter_var(
$_POST['o1'] ?? $_POST['o2'] ?? null,
FILTER_VALIDATE_REGEXP,
['options' => ['regexp' => '/^(a|c|d|m|s|u|w)$/']]
);
if ($action !== false) {
$o = $action;
}
/**
* Actions forbidden if server is a remote
*/
$forbiddenIfRemote = [
SERVER_ADD,
SERVER_MODIFY,
SERVER_ENABLE,
SERVER_DISABLE,
SERVER_DUPLICATE,
SERVER_DELETE,
];
if ($isRemote && in_array($o, $forbiddenIfRemote)) {
require_once $path . '../../core/errors/alt_error.php';
exit();
}
switch ($o) {
case SERVER_ADD:
case SERVER_WATCH:
case SERVER_MODIFY:
require_once $path . 'formServers.php';
break;
case SERVER_ENABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($server_id !== false) {
enableServerInDB($server_id);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listServers.php';
break;
case SERVER_DISABLE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($server_id !== false) {
disableServerInDB($server_id);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listServers.php';
break;
case SERVER_DUPLICATE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $select) && ! in_array(false, $dupNbr)) {
duplicateServer($select, $dupNbr);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listServers.php';
break;
case SERVER_DELETE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $select)) {
deleteServerInDB($select);
}
} else {
unvalidFormMessage();
}
// then require the same file than default
// no break
default:
require_once $path . 'listServers.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/configServers/DB-Func.php | centreon/www/include/configuration/configServers/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\PlatformTopology\Model\PlatformRegistered;
use Core\MonitoringServer\Model\MonitoringServer;
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . '/www/class/centreon-config/centreonMainCfg.class.php';
const ZMQ = 1;
const SSH = 2;
/**
* Retrieve the next available suffixes for this server name from database
*
* @param string $serverName Server name to process
* @param int $numberOf Number of suffix requested
* @param string $separator Character used to separate the server name and suffix
*
* @throws Exception
* @return array Return the next available suffixes
* @global CentreonDB $pearDB DB connector
*/
function getAvailableSuffixIds(
string $serverName,
int $numberOf,
string $separator = '_',
): array {
if ($numberOf < 0) {
return [];
}
global $pearDB;
/**
* To avoid that this column value will be interpreted like regular
* expression in the database query
*/
$serverName = preg_quote($serverName);
// Get list of suffix already used
$query = <<<'SQL'
SELECT CAST(SUBSTRING_INDEX(name, '_', -1) AS SIGNED) AS suffix
FROM nagios_server WHERE name REGEXP :server_name_separator
ORDER BY suffix
SQL;
$stmt = $pearDB->prepare($query);
$stmt->bindValue(':server_name_separator', '^"' . $serverName . $separator . '[0-9]+$', PDO::PARAM_STR);
$stmt->execute();
$notAvailableSuffixes = [];
while ($result = $stmt->fetch()) {
$suffix = (int) $result['suffix'];
if (! in_array($suffix, $notAvailableSuffixes)) {
$notAvailableSuffixes[] = $suffix;
}
}
/**
* Search for available suffixes taking into account those found in the database
*/
$nextAvailableSuffixes = [];
$counter = 1;
while (count($nextAvailableSuffixes) < $numberOf) {
if (! in_array($counter, $notAvailableSuffixes)) {
$nextAvailableSuffixes[] = $counter;
}
$counter++;
}
return $nextAvailableSuffixes;
}
/**
* Check if Master Remote is selected to use additional Remote Server
*
* @param array $values the values of Remote Servers selectboxes
*
* @return false only if additional Remote Server selectbox is not empty and Master selectbox is empty
*/
function testAdditionalRemoteServer(array $values)
{
// If remote_additional_id select2 is not empty
if (
isset($values[0])
&& is_array($values[0])
&& count($values[0]) >= 1
) {
// If Master Remote Server is not empty
return (bool) (isset($values[1]) && trim($values[1]) != '');
}
return true;
}
/**
* Check if the name already exist in database
*
* @param string $name Name to check
*
* @return bool Return true if the name does not exist in database
*/
function testExistence($name = null): bool
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('id');
}
$query = 'SELECT name, id FROM `nagios_server` WHERE `name` = :name';
$statement = $pearDB->prepare($query);
$statement->bindValue(':name', htmlentities($name, ENT_QUOTES, 'UTF-8'), PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
if ($statement->rowCount() >= 1 && $row['id'] == $id) {
return true;
}
return ! ($statement->rowCount() >= 1 && $row['id'] != $id);
}
/**
* Test is the IP address is a valid IPv4/IPv6 or FQDN
*
* @param string $ipAddress The IP address to test
* @return bool
*/
function isValidIpAddress(string $ipAddress): bool
{
// Check IPv6, IPv4 and FQDN format
return ! (
! filter_var($ipAddress, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)
&& ! filter_var($ipAddress, FILTER_VALIDATE_IP)
);
}
/**
* Enable a server
*
* @param int $id Id of the server
*
* @throws Exception
* @global CentreonDB $pearDB DB connector
* @global Centreon $centreon
*/
function enableServerInDB(int $id): void
{
global $pearDB, $centreon;
$dbResult = $pearDB->query('SELECT name FROM `nagios_server` WHERE `id` = ' . $id . ' LIMIT 1');
$row = $dbResult->fetch();
$pearDB->query("UPDATE `nagios_server` SET `ns_activate` = '1' WHERE id = " . $id);
$centreon->CentreonLogAction->insertLog('poller', $id, $row['name'], 'enable');
$query = 'SELECT MIN(`nagios_id`) AS idEngine FROM cfg_nagios WHERE `nagios_server_id` = ' . $id;
$dbResult = $pearDB->query($query);
$idEngine = $dbResult->fetch();
if ($idEngine['idEngine']) {
$pearDB->query(
"UPDATE `cfg_nagios` SET `nagios_activate` = '0' WHERE `nagios_server_id` = " . $id
);
$pearDB->query(
"UPDATE cfg_nagios SET nagios_activate = '1' WHERE nagios_id = " . (int) $idEngine['idEngine']
);
}
}
/**
* Disable a server
*
* @param int $id Id of the server
*
* @throws Exception
* @global CentreonDB $pearDB DB connector
* @global Centreon $centreon
*/
function disableServerInDB(int $id): void
{
global $pearDB, $centreon;
$dbResult = $pearDB->query('SELECT name FROM `nagios_server` WHERE `id` = ' . $id . ' LIMIT 1');
$row = $dbResult->fetch();
$pearDB->query("UPDATE `nagios_server` SET `ns_activate` = '0' WHERE id = " . $id);
$centreon->CentreonLogAction->insertLog(
'poller',
$id,
$row['name'],
'disable'
);
$pearDB->query(
"UPDATE `cfg_nagios` SET `nagios_activate` = '0' WHERE `nagios_server_id` = " . $id
);
}
/**
* Delete a server
*
* @param array $serverIds
*
* @global CentreonDB $pearDB DB connector
* @global Centreon $centreon
*/
function deleteServerInDB(array $serverIds): void
{
global $pearDB, $pearDBO, $centreon;
foreach (array_keys($serverIds) as $serverId) {
$statement = $pearDB->prepare('SELECT `id`, `type` FROM `platform_topology` WHERE server_id = :serverId ');
$statement->bindValue(':serverId', (int) $serverId, PDO::PARAM_INT);
$statement->execute();
// If the deleted platform is a remote, reassign the parent_id of its children to the top level platform
if (
($platformInTopology = $statement->fetch(PDO::FETCH_ASSOC))
&& $platformInTopology['type'] === PlatformRegistered::TYPE_REMOTE
) {
$statement = $pearDB->query('SELECT id FROM `platform_topology` WHERE parent_id IS NULL');
if ($topPlatform = $statement->fetch(PDO::FETCH_ASSOC)) {
$statement2 = $pearDB->prepare('
UPDATE `platform_topology`
SET `parent_id` = :topPlatformId
WHERE `parent_id` = :remoteId
');
$statement2->bindValue(':topPlatformId', (int) $topPlatform['id'], PDO::PARAM_INT);
$statement2->bindValue(':remoteId', (int) $platformInTopology['id'], PDO::PARAM_INT);
$statement2->execute();
}
}
$result = $pearDB->query(
'SELECT name, ns_ip_address AS ip FROM `nagios_server` WHERE `id` = ' . $serverId . ' LIMIT 1'
);
$row = $result->fetch();
// Is a Remote Server?
$statement = $pearDB->prepare(
'SELECT * FROM remote_servers WHERE server_id = :id'
);
$statement->bindValue(':id', $serverId, PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount() > 0) {
// Delete entry from remote_servers
$statement = $pearDB->prepare(
'DELETE FROM remote_servers WHERE server_id = :id'
);
$statement->bindValue(':id', $serverId, PDO::PARAM_INT);
$statement->execute();
// Delete all relation between this Remote Server and pollers
$pearDB->query(
"DELETE FROM rs_poller_relation WHERE remote_server_id = '" . $serverId . "'"
);
} else {
// Delete all relation between this poller and Remote Servers
$pearDB->query(
"DELETE FROM rs_poller_relation WHERE poller_server_id = '" . $serverId . "'"
);
}
$pearDB->query('DELETE FROM `nagios_server` WHERE id = ' . $serverId);
$pearDBO->query(
"UPDATE `instances` SET deleted = '1' WHERE instance_id = " . $serverId
);
deleteCentreonBrokerByPollerId($serverId);
$centreon->CentreonLogAction->insertLog(
'poller',
$serverId,
$row['name'],
'd'
);
}
}
/**
* Delete Centreon Broker configurations
*
* @param int $id The Id poller
*
* @global CentreonDB $pearDB DB connector
*/
function deleteCentreonBrokerByPollerId(int $id)
{
global $pearDB;
$pearDB->query(
'DELETE FROM cfg_centreonbroker WHERE ns_nagios_server = ' . $id
);
}
/**
* Duplicate server
*
* @param array $server List of server id to duplicate
* @param array $nbrDup Number of duplications per server id
*
* @throws Exception
* @global CentreonDB $pearDB DB connector
*/
function duplicateServer(array $server, array $nbrDup): void
{
global $pearDB;
$obj = new CentreonMainCfg();
foreach (array_keys($server) as $serverId) {
$result = $pearDB->query(
'SELECT * FROM `nagios_server` WHERE id = ' . (int) $serverId . ' LIMIT 1'
);
$rowServer = $result->fetch();
$rowServer['id'] = null;
$rowServer['ns_activate'] = '0';
$rowServer['is_default'] = '0';
$rowServer['localhost'] = '0';
$result->closeCursor();
if (! isset($rowServer['name'])) {
continue;
}
$rowBks = $obj->getBrokerModules($serverId);
$availableSuffix = getAvailableSuffixIds(
$rowServer['name'],
$nbrDup[$serverId]
);
foreach ($availableSuffix as $suffix) {
$queryValues = null;
$serverName = null;
foreach ($rowServer as $columnName => $columnValue) {
if ($columnName == 'name') {
$columnValue .= '_' . $suffix;
$serverName = $columnValue;
}
if (is_null($queryValues)) {
$queryValues .= $columnValue != null
? ("'" . $columnValue . "'")
: 'NULL';
} else {
$queryValues .= $columnValue != null
? (", '" . $columnValue . "'")
: ', NULL';
}
}
if (! is_null($queryValues) && testExistence($serverName)) {
if ($queryValues) {
$pearDB->query('INSERT INTO `nagios_server` VALUES (' . $queryValues . ')');
}
$queryGetId = 'SELECT id FROM nagios_server WHERE name = :name';
try {
$statement = $pearDB->prepare($queryGetId);
$statement->bindValue(':name', $serverName, PDO::PARAM_STR);
$statement->execute();
if ($statement->rowCount() > 0) {
$row = $statement->fetch(PDO::FETCH_ASSOC);
$iId = $obj->insertServerInCfgNagios($serverId, $row['id'], $serverName);
$obj->insertCfgNagiosLogger($iId, $serverId);
if (isset($rowBks)) {
$rqBk = 'INSERT INTO cfg_nagios_broker_module (`cfg_nagios_id`, `broker_module`)'
. ' VALUES (:cfg_nagios_id, :broker_module)';
$statement = $pearDB->prepare($rqBk);
foreach ($rowBks as $keyBk => $valBk) {
if ($valBk['broker_module']) {
$statement->bindValue(':cfg_nagios_id', (int) $iId, PDO::PARAM_INT);
$statement->bindValue(':broker_module', $valBk['broker_module'], PDO::PARAM_STR);
$statement->execute();
}
}
}
$queryRel = 'INSERT INTO cfg_resource_instance_relations (resource_id, instance_id) '
. 'SELECT b.resource_id, :instance_id FROM '
. 'cfg_resource_instance_relations as b WHERE b.instance_id = :b_instance_id';
$statement = $pearDB->prepare($queryRel);
$statement->bindValue(':instance_id', (int) $row['id'], PDO::PARAM_INT);
$statement->bindValue(':b_instance_id', (int) $serverId, PDO::PARAM_INT);
$statement->execute();
$queryCmd = 'INSERT INTO poller_command_relations (poller_id, command_id, command_order) '
. 'SELECT :poller_id, b.command_id, b.command_order FROM '
. 'poller_command_relations as b WHERE b.poller_id = :b_poller_id';
$statement = $pearDB->prepare($queryCmd);
$statement->bindValue(':poller_id', (int) $row['id'], PDO::PARAM_INT);
$statement->bindValue(':b_poller_id', (int) $serverId, PDO::PARAM_INT);
$statement->execute();
duplicateRemoteServerInformation((int) $serverId, (int) $row['id']);
}
} catch (PDOException $e) {
// Nothing to do
}
}
}
}
}
/**
* Insert additionnal Remote Servers relation
*
* @param int $id Id of the server
* @param array $remotes Id of the additionnal Remote Servers
*
* @throws Exception
* @return void
*
* @global CentreonDB $pearDB DB connector
*/
function additionnalRemoteServersByPollerId(int $id, ?array $remotes = null): void
{
global $pearDB;
$statement = $pearDB->prepare('DELETE FROM rs_poller_relation WHERE poller_server_id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$statement->execute();
if (! is_null($remotes)) {
$statement = $pearDB->prepare('INSERT INTO rs_poller_relation VALUES (:remote_id,:poller_id)');
foreach ($remotes as $remote) {
$statement->bindParam(':remote_id', $remote, PDO::PARAM_INT);
$statement->bindParam(':poller_id', $id, PDO::PARAM_INT);
$statement->execute();
}
}
}
/**
* Insert a new server
*
* @param array $data Data of the new server
*
* @return int Id of the new server
*/
function insertServerInDB(array $data): int
{
$srvObj = new CentreonMainCfg();
$sName = '';
$id = insertServer($data);
if (isset($data['name'])) {
$sName = $data['name'];
}
$iIdNagios = $srvObj->insertServerInCfgNagios(-1, $id, $sName);
additionnalRemoteServersByPollerId($id, $data['remote_additional_id']);
if (! empty($iIdNagios)) {
$srvObj->insertBrokerDefaultDirectives($iIdNagios, 'ui');
$srvObj->insertDefaultCfgNagiosLogger($iIdNagios);
}
addUserRessource($id);
return $id;
}
/**
* Create a server in database
*
* @param array $data Data of the new server
*
* @return int Id of the new server
* @global Centreon $centreon
* @global CentreonDB $pearDB DB connector
*/
function insertServer(array $data): int
{
global $pearDB, $centreon;
$retValue = [];
$rq = 'INSERT INTO `nagios_server` (`name` , `localhost`, `ns_ip_address`, `ssh_port`, '
. '`gorgone_communication_type`, `gorgone_port`, `nagios_bin`, `nagiostats_bin`, '
. '`engine_start_command`, `engine_stop_command`, `engine_restart_command`, `engine_reload_command`, '
. '`init_script_centreontrapd`, `snmp_trapd_path_conf`, '
. '`nagios_perfdata` , `broker_reload_command`, '
. '`centreonbroker_cfg_path`, `centreonbroker_module_path`, `centreonconnector_path`, '
. '`is_default`, `ns_activate`, `centreonbroker_logs_path`, `remote_id`, `remote_server_use_as_proxy`) ';
$rq .= 'VALUES (';
if (isset($data['name']) && $data['name'] != null) {
$rq .= ':name, ';
$retValue[':name'] = htmlentities(trim($data['name']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['localhost']['localhost']) && $data['localhost']['localhost'] != null) {
$rq .= ':localhost, ';
$retValue[':localhost'] = htmlentities($data['localhost']['localhost'], ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['ns_ip_address']) && $data['ns_ip_address'] != null) {
$rq .= ':ns_ip_address, ';
$retValue[':ns_ip_address'] = htmlentities(trim($data['ns_ip_address']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['ssh_port']) && $data['ssh_port'] != null) {
$rq .= ':ssh_port, ';
$retValue[':ssh_port'] = (int) $data['ssh_port'];
} else {
$rq .= '22, ';
}
if (
isset($data['gorgone_communication_type']['gorgone_communication_type'])
&& $data['gorgone_communication_type']['gorgone_communication_type'] != null
) {
$rq .= ':gorgone_communication_type, ';
$retValue[':gorgone_communication_type']
= htmlentities(trim($data['gorgone_communication_type']['gorgone_communication_type']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= "'1', ";
}
if (isset($data['gorgone_port']) && $data['gorgone_port'] != null) {
$rq .= ':gorgone_port, ';
$retValue[':gorgone_port'] = (int) $data['gorgone_port'];
} else {
$rq .= '5556, ';
}
if (isset($data['nagios_bin']) && $data['nagios_bin'] != null) {
$rq .= ':nagios_bin, ';
$retValue[':nagios_bin'] = htmlentities(trim($data['nagios_bin']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['nagiostats_bin']) && $data['nagiostats_bin'] != null) {
$rq .= ':nagiostats_bin, ';
$retValue[':nagiostats_bin'] = htmlentities(trim($data['nagiostats_bin']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['engine_start_command']) && $data['engine_start_command'] != null) {
$rq .= ':engine_start_command, ';
$retValue[':engine_start_command'] = htmlentities(trim($data['engine_start_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['engine_stop_command']) && $data['engine_stop_command'] != null) {
$rq .= ':engine_stop_command, ';
$retValue[':engine_stop_command'] = htmlentities(trim($data['engine_stop_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['engine_restart_command']) && $data['engine_restart_command'] != null) {
$rq .= ':engine_restart_command, ';
$retValue[':engine_restart_command'] = htmlentities(trim($data['engine_restart_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['engine_reload_command']) && $data['engine_reload_command'] != null) {
$rq .= ':engine_reload_command, ';
$retValue[':engine_reload_command'] = htmlentities(trim($data['engine_reload_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['init_script_centreontrapd']) && $data['init_script_centreontrapd'] != null) {
$rq .= ':init_script_centreontrapd, ';
$retValue[':init_script_centreontrapd']
= htmlentities(trim($data['init_script_centreontrapd']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['snmp_trapd_path_conf']) && $data['snmp_trapd_path_conf'] != null) {
$rq .= ':snmp_trapd_path_conf, ';
$retValue[':snmp_trapd_path_conf'] = htmlentities(trim($data['snmp_trapd_path_conf']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['nagios_perfdata']) && $data['nagios_perfdata'] != null) {
$rq .= ':nagios_perfdata, ';
$retValue[':nagios_perfdata'] = htmlentities(trim($data['nagios_perfdata']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['broker_reload_command']) && $data['broker_reload_command'] != null) {
$rq .= ':broker_reload_command, ';
$retValue[':broker_reload_command'] = htmlentities(trim($data['broker_reload_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['centreonbroker_cfg_path']) && $data['centreonbroker_cfg_path'] != null) {
$rq .= ':centreonbroker_cfg_path, ';
$retValue[':centreonbroker_cfg_path']
= htmlentities(trim($data['centreonbroker_cfg_path']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['centreonbroker_module_path']) && $data['centreonbroker_module_path'] != null) {
$rq .= ':centreonbroker_module_path, ';
$retValue[':centreonbroker_module_path']
= htmlentities(trim($data['centreonbroker_module_path']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['centreonconnector_path']) && $data['centreonconnector_path'] != null) {
$rq .= ':centreonconnector_path, ';
$retValue[':centreonconnector_path'] = htmlentities(trim($data['centreonconnector_path']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['is_default']['is_default']) && $data['is_default']['is_default'] != null) {
$rq .= ':is_default, ';
$retValue[':is_default'] = htmlentities(trim($data['is_default']['is_default']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['ns_activate']['ns_activate']) && $data['ns_activate']['ns_activate'] != 2) {
$rq .= ':ns_activate, ';
$retValue[':ns_activate'] = $data['ns_activate']['ns_activate'];
} else {
$rq .= 'NULL, ';
}
if (isset($data['centreonbroker_logs_path']) && $data['centreonbroker_logs_path'] != null) {
$rq .= ':centreonbroker_logs_path, ';
$retValue[':centreonbroker_logs_path']
= htmlentities(trim($data['centreonbroker_logs_path']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (isset($data['remote_id']) && $data['remote_id'] != null) {
$rq .= ':remote_id, ';
$retValue[':remote_id'] = htmlentities(trim($data['remote_id']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
if (
isset($data['remote_server_use_as_proxy']['remote_server_use_as_proxy'])
&& $data['remote_server_use_as_proxy']['remote_server_use_as_proxy'] != null
) {
$rq .= ':remote_server_use_as_proxy ';
$retValue[':remote_server_use_as_proxy']
= htmlentities($data['remote_server_use_as_proxy']['remote_server_use_as_proxy'], ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL ';
}
$rq .= ')';
$stmt = $pearDB->prepare($rq);
foreach ($retValue as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->execute();
$result = $pearDB->query('SELECT MAX(id) as last_id FROM `nagios_server`');
$poller = $result->fetch();
$result->closeCursor();
try {
insertServerIntoPlatformTopology($retValue, (int) $poller['last_id']);
} catch (Exception $e) {
// catch exception but don't return anything to avoid blank pages on form
}
if (isset($_REQUEST['pollercmd'])) {
$instanceObj = new CentreonInstance($pearDB);
$instanceObj->setCommands($poller['last_id'], $_REQUEST['pollercmd']);
}
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($data);
$centreon->CentreonLogAction->insertLog(
'poller',
$poller['last_id'] ?? null,
CentreonDB::escape($data['name']),
'a',
$fields
);
/**
* Update poller ACL.
*/
$centreon->user->access->updatePollerACL();
return (int) $poller['last_id'];
}
/**
* @param int $serverId Id of the server
*
* @return bool Return true if ok
* @global CentreonDB $pearDB DB connector
* global Centreon $centreon
*/
function addUserRessource(int $serverId): bool
{
global $pearDB, $centreon;
$queryInsert = 'INSERT INTO cfg_resource_instance_relations (resource_id, instance_id) VALUES (%d, %d)';
$queryGetResources = 'SELECT resource_id, resource_name FROM cfg_resource ORDER BY resource_id';
try {
$res = $pearDB->query($queryGetResources);
} catch (PDOException $e) {
return false;
}
$isInsert = [];
while ($resource = $res->fetch()) {
if (! in_array($resource['resource_name'], $isInsert)) {
$isInsert[] = $resource['resource_name'];
$query = sprintf(
$queryInsert,
(int) $resource['resource_id'],
$serverId
);
$pearDB->query($query);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($resource);
$centreon->CentreonLogAction->insertLog(
'resource',
$serverId,
CentreonDB::escape($resource['resource_name']),
'a',
$fields
);
}
}
return true;
}
/**
* Update Remote Server information
*
* @param array $data
* @param int $id remote server id
*/
function updateRemoteServerInformation(array $data, int $id)
{
global $pearDB;
$statement = $pearDB->prepare('SELECT COUNT(*) AS total FROM remote_servers WHERE server_id = :id');
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$total = (int) $statement->fetch(PDO::FETCH_ASSOC)['total'];
if ($total === 1) {
$statement = $pearDB->prepare('
UPDATE remote_servers
SET http_method = :http_method, http_port = :http_port,
no_check_certificate = :no_check_certificate, no_proxy = :no_proxy, ip = :new_ip
WHERE server_id = :id
');
$statement->bindValue(':http_method', $data['http_method']);
$statement->bindValue(':http_port', $data['http_port'] ?? null, PDO::PARAM_INT);
$statement->bindValue(':no_proxy', $data['no_proxy']['no_proxy']);
$statement->bindValue(':no_check_certificate', $data['no_check_certificate']['no_check_certificate']);
$statement->bindValue(':new_ip', $data['ns_ip_address']);
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
}
}
/**
* Update a server
*
* @param int $id
* @param array $data
*
* @throws Exception
*/
function updateServer(int $id, array $data): void
{
global $pearDB, $centreon;
if ($data['localhost']['localhost'] == 1) {
$pearDB->query("UPDATE `nagios_server` SET `localhost` = '0'");
}
if ($data['is_default']['is_default'] == 1) {
$pearDB->query("UPDATE `nagios_server` SET `is_default` = '0'");
}
$retValue = [];
// We retrieve IP address that was defined before the update request
$statement = $pearDB->prepare('SELECT ns_ip_address FROM nagios_server WHERE id = :id');
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$ipAddressBeforeChanges = ($result = $statement->fetch(PDO::FETCH_ASSOC))
? $result['ns_ip_address']
: null;
$rq = 'UPDATE `nagios_server` SET ';
$rq .= '`name` = ';
if (isset($data['name']) && $data['name'] != null) {
$rq .= ':name, ';
$retValue[':name'] = $data['name'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`localhost` = ';
if (isset($data['localhost']['localhost']) && $data['localhost']['localhost'] != null) {
$rq .= ':localhost, ';
$retValue[':localhost'] = htmlentities($data['localhost']['localhost'], ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`ns_ip_address` = ';
if (isset($data['ns_ip_address']) && $data['ns_ip_address'] != null) {
$rq .= ':ns_ip_address, ';
$retValue[':ns_ip_address'] = htmlentities(trim($data['ns_ip_address']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`ssh_port` = ';
if (isset($data['ssh_port']) && $data['ssh_port'] != null) {
$rq .= ':ssh_port, ';
$retValue[':ssh_port'] = (int) $data['ssh_port'];
} else {
$rq .= '22, ';
}
$rq .= '`gorgone_communication_type` = ';
if (
isset($data['gorgone_communication_type']['gorgone_communication_type'])
&& $data['gorgone_communication_type']['gorgone_communication_type'] != null
) {
$rq .= ':gorgone_communication_type, ';
$retValue[':gorgone_communication_type']
= htmlentities(trim($data['gorgone_communication_type']['gorgone_communication_type']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= "'1', ";
}
$rq .= '`gorgone_port` = ';
if (isset($data['gorgone_port']) && $data['gorgone_port'] != null) {
$rq .= ':gorgone_port, ';
$retValue[':gorgone_port'] = (int) $data['gorgone_port'];
} else {
$rq .= '5556, ';
}
$rq .= '`engine_start_command` = ';
if (isset($data['engine_start_command']) && $data['engine_start_command'] != null) {
$rq .= ':engine_start_command, ';
$retValue[':engine_start_command'] = htmlentities(trim($data['engine_start_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`engine_stop_command` = ';
if (isset($data['engine_stop_command']) && $data['engine_stop_command'] != null) {
$rq .= ':engine_stop_command, ';
$retValue[':engine_stop_command'] = htmlentities(trim($data['engine_stop_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`engine_restart_command` = ';
if (isset($data['engine_restart_command']) && $data['engine_restart_command'] != null) {
$rq .= ':engine_restart_command, ';
$retValue[':engine_restart_command'] = htmlentities(trim($data['engine_restart_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`engine_reload_command` = ';
if (isset($data['engine_reload_command']) && $data['engine_reload_command'] != null) {
$rq .= ':engine_reload_command, ';
$retValue[':engine_reload_command'] = htmlentities(trim($data['engine_reload_command']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`init_script_centreontrapd` = ';
if (isset($data['init_script_centreontrapd']) && $data['init_script_centreontrapd'] != null) {
$rq .= ':init_script_centreontrapd, ';
$retValue[':init_script_centreontrapd']
= htmlentities(trim($data['init_script_centreontrapd']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`snmp_trapd_path_conf` = ';
if (isset($data['snmp_trapd_path_conf']) && $data['snmp_trapd_path_conf'] != null) {
$rq .= ':snmp_trapd_path_conf, ';
$retValue[':snmp_trapd_path_conf'] = htmlentities(trim($data['snmp_trapd_path_conf']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`nagios_bin` = ';
if (isset($data['nagios_bin']) && $data['nagios_bin'] != null) {
$rq .= ':nagios_bin, ';
$retValue[':nagios_bin'] = htmlentities(trim($data['nagios_bin']), ENT_QUOTES, 'UTF-8');
} else {
$rq .= 'NULL, ';
}
$rq .= '`nagiostats_bin` = ';
if (isset($data['nagiostats_bin']) && $data['nagiostats_bin'] != null) {
$rq .= ':nagiostats_bin, ';
| 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/configServers/popup/popup.php | centreon/www/include/configuration/configServers/popup/popup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . 'bootstrap.php';
require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
require_once _CENTREON_PATH_ . '/www/class/centreonRestHttp.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
$pearDB = $dependencyInjector['configuration_db'];
// Check Session
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $pearDB)) {
echo 'Bad Session';
exit();
}
$centreon = $_SESSION['centreon'];
$pollerId = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT);
if ($pollerId === false) {
echo 'Bad Poller Id';
exit();
}
$userId = (int) $centreon->user->user_id;
$isAdmin = (bool) $centreon->user->admin;
if ($isAdmin === false) {
$acl = new CentreonACL($userId, $isAdmin);
$aclPollers = $acl->getPollers();
if (! array_key_exists($pollerId, $aclPollers)) {
echo 'No access rights to this Poller';
exit();
}
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate();
// get remote server ip
$query = 'SELECT ip FROM remote_servers';
$dbResult = $pearDB->query($query);
$remotesServerIPs = $dbResult->fetchAll(PDO::FETCH_COLUMN);
$dbResult->closeCursor();
// get poller informations
$statement = $pearDB->prepare(
"SELECT ns.`id`, ns.`name`, ns.`gorgone_port`, ns.`ns_ip_address`, ns.`localhost`, ns.remote_id,
remote_server_use_as_proxy, cn.`command_file`, GROUP_CONCAT( pr.`remote_server_id` ) AS list_remote_server_id
FROM nagios_server AS ns
LEFT JOIN remote_servers AS rs ON rs.server_id = ns.id
LEFT JOIN cfg_nagios AS cn ON cn.`nagios_id` = ns.`id`
LEFT JOIN rs_poller_relation AS pr ON pr.`poller_server_id` = ns.`id`
WHERE ns.ns_activate = '1'
AND ns.`id` = :server_id"
);
$statement->bindValue(':server_id', (int) $pollerId, PDO::PARAM_INT);
$statement->execute();
$server = $statement->fetch();
// get gorgone api informations
$gorgoneApi = [];
$dbResult = $pearDB->query('SELECT * from options WHERE `key` LIKE "gorgone%"');
while ($row = $dbResult->fetch()) {
$gorgoneApi[$row['key']] = $row['value'];
}
$tpl->assign('serverIp', $server['ns_ip_address']);
if (
(empty($server['remote_id']) && empty($server['list_remote_server_id']))
|| $server['remote_server_use_as_proxy'] == 0
) {
// parent is the central
$query = "SELECT `id` FROM nagios_server WHERE ns_activate = '1' AND localhost = '1'";
$dbResult = $pearDB->query($query);
$parents = $dbResult->fetchAll(PDO::FETCH_COLUMN);
} else {
$dbResult = $pearDB->query($query);
$parents = [$server['remote_id']];
if (! empty($server['list_remote_server_id'])) {
$remote = explode(',', $server['list_remote_server_id']);
$parents = array_merge($parents, $remote);
}
$query = 'SELECT `id` FROM nagios_server WHERE `ns_activate` = "1" AND `id` IN (' . implode(',', $parents) . ')';
$dbResult = $pearDB->query($query);
$parents = $dbResult->fetchAll(PDO::FETCH_COLUMN);
}
$kernel = App\Kernel::createForWeb();
/**
* @var Centreon\Domain\Gorgone\Interfaces\GorgoneServiceInterface $gorgoneService
*/
$gorgoneError = false;
if ($server['localhost'] === '1') {
$config = file_get_contents('./central.yaml');
$config = str_replace(
[
'__SERVERNAME__',
'__SERVERID__',
'__COMMAND__',
'__CENTREON_VARLIB__',
'__CENTREON_CACHEDIR__',
],
[
$server['name'],
$server['id'],
$server['command_file'],
_CENTREON_VARLIB_,
_CENTREON_CACHEDIR_,
],
$config
);
} else {
$gorgoneService = $kernel->getContainer()->get(Centreon\Domain\Gorgone\Interfaces\GorgoneServiceInterface::class);
$thumbprints = '';
$dataError = '';
$timeout = 0;
try {
foreach ($parents as $serverId) {
$lastActionLog = null;
$thumbprintCommand = new Centreon\Domain\Gorgone\Command\Thumbprint($serverId);
$gorgoneResponse = $gorgoneService->send($thumbprintCommand);
// check if we have log for 30 s every 2s
do {
$lastActionLog = $gorgoneResponse->getLastActionLog();
sleep(2);
$timeout += 2;
} while (
($lastActionLog == null
|| $lastActionLog->getCode() === Centreon\Domain\Gorgone\Response::STATUS_BEGIN)
&& $timeout <= 30
);
if ($timeout > 30) {
// add 10 s for the next server
$timeout -= 10;
$gorgoneError = true;
$dataError .= '
- error : TimeOut error for poller ' . $serverId . ' We can\'t get log';
continue;
}
$thumbprintResponse = json_decode($lastActionLog->getData(), true);
if ($lastActionLog->getCode() === Centreon\Domain\Gorgone\Response::STATUS_OK) {
$thumbprints .= '
- key: ' . $thumbprintResponse['data']['thumbprint'];
} else {
$gorgoneError = true;
$dataError .= '
- error : Poller ' . $serverId . ' : ' . $thumbprintResponse['message'];
}
}
} catch (Exception $ex) {
$gorgoneError = true;
$dataError = $ex->getMessage();
}
if (! empty($dataError)) {
$config = $dataError;
} elseif (in_array($server['ns_ip_address'], $remotesServerIPs)) {
// config for remote
$config = file_get_contents('./remote.yaml');
$config = str_replace(
[
'__SERVERNAME__',
'__SERVERID__',
'__GORGONEPORT__',
'__THUMBPRINT__',
'__COMMAND__',
'__CENTREON_VARLIB__',
'__CENTREON_CACHEDIR__',
],
[
$server['name'],
$server['id'],
$server['gorgone_port'],
$thumbprints,
$server['command_file'],
_CENTREON_VARLIB_,
_CENTREON_CACHEDIR_,
],
$config
);
} else {
// config for poller
$config = file_get_contents('./poller.yaml');
$config = str_replace(
[
'__SERVERNAME__',
'__SERVERID__',
'__GORGONEPORT__',
'__THUMBPRINT__',
'__COMMAND__',
],
[
$server['name'],
$server['id'],
$server['gorgone_port'],
$thumbprints,
$server['command_file'],
],
$config
);
}
}
$tpl->assign('args', $config);
$tpl->assign('gorgoneError', $gorgoneError);
$tpl->display('popup.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/configResources/resources.php | centreon/www/include/configuration/configResources/resources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
// Path to the configuration dir
$path = './include/configuration/configResources/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
/**
* Page forbidden if server is a remote
*/
if ($isRemote) {
require_once $path . '../../core/errors/alt_error.php';
exit();
}
define('MACRO_ADD', 'a');
define('MACRO_DELETE', 'd');
define('MACRO_DISABLE', 'u');
define('MACRO_DUPLICATE', 'm');
define('MACRO_ENABLE', 's');
define('MACRO_MODIFY', 'c');
define('MACRO_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;
}
// If resource_id is not correctly typed, value will be set to false
$resourceId = filter_var(
$_GET['resource_id'] ?? $_POST['resource_id'] ?? null,
FILTER_VALIDATE_INT
);
// If one data are not correctly typed in array, it will be set to false
$selectIds = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
// If one data are not correctly typed in array, it will be set to false
$duplicateNbr = filter_var_array(
$_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [],
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;
$serverString = $acl->getPollerString();
$allowedResourceConf = [];
if ($serverString != "''" && ! empty($serverString)) {
$sql = 'SELECT resource_id
FROM cfg_resource_instance_relations
WHERE instance_id IN (' . $serverString . ')';
$res = $pearDB->query($sql);
while ($row = $res->fetchRow()) {
$allowedResourceConf[$row['resource_id']] = true;
}
}
switch ($o) {
case MACRO_ADD:
// Add a Resource
require_once $path . 'formResources.php';
break;
case MACRO_WATCH:
// Watch a Resource
require_once $path . 'formResources.php';
break;
case MACRO_MODIFY:
// Modify a Resource
require_once $path . 'formResources.php';
break;
case MACRO_ENABLE:
// Activate a Resource
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($resourceId !== false) {
enableResourceInDB($resourceId);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listResources.php';
break;
case MACRO_DISABLE:
// Desactivate a Resource
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($resourceId !== false) {
disableResourceInDB($resourceId);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listResources.php';
break;
case MACRO_DUPLICATE:
// Duplicate n resources only if data sent are correctly typed
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds) && ! in_array(false, $duplicateNbr)) {
multipleResourceInDB(
$selectIds,
$duplicateNbr
);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listResources.php';
break;
case MACRO_DELETE:
// Delete n resources only if data sent are correctly typed
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
deleteResourceInDB($selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listResources.php';
break;
default:
require_once $path . 'listResources.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/configResources/formResources.php | centreon/www/include/configuration/configResources/formResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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($resourceId)
&& count($allowedResourceConf)
&& ! isset($allowedResourceConf[$resourceId])
) {
$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;
}
const PASSWORD_REPLACEMENT_VALUE_FORM = '**********';
$initialValues = [];
/*
$instances = $acl->getPollerAclConf(array('fields' => array('id', 'name'),
'keys' => array('id'),
'get_row' => 'name',
'order' => array('name')));
*/
/**
* Database retrieve information for Resources CFG
*/
if (($o == MACRO_MODIFY || $o == MACRO_WATCH) && is_int($resourceId)) {
$query = "SELECT * FROM cfg_resource WHERE resource_id = {$resourceId} LIMIT 1";
$DBRESULT = $pearDB->query($query);
// Set base value
$rs = array_map('myDecode', $DBRESULT->fetchRow());
if (! empty($rs['resource_line']) && $rs['is_password']) {
$rs['original_value'] = $rs['resource_line'];
$rs['resource_line'] = PASSWORD_REPLACEMENT_VALUE_FORM;
}
$DBRESULT->closeCursor();
}
/**
* Var information to format the element
*/
$attrsText = ['size' => '35'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$attrsAdvSelect = ['style' => 'width: 220px; height: 220px;'];
$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>';
require_once _CENTREON_PATH_ . 'www/class/centreonInstance.class.php';
/**
* Form
*/
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == MACRO_ADD) {
$form->addElement('header', 'title', _('Add a Resource'));
} elseif ($o == MACRO_MODIFY) {
$form->addElement('header', 'title', _('Modify a Resource'));
} elseif ($o == MACRO_WATCH) {
$form->addElement('header', 'title', _('View Resource'));
}
$isPassword = isset($rs['is_password']) && $rs['is_password'];
/**
* Resources CFG basic information
*/
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'resource_name', _('Resource Name'), $attrsText);
$form->addElement($isPassword ? 'password' : 'text', 'resource_line', _('MACRO Expression'), $attrsText);
$form->addElement(
'checkbox',
'is_password',
_('Password'),
null,
$isPassword ? ['disabled' => 'disabled'] : ['onClick' => 'javascript:change_macro_input_type(this)']
);
$attrPoller = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_poller&action=list', 'multiple' => true, 'linkedObject' => 'centreonInstance'];
// Host Parents
$route = './api/internal.php?object=centreon_configuration_poller&action=defaultValues'
. '&target=resources&field=instance_id&id=' . $resourceId;
$attrPoller1 = array_merge(
$attrPoller,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'instance_id', _('Linked Instances'), [], $attrPoller1);
/**
* Further information
*/
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$rsActivation[] = $form->createElement('radio', 'resource_activate', null, _('Enabled'), '1');
$rsActivation[] = $form->createElement('radio', 'resource_activate', null, _('Disabled'), '0');
$form->addGroup($rsActivation, 'resource_activate', _('Status'), ' ');
$form->setDefaults(['resource_activate' => '1']);
$form->addElement('textarea', 'resource_comment', _('Comment'), $attrsTextarea);
$tab = [];
$tab[] = $form->createElement('radio', 'action', null, _('List'), '1');
$tab[] = $form->createElement('radio', 'action', null, _('Form'), '0');
$form->addGroup($tab, 'action', _('Post Validation'), ' ');
$form->setDefaults(['action' => '1']);
$form->addElement('hidden', 'resource_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
/**
* Form definition
*/
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['resource_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('resource_name', 'myReplace');
$form->registerRule('validateName', 'callback', 'validateName');
$form->addRule('resource_name', _("Name must start and end with a '$'"), 'validateName');
$form->addRule('resource_name', _('Compulsory Name'), 'required');
$form->addRule('resource_line', _('Compulsory Alias'), 'required');
$form->addRule('instance_id', _('Compulsory Instance'), 'required');
$form->registerRule('exist', 'callback', 'testExistence');
$form->addRule('resource_name', _('Resource used by one of the instances'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch a Resources CFG information
if ($o == MACRO_WATCH) {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&resource_id=' . $resourceId . "'"]
);
}
$form->setDefaults($rs);
$form->freeze();
} elseif ($o == MACRO_MODIFY) {
// Modify a Resources CFG information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($rs);
} elseif ($o == MACRO_ADD) {
// Add a Resources CFG 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()) {
$rsObj = $form->getElement('resource_id');
if ($form->getSubmitValue('submitA')) {
$rsObj->setValue(insertResourceInDB());
} elseif ($form->getSubmitValue('submitC')) {
$submitedValues = $form->getSubmitValues();
if ($rs['is_password']) {
$submitedValues['is_password'] = $rs['is_password'];
if ($submitedValues['resource_line'] === PASSWORD_REPLACEMENT_VALUE_FORM) {
$submitedValues['resource_line'] = $rs['original_value'];
}
}
updateResourceInDB($rsObj->getValue(), $submitedValues);
}
$o = null;
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&resource_id=' . $rsObj->getValue() . "'"]
);
$valid = true;
}
$action = $form->getSubmitValue('action');
if ($valid) {
require_once $path . 'listResources.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <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('formResources.ihtml');
}
?>
<script>
function change_macro_input_type() {
if (jQuery("input[name='is_password'").is(":checked") === true) {
jQuery("input[name='resource_line'").attr('type', 'password');
} else {
jQuery("input[name='resource_line'").attr('type', 'text');
}
}
</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/configResources/listResources.php | centreon/www/include/configuration/configResources/listResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
const PASSWORD_REPLACEMENT_VALUE_LISTING = '**********';
// Search engine
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchR'] ?? $_GET['searchR'] ?? null
);
if (isset($_POST['searchR']) || isset($_GET['searchR'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$SearchTool = '';
if ($search) {
$SearchTool .= " WHERE resource_name LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8') . "%'";
}
$aclCond = '';
if (! $oreon->user->admin && count($allowedResourceConf)) {
$aclCond = isset($search) && $search ? ' AND ' : ' WHERE ';
$aclCond .= 'resource_id IN (' . implode(',', array_keys($allowedResourceConf)) . ') ';
}
// resources list
$dbResult = $pearDB->query(
'SELECT SQL_CALC_FOUND_ROWS * FROM cfg_resource ' . $SearchTool . $aclCond
. ' ORDER BY resource_name LIMIT ' . $num * $limit . ', ' . $limit
);
$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_values', _('Values'));
$tpl->assign('headerMenu_comment', _('Description'));
$tpl->assign('headerMenu_associated_poller', _('Associated pollers'));
$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';
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $resource = $dbResult->fetch(); $i++) {
preg_match('$USER([0-9]*)$', $resource['resource_name'], $tabResources);
$selectedElements = $form->addElement('checkbox', 'select[' . $resource['resource_id'] . ']');
$moptions = '';
if ($resource['resource_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&resource_id=' . $resource['resource_id'] . '&o=u&limit='
. $limit . '&num=' . $num . '&search=' . $search . '¢reon_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 . '&resource_id=' . $resource['resource_id'] . '&o=s&limit='
. $limit . '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' "
. "class='ico-14 margin_right' border='0' alt='" . _('Enabled') . "'></a>";
}
$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["
. $resource['resource_id'] . "]' />";
$elemArr[$i] = ['order' => $tabResources[1] ?? null, 'MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(
$resource['resource_name'],
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&resource_id=' . $resource['resource_id'], 'RowMenu_values' => CentreonUtils::escapeSecure(
$resource['is_password'] ? PASSWORD_REPLACEMENT_VALUE_LISTING : substr($resource['resource_line'], 0, 40),
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_comment' => CentreonUtils::escapeSecure(
substr(
html_entity_decode(
$resource['resource_comment'],
ENT_QUOTES,
'UTF-8'
),
0,
40
),
CentreonUtils::ESCAPE_ALL_EXCEPT_LINK
), 'RowMenu_associated_poller' => getLinkedPollerList($resource['resource_id']), 'RowMenu_status' => $resource['resource_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $resource['resource_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$flag = 1;
while ($flag) {
$flag = 0;
foreach ($elemArr as $key => $value) {
$key1 = $key + 1;
if (isset($elemArr[$key + 1]) && $value['order'] > $elemArr[$key + 1]['order']) {
$swmapTab = $elemArr[$key + 1];
$elemArr[$key + 1] = $elemArr[$key];
$elemArr[$key] = $swmapTab;
$flag = 1;
} elseif (! isset($elemArr[$key + 1]) && isset($elemArr[$key - 1]['order'])) {
if ($value['order'] < $elemArr[$key - 1]['order']) {
$swmapTab = $elemArr[$key - 1];
$elemArr[$key - 1] = $elemArr[$key];
$elemArr[$key] = $swmapTab;
$flag = 1;
}
}
}
}
$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
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['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')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchR', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listResources.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/configResources/DB-Func.php | centreon/www/include/configuration/configResources/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
*
*/
declare(strict_types=1);
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/include/common/vault-functions.php';
use App\Kernel;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroName;
use Centreon\Domain\Log\Logger;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
/**
* Indicates if the resource name has already been used.
*
* @global CentreonDB $pearDB
* @global HTML_QuickFormCustom $form
*
* @param string $name
* @param int $instanceId
*
* @return bool Return false if the resource name has already been used
*/
function testExistence($name = null, $instanceId = null)
{
global $pearDB, $form;
$id = 0;
$instanceIds = [];
if (isset($form)) {
$id = (int) $form->getSubmitValue('resource_id');
$instanceIds = $form->getSubmitValue('instance_id');
$instanceIds = filter_var_array(
$instanceIds,
FILTER_VALIDATE_INT
);
if (in_array(false, $instanceIds, true)) {
return true;
}
} elseif (! is_null($instanceId) && $instanceId) {
$instanceIds = [(int) $instanceId];
}
if ($instanceIds === []) {
return true;
}
$prepare = $pearDB->prepare(
'SELECT cr.resource_name, crir.resource_id, crir.instance_id '
. 'FROM cfg_resource cr, cfg_resource_instance_relations crir '
. 'WHERE cr.resource_id = crir.resource_id '
. 'AND crir.instance_id IN (' . implode(',', $instanceIds) . ') '
. 'AND cr.resource_name = :resource_name'
);
$prepare->bindValue(':resource_name', $name, PDO::PARAM_STR);
$prepare->execute();
$total = $prepare->rowCount();
$result = $prepare->fetch(PDO::FETCH_ASSOC);
if ($total >= 1 && $result['resource_id'] === $id) {
/**
* In case of modification.
*/
return true;
}
return ! ($total >= 1 && $result['resource_id'] !== $id);
/**
* In case of duplicate.
*/
}
/**
* Deletes resources.
*
* @global CentreonDB $pearDB
*
* @param int[] $resourceIds Resource ids to delete
*/
function deleteResourceInDB($resourceIds = []): void
{
global $pearDB;
foreach (array_keys($resourceIds) as $currentResourceId) {
if (is_int($currentResourceId)) {
$statement = $pearDB->prepare(
'SELECT *FROM cfg_resource WHERE resource_id = :resourceId'
);
$statement->bindValue(':resourceId', $currentResourceId);
$statement->execute();
if (false !== $data = $statement->fetch()) {
deleteFromVault($data);
$pearDB->query(
"DELETE FROM cfg_resource WHERE resource_id = {$currentResourceId}"
);
}
}
}
}
/**
* Enables a resource.
*
* @global CentreonDB $pearDB
*
* @param int[] $resourceId Resource id to enable
*/
function enableResourceInDB($resourceId): void
{
global $pearDB;
if (is_int($resourceId)) {
$pearDB->query(
"UPDATE cfg_resource SET resource_activate = '1' "
. "WHERE resource_id = {$resourceId}"
);
}
}
/**
* Disables a resource.
*
* @global CentreonDB $pearDB
*
* @param int $resourceId Resource id to disable
*/
function disableResourceInDB($resourceId): void
{
global $pearDB;
if (is_int($resourceId)) {
$pearDB->query(
"UPDATE cfg_resource SET resource_activate = '0' "
. "WHERE resource_id = {$resourceId}"
);
}
}
/**
* Duplicates resource.
*
* @global CentreonDB $pearDB
*
* @param array $resourceIds List of resource id to duplicate
* @param int[] $nbrDup Number of copy
*/
function multipleResourceInDB($resourceIds = [], $nbrDup = []): void
{
global $pearDB;
foreach (array_keys($resourceIds) as $resourceId) {
if (is_int($resourceId)) {
$dbResult = $pearDB->query("SELECT * FROM cfg_resource WHERE resource_id = {$resourceId} LIMIT 1");
/**
* @var array{
* resource_id:int,
* resource_name:string,
* resource_line:string,
* resource_comment:string,
* resource_activate:string,
* is_password:int
* } $resourceConfiguration
*/
$resourceConfiguration = $dbResult->fetch();
for ($newIndex = 1; $newIndex <= $nbrDup[$resourceId]; $newIndex++) {
$name = preg_match('/^\$(.*)\$$/', $resourceConfiguration['resource_name'])
? rtrim($resourceConfiguration['resource_name'], '$') . '_' . $newIndex . '$'
: $resourceConfiguration['resource_name'] . '_' . $newIndex;
$value = $resourceConfiguration['resource_line'];
if (
(bool) $resourceConfiguration['is_password'] === true
&& str_starts_with($resourceConfiguration['resource_line'], VaultConfiguration::VAULT_PATH_PATTERN)
) {
$resourcesFromVault = getFromVault($resourceConfiguration['resource_line']);
$value = $resourcesFromVault[$resourceConfiguration['resource_name']];
}
if (testExistence($name) && ! is_null($value)) {
if ((bool) $resourceConfiguration['is_password'] === true) {
$vaultPath = saveInVault($name, $value);
}
$value = $vaultPath ?? $value;
$statement = $pearDB->prepare(
<<<'SQL'
INSERT INTO cfg_resource
(resource_id, resource_name, resource_line, resource_comment, resource_activate, is_password)
VALUES (NULL, :name, :value, :comment, :is_active, :is_password)
SQL
);
$statement->bindValue(':name', $name, PDO::PARAM_STR);
$statement->bindValue(':value', $value, PDO::PARAM_STR);
$statement->bindValue(':comment', $resourceConfiguration['resource_comment'], PDO::PARAM_STR);
$statement->bindValue(':is_active', $resourceConfiguration['resource_activate'], PDO::PARAM_STR);
$statement->bindValue(':is_password', $resourceConfiguration['is_password'], PDO::PARAM_INT);
$statement->execute();
$lastId = $pearDB->lastInsertId();
$pearDB->query(
'INSERT INTO cfg_resource_instance_relations ('
. "SELECT {$lastId}, instance_id "
. 'FROM cfg_resource_instance_relations '
. "WHERE resource_id = {$resourceId})"
);
}
}
}
}
}
/**
* @param int|null $resource_id
* @param array<string,mixed> $submitedValues
*/
function updateResourceInDB($resource_id = null, array $submitedValues): void
{
if (! $resource_id) {
return;
}
updateResource((int) $resource_id, $submitedValues);
insertInstanceRelations((int) $resource_id);
}
/**
* Updates a resource which is in the form.
*
* @global HTML_QuickFormCustom $form
* @global CentreonDB $pearDB
* @global Centreon $centreon
*
* @param int $resourceId
* @param array<string,mixed> $submitedValues
*/
function updateResource(int $resourceId, array $submitedValues): void
{
global $pearDB, $centreon;
if (is_null($resourceId)) {
return;
}
$isActivate = isset($submitedValues['resource_activate'], $submitedValues['resource_activate']['resource_activate'])
&& $submitedValues['resource_activate']['resource_activate'] === '1'
? true
: false;
if ($submitedValues['is_password']) {
if (! str_starts_with($submitedValues['resource_line'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$vaultPath = saveInVault($submitedValues['resource_name'], $submitedValues['resource_line']);
$submitedValues['resource_line'] = $vaultPath ?? $submitedValues['resource_line'];
} else {
$oldResourceStatement = $pearDB->prepareQuery(
<<<'SQL'
SELECT resource_name, resource_line
FROM cfg_resource
WHERE resource_id = :resource_id
SQL
);
$pearDB->executePreparedQuery($oldResourceStatement, ['resource_id' => $resourceId]);
$oldResource = $oldResourceStatement->fetch();
$vaultData = getFromVault($submitedValues['resource_line']);
if (array_key_exists($oldResource['resource_name'], $vaultData)) {
deleteFromVault([
'resource_line' => $oldResource['resource_line'],
'resource_name' => $oldResource['resource_name'],
]);
if (str_starts_with($submitedValues['resource_line'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$submitedValues['resource_line'] = $vaultData[$oldResource['resource_name']];
}
$submitedValues['resource_line'] = saveInVault($submitedValues['resource_name'], $submitedValues['resource_line']);
}
}
}
$prepare = $pearDB->prepare(
<<<'SQL'
UPDATE cfg_resource
SET resource_name = :resource_name, resource_line = :resource_line,
resource_comment= :resource_comment, resource_activate= :is_activate,
is_password = :is_password
WHERE resource_id = :resource_id
SQL
);
$prepare->bindValue(
':resource_name',
$pearDB->escape($submitedValues['resource_name']),
PDO::PARAM_STR
);
$prepare->bindValue(
':resource_line',
$pearDB->escape($submitedValues['resource_line']),
PDO::PARAM_STR
);
$prepare->bindValue(
':resource_comment',
$pearDB->escape($submitedValues['resource_comment']),
PDO::PARAM_STR
);
$prepare->bindValue(
':is_activate',
($isActivate ? '1' : '0'),
PDO::PARAM_STR
);
$prepare->bindValue(':resource_id', $resourceId, PDO::PARAM_INT);
$prepare->bindValue(':is_password', (int) $submitedValues['is_password'], PDO::PARAM_INT);
$prepare->execute();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($submitedValues);
$centreon->CentreonLogAction->insertLog(
'resource',
$resourceId,
CentreonDB::escape($submitedValues['resource_name']),
'c',
$fields
);
}
function insertResourceInDB()
{
$resource_id = insertResource();
insertInstanceRelations($resource_id);
return $resource_id;
}
function insertResource($ret = [])
{
global $form, $pearDB, $centreon;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
if ($ret['is_password']) {
$vaultPath = saveInVault($ret['resource_name'], $ret['resource_line']);
$ret['resource_line'] = $vaultPath ?? $ret['resource_line'];
}
$statement = $pearDB->prepare(
'INSERT INTO cfg_resource
(resource_name, resource_line, resource_comment, resource_activate, is_password)
VALUES (:name, :line, :comment, :is_activated, :is_password)'
);
$statement->bindValue(
':name',
! empty($ret['resource_name'])
? $ret['resource_name']
: null
);
$statement->bindValue(
':line',
! empty($ret['resource_line'])
? $ret['resource_line']
: null
);
$statement->bindValue(
':comment',
! empty($ret['resource_comment'])
? $ret['resource_comment']
: null
);
$isActivated = isset($ret['resource_activate']['resource_activate'])
&& (bool) (int) $ret['resource_activate']['resource_activate'];
$statement->bindValue(':is_activated', (string) (int) $isActivated);
$statement->bindValue('is_password', (int) $ret['is_password'], PDO::PARAM_INT);
$statement->execute();
$dbResult = $pearDB->query('SELECT MAX(resource_id) FROM cfg_resource');
$resource_id = $dbResult->fetch();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
'resource',
$resource_id['MAX(resource_id)'],
CentreonDB::escape($ret['resource_name']),
'a',
$fields
);
return $resource_id['MAX(resource_id)'];
}
function insertInstanceRelations($resourceId, $instanceId = null): void
{
if (is_numeric($resourceId)) {
global $pearDB;
$pearDB->query('DELETE FROM cfg_resource_instance_relations WHERE resource_id = ' . (int) $resourceId);
if (! is_null($instanceId)) {
$instances = [$instanceId];
} else {
global $form;
$instances = CentreonUtils::mergeWithInitialValues($form, 'instance_id');
}
$subQuery = '';
foreach ($instances as $instanceId) {
if (is_numeric($instanceId)) {
if (! empty($subQuery)) {
$subQuery .= ', ';
}
$subQuery .= '(' . (int) $resourceId . ', ' . (int) $instanceId . ')';
}
}
if (! empty($subQuery)) {
$pearDB->query(
'INSERT INTO cfg_resource_instance_relations (resource_id, instance_id) VALUES ' . $subQuery
);
}
}
}
function getLinkedPollerList($resource_id)
{
global $pearDB;
$str = '';
$query = 'SELECT ns.name, ns.id FROM cfg_resource_instance_relations nsr, cfg_resource r, nagios_server ns '
. "WHERE nsr.resource_id = r.resource_id AND nsr.instance_id = ns.id AND nsr.resource_id = '"
. $resource_id . "'";
$dbResult = $pearDB->query($query);
while ($data = $dbResult->fetch()) {
$str .= "<a href='main.php?p=60901&o=c&server_id=" . $data['id'] . "'>" . HtmlSanitizer::createFromString($data['name'])->sanitize()->getString() . '</a> ';
}
unset($dbResult);
return $str;
}
/**
* @param string $vaultPath
*
* @return array<string,string>
*/
function getFromVault(string $vaultPath): array
{
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
/** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null) {
/** @var ReadVaultRepositoryInterface $readVaultRepository */
$readVaultRepository = $kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
try {
return $readVaultRepository->findFromPath($vaultPath);
} catch (Throwable $ex) {
$logger->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
error_log((string) $ex);
}
}
return [];
}
function saveInVault(string $key, string $value): ?string
{
global $pearDB;
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
/** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null) {
/** @var ReadVaultRepositoryInterface $readVaultRepository */
$readVaultRepository = $kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
/** @var WriteVaultRepositoryInterface $writeVaultRepository */
$writeVaultRepository = $kernel->getContainer()->get(WriteVaultRepositoryInterface::class);
$writeVaultRepository->setCustomPath(AbstractVaultRepository::POLLER_MACRO_VAULT_PATH);
try {
return upsertPollerMacroSecretInVault(
$readVaultRepository,
$writeVaultRepository,
$key,
$value,
retrievePollerMacroVaultPathFromDatabase($pearDB)
);
} catch (Throwable $ex) {
$logger->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
error_log((string) $ex);
}
}
return null;
}
/**
* @param array{resource_line:string,resource_name:string} $data
*/
function deleteFromVault(array $data): void
{
if (str_starts_with($data['resource_line'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$uuid = preg_match(
'/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/',
$data['resource_line'],
$matches
)
&& isset($matches[2]) ? $matches[2] : null;
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
/** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null) {
/** @var ReadVaultRepositoryInterface $readVaultRepository */
$readVaultRepository = $kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
/** @var WriteVaultRepositoryInterface $writeVaultRepository */
$writeVaultRepository = $kernel->getContainer()->get(WriteVaultRepositoryInterface::class);
$writeVaultRepository->setCustomPath(AbstractVaultRepository::POLLER_MACRO_VAULT_PATH);
try {
deletePollerMacroSecretInVault(
$readVaultRepository,
$writeVaultRepository,
$uuid,
$data['resource_line'],
$data['resource_name'],
);
} catch (Throwable $ex) {
$logger->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
error_log((string) $ex);
}
}
}
}
function validateName(string $name): bool
{
return (bool) preg_match(GlobalMacroName::NAMING_VALIDATION_REGEX, $name);
}
| 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/configGenerate/common-Func.php | centreon/www/include/configuration/configGenerate/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
*
*/
/**
* format and add debug in CentreonXML
*
* @param CentreonXML $xml
* @param mixed[] $tabs
* @return int
*/
function printDebug($xml, array $tabs): int
{
global $pearDB, $ret, $centreon, $nagiosCFGPath;
$DBRESULT_Servers = $pearDB->query(
"SELECT `nagios_bin` FROM `nagios_server`
WHERE `localhost` = '1' ORDER BY ns_activate DESC LIMIT 1"
);
$nagios_bin = $DBRESULT_Servers->fetch();
$DBRESULT_Servers->closeCursor();
$msg_debug = [];
$tab_server = [];
foreach ($tabs as $tab) {
if (isset($ret['host']) && ($ret['host'] == 0 || in_array($tab['id'], $ret['host']))) {
$tab_server[$tab['id']] = ['id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost']];
}
}
foreach ($tab_server as $host) {
$stdout = shell_exec(
escapeshellarg($nagios_bin['nagios_bin']) . ' -v ' . $nagiosCFGPath
. escapeshellarg($host['id']) . '/centengine.DEBUG 2>&1'
);
$stdout = htmlspecialchars($stdout, ENT_QUOTES, 'UTF-8');
$msg_debug[$host['id']] = str_replace("\n", '<br />', $stdout);
$msg_debug[$host['id']] = str_replace(
'Warning:',
"<font color='orange'>Warning</font>",
$msg_debug[$host['id']]
);
$msg_debug[$host['id']] = str_replace(
'warning: ',
"<font color='orange'>Warning</font> ",
$msg_debug[$host['id']]
);
$msg_debug[$host['id']] = str_replace('Error:', "<font color='red'>Error</font>", $msg_debug[$host['id']]);
$msg_debug[$host['id']] = str_replace('error:', "<font color='red'>Error</font>", $msg_debug[$host['id']]);
$msg_debug[$host['id']] = str_replace('reading', 'Reading', $msg_debug[$host['id']]);
$msg_debug[$host['id']] = str_replace('running', 'Running', $msg_debug[$host['id']]);
$msg_debug[$host['id']] = str_replace(
'Total Warnings: 0',
"<font color='green'>Total Warnings: 0</font>",
$msg_debug[$host['id']]
);
$msg_debug[$host['id']] = str_replace(
'Total Errors: 0',
"<font color='green'>Total Errors: 0</font>",
$msg_debug[$host['id']]
);
$msg_debug[$host['id']] = str_replace('<br />License:', ' - License:', $msg_debug[$host['id']]);
$msg_debug[$host['id']] = preg_replace('/(\[[0-9]+?\]) \[[0-9]+?\]/', '$1', $msg_debug[$host['id']]);
$msg_debug[$host['id']] = preg_replace(
'/(\[\d{4}-[0-1]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d.\d{3}\+[0-1]\d:00\]) \[\w+\] \[\w+\]/',
'$1',
$msg_debug[$host['id']]
);
$lines = preg_split("/\<br\ \/\>/", $msg_debug[$host['id']]);
$lines = array_map('unifyDateFormats', $lines);
$lines = array_unique($lines);
$lines = array_map('removeTimestamp', $lines);
$msg_debug[$host['id']] = '';
$i = 0;
foreach ($lines as $line) {
if (
strncmp($line, 'Processing object config file', strlen('Processing object config file'))
&& strncmp($line, 'Website: http://www.nagios.org', strlen('Website: http://www.nagios.org'))
) {
$msg_debug[$host['id']] .= $line . '<br>';
}
$i++;
}
}
$xml->startElement('debug');
$str = '';
$returnCode = 0;
foreach ($msg_debug as $pollerId => $message) {
$show = 'none';
$toggler = "<label id='togglerp_" . $pollerId . "'>[ + ]</label><label id='togglerm_" . $pollerId
. "' style='display: none'>[ - ]</label>";
$pollerNameColor = 'green';
if (preg_match_all("/Total (Errors|Warnings)\:[ ]+([0-9]+)/", $message, $globalMatches, PREG_SET_ORDER)) {
foreach ($globalMatches as $matches) {
if ($matches[2] != '0') {
$show = 'block';
$toggler = "<label id='togglerp_" . $pollerId
. "' style='display: none'>[ + ]</label><label id='togglerm_" . $pollerId . "'>[ - ]</label>";
if ($matches[1] == 'Errors') {
$pollerNameColor = 'red';
$returnCode = 1;
} elseif ($matches[1] == 'Warnings') {
$pollerNameColor = 'orange';
}
}
}
} else {
$show = 'block';
$pollerNameColor = 'red';
$toggler = "<label id='togglerp_" . $pollerId
. "' style='display: none'>[ + ]</label><label id='togglerm_" . $pollerId . "'>[ - ]</label>";
$returnCode = 1;
}
$str .= "<a href='#' onClick=\"toggleDebug('" . $pollerId . "'); return false;\">";
$str .= $toggler . '</a> ';
$str .= "<b><font color='{$pollerNameColor}'>" . $tab_server[$pollerId]['name'] . '</font></b><br/>';
$str .= "<div style='display: {$show};' id='debug_" . $pollerId . "'>" . htmlentities($message) . '</div><br/>';
}
$xml->text($str);
$xml->endElement();
return $returnCode;
}
/**
* @param string $originalLog
* @return string
*/
function unifyDateFormats(string $originalLog): string
{
$log = null;
$dateFormatPattern = '/\[(\d{4}-[0-1]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d.\d{3}\+[0-1]\d:00)\]/';
if (preg_match($dateFormatPattern, $originalLog, $matches)) {
$date = new DateTimeImmutable($matches[1]);
$log = preg_replace(
$dateFormatPattern,
'[' . $date->getTimestamp() . ']',
$originalLog
);
}
return $log ?? $originalLog;
}
/**
* @param string $log
* @return string
*/
function removeTimestamp(string $log): string
{
return preg_replace('/\[[0-9]+?\] /', '', $log) ?? $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/configGenerate/help.php | centreon/www/include/configuration/configGenerate/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['host'] = dgettext('help', 'Select the poller you would like to interact with.');
$help['gen'] = dgettext('help', 'Generates configuration files and stores them in cache directory.');
$help['debug'] = dgettext('help', 'Runs the scheduler debug mode.');
$help['move'] = dgettext('help', "Copies the generated files into the scheduler's configuration folder.");
$help['restart'] = dgettext('help', 'Restart the scheduler: Restart, Reload or External Command.');
$help['postcmd'] = dgettext(
'help',
'Run the commands that are defined in the poller configuration page (Configuration > Centreon > '
. 'Poller > Post-Restart command).'
);
| 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/configGenerate/generateFiles.php | centreon/www/include/configuration/configGenerate/generateFiles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
// Path to the option dir
$path = './include/configuration/configGenerate/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
/**
* Page forbidden if server is a remote
*/
if ($isRemote) {
require_once $path . '../../core/errors/alt_error.php';
exit();
}
switch ($o) {
default:
require_once $path . 'formGenerateFiles.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/configGenerate/formGenerateFiles.php | centreon/www/include/configuration/configGenerate/formGenerateFiles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_cfg') === 0) {
require_once _CENTREON_PATH_ . 'www/include/core/errors/alt_error.php';
return null;
}
// 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
$pollersFromUrl = $_GET['poller'] ?? '';
$pollersId = explode(',', $pollersFromUrl);
$selectedPollers = [];
foreach ($tab_nagios_server as $key => $name) {
if (in_array($key, $pollersId)) {
$selectedPollers[] = ['id' => $key, 'text' => $name];
}
}
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->addElement('checkbox', 'debug', _('Run monitoring engine debug (-v)'), null, ['id' => 'ndebug']);
$form->addElement('checkbox', 'gen', _('Generate Configuration Files'), null, ['id' => 'ngen']);
$form->addElement('checkbox', 'move', _('Move Export Files'), null, ['id' => 'nmove']);
$form->addElement('checkbox', 'restart', _('Restart Monitoring Engine'), null, ['id' => 'nrestart']);
$form->addElement('checkbox', 'postcmd', _('Post generation command'), null, ['id' => 'npostcmd']);
$form->addElement(
'select',
'restart_mode',
_('Method'),
[2 => _('Restart'), 1 => _('Reload')],
['id' => 'nrestart_mode', 'style' => 'width: 220px;']
);
$form->setDefaults(['debug' => '1', 'gen' => '1', 'restart_mode' => '1']);
// Add multiselect for pollers
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_poller&action=list';
$attrPoller = ['datasourceOrigin' => 'ajax', 'allowClear' => true, 'availableDatasetRoute' => $route, 'multiple' => true];
$form->addElement('select2', 'nhost', _('Pollers'), ['class' => 'required'], $attrPoller);
$form->addRule('nhost', _('You need to select a least one polling instance.'), 'required', null, 'client');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$sub = $form->addElement(
'button',
'submit',
_('Export'),
['id' => 'exportBtn', 'onClick' => 'generationProcess();', 'class' => 'btc bt_success']
);
$msg = null;
$stdout = null;
$tpl->assign('noPollerSelectedLabel', _('Compulsory Poller'));
$tpl->assign('consoleLabel', _('Console'));
$tpl->assign('progressLabel', _('Progress'));
$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"'
);
include_once 'help.php';
$helptext = '';
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} <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('formGenerateFiles.ihtml');
?>
<script type='text/javascript'>
var initPollers = '<?php echo json_encode($selectedPollers); ?>';
var selectedPoller;
var debugOption;
var generateOption;
var moveOption;
var restartOption;
var restartMode;
var exportBtn;
var steps = new Array();
var stepProgress;
var curProgress;
var postcmdOption;
var tooltip = new CentreonToolTip();
var svg = "<?php displaySvg('www/img/icons/question.svg', 'var(--help-tool-tip-icon-fill-color)', 18, 18); ?>"
tooltip.setSource(svg);
var session_id = "<?php echo session_id(); ?>";
tooltip.render();
var msgTab = new Array();
msgTab['start'] = "<?php echo addslashes(_('Preparing environment')); ?>";
msgTab['gen'] = "<?php echo addslashes(_('Generating files')); ?>";
msgTab['debug'] = "<?php echo addslashes(_('Running debug mode')); ?>";
msgTab['move'] = "<?php echo addslashes(_('Moving files')); ?>";
msgTab['restart'] = "<?php echo addslashes(_('Restarting engine')); ?>";
msgTab['abort'] = "<?php echo addslashes(_('Aborted.')); ?>";
msgTab['noPoller'] = "<?php echo addslashes(_('No poller selected')); ?>";
msgTab['postcmd'] = "<?php echo addslashes(_('Executing command')); ?>";
jQuery(function () {
$('#progress_bar').progressbar({
value: 0
}).removeClass('ui-corner-all');
var pollers = JSON.parse(initPollers);
for (var i = 0; i < pollers.length; i++) {
jQuery('#nhost').append(
'<option value="' + pollers[i].id + '" selected>' + pollers[i].text + '</option>'
);
}
jQuery('#nhost').trigger('change');
});
/**
* Next step
*
* @returns void
*/
function nextStep() {
var func = window[steps.shift()];
if (typeof(func) === 'function') {
func();
} else {
// no more step
exportBtn.disabled = false;
}
}
/**
* Display error if no poller is selected
*
* @returns boolean
*/
function checkSelectedPoller() {
var countSelectedPoller = jQuery('#nhost').next('span').find('.select2-selection__choice').length;
if (countSelectedPoller > 0) {
jQuery('#noSelectedPoller').hide();
jQuery('#noSelectedPoller').next('br').remove();
return true;
} else {
jQuery('#noSelectedPoller').show();
if (!jQuery('#noSelectedPoller').next('br').length) {
jQuery('#noSelectedPoller').after('<br>');
}
return false;
}
}
/**
* Generation process
*
* @return void
*/
function generationProcess() {
if (!checkSelectedPoller()) {
return null;
}
curProgress = 0;
stepProgress = 0;
updateProgress();
cleanErrorPhp();
document.getElementById('console').style.visibility = 'visible';
$('#consoleContent').html(msgTab['start'] + "... ");
$('#consoleDetails').html("");
initEnvironment();
if (selectedPoller !== "-1") {
nextStep();
}
}
/**
* Initializes generation options
*/
function initEnvironment() {
selectedPoller = jQuery('#nhost').val().join(',');
debugOption = document.getElementById('ndebug').checked;
generateOption = document.getElementById('ngen').checked;
if (generateOption) {
steps.push("generateFiles");
}
moveOption = document.getElementById('nmove').checked;
if (moveOption) {
steps.push("moveFiles");
}
restartOption = document.getElementById('nrestart').checked;
if (restartOption) {
steps.push("restartPollers");
}
restartMode = document.getElementById('nrestart_mode').value;
postcmdOption = 0;
if (document.getElementById('npostcmd')) {
postcmdOption = document.getElementById('npostcmd').checked;
}
if (postcmdOption) {
steps.push("executeCommand");
}
stepProgress = 100 / steps.length;
curProgress = 0;
exportBtn = document.getElementById('exportBtn');
exportBtn.disabled = true;
if (selectedPoller == "-1") {
$('#consoleContent').append("<b><font color='red'>NOK</font></b> (" + msgTab['noPoller'] + ")<br/>");
abortProgress();
return null;
}
$('#consoleContent').append("<b><font color='green'>OK</font></b><br/>");
}
/**
* Generate files
*/
function generateFiles() {
if (debugOption && !generateOption) {
$('#consoleContent').append(msgTab['debug'] + '... ');
} else {
$('#consoleContent').append(msgTab['gen'] + "... ");
}
jQuery.ajax({
url: './include/configuration/configGenerate/xml/generateFiles.php',
type: 'POST',
dataType: "xml",
data: {
poller: selectedPoller,
debug: debugOption,
generate: generateOption
},
success: function (data) {
data = $(data);
displayStatusMessage(data);
displayDetails(data);
displayPhpErrorMsg('generate', data);
if (isError(data) == "1") {
abortProgress();
return null;
}
updateProgress();
nextStep();
}
});
}
/**
* Move files
*/
function moveFiles() {
$('#consoleContent').append(msgTab['move'] + "... ");
jQuery.ajax({
url: './include/configuration/configGenerate/xml/moveFiles.php',
type: 'POST',
dataType: "xml",
data: {
poller: selectedPoller
},
success: function (data) {
data = $(data);
displayStatusMessage(data);
displayDetails(data);
displayPhpErrorMsg('move', data);
if (isError(data) == "1") {
abortProgress();
return null;
}
updateProgress();
nextStep();
}
});
}
/**
* Restart Pollers
*/
function restartPollers() {
$('#consoleContent').append(msgTab['restart'] + "... ");
jQuery.ajax({
url: './include/configuration/configGenerate/xml/restartPollers.php',
type: 'POST',
dataType: "xml",
data: {
poller: selectedPoller,
mode: restartMode
},
success: function (data) {
data = $(data);
displayStatusMessage(data);
displayDetails(data);
displayPhpErrorMsg('restart', data);
if (isError(data) == "1") {
abortProgress();
return null;
}
updateProgress();
nextStep();
}
});
}
/**
* Execute commands
*/
function executeCommand() {
$('#consoleContent').append(msgTab['postcmd'] + "... ");
jQuery.ajax({
url: './include/configuration/configGenerate/xml/postcommand.php',
type: 'POST',
dataType: "xml",
data: {
poller: selectedPoller
},
success: function (data) {
data = $(data);
displayPostExecutionCommand(data);
if (isError(data) == "1") {
abortProgress();
return null;
}
updateProgress();
nextStep();
}
});
}
/**
* Display status message
*/
function displayStatusMessage(responseXML) {
var status = responseXML.find("status");
var error = responseXML.find("error");
var str;
str = status.text();
if (error.length) {
str += " (" + error.text() + ")";
}
str += "<br/>";
$('#consoleContent').append(str);
}
/**
* Display details
*/
function displayDetails(responseXML) {
var debug = responseXML.find("debug");
var str;
str = "";
if (debug.length) {
str = debug.text();
}
str += "<br/>";
$('#consoleDetails').append(str);
}
/**
* Display post command result and output
*/
function displayPostExecutionCommand(responseXML) {
var xml = responseXML.find("result");
var xmlStatus = responseXML.find("status");
var str;
str = "";
if (xml.length) {
str += xml.text();
}
str += "<br/>";
$('#consoleDetails').append(str);
$('#consoleContent').append(xmlStatus.text());
}
/**
* Returns 1 if is error
* Returns 0 otherwise
*/
function isError(responseXML) {
var statuscode = responseXML.find("statuscode");
if (statuscode.length) {
return statuscode.text();
}
return 0;
}
/**
* Action (generate, move, restart)
*/
var errorClass = 'list_two';
function displayPhpErrorMsg(action, responseXML) {
var errors = responseXML.find('errorPhp');
var titleError;
if (errorClass == 'list_one') {
errorClass = 'list_two';
} else {
errorClass = 'list_one';
}
if (errors.length == 0) {
return;
}
switch (action) {
case 'generate':
titleError = '<b>Errors/warnings in generate</b>';
break;
case 'move':
titleError = '<b>Errors/warnings in move files</b>';
break;
case 'restart':
titleError = '<b>Errors/warnings in restart</b>';
break;
}
var bodyErrors = document.getElementById('error_log');
var trEl = document.createElement('tr');
trEl.setAttribute('class', errorClass);
bodyErrors.appendChild(trEl);
var tdEl1 = document.createElement('td');
tdEl1.setAttribute('class', 'FormRowField');
tdEl1.innerHTML = titleError;
trEl.appendChild(tdEl1);
var tdEl2 = document.createElement('td');
tdEl2.setAttribute('class', 'FormRowValue');
tdEl2.innerHTML = '<span style="position: relative; float: left; margin-right: 5px;">' +
'<a href="javascript:toggleErrorPhp(\'' + action + '\');" id="expend_' + action + '">[ + ]</a></span>';
trEl.appendChild(tdEl2);
var divErrors = document.createElement('div');
divErrors.setAttribute('id', 'errors_' + action);
divErrors.setAttribute('style', 'position: relative; float: left;');
divErrors.style.visibility = 'hidden';
tdEl2.appendChild(divErrors);
for (var i = 0; i < errors.length; i++) {
divErrors.innerHTML += errors.get(i).firstChild.data + "<br/>";
}
}
function toggleErrorPhp(action) {
var linkEl = document.getElementById('expend_' + action);
var divErrors = document.getElementById('errors_' + action);
if (linkEl.innerHTML == '[ + ]') {
linkEl.innerHTML = '[ - ]';
divErrors.style.visibility = 'visible';
} else {
linkEl.innerHTML = '[ + ]';
divErrors.style.visibility = 'hidden';
}
}
function cleanErrorPhp() {
var bodyErrors = document.getElementById('error_log');
while (bodyErrors.hasChildNodes()) {
bodyErrors.removeChild(bodyErrors.firstChild);
}
}
/**
* Updates progress
*/
function updateProgress() {
var pct = 0;
if (typeof(curProgress) != 'undefined' && typeof(stepProgress) != 'undefined') {
pct = curProgress + stepProgress;
curProgress += stepProgress;
}
if (pct > 100) {
pct = 100;
}
$('#progress_bar').progressbar('value', pct);
$('#progressPct').html(Math.round(pct) + "%");
}
/**
* Toggle debug
*/
function toggleDebug(pollerId) {
if (pollerId) {
if ($('#debug_' + pollerId).is(':visible')) {
$('#togglerp_' + pollerId).show();
$('#togglerm_' + pollerId).hide();
$('#debug_' + pollerId).hide();
} else {
$('#togglerp_' + pollerId).hide();
$('#togglerm_' + pollerId).show();
$('#debug_' + pollerId).show();
}
}
}
function abortProgress() {
$('#consoleContent').append(msgTab['abort']);
exportBtn.disabled = false;
steps = new Array();
}
</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/configGenerate/DB-Func.php | centreon/www/include/configuration/configGenerate/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
*
*/
/**
* Get the configuration path for Centreon Broker
*
* @param int $ns_id The nagios server id
* @return string
*/
function getCentreonBrokerDirCfg($ns_id)
{
global $pearDB;
$query = 'SELECT centreonbroker_cfg_path
FROM nagios_server
WHERE id = ' . $ns_id;
$res = $pearDB->query($query);
$row = $res->fetch();
if (trim($row['centreonbroker_cfg_path']) != '') {
return trim($row['centreonbroker_cfg_path']);
}
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/configuration/configGenerate/xml/restartPollers.php | centreon/www/include/configuration/configGenerate/xml/restartPollers.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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');
use App\Kernel;
use Centreon\Domain\Contact\Interfaces\ContactServiceInterface;
use Core\Domain\Engine\Model\EngineCommandGenerator;
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../../../../config/bootstrap.php');
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/DB-Func.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/centreon.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonBroker.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php';
if (! defined('STATUS_OK')) {
define('STATUS_OK', 0);
}
if (! defined('STATUS_NOK')) {
define('STATUS_NOK', 1);
}
$pearDB = new CentreonDB();
$xml = new CentreonXML();
$okMsg = "<b><font color='green'>OK</font></b>";
$nokMsg = "<b><font color='red'>NOK</font></b>";
$kernel = new Kernel('prod', false);
$kernel->boot();
$container = $kernel->getContainer();
if ($container == null) {
throw new Exception(_('Unable to load the Symfony container'));
}
if (isset($_SERVER['HTTP_X_AUTH_TOKEN'])) {
$contactService = $container->get(ContactServiceInterface::class);
$contact = $contactService->findByAuthenticationToken($_SERVER['HTTP_X_AUTH_TOKEN']);
if ($contact === null) {
$xml->startElement('response');
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', STATUS_NOK);
$xml->writeElement('error', 'Contact not found');
$xml->endElement();
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: no-cache');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate');
}
$xml->output();
exit();
}
$centreon = new Centreon([
'contact_id' => $contact->getId(),
'contact_name' => $contact->getName(),
'contact_alias' => $contact->getAlias(),
'contact_email' => $contact->getEmail(),
'contact_admin' => $contact->isAdmin(),
'contact_lang' => null,
'contact_passwd' => null,
'contact_autologin_key' => null,
'contact_location' => null,
'reach_api' => $contact->hasAccessToApiConfiguration(),
'reach_api_rt' => $contact->hasAccessToApiRealTime(),
'show_deprecated_pages' => false,
'show_deprecated_custom_views' => false,
]);
} else {
// Check Session
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $pearDB)) {
echo 'Bad Session';
exit();
}
$centreon = $_SESSION['centreon'];
}
if (! isset($_POST['poller']) || ! isset($_POST['mode'])) {
exit();
}
/**
* List of error from php
*/
global $generatePhpErrors;
$generatePhpErrors = [];
/**
* The error handler for get error from PHP
*
* @see set_error_handler
*/
$log_error = function ($errno, $errstr, $errfile, $errline) {
global $generatePhpErrors;
if (! (error_reporting() && $errno)) {
return;
}
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
case E_CORE_ERROR:
$generatePhpErrors[] = ['error', $errstr];
break;
case E_WARNING:
case E_USER_WARNING:
case E_CORE_WARNING:
$generatePhpErrors[] = ['warning', $errstr];
break;
}
return true;
};
try {
$pollers = explode(',', $_POST['poller']);
$ret = [];
$ret['host'] = $pollers;
$ret['restart_mode'] = $_POST['mode'];
chdir(_CENTREON_PATH_ . 'www');
$nagiosCFGPath = _CENTREON_CACHEDIR_ . '/config/engine/';
$centreonBrokerPath = _CENTREON_CACHEDIR_ . '/config/broker/';
// Set new error handler
set_error_handler($log_error);
$centcoreDirectory = defined('_CENTREON_VARLIB_') ? _CENTREON_VARLIB_ : '/var/lib/centreon';
if (is_dir($centcoreDirectory . '/centcore')) {
$centcorePipe = $centcoreDirectory . '/centcore/' . microtime(true) . '-externalcommand.cmd';
} else {
$centcorePipe = $centcoreDirectory . '/centcore.cmd';
}
$stdout = '';
if (! isset($msg_restart)) {
$msg_restart = [];
}
$tabs = $centreon->user->access->getPollerAclConf([
'fields' => [
'name',
'id',
'engine_restart_command',
'engine_reload_command',
'broker_reload_command',
],
'order' => ['name'],
'conditions' => ['ns_activate' => '1'],
'keys' => ['id'],
]);
foreach ($tabs as $tab) {
if (isset($ret['host']) && ($ret['host'] == 0 || in_array($tab['id'], $ret['host']))) {
$poller[$tab['id']] = ['id' => $tab['id'], 'name' => $tab['name'], 'engine_restart_command' => $tab['engine_restart_command'], 'engine_reload_command' => $tab['engine_reload_command'], 'broker_reload_command' => $tab['broker_reload_command']];
}
}
// Restart broker
$brk = new CentreonBroker($pearDB);
$brk->reload();
/**
* @var EngineCommandGenerator $commandGenerator
*/
$commandGenerator = $container->get(EngineCommandGenerator::class);
foreach ($poller as $host) {
if ($ret['restart_mode'] == 1) {
if ($fh = @fopen($centcorePipe, 'a+')) {
$reloadCommand = ($commandGenerator !== null)
? $commandGenerator->getEngineCommand('RELOAD')
: 'RELOAD';
fwrite($fh, $reloadCommand . ':' . $host['id'] . "\n");
fclose($fh);
} else {
throw new Exception(_('Could not write into centcore.cmd. Please check file permissions.'));
}
// Manage Error Message
if (! isset($msg_restart[$host['id']])) {
$msg_restart[$host['id']] = '';
}
$msg_restart[$host['id']] .= _(
'<br><b>Centreon : </b>A reload signal has been sent to '
. htmlspecialchars(string: $host['name'], encoding: 'UTF-8') . "\n"
);
} elseif ($ret['restart_mode'] == 2) {
if ($fh = @fopen($centcorePipe, 'a+')) {
$restartCommand = ($commandGenerator !== null)
? $commandGenerator->getEngineCommand('RESTART')
: 'RESTART';
fwrite($fh, $restartCommand . ':' . $host['id'] . "\n");
fclose($fh);
} else {
throw new Exception(_('Could not write into centcore.cmd. Please check file permissions.'));
}
// Manage error Message
if (! isset($msg_restart[$host['id']])) {
$msg_restart[$host['id']] = '';
}
$msg_restart[$host['id']] .= _(
'<br><b>Centreon : </b>A restart signal has been sent to '
. htmlspecialchars(string: $host['name'], encoding: 'UTF-8') . "\n"
);
}
$DBRESULT = $pearDB->query("UPDATE `nagios_server` SET `last_restart` = '"
. time() . "', `updated` = '0' WHERE `id` = '" . $host['id'] . "'");
}
foreach ($msg_restart as $key => $str) {
$msg_restart[$key] = str_replace("\n", '<br>', $str);
}
$xml->startElement('response');
$xml->writeElement('status', $okMsg);
$xml->writeElement('statuscode', STATUS_OK);
} catch (Exception $e) {
$xml->startElement('response');
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', STATUS_NOK);
$xml->writeElement('error', $e->getMessage());
}
// Restore default error handler
restore_error_handler();
// Add error form php
$xml->startElement('errorsPhp');
foreach ($generatePhpErrors as $error) {
if ($error[0] == 'error') {
$errmsg = '<span style="color: red;">Error</span><span style="margin-left: 5px;">' . $error[1] . '</span>';
} else {
$errmsg = '<span style="color: orange;">Warning</span><span style="margin-left: 5px;">' . $error[1] . '</span>';
}
$xml->writeElement('errorPhp', $errmsg);
}
$xml->endElement();
$xml->endElement();
// Headers
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: no-cache');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate');
}
// Send Data
$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/configuration/configGenerate/xml/moveFiles.php | centreon/www/include/configuration/configGenerate/xml/moveFiles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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');
use App\Kernel;
use Centreon\Domain\Contact\Interfaces\ContactServiceInterface;
use Centreon\Domain\Entity\Task;
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../../../../config/bootstrap.php');
require_once realpath(__DIR__ . '/../../../../../bootstrap.php');
require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/DB-Func.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/centreon.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonUser.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonConfigCentreonBroker.php';
if (! defined('STATUS_OK')) {
define('STATUS_OK', 0);
}
if (! defined('STATUS_NOK')) {
define('STATUS_NOK', 1);
}
$pearDB = new CentreonDB();
$xml = new CentreonXML();
$okMsg = "<b><font color='green'>OK</font></b>";
$nokMsg = "<b><font color='red'>NOK</font></b>";
if (isset($_SERVER['HTTP_X_AUTH_TOKEN'])) {
$kernel = new Kernel('prod', false);
$kernel->boot();
$container = $kernel->getContainer();
if ($container == null) {
throw new Exception(_('Unable to load the Symfony container'));
}
$contactService = $container->get(ContactServiceInterface::class);
$contact = $contactService->findByAuthenticationToken($_SERVER['HTTP_X_AUTH_TOKEN']);
if ($contact === null) {
$xml->startElement('response');
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', STATUS_NOK);
$xml->writeElement('error', 'Contact not found');
$xml->endElement();
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: no-cache');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate');
}
$xml->output();
exit();
}
$centreon = new Centreon([
'contact_id' => $contact->getId(),
'contact_name' => $contact->getName(),
'contact_alias' => $contact->getAlias(),
'contact_email' => $contact->getEmail(),
'contact_admin' => $contact->isAdmin(),
'contact_lang' => null,
'contact_passwd' => null,
'contact_autologin_key' => null,
'contact_location' => null,
'reach_api' => $contact->hasAccessToApiConfiguration(),
'reach_api_rt' => $contact->hasAccessToApiRealTime(),
'show_deprecated_pages' => false,
'show_deprecated_custom_views' => false,
]);
} else {
// Check Session
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $pearDB)) {
echo 'Bad Session';
exit();
}
$centreon = $_SESSION['centreon'];
}
if (! isset($_POST['poller']) || ! $centreon->user->access->checkAction('generate_cfg')) {
exit;
}
/**
* List of error from php
*/
global $generatePhpErrors;
global $dependencyInjector;
$generatePhpErrors = [];
$pollers = explode(',', $_POST['poller']);
// Add task to export files if there is a remote
$pollerParams = [];
foreach ($pollers as $index => $pollerId) {
if (is_numeric($pollerId)) {
$pollerParams[':poller_' . $index] = $pollerId;
}
}
// SELECT Remote Servers from selected pollers
// Then add all simple pollers linked directly to those Remote Servers
// Then add all pollers which have an additional link to those Remote Servers
$statementRemotes = $pearDB->prepare(
'SELECT ns.id
FROM nagios_server AS ns
JOIN platform_topology AS pt ON (ns.id = pt.server_id)
WHERE ns.id IN (' . implode(',', array_keys($pollerParams)) . ')
AND pt.type = "remote"
UNION
SELECT ns1.id
FROM nagios_server AS ns1
JOIN platform_topology AS pt ON (ns1.id = pt.server_id)
JOIN nagios_server AS ns2 ON ns1.id = ns2.remote_id
WHERE ns2.id IN (' . implode(',', array_keys($pollerParams)) . ')
AND pt.type = "remote"
UNION
SELECT ns1.id
FROM nagios_server AS ns1
JOIN platform_topology AS pt ON (ns1.id = pt.server_id)
JOIN rs_poller_relation AS rspr ON rspr.remote_server_id = ns1.id
WHERE rspr.poller_server_id IN (' . implode(',', array_keys($pollerParams)) . ')
AND pt.type = "remote"'
);
foreach ($pollerParams as $key => $value) {
$statementRemotes->bindValue($key, $value, PDO::PARAM_INT);
}
$statementRemotes->execute();
$remotesResults = $statementRemotes->fetchAll(PDO::FETCH_ASSOC);
if (! empty($remotesResults)) {
foreach ($remotesResults as $remote) {
$linkedStatement = $pearDB->prepare(
'SELECT id
FROM nagios_server
WHERE remote_id = :remote_id
UNION
SELECT poller_server_id AS id
FROM rs_poller_relation
WHERE remote_server_id = :remote_id'
);
$linkedStatement->bindValue(':remote_id', $remote['id'], PDO::PARAM_INT);
$linkedStatement->execute();
$linkedResults = $linkedStatement->fetchAll(PDO::FETCH_ASSOC);
$exportParams = [
'server' => $remote['id'],
'pollers' => [],
];
$exportParams['pollers'] = ! empty($linkedResults) ? array_column($linkedResults, 'id') : [$remote['id']];
$dependencyInjector['centreon.taskservice']->addTask(Task::TYPE_EXPORT, ['params' => $exportParams]);
}
}
/**
* The error handler for get error from PHP
*
* @see set_error_handler
*/
$log_error = function ($errno, $errstr, $errfile, $errline) {
global $generatePhpErrors;
if (! (error_reporting() && $errno)) {
return;
}
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
case E_CORE_ERROR:
$generatePhpErrors[] = ['error', $errstr];
break;
case E_WARNING:
case E_USER_WARNING:
case E_CORE_WARNING:
$generatePhpErrors[] = ['warning', $errstr];
break;
}
return true;
};
try {
$ret = [];
$ret['host'] = $pollers;
chdir(_CENTREON_PATH_ . 'www');
$nagiosCFGPath = _CENTREON_CACHEDIR_ . '/config/engine/';
$centreonBrokerPath = _CENTREON_CACHEDIR_ . '/config/broker/';
$vmWareConfigPath = _CENTREON_CACHEDIR_ . '/config/vmware/';
// Set new error handler
set_error_handler($log_error);
// Centcore pipe path
$centcore_pipe = _CENTREON_VARLIB_ . '/centcore.cmd';
$tab_server = [];
$tabs = $centreon->user->access->getPollerAclConf(['fields' => ['name', 'id', 'localhost'], 'order' => ['name'], 'conditions' => ['ns_activate' => '1'], 'keys' => ['id']]);
foreach ($tabs as $tab) {
if (isset($ret['host']) && ($ret['host'] == 0 || in_array($tab['id'], $ret['host']))) {
$tab_server[$tab['id']] = ['id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost']];
}
}
foreach ($tab_server as $host) {
if (isset($pollers) && ($pollers == 0 || in_array($host['id'], $pollers))) {
$listBrokerFile = glob($centreonBrokerPath . $host['id'] . '/*.{xml,json,cfg,sql}', GLOB_BRACE);
$listVmWareFile = glob($vmWareConfigPath . $host['id'] . '/*.json', GLOB_BRACE);
if (isset($host['localhost']) && $host['localhost'] == 1) {
// Check if monitoring engine's configuration directory existss
$dbResult = $pearDB->query("
SELECT cfg_dir FROM cfg_nagios, nagios_server
WHERE nagios_server.id = cfg_nagios.nagios_server_id
AND nagios_server.localhost = '1'
ORDER BY cfg_nagios.nagios_activate
DESC LIMIT 1");
$nagiosCfg = $dbResult->fetch();
if (! is_dir($nagiosCfg['cfg_dir'])) {
throw new Exception(
sprintf(
_(
"Could not find configuration directory '%s' for monitoring engine '%s'.
Please check its path or create it"
),
$nagiosCfg['cfg_dir'],
$host['name']
)
);
}
// Copy monitoring engine's configuration files
foreach (glob($nagiosCFGPath . $host['id'] . '/*.{json,cfg}', GLOB_BRACE) as $filename) {
$targetFilePath = rtrim($nagiosCfg['cfg_dir'], '/') . '/' . basename($filename);
$succeded = @copy($filename, $targetFilePath);
if (! $succeded) {
throw new Exception(
sprintf(
_(
"Could not write to file '%s' for monitoring engine '%s'. Please add writing
permissions for the webserver's user"
),
basename($filename),
$host['name']
)
);
}
if (posix_getuid() === fileowner($targetFilePath)) {
@chmod($targetFilePath, 0664);
}
}
// Centreon Broker configuration
if (count($listBrokerFile) > 0) {
$centreonBrokerDirCfg = getCentreonBrokerDirCfg($host['id']);
if (! is_null($centreonBrokerDirCfg)) {
if (! is_dir($centreonBrokerDirCfg)) {
if (! mkdir($centreonBrokerDirCfg, 0755)) {
throw new Exception(
sprintf(
_(
"Centreon Broker's configuration directory '%s' does not exist and could not
be created for monitoring engine '%s'. Please check its path or create it"
),
$centreonBrokerDirCfg,
$host['name']
)
);
}
}
foreach ($listBrokerFile as $fileCfg) {
$targetFilePath = rtrim($centreonBrokerDirCfg, '/') . '/' . basename($fileCfg);
$succeded = @copy($fileCfg, $targetFilePath);
if (! $succeded) {
throw new Exception(
sprintf(
_(
"Could not write to Centreon Broker's configuration file '%s' for monitoring
engine '%s'. Please add writing permissions for the webserver's user"
),
basename($fileCfg),
$host['name']
)
);
}
if (posix_getuid() === fileowner($targetFilePath)) {
@chmod($targetFilePath, 0664);
}
}
}
}
/**
* VMWare configuration
*/
if (! is_array($listVmWareFile) || count($listVmWareFile) != 1) {
throw new Exception(
sprintf(
<<<'MSG'
There must be one and only one VMWare configuration file for monitoring engine '%s'.
Please check its path or create it
MSG,
$host['name']
)
);
}
if (! copy($listVmWareFile[0], _CENTREON_ETC_ . '/' . 'centreon_vmware.json')) {
throw new Exception(sprintf(
<<<'MSG'
Could not write to VMWare's configuration file '%s' for monitoring server '%s'.
Please add writing permissions for the webserver's user.
MSG,
basename($listVmWareFile[0] ?? ''),
$host['name']
));
}
} else {
passthru(
escapeshellcmd("echo 'SENDCFGFILE:{$host['id']}'") . ' >> ' . escapeshellcmd($centcore_pipe),
$return
);
if ($return) {
throw new Exception(_('Could not write into centcore.cmd. Please check file permissions.'));
}
if (! isset($msg_restart[$host['id']])) {
$msg_restart[$host['id']] = '';
}
$msg_restart[$host['id']] .= _('<br><b>Centreon : </b>All configuration will be send to '
. $host['name'] . ' by centcore in several minutes.');
}
}
}
$xml->startElement('response');
$xml->writeElement('status', $okMsg);
$xml->writeElement('statuscode', STATUS_OK);
} catch (Exception $e) {
$xml->startElement('response');
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', STATUS_NOK);
$xml->writeElement('error', $e->getMessage());
}
// Restore default error handler
restore_error_handler();
// Add error form php
$xml->startElement('errorsPhp');
foreach ($generatePhpErrors as $error) {
if ($error[0] == 'error') {
$errmsg = '<span style="color: red;">Error</span><span style="margin-left: 5px;">' . $error[1] . '</span>';
} else {
$errmsg = '<span style="color: orange;">Warning</span><span style="margin-left: 5px;">' . $error[1] . '</span>';
}
$xml->writeElement('errorPhp', $errmsg);
}
$xml->endElement();
$xml->endElement();
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: 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/configuration/configGenerate/xml/generateFiles.php | centreon/www/include/configuration/configGenerate/xml/generateFiles.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 App\Kernel;
use Centreon\Domain\Contact\Interfaces\ContactServiceInterface;
ini_set('display_errors', 'Off');
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../../../../config/bootstrap.php');
require_once realpath(__DIR__ . '/../../../../../bootstrap.php');
require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/DB-Func.php';
require_once _CENTREON_PATH_ . 'www/include/configuration/configGenerate/common-Func.php';
require_once _CENTREON_PATH_ . 'www/class/config-generate/generate.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreon.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonACL.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/centreonSession.class.php';
global $dependencyInjector;
global $pearDB;
$pearDB = $dependencyInjector['configuration_db'];
$xml = new CentreonXML();
$okMsg = "<b><font color='green'>OK</font></b>";
$nokMsg = "<b><font color='red'>NOK</font></b>";
if (isset($_SERVER['HTTP_X_AUTH_TOKEN'])) {
$kernel = new Kernel('prod', false);
$kernel->boot();
$container = $kernel->getContainer();
if ($container == null) {
throw new Exception(_('Unable to load the Symfony container'));
}
$contactService = $container->get(ContactServiceInterface::class);
$contact = $contactService->findByAuthenticationToken($_SERVER['HTTP_X_AUTH_TOKEN']);
if ($contact === null) {
$xml->startElement('response');
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', 1);
$xml->writeElement('error', 'Contact not found');
$xml->endElement();
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: no-cache');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate');
}
$xml->output();
exit();
}
$centreon = new Centreon([
'contact_id' => $contact->getId(),
'contact_name' => $contact->getName(),
'contact_alias' => $contact->getAlias(),
'contact_email' => $contact->getEmail(),
'contact_admin' => $contact->isAdmin(),
'contact_lang' => null,
'contact_passwd' => null,
'contact_autologin_key' => null,
'contact_location' => null,
'reach_api' => $contact->hasAccessToApiConfiguration(),
'reach_api_rt' => $contact->hasAccessToApiRealTime(),
'show_deprecated_pages' => false,
'show_deprecated_custom_views' => false,
]);
} else {
// Check Session
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $pearDB)) {
echo 'Bad Session';
exit();
}
$centreon = $_SESSION['centreon'];
if (! $centreon->user->admin && $centreon->user->access->checkAction('generate_cfg') === 0) {
echo 'You are not allowed to generate configuration';
exit();
}
}
if (! isset($_POST['poller']) || ! isset($_POST['debug'])) {
exit();
}
// List of error from php
global $generatePhpErrors;
$generatePhpErrors = [];
$path = _CENTREON_PATH_ . 'www/include/configuration/configGenerate/';
$nagiosCFGPath = _CENTREON_CACHEDIR_ . '/config/engine/';
$centreonBrokerPath = _CENTREON_CACHEDIR_ . '/config/broker/';
chdir(_CENTREON_PATH_ . 'www');
$username = 'unknown';
if (isset($centreon->user->name)) {
$username = $centreon->user->name;
}
$config_generate = new Generate($dependencyInjector);
$pollers = explode(',', $_POST['poller']);
$debug = ($_POST['debug'] == 'true') ? 1 : 0;
$generate = ($_POST['generate'] == 'true') ? 1 : 0;
$ret = [];
$ret['host'] = $pollers;
$ret['debug'] = $debug;
/**
* The error handler for get error from PHP
*
* @see set_error_handler
*/
$log_error = function ($errno, $errstr, $errfile, $errline) {
global $generatePhpErrors;
if (! (error_reporting() && $errno)) {
return;
}
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
case E_CORE_ERROR:
$generatePhpErrors[] = ['error', $errstr];
break;
case E_WARNING:
case E_USER_WARNING:
case E_CORE_WARNING:
$generatePhpErrors[] = ['warning', $errstr];
break;
}
return true;
};
// Set new error handler
set_error_handler($log_error);
$xml->startElement('response');
try {
$tabs = [];
if ($generate) {
$tabs = $centreon->user->access->getPollerAclConf(['fields' => ['id', 'name', 'localhost'], 'order' => ['name'], 'keys' => ['id'], 'conditions' => ['ns_activate' => '1']]);
}
// Sync contactgroups to ldap
$cgObj = new CentreonContactgroup($pearDB);
$cgObj->syncWithLdapConfigGen();
// Generate configuration
if ($pollers == '0') {
$config_generate->configPollers($username);
} else {
foreach ($pollers as $poller) {
$config_generate->reset();
$config_generate->configPollerFromId($poller, $username);
}
}
// Debug configuration
$statusMsg = $okMsg;
$statusCode = 0;
if ($debug) {
$statusCode = printDebug($xml, $tabs);
}
if ($statusCode == 1) {
$statusMsg = $nokMsg;
}
$xml->writeElement('status', $statusMsg);
$xml->writeElement('statuscode', $statusCode);
} catch (Exception $e) {
$xml->writeElement('status', $nokMsg);
$xml->writeElement('statuscode', 1);
$xml->writeElement('error', $e->getMessage());
}
// Restore default error handler
restore_error_handler();
// Add error form php
$xml->startElement('errorsPhp');
foreach ($generatePhpErrors as $error) {
if ($error[0] == 'error') {
$errmsg = '<p>
<span style="color: red;">Error</span>
<span style="margin-left: 5px;">' . $error[1] . '</span>
</p>';
$xml->writeElement('errorPhp', $errmsg);
}
}
$xml->endElement();
if (! headers_sent()) {
header('Content-Type: application/xml');
header('Cache-Control: 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/configuration/configGenerate/xml/postcommand.php | centreon/www/include/configuration/configGenerate/xml/postcommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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($_POST['poller'])) {
exit();
}
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.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/centreonInstance.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . 'bootstrap.php';
$db = new CentreonDB();
// Check Session
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $db)) {
echo 'Bad Session';
exit();
}
$pollers = explode(',', $_POST['poller']);
$xml = new CentreonXML();
$kernel = App\Kernel::createForWeb();
$gorgoneService = $kernel->getContainer()->get(Centreon\Domain\Gorgone\Interfaces\GorgoneServiceInterface::class);
$res = $db->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1'");
$idCentral = (int) $res->fetch(PDO::FETCH_COLUMN);
$res = $db->query("SELECT `name`, `id`, `localhost`
FROM `nagios_server`
WHERE `ns_activate` = '1'
ORDER BY `name` ASC");
$xml->startElement('response');
$str = sprintf('<br/><b>%s</b><br/>', _('Post execution command results'));
$ok = true;
$instanceObj = new CentreonInstance($db);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($pollers == 0 || in_array($row['id'], $pollers)) {
$commands = $instanceObj->getCommandData($row['id']);
if (! count($commands)) {
continue;
}
$str .= "<br/><strong>{$row['name']}</strong><br/>";
foreach ($commands as $command) {
$requestData = json_encode(
[
[
'command' => $command['command_line'],
'timeout' => 30,
'continue_on_error' => true,
],
]
);
$gorgoneCommand = new Centreon\Domain\Gorgone\Command\Command($idCentral, $requestData);
$gorgoneResponse = $gorgoneService->send($gorgoneCommand);
$str .= _('Executing command') . ': ' . $command['command_name'] . '<br/>';
}
}
}
$statusStr = $ok === false ? "<b><font color='red'>NOK</font></b>" : "<b><font color='green'>OK</font></b>";
$xml->writeElement('result', $str);
$xml->writeElement('status', $statusStr);
$xml->endElement();
header('Content-Type: application/xml');
header('Cache-Control: 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/configuration/configObject/service_dependency/help.php | centreon/www/include/configuration/configObject/service_dependency/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['name'] = dgettext('help', 'Define a short name for this dependency.');
$help['description'] = dgettext(
'help',
'Define a description for this dependency for easier identification and differentiation.'
);
$help['inherits_parent'] = sprintf(
"%s<br/><font color='red'><b><i>%s</i></b></font>",
dgettext(
'help',
'This directive indicates whether or not the dependency inherits dependencies of the host that is '
. 'being depended upon (also referred to as the master host). In other words, if the master host is '
. 'dependent upon other hosts and any one of those dependencies fail, this dependency will also fail.'
),
dgettext('help', 'Ignored by Centreon Engine.')
);
$help['execution_failure_criteria'] = dgettext(
'help',
'This directive is used to specify the criteria that determine when the dependent host should not be '
. 'actively checked. If the master host is in one of the failure states we specify, the dependent host will '
. 'not be actively checked. If you specify None as an option, the execution dependency will never fail and '
. 'the dependent host will always be actively checked (if other conditions allow for it to be).'
);
$help['notification_failure_criteria'] = dgettext(
'help',
'This directive is used to define the criteria that determine when notifications for the dependent host '
. 'should not be sent out. If the master host is in one of the failure states we specify, notifications '
. 'for the dependent host will not be sent to contacts. If you specify None as an option, the notification '
. 'dependency will never fail and notifications for the dependent host will always be sent out.'
);
// Host service description
$help['host_name'] = dgettext(
'help',
'This directive is used to identify the host(s) that the service that is being depended upon '
. '(also referred to as the master service) "runs" on or is associated with.'
);
$help['service_description'] = dgettext(
'help',
'This directive is used to identify the description of the service that is being depended upon '
. '(also referred to as the master service).'
);
$help['dependent_host_name'] = dgettext(
'help',
'This directive is used to identify the host(s) that the dependent service "runs" on or is '
. 'associated with. Leaving this directive blank can be used to create "same host" dependencies.'
);
$help['dependent_service_description'] = dgettext(
'help',
'This directive is used to identify the description of the dependent service.'
);
$help['hostgroup_name'] = dgettext(
'help',
'This directive is used to identify the short name(s) of the hostgroup(s) that the service that is being '
. 'depended upon (also referred to as the master service) "runs" on or is associated with. '
. 'Multiple hostgroups should be separated by commas. The hostgroup_name may be used instead of, or '
. 'in addition to, the host_name directive.'
);
$help['dependent_hostgroup_name'] = dgettext(
'help',
'This directive is used to specify the short name (s) of the hostgroup(s) that the dependent service "runs" on '
. 'or is associated with. The dependent_hostgroup may be used instead of, or in addition to, '
. 'the dependent_host directive.'
);
$help['servicegroup_name'] = dgettext(
'help',
'This directive is used to identify the description of the service group that is being depended upon '
. '(also referred to as the master service group).'
);
$help['dependent_servicegroup_name'] = dgettext(
'help',
'This directive is used to identify the description of the dependent service group.'
);
$help['metaservice_name'] = dgettext(
'help',
'This directive is used to identify the description of the meta service that is being depended upon '
. '(also referred to as the master meta service).'
);
$help['dependent_metaservice_name'] = dgettext(
'help',
'This directive is used to identify the description of the dependent meta service.'
);
// unsupported in centreon
$help['dependency_period'] = dgettext(
'help',
'This directive is used to specify the short name of the time period during which this dependency is valid. '
. 'If this directive is not specified, the dependency is considered to be valid during all times.'
);
$help['dep_hHostChi'] = sprintf(
"%s<br/><font color='red'><b><i>%s</i></b></font>",
dgettext('help', 'This directive is used to identify the description of the dependent host.'),
dgettext('help', 'Compatible with Centreon Broker only.')
);
| 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/service_dependency/serviceDependency.php | centreon/www/include/configuration/configObject/service_dependency/serviceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/service_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;
$dbmon = $acl->getNameDBAcl();
switch ($o) {
case ADD_DEPENDENCY:
case WATCH_DEPENDENCY:
case MODIFY_DEPENDENCY:
require_once $path . 'formServiceDependency.php';
break;
case DUPLICATE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceDependencyInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceDependency.php';
break;
case DELETE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceDependencyInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceDependency.php';
break;
default:
require_once $path . 'listServiceDependency.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/service_dependency/DB-Func.php | centreon/www/include/configuration/configObject/service_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 testServiceDependencyExistence($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 testCycleH($childs = null)
{
global $pearDB;
global $form;
$parents = [];
$childs = [];
if (isset($form)) {
$parents = $form->getSubmitValue('dep_hSvPar');
$childs = $form->getSubmitValue('dep_hSvChi');
$childs = array_flip($childs);
}
foreach ($parents as $parent) {
if (array_key_exists($parent, $childs)) {
return false;
}
}
return true;
}
function deleteServiceDependencyInDB($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();
$dbResult = $pearDB->query("DELETE FROM dependency WHERE dep_id = '" . $key . "'");
$oreon->CentreonLogAction->insertLog('service dependency', $key, $row['dep_name'], 'd');
}
}
function multipleServiceDependencyInDB($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) && testServiceDependencyExistence($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 * FROM dependency_hostChild_relation WHERE dependency_dep_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['dep_hostPar'] = '';
$query = 'INSERT INTO dependency_hostChild_relation VALUES (:dep_id, :host_host_id)';
$statement = $pearDB->prepare($query);
while ($host = $dbResult->fetch()) {
$statement->bindValue(':dep_id', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT);
$statement->bindValue(':host_host_id', (int) $host['host_host_id'], PDO::PARAM_INT);
$statement->execute();
$fields['dep_hostPar'] .= $host['host_host_id'] . ',';
}
$fields['dep_hostPar'] = trim($fields['dep_hostPar'], ',');
$query = "SELECT * FROM dependency_serviceParent_relation WHERE dependency_dep_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['dep_hSvPar'] = '';
$query = 'INSERT INTO dependency_serviceParent_relation
VALUES (:dep_id, :service_service_id, :host_host_id)';
$statement = $pearDB->prepare($query);
while ($service = $dbResult->fetch()) {
$statement->bindValue(':dep_id', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT);
$statement->bindValue(
':service_service_id',
(int) $service['service_service_id'],
PDO::PARAM_INT
);
$statement->bindValue(':host_host_id', (int) $service['host_host_id'], PDO::PARAM_INT);
$statement->execute();
$fields['dep_hSvPar'] .= $service['service_service_id'] . ',';
}
$fields['dep_hSvPar'] = trim($fields['dep_hSvPar'], ',');
$query = "SELECT * FROM dependency_serviceChild_relation WHERE dependency_dep_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['dep_hSvChi'] = '';
$query = 'INSERT INTO dependency_serviceChild_relation
VALUES (:dep_id, :service_service_id, :host_host_id)';
$statement = $pearDB->prepare($query);
while ($service = $dbResult->fetch()) {
$statement->bindValue(':dep_id', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT);
$statement->bindValue(
':service_service_id',
(int) $service['service_service_id'],
PDO::PARAM_INT
);
$statement->bindValue(':host_host_id', (int) $service['host_host_id'], PDO::PARAM_INT);
$statement->execute();
$fields['dep_hSvChi'] .= $service['service_service_id'] . ',';
}
$fields['dep_hSvChi'] = trim($fields['dep_hSvChi'], ',');
$oreon->CentreonLogAction->insertLog(
'service dependency',
$maxId['MAX(dep_id)'],
$dep_name,
'a',
$fields
);
}
}
}
}
}
function updateServiceDependencyInDB($dep_id = null)
{
if (! $dep_id) {
exit();
}
updateServiceDependency($dep_id);
updateServiceDependencyServiceParents($dep_id);
updateServiceDependencyServiceChilds($dep_id);
updateServiceDependencyHostChildren($dep_id);
}
function insertServiceDependencyInDB($ret = [])
{
$dep_id = insertServiceDependency($ret);
updateServiceDependencyServiceParents($dep_id, $ret);
updateServiceDependencyServiceChilds($dep_id, $ret);
updateServiceDependencyHostChildren($dep_id, $ret);
return $dep_id;
}
/**
* Create a service dependency
*
* @param array<string, mixed> $ret
* @return int
*/
function insertServiceDependency($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'] ?? null,
PDO::PARAM_STR
);
$statement->bindValue(
':notificationFailure',
$resourceValues['notification_failure_criteria'] ?? null,
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();
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
'service dependency',
$depId['MAX(dep_id)'],
$resourceValues['dep_name'],
'a',
$fields
);
return (int) $depId['MAX(dep_id)'];
}
/**
* Update a service dependency
*
* @param null|int $depId
*/
function updateServiceDependency($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'] ?? null,
PDO::PARAM_STR
);
$statement->bindValue(
':notificationFailure',
$resourceValues['notification_failure_criteria'] ?? null,
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(
'service dependency',
$depId,
$resourceValues['dep_name'],
'c',
$fields
);
}
/**
* sanitize resources parameter for Create / Update a service 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';
if (isset($resources['execution_failure_criteria']) && is_array($resources['execution_failure_criteria'])) {
$sanitizedParameters['execution_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags(
implode(
',',
array_keys($resources['execution_failure_criteria'])
)
);
}
if (isset($resources['notification_failure_criteria']) && is_array($resources['notification_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 updateServiceDependencyServiceParents($dep_id = null, $ret = [])
{
if (! $dep_id) {
exit();
}
global $form;
global $pearDB;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$rq = 'DELETE FROM dependency_serviceParent_relation ';
$rq .= "WHERE dependency_dep_id = '" . $dep_id . "'";
$dbResult = $pearDB->query($rq);
$ret1 = $ret['dep_hSvPar'] ?? CentreonUtils::mergeWithInitialValues($form, 'dep_hSvPar');
$counter = count($ret1);
for ($i = 0; $i < $counter; $i++) {
$exp = explode('-', $ret1[$i]);
if (count($exp) == 2) {
$rq = 'INSERT INTO dependency_serviceParent_relation ';
$rq .= '(dependency_dep_id, service_service_id, host_host_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $dep_id . "', '" . $exp[1] . "', '" . $exp[0] . "')";
$dbResult = $pearDB->query($rq);
}
}
}
function updateServiceDependencyServiceChilds($dep_id = null, $ret = [])
{
if (! $dep_id) {
exit();
}
global $form;
global $pearDB;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$rq = 'DELETE FROM dependency_serviceChild_relation ';
$rq .= "WHERE dependency_dep_id = '" . $dep_id . "'";
$dbResult = $pearDB->query($rq);
$ret1 = $ret['dep_hSvChi'] ?? CentreonUtils::mergeWithInitialValues($form, 'dep_hSvChi');
$counter = count($ret1);
for ($i = 0; $i < $counter; $i++) {
$exp = explode('-', $ret1[$i]);
if (count($exp) == 2) {
$rq = 'INSERT INTO dependency_serviceChild_relation ';
$rq .= '(dependency_dep_id, service_service_id, host_host_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $dep_id . "', '" . $exp[1] . "', '" . $exp[0] . "')";
$dbResult = $pearDB->query($rq);
}
}
}
/**
* Update Service Dependency Host Children
* @param null|mixed $dep_id
* @param mixed $ret
*/
function updateServiceDependencyHostChildren($dep_id = null, $ret = [])
{
if (! $dep_id) {
exit();
}
global $form;
global $pearDB;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$rq = 'DELETE FROM dependency_hostChild_relation ';
$rq .= "WHERE dependency_dep_id = '" . $dep_id . "'";
$dbResult = $pearDB->query($rq);
if (isset($ret['dep_hHostChi'])) {
$ret1 = $ret['dep_hHostChi'];
} else {
$ret1 = CentreonUtils::mergeWithInitialValues($form, 'dep_hHostChi');
}
$counter = count($ret1);
for ($i = 0; $i < $counter; $i++) {
$rq = 'INSERT INTO dependency_hostChild_relation ';
$rq .= '(dependency_dep_id, host_host_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $dep_id . "', '" . $ret1[$i] . "')";
$dbResult = $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/service_dependency/listServiceDependency.php | centreon/www/include/configuration/configObject/service_dependency/listServiceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$list = $_GET['list'] ?? null;
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchSD'] ?? $_GET['searchSD'] ?? null
);
if (isset($_POST['searchSD']) || isset($_GET['searchSD'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$aclFrom = '';
$aclCond = '';
if (! $oreon->user->admin) {
$aclFrom = ", `{$dbmon}`.centreon_acl acl ";
$aclCond = ' AND dspr.host_host_id = acl.host_id
AND acl.service_id = dspr.service_service_id
AND acl.group_id IN (' . $acl->getAccessGroupsString() . ') ';
}
$rq = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT dep_id, dep_name, dep_description '
. 'FROM dependency dep, dependency_serviceParent_relation dspr ' . $aclFrom . ' '
. 'WHERE dspr.dependency_dep_id = dep.dep_id ' . $aclCond . ' '
. "AND dspr.host_host_id NOT IN (SELECT host_id FROM host WHERE host_register = '2') ";
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 mutlidimensionnal Array we put in $tpl
$elemArr = [];
for ($i = 0; $dep = $DBRESULT->fetchRow(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $dep['dep_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[" . $dep['dep_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(myDecode($dep['dep_name'])), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&dep_id=' . $dep['dep_id'], 'RowMenu_description' => CentreonUtils::escapeSecure(myDecode($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('searchSD', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listServiceDependency.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/configObject/service_dependency/formServiceDependency.php | centreon/www/include/configuration/configObject/service_dependency/formServiceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 = [];
$parentServices = [];
$childServices = [];
$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();
}
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '10'];
$attrsAdvSelect = ['style' => 'width: 400px; height: 200px;'];
$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_host&action=list';
$attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonHost'];
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list';
$attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonService'];
// 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'), ' ');
$form->setDefaults(['inherits_parent' => '1']);
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok'),
['id' => 'nOk', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'nWarning', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'nUnknown', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'nCritical', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'nPending', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'nNone', 'onClick' => 'applyNotificationRules(this);']
);
$form->addGroup($tab, 'notification_failure_criteria', _('Notification Failure Criteria'), ' ');
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok'),
['id' => 'eOk', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'eWarning', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'eUnknown', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'eCritical', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'ePending', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'eNone', 'onClick' => 'applyExecutionRules(this);']
);
$form->addGroup($tab, 'execution_failure_criteria', _('Execution Failure Criteria'), ' ');
$form->addElement('textarea', 'dep_comment', _('Comments'), $attrsTextarea);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&'
. 'action=defaultValues&target=dependency&field=dep_hSvPar&id=' . $dep_id;
$attrService1 = array_merge(
$attrServices,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_hSvPar', _('Services'), [], $attrService1);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=defaultValues'
. '&target=dependency&field=dep_hSvChi&id=' . $dep_id;
$attrService2 = array_merge(
$attrServices,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_hSvChi', _('Dependent Services'), [], $attrService2);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&'
. 'action=defaultValues&target=dependency&field=dep_hHostChi&id=' . $dep_id;
$attrHost2 = array_merge(
$attrHosts,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_hHostChi', _('Dependent Hosts'), [], $attrHost2);
$form->addElement('hidden', 'dep_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// 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_hSvPar', _('Required Field'), 'required');
$form->registerRule('cycleH', 'callback', 'testCycleH');
$form->addRule('dep_hSvChi', _('Circular Definition'), 'cycleH');
$form->registerRule('exist', 'callback', 'testServiceDependencyExistence');
$form->addRule('dep_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->addRule('execution_failure_criteria', _('Required Field'), 'required');
$form->addRule('notification_failure_criteria', _('Required Field'), 'required');
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign('sort1', _('Information'));
$tpl->assign('sort2', _('Service Description'));
$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);
// 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) {
$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) {
$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('nagios', $oreon->user->get_version());
$valid = false;
if ($form->validate()) {
$depObj = $form->getElement('dep_id');
if ($form->getSubmitValue('submitA')) {
$depObj->setValue(insertServiceDependencyInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateServiceDependencyInDB($depObj->getValue('dep_id'));
}
$o = null;
$valid = true;
}
if ($valid) {
require_once 'listServiceDependency.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <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('formServiceDependency.ihtml');
}
?>
<script type="text/javascript">
function applyNotificationRules(object) {
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/service/serviceByHost.php | centreon/www/include/configuration/configObject/service/serviceByHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
global $form_service_type;
$form_service_type = 'BYHOST';
const SERVICE_ADD = 'a';
const SERVICE_WATCH = 'w';
const SERVICE_MODIFY = 'c';
const SERVICE_MASSIVE_CHANGE = 'mc';
const SERVICE_DIVISION = 'dv';
const SERVICE_ACTIVATION = 's';
const SERVICE_MASSIVE_ACTIVATION = 'ms';
const SERVICE_DEACTIVATION = 'u';
const SERVICE_MASSIVE_DEACTIVATION = 'mu';
const SERVICE_DUPLICATION = 'm';
const SERVICE_DELETION = 'd';
// Check options
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] !== '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] !== '') {
$o = $_POST['o2'];
}
}
$service_id = $o === SERVICE_MASSIVE_CHANGE ? false : filter_var(
$_GET['service_id'] ?? $_POST['service_id'] ?? null,
FILTER_VALIDATE_INT
);
// Path to the configuration dir
$path = './include/configuration/configObject/service/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
/*
* Create a suffix for file name in order to redirect service by hostgroup
* on a good page.
*/
$linkType = '';
if ($service_id !== false) {
// Check if a service is a service by hostgroup or not
$statement = $pearDB->prepare('SELECT * FROM host_service_relation WHERE service_service_id = :service_id');
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
while ($data = $statement->fetch()) {
if (isset($data['hostgroup_hg_id']) && $data['hostgroup_hg_id'] !== '') {
$linkType = 'Group';
$form_service_type = 'BYHOSTGROUP';
}
}
}
// 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;
$aclDbName = $acl->getNameDBAcl();
switch ($o) {
case SERVICE_ADD:
case SERVICE_WATCH:
case SERVICE_MODIFY:
case SERVICE_MASSIVE_CHANGE:
require_once $path . 'formService.php';
break;
case SERVICE_DIVISION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
divideGroupedServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
unset($_GET['service_id']);
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
unset($_GET['service_id']);
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . "listServiceByHost{$linkType}.php";
break;
case SERVICE_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceByApi($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . "listServiceByHost{$linkType}.php";
break;
default:
require_once $path . "listServiceByHost{$linkType}.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/service/serviceByHostGroup.php | centreon/www/include/configuration/configObject/service/serviceByHostGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
global $form_service_type;
$form_service_type = 'BYHOSTGROUP';
const SERVICE_ADD = 'a';
const SERVICE_WATCH = 'w';
const SERVICE_MODIFY = 'c';
const SERVICE_MASSIVE_CHANGE = 'mc';
const SERVICE_DIVISION = 'dv';
const SERVICE_MOVE_TO_HOST = 'mvH';
const SERVICE_ACTIVATION = 's';
const SERVICE_MASSIVE_ACTIVATION = 'ms';
const SERVICE_DEACTIVATION = 'u';
const SERVICE_MASSIVE_DEACTIVATION = 'mu';
const SERVICE_DUPLICATION = 'm';
const SERVICE_DELETION = 'd';
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] != '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] != '') {
$o = $_POST['o2'];
}
}
$service_id = $o === SERVICE_MASSIVE_CHANGE ? false : filter_var(
$_GET['service_id'] ?? $_POST['service_id'] ?? null,
FILTER_VALIDATE_INT
);
// Path to the configuration dir
$path = './include/configuration/configObject/service/';
// PHP functions
require_once './class/centreonDB.class.php';
$pearDBO = new CentreonDB('centstorage');
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$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 = $centreon->user->access;
$aclDbName = $acl->getNameDBAcl();
switch ($o) {
case SERVICE_ADD:
case SERVICE_WATCH:
case SERVICE_MODIFY:
case SERVICE_MASSIVE_CHANGE:
require_once $path . 'formService.php';
break;
case SERVICE_DIVISION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
divideGroupedServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_MOVE_TO_HOST:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
divideGroupedServiceInDB(null, $select ?? [], 1);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
case SERVICE_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceByHostGroup.php';
break;
default:
require_once $path . 'listServiceByHostGroup.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/service/help.php | centreon/www/include/configuration/configObject/service/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['mc_update'] = dgettext(
'help',
'Choose the update mode for the below field: incremental adds the selected values, replacement '
. 'overwrites the original values.'
);
// Service Configuration
$help['service_alias'] = dgettext('help', 'Name used for service in auto-deploy by template.');
$help['service_description'] = dgettext(
'help',
"Name of the service or template. It cannot contain white spaces, or special characters like ~!$%^&*\"|'<>?,()=."
. ' Each service of an host must have a unique name. The name of a service template must be unique.'
);
$help['use'] = dgettext(
'help',
'This is where you specify the name of the template object that you want to inherit properties/variables from. '
. "Inherited properties doesn't need to be specified again. \"Local\" object variables always take "
. 'precedence over variables defined in the template object. Objects can inherit properties/variables '
. 'from multiple levels of template objects. When defining multiple sources, the first template specified '
. 'takes precedence over the later one, in the case where a property is defined in both.'
);
$help['is_volatile'] = dgettext(
'help',
'This directive is used to denote whether the service is "volatile". A volatile service resets its '
. 'state to OK with every query. Services are normally not volatile.'
);
$help['check_period'] = dgettext(
'help',
'Specify the time period during which active checks of this service can be made.'
);
$help['check_command'] = dgettext(
'help',
'Specify the command that monitoring engine will run in order to check the status of the service.'
);
$help['check_command_args'] = dgettext('help', 'Specify the parameters for the selected check command here.');
$help['max_check_attempts'] = dgettext(
'help',
'Define the number of times that monitoring engine will retry the service check command if it returns any '
. 'state other than an OK state. Setting this value to 1 will cause monitoring engine to generate an alert '
. 'without retrying the service check again. (default value: 0)'
);
$help['check_interval'] = dgettext(
'help',
'Define the number of "time units" between regularly scheduled checks of the service. With the default '
. 'time unit of 60s, this number will mean multiples of 1 minute. "Regular" checks are those that occur '
. 'when the service is in an OK state or when the service is in a non-OK state, but has already been '
. 'rechecked max_check_attempts number of times. (default value: 5)'
);
$help['retry_interval'] = dgettext(
'help',
'Define the number of "time units" to wait before scheduling a re-check for this service after a '
. 'non-OK state was detected. With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'Once the service has been retried max_check_attempts times without a change in its status, it will revert '
. 'to being scheduled at its "normal" check interval rate. (default value: 1)'
);
$help['active_checks_enabled'] = dgettext(
'help',
'Enable or disable active checks (either regularly scheduled or on-demand) of this service here. '
. 'By default active service checks are enabled.'
);
$help['passive_checks_enabled'] = dgettext(
'help',
'Enable or disable passive checks here. When disabled submitted states will be not accepted.'
);
$help['notifications_enabled'] = dgettext('help', 'Specify whether or not notifications for this service are enabled.');
$help['contact_additive_inheritance'] = dgettext(
'help',
'When enabled, the contact definition will not override the definitions on template levels, it will be '
. 'appended instead.'
);
$help['cg_additive_inheritance'] = dgettext(
'help',
'When enabled, the contactgroup definition will not override the definitions on template levels, '
. 'it will be appended instead.'
);
$help['contacts'] = dgettext(
'help',
'This is a list of contacts that should be notified whenever there are problems (or recoveries) with '
. "this host. Useful if you want notifications to go to just a few people and don't want to configure "
. 'contact groups. You must specify at least one contact or contact group in each host definition '
. '(or indirectly through its template).'
);
$help['inherit_contacts_from_host'] = dgettext(
'help',
"Specify whether or not the service will inherit host's contacts and contactgroups (if no contacts or "
. 'contactgroups are defined for the service).'
);
$help['use_only_contacts_from_host'] = dgettext('help', 'To fill');
$help['contacts'] = dgettext(
'help',
'This is a list of contacts that should be notified whenever there are problems (or recoveries) with '
. "this service. Useful if you want notifications to go to just a few people and don't want to configure contact "
. 'groups. You must specify at least one contact or contact group in each service definition '
. '(or indirectly through its template).'
);
$help['contact_groups'] = dgettext(
'help',
'This is a list of contact groups that should be notified whenever there are problems (or recoveries) '
. 'with this service. You must specify at least one contact or contact group in each service definition.'
);
$help['notification_interval'] = dgettext(
'help',
'Define the number of "time units" to wait before re-notifying a contact that this service is still in a '
. 'warning or critical condition. With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'A value of 0 disables re-notifications of contacts about problems for this service - only one problem '
. 'notification will be sent out. (default value: 30)'
);
$help['notification_period'] = dgettext(
'help',
'Specify the time period during which notifications of events for this service can be sent out to contacts. '
. 'If a state change occurs during a time which is not covered by the time period, no notifications will be sent out.'
);
$help['notification_options'] = dgettext(
'help',
'Define the states of the service for which notifications should be sent out. If you specify None as an '
. 'option, no service notifications will be sent out. If you do not specify any notification options, '
. 'monitoring engine will assume that you want notifications to be sent out for all possible states.'
);
$help['first_notification_delay'] = dgettext(
'help',
'Define the number of "time units" to wait before sending out the first problem notification when this '
. 'service enters a non-OK state. '
. 'With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'If you set this value to 0, monitoring engine will start sending out notifications immediately.'
);
$help['recovery_notification_delay'] = dgettext(
'help',
'Define the number of "time units" to wait before sending out the recovery notification when this '
. 'service enters an OK state. '
. 'With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'If you set this value to 0, monitoring engine will start sending out notifications immediately.'
);
$help['use_only_contacts_from_host'] = dgettext(
'help',
"If this option is enabled, use host's notification parameters instead of service or from template of "
. 'service parameters inherited'
);
// Relations
$help['host_templates'] = dgettext(
'help',
'When one of these host template is applied to a host, a service will be created based on the current template.'
);
$help['host_name'] = dgettext('help', 'Host(s) to which the service is attached');
$help['hostgroup_name'] = dgettext(
'help',
'Specify the hostgroup(s) that this service "runs" on or is associated with. One or more hostgroup(s) '
. 'may be used instead of, or in addition to, specifying hosts.'
);
$help['servicegroups'] = dgettext(
'help',
'Service groups linked to the service.'
);
$help['snmptraps'] = dgettext('help', 'Specify the relation of known SNMP traps to state changes of this service.');
// Data processing
$help['obsess_over_service'] = dgettext(
'help',
'This directive determines whether or not checks for the service will be "obsessed" over. '
. 'When enabled the obsess over service command will be executed after every check of this service.'
);
$help['check_freshness'] = dgettext(
'help',
'This directive is used to determine whether or not freshness checks are enabled for this service. '
. 'When enabled monitoring engine will trigger an active check when last passive result is older than '
. 'the value defined in the threshold. By default freshness checks are enabled.'
);
$help['freshness_threshold'] = dgettext(
'help',
'This directive is used to specify the freshness threshold (in seconds) for this service. '
. 'If you set this directive to a value of 0, monitoring engine will determine a '
. 'freshness threshold to use automatically.'
);
$help['flap_detection_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not flap detection is enabled for this service. '
. 'A service is marked as flapping when frequent state changes occur.'
);
$help['low_flap_threshold'] = dgettext(
'help',
'Specify the low state change threshold used in flap detection for this service. A service with a state '
. 'change rate below this threshold is marked normal. '
. 'By setting the value to 0, the program-wide value will be used.'
);
$help['high_flap_threshold'] = dgettext(
'help',
'Specify the high state change threshold used in flap detection for this service. A service with a state '
. 'change rate above or equal to this threshold is marked as flapping. By setting the value to 0, '
. 'the program-wide value will be used.'
);
$help['process_perf_data'] = dgettext(
'help',
'Specify whether or not the processing of performance data is enabled for this service.'
);
$help['retain_status_information'] = dgettext(
'help',
'Specify whether or not status-related information about the service is retained across program restarts. '
. 'This is only useful if you have enabled state retention using the retain_state_information directive.'
);
$help['retain_nonstatus_information'] = dgettext(
'help',
'Specify whether or not non-status information about the service is retained across program restarts. '
. 'This is only useful if you have enabled state retention using the retain_state_information directive.'
);
$help['stalking_options'] = dgettext('help', 'Define which service states "stalking" is enabled for.');
$help['event_handler_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not the event handler for this service is enabled.'
);
$help['event_handler'] = dgettext(
'help',
'This directive is used to specify the command that should be run whenever a change in the state of the '
. 'service is detected (i.e. whenever it changes to non-OK or recovers).'
);
$help['event_handler_args'] = dgettext(
'help',
'This parameters are passed to the event handler commands in the same way check command parameters are handled. '
. 'The format is: !ARG1!ARG2!...ARGn'
);
$help['service_acknowledgement_timeout'] = dgettext(
'help',
'Specify a duration of acknowledgement for this service or service depending to this template. '
. 'If you leave it blank, no timeout will be set.'
);
// Service extended infos
$help['graph_template'] = dgettext(
'help',
'The optional definition of a graph template will be used as default graph template for this service.'
);
$help['categories'] = dgettext(
'help',
'Host categories linked to the service.'
);
$help['notes_url'] = dgettext(
'help',
'Clickable URL displayed in the Notes column of the Resources Status page.'
);
$help['notes'] = dgettext(
'help',
'Information note displayed as a tooltip in the Notes column of the Resources Status page.'
);
$help['action_url'] = dgettext(
'help',
'Define an optional URL that can be used to provide more actions to be performed on the service. '
. 'You will see the link to the action URL in the service details.'
);
$help['icon_image'] = dgettext(
'help',
'Define the image that should be associated with this service here. This image will be displayed in the '
. 'various places. The image will look best if it is 40x40 pixels in size.'
);
$help['icon_image_alt'] = dgettext(
'help',
'Define an optional string that is used in the alternative description of the icon image.'
);
$help['criticality_id'] = dgettext(
'help',
'Service severity level. Can be used to sort alerts in the monitoring menus, including the Resources Status page.'
);
$help['geo_coords'] = dgettext(
'help',
'Geographic coordinates to allow Centreon MAP to plot the resource on a geographic view.'
. " Format: Latitude,Longitude. For example, Paris' coordinates are 48.51,2.20"
);
// Macros
$help['macro'] = dgettext(
'help',
'Macros are used as object-specific variables/properties, which can be referenced in commands and '
. 'extended infos. A Macro named TECHCONTACT can be referenced as $_SERVICETECHCONTACT$.'
);
// unsupported in centreon
$help['display_name'] = dgettext(
'help',
'This directive is used to define an alternate name that should be displayed in the web interface '
. 'for this service. If not specified, this defaults to the value you specify as service description.'
);
$help['flap_detection_options'] = dgettext(
'help',
'This directive is used to determine what service states the flap detection logic will use for this service.'
);
$help['initial_state'] = dgettext(
'help',
'By default monitoring engine will assume that all services are in OK states when it starts.'
. 'You can override the initial state for a service by using this directive.'
);
$help['service_activate'] = dgettext(
'help',
'This setting determines whether the service must be monitored or not.'
);
| 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/service/formService.php | centreon/www/include/configuration/configObject/service/formService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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();
}
global $form_service_type;
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
$serviceObj = new CentreonService($pearDB);
$serviceHgParsFieldIsAdded = false;
$serviceHParsFieldIsAdded = false;
const BASE_ROUTE = './include/common/webServices/rest/internal.php';
$datasetRoutes = [
'timeperiods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=list',
'contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=list',
'default_contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=defaultValues&target=service&field=service_cs&id=' . $service_id,
'contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=list',
'default_contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=defaultValues&target=service&field=service_cgs&id=' . $service_id,
'hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=list',
'default_hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=service&field=service_hPars&id=' . $service_id,
'host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=list',
'service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=list',
'service_groups' => BASE_ROUTE . '?object=centreon_configuration_servicegroup&action=list',
'service_categories' => BASE_ROUTE . '?object=centreon_configuration_servicecategory&action=list&t=c',
'traps' => BASE_ROUTE . '?object=centreon_configuration_trap&action=list',
'check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=list&t=2',
'event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=list',
'default_check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=service&field=command_command_id&id=' . $service_id,
'graph_templates' => BASE_ROUTE . '?object=centreon_configuration_graphtemplate&action=list',
'default_service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=defaultValues&target=service&field=service_template_model_stm_id&id=' . $service_id,
'default_event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=service&field=command_command_id2&id=' . $service_id,
'default_check_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=service&field=timeperiod_tp_id&id=' . $service_id,
'default_notification_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=service&field=timeperiod_tp_id2&id=' . $service_id,
'default_host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=defaultValues&target=service&field=service_hgPars&id=' . $service_id,
'default_service_groups' => BASE_ROUTE . '?object=centreon_configuration_servicegroup&action=defaultValues&target=service&field=service_sgs&id=' . $service_id,
'default_traps' => BASE_ROUTE . '?object=centreon_configuration_trap&action=defaultValues&target=service&field=service_traps&id=' . $service_id,
'default_graph_templates' => BASE_ROUTE . '?object=centreon_configuration_graphtemplate&action=defaultValues&target=service&field=graph_id&id=' . $service_id,
'default_service_categories' => BASE_ROUTE . '?object=centreon_configuration_servicecategory&action=defaultValues&target=service&field=service_categories&id=' . $service_id,
];
$attributes = [
'timeperiods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'contacts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contacts'],
'defaultDatasetRoute' => $datasetRoutes['default_contacts'],
'multiple' => true,
'linkedObject' => 'centreonContact',
],
'contact_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contact_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_contact_groups'],
'multiple' => true,
'linkedObject' => 'centreonContactgroup',
],
'check_commands' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_check_commands'],
'availableDatasetRoute' => $datasetRoutes['check_commands'],
],
'hosts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_hosts'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'hosts_cloud_specific' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_hosts'],
'multiple' => false,
'linkedObject' => 'centreonHost',
],
'host_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_host_groups'],
'multiple' => true,
'linkedObject' => 'centreonHostgroups',
],
'templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_service_templates'],
'multiple' => false,
'linkedObject' => 'centreonServicetemplates',
],
'service_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_service_groups'],
'multiple' => true,
'linkedObject' => 'centreonServicegroups',
],
'service_categories' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_categories'],
'defaultDatasetRoute' => $datasetRoutes['default_service_categories'],
'multiple' => true,
'linkedObject' => 'centreonServicecategories',
],
'traps' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['traps'],
'defaultDatasetRoute' => $datasetRoutes['default_traps'],
'multiple' => true,
'linkedObject' => 'centreonTraps',
],
'graph_templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['graph_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_graph_templates'],
'multiple' => false,
'linkedObject' => 'centreonGraphTemplate',
],
'event_handlers' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_event_handlers'],
'availableDatasetRoute' => $datasetRoutes['event_handlers'],
],
'check_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_check_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'notification_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_notification_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
];
const PASSWORD_REPLACEMENT_VALUE = '**********';
/**
* Database retrieve information for Service.
*
* @param ?string $arg
*/
function myDecodeService($arg)
{
$arg = str_replace('#BR#', '\\n', $arg ?? '');
$arg = str_replace('#T#', '\\t', $arg);
$arg = str_replace('#R#', '\\r', $arg);
$arg = str_replace('#S#', '/', $arg);
$arg = str_replace('#BS#', '\\', $arg);
return html_entity_decode($arg, ENT_QUOTES, 'UTF-8');
}
if (
! $centreon->user->admin
&& is_numeric($service_id)
) {
$checkres = $pearDB->query(
"SELECT service_id
FROM `{$aclDbName}`.centreon_acl
WHERE service_id = " . $pearDB->escape($service_id) . '
AND group_id IN (' . $acl->getAccessGroupsString() . ')'
);
if (! $checkres->rowCount()) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this service'));
return;
}
}
$cmdId = 0;
$service = [];
$serviceTplId = null;
$initialValues = [];
// Used to store all macro passwords
$macroPasswords = [];
if (($o === SERVICE_MODIFY || $o === SERVICE_WATCH) && $service_id) {
$statement = $pearDB->prepare(
'SELECT *
FROM service
LEFT JOIN extended_service_information esi
ON esi.service_service_id = service_id
WHERE service_id = :service_id LIMIT 1'
);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
// Set base value
$service = array_map('myDecodeService', $statement->fetch());
$serviceTplId = $service['service_template_model_stm_id'];
$cmdId = $service['command_command_id'];
// Set Service Notification Options
$tmp = explode(',', $service['service_notification_options']);
foreach ($tmp as $key => $value) {
$service['service_notifOpts'][trim($value)] = 1;
}
// Set Stalking Options
$tmp = explode(',', $service['service_stalking_options']);
foreach ($tmp as $key => $value) {
$service['service_stalOpts'][trim($value)] = 1;
}
// Set criticality
$statement = $pearDB->prepare(
'SELECT sc.sc_id
FROM service_categories sc
INNER JOIN service_categories_relation scr
ON scr.sc_id = sc.sc_id
WHERE scr.service_service_id = :service_id AND sc.level IS NOT NULL
ORDER BY sc.level ASC LIMIT 1'
);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$cr = $statement->fetch();
$service['criticality_id'] = $cr['sc_id'];
}
}
/**
* define variable to avoid null count.
*/
$aMacros = [];
if (($o === SERVICE_MODIFY || $o === SERVICE_WATCH) && $service_id) {
$aListTemplate = getListTemplates($pearDB, $service_id);
if (! isset($cmdId)) {
$cmdId = '';
}
if (isset($_REQUEST['macroInput'])) {
/**
* We don't taking into account the POST data sent from the interface in order the retrieve the original value
* of all passwords.
*/
$aMacros = $serviceObj->getMacros($service_id, $aListTemplate, $cmdId);
/**
* If a password has been modified from the interface, we retrieve the old password existing in the repository
* (giving by the $aMacros variable) to inject it before saving.
* Passwords will be saved using the $_REQUEST variable.
*/
foreach ($_REQUEST['macroInput'] as $index => $macroName) {
if (
! isset($_REQUEST['macroFrom'][$index])
|| ! isset($_REQUEST['macroPassword'][$index])
|| $_REQUEST['macroPassword'][$index] !== '1' // Not a password
|| $_REQUEST['macroValue'][$index] !== PASSWORD_REPLACEMENT_VALUE // The password has not changed
) {
continue;
}
foreach ($aMacros as $macroAlreadyExist) {
if (
$macroAlreadyExist['macroInput_#index#'] === $macroName
&& $_REQUEST['macroFrom'][$index] === $macroAlreadyExist['source']
) {
/**
* if the password has not been changed, we replace the password coming from the interface with
* the original value (from the repository) before saving.
*/
$_REQUEST['macroValue'][$index] = $macroAlreadyExist['macroValue_#index#'];
}
}
}
}
// We taking into account the POST data sent from the interface
$aMacros = $serviceObj->getMacros($service_id, $aListTemplate, $cmdId, $_POST);
// We hide all passwords in the jsData property to prevent them from appearing in the HTML code.
foreach ($aMacros as $index => $macroValues) {
if ($macroValues['macroPassword_#index#'] === 1) {
$macroPasswords[$index]['password'] = $aMacros[$index]['macroValue_#index#'];
// It's a password macro
$aMacros[$index]['macroOldValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
$aMacros[$index]['macroValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
// Keep the original name of the input field in case its name changes.
$aMacros[$index]['macroOriginalName_#index#'] = $aMacros[$index]['macroInput_#index#'];
}
}
}
$cdata = CentreonData::getInstance();
$cdata->addJsData('clone-values-macro', htmlspecialchars(
json_encode($aMacros),
ENT_QUOTES
));
$cdata->addJsData('clone-count-macro', count($aMacros));
// IMG comes from DB -> Store in $extImg Array
$extImg = [];
$extImg = return_image_list(1);
//
// End of "database-retrieved" information
// #########################################################
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '6'];
$attrsTextURL = ['size' => '50'];
$attrsAdvSelect_small = ['style' => 'width: 270px; height: 70px;'];
$attrsAdvSelect = ['style' => 'width: 270px; height: 100px;'];
$attrsAdvSelect_big = ['style' => 'width: 270px; height: 200px;'];
$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>';
// For a shitty reason, Quickform set checkbox with stal[o] name
unset($_POST['o']);
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === SERVICE_ADD) {
$form->addElement('header', 'title', _('Add a Service'));
} elseif ($o === SERVICE_MODIFY) {
$form->addElement('header', 'title', _('Modify a Service'));
} elseif ($o === SERVICE_WATCH) {
$form->addElement('header', 'title', _('View a Service'));
} elseif ($o === SERVICE_MASSIVE_CHANGE) {
$form->addElement('header', 'title', _('Mass Change'));
}
//
// # Service basic information
//
/*
* - No possibility to change name and alias, because there's no interest
* - May be ? #409
*/
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->addElement('text', 'service_description', _('Name'), $attrsText);
}
$form->addElement('text', 'service_alias', _('Alias'), $attrsText);
$serviceTplSelect = $form->addElement(
'select2',
'service_template_model_stm_id',
_('Template'),
[],
$attributes['templates']
);
$serviceTplSelect->addJsCallback('change', 'changeServiceTemplate(this.value)');
$form->addElement('static', 'tplText', _('Using a Template exempts you to fill required fields'));
//
// # Check information
//
$form->addElement('header', 'check', _('Service State'));
$checkCommandSelect = $form->addElement(
'select2',
'command_command_id',
_('Check Command'),
[],
$attributes['check_commands']
);
if ($o === SERVICE_MASSIVE_CHANGE) {
$checkCommandSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id","example1");'
);
} else {
$checkCommandSelect->addJsCallback('change', 'changeCommand(this.value);');
}
$form->addElement('text', 'command_command_id_arg', _('Args'), $attrsText);
$serviceEHE = [
$form->createElement('radio', 'service_event_handler_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_event_handler_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_event_handler_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceEHE, 'service_event_handler_enabled', _('Event Handler Enabled'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_event_handler_enabled' => '2']);
}
$eventHandlerSelect = $form->addElement(
'select2',
'command_command_id2',
_('Event Handler'),
[],
$attributes['event_handlers']
);
$eventHandlerSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id2","example2");'
);
if (! $isCloudPlatform) {
$serviceIV = [
$form->createElement('radio', 'service_is_volatile', null, _('Yes'), '1'),
$form->createElement('radio', 'service_is_volatile', null, _('No'), '0'),
$form->createElement('radio', 'service_is_volatile', null, _('Default'), '2'),
];
$form->addGroup($serviceIV, 'service_is_volatile', _('Is Volatile'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_is_volatile' => '2']);
}
$form->addElement('text', 'command_command_id_arg2', _('Args'), $attrsText);
$serviceACE = [
$form->createElement('radio', 'service_active_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_active_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_active_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceACE, 'service_active_checks_enabled', _('Active Checks Enabled'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_active_checks_enabled' => '2']);
}
$servicePCE = [
$form->createElement('radio', 'service_passive_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_passive_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_passive_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($servicePCE, 'service_passive_checks_enabled', _('Passive Checks Enabled'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_passive_checks_enabled' => '2']);
}
$form->addElement('header', 'information', _('Service Basic Information'));
// Notification information
$form->addElement('header', 'notification', _('Notification'));
$serviceNE = [
$form->createElement('radio', 'service_notifications_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_notifications_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_notifications_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceNE, 'service_notifications_enabled', _('Notification Enabled'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_notifications_enabled' => '2']);
}
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_cgs = [
$form->createElement('radio', 'mc_mod_cgs', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_cgs', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_cgs, 'mc_mod_cgs', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_cgs' => '0']);
}
// Use only contacts/contacts group of host and host template
$form->addElement('header', 'use_only_contacts_from_host', _('Inherit only contacts/contacts group from host'));
$serviceIOHC = [
$form->createElement('radio', 'service_use_only_contacts_from_host', null, _('Yes'), '1'),
$form->createElement('radio', 'service_use_only_contacts_from_host', null, _('No'), '0'),
];
$form->addGroup(
$serviceIOHC,
'service_use_only_contacts_from_host',
_('Inherit only contacts/contacts group from host'),
' '
);
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_use_only_contacts_from_host' => '0']);
}
// Additive
if ($o === SERVICE_MASSIVE_CHANGE) {
$contactAdditive = [
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_contact_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup($contactAdditive, 'mc_contact_additive_inheritance', _('Contact additive inheritance'), ' ');
$contactGroupAdditive = [
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_cg_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup(
$contactGroupAdditive,
'mc_cg_additive_inheritance',
_('Contact group additive inheritance'),
' '
);
} else {
$form->addElement('checkbox', 'contact_additive_inheritance', '', _('Contact additive inheritance'));
$form->addElement('checkbox', 'cg_additive_inheritance', '', _('Contact group additive inheritance'));
}
// Contacts
$form->addElement('select2', 'service_cs', _('Implied Contacts'), [], $attributes['contacts']);
// Contact groups
$form->addElement('select2', 'service_cgs', _('Implied Contact Groups'), [], $attributes['contact_groups']);
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_notifopt_first_notification_delay = [
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_first_notification_delay,
'mc_mod_notifopt_first_notification_delay',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_first_notification_delay' => '0']);
}
$form->addElement('text', 'service_first_notification_delay', _('First notification delay'), $attrsText2);
$form->addElement('text', 'service_recovery_notification_delay', _('Recovery notification delay'), $attrsText2);
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_notifopt_notification_interval = [
$form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Incremental'),
'0'
),
$mc_mod_notifopt_notification_interval[] = $form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_notification_interval,
'mc_mod_notifopt_notification_interval',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_notification_interval' => '0']);
}
$form->addElement('text', 'service_notification_interval', _('Notification Interval'), $attrsText2);
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_notifopt_timeperiod = [
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Replacement'),
'1'
),
];
$form->addGroup($mc_mod_notifopt_timeperiod, 'mc_mod_notifopt_timeperiod', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopt_timeperiod' => '0']);
}
$form->addElement('select2', 'timeperiod_tp_id2', _('Notification Period'), [], $attributes['notification_periods']);
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_notifopts = [
$form->createElement('radio', 'mc_mod_notifopts', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_notifopts', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_notifopts, 'mc_mod_notifopts', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopts' => '0']);
}
$serviceNotifOpt = [
$form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'notifW', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'notifU', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'notifC', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'notifR', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'notifF', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'notifDS', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'notifN', 'onClick' => 'uncheckNotifOption(this);']
),
];
$form->addGroup($serviceNotifOpt, 'service_notifOpts', _('Notification Type'), ' ');
$serviceStalOpt = [
$form->createElement('checkbox', 'o', ' ,', _('Ok')),
$form->createElement('checkbox', 'w', ' ,', _('Warning')),
$form->createElement('checkbox', 'u', ' ,', _('Unknown')),
$form->createElement('checkbox', 'c', ' ,', _('Critical')),
];
$form->addGroup($serviceStalOpt, 'service_stalOpts', _('Stalking Options'), ' ');
$form->addElement('textarea', 'service_comment', _('Comments'), $attrsTextarea);
}
$serviceActivation = [
$form->createElement('radio', 'service_activate', null, _('Enabled'), '1'),
$form->createElement('radio', 'service_activate', null, _('Disabled'), '0'),
];
$form->addGroup($serviceActivation, 'service_activate', _('Enable/disable resource'), ' ');
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->setDefaults(['service_activate' => '1']);
}
$form->addElement('text', 'service_max_check_attempts', _('Max Check Attempts'), $attrsText2);
$form->addElement('text', 'service_normal_check_interval', _('Normal Check Interval'), $attrsText2);
$form->addElement('text', 'service_retry_check_interval', _('Retry Check Interval'), $attrsText2);
$form->addElement('select2', 'timeperiod_tp_id', _('Check Period'), [], $attributes['check_periods']);
$cloneSetMacro = [
$form->addElement(
'text',
'macroInput[#index#]',
_('Name'),
[
'id' => 'macroInput_#index#',
'size' => 25,
]
),
$form->addElement(
'text',
'macroValue[#index#]',
_('Value'),
[
'id' => 'macroValue_#index#',
'size' => 25,
]
),
$form->addElement(
'checkbox',
'macroPassword[#index#]',
_('Password'),
null,
[
'id' => 'macroPassword_#index#',
'onClick' => 'javascript:change_macro_input_type(this, false)',
]
),
$form->addElement(
'hidden',
'macroFrom[#index#]',
'direct',
['id' => 'macroFrom_#index#']
),
];
if ($isCloudPlatform) {
$form->addElement('header', 'information', _('General information'));
}
// Acknowledgement timeout.
$form->addElement('text', 'service_acknowledgement_timeout', _('Acknowledgement timeout'), $attrsText2);
// Further information
$form->addElement('header', 'furtherInfos', _('Additional Information'));
//
// # Sort 2 - Service Relations
//
if ($o === SERVICE_ADD) {
$form->addElement('header', 'title2', _('Add relations'));
} elseif ($o === SERVICE_MODIFY) {
$form->addElement('header', 'title2', _('Modify relations'));
} elseif ($o === SERVICE_WATCH) {
$form->addElement('header', 'title2', _('View relations'));
} elseif ($o === SERVICE_MASSIVE_CHANGE) {
$form->addElement('header', 'title2', _('Mass Change'));
}
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_Pars = [];
$mc_mod_Pars[] = $form->createElement('radio', 'mc_mod_Pars', null, _('Incremental'), '0');
$mc_mod_Pars[] = $form->createElement('radio', 'mc_mod_Pars', null, _('Replacement'), '1');
$form->addGroup($mc_mod_Pars, 'mc_mod_Pars', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_Pars' => '0']);
}
$sgReadOnly = false;
if ($form_service_type === 'BYHOST') {
if ($isCloudPlatform) {
$defaultDataset = [];
if ($service_id !== false) {
$hostsBounded = findHostsOfService($service_id);
$defaultDataset = ($hostsBounded !== [])
? ['0' => $hostsBounded[0]]
: [];
}
$form->addElement(
'select2',
'service_hPars',
_('Host'),
[],
array_merge($attributes['hosts_cloud_specific'], ['defaultDataset' => $defaultDataset])
);
if ($o !== SERVICE_MASSIVE_CHANGE) {
$form->addRule('service_hPars', _('Host / Service Required'), 'required');
}
} else {
if (isset($service['service_hPars']) && count($service['service_hPars']) > 1) {
$sgReadOnly = true;
}
$form->addElement('select2', 'service_hPars', _('Hosts'), [], $attributes['hosts']);
$serviceHParsFieldIsAdded = true;
}
}
if ($form_service_type === 'BYHOSTGROUP') {
$form->addElement('select2', 'service_hgPars', _('Linked with Host Groups'), [], $attributes['host_groups']);
$serviceHgParsFieldIsAdded = true;
if (isset($service['service_hgPars']) && count($service['service_hgPars']) > 1) {
$sgReadOnly = true;
}
}
// Service relations
if ($isCloudPlatform) {
$form->addElement('header', 'classification', _('Classification'));
} else {
$form->addElement('header', 'links', _('Relations'));
}
if ($o === SERVICE_MASSIVE_CHANGE) {
$mc_mod_sgs = [];
$mc_mod_sgs[] = $form->createElement('radio', 'mc_mod_sgs', null, _('Incremental'), '0');
$mc_mod_sgs[] = $form->createElement('radio', 'mc_mod_sgs', null, _('Replacement'), '1');
$form->addGroup($mc_mod_sgs, 'mc_mod_sgs', _('Update mode'), ' ');
| 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/configObject/service/listServiceByHost.php | centreon/www/include/configuration/configObject/service/listServiceByHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './class/centreonUtils.class.php';
$hostgroupsFilter ??= null;
$statusHostFilter ??= null;
// Object init
$mediaObj = new CentreonMedia($pearDB);
// Get Extended informations
$ehiCache = [];
$dbResult = $pearDB->query('SELECT ehi_icon_image, host_host_id FROM extended_host_information');
while ($ehi = $dbResult->fetch()) {
$ehiCache[$ehi['host_host_id']] = $ehi['ehi_icon_image'];
}
$dbResult->closeCursor();
$hostgroups = null;
$template = filter_var(
$_POST['template'] ?? $_GET['template'] ?? 0,
FILTER_VALIDATE_INT
);
$searchH = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchH'] ?? $_GET['search'] ?? null
);
$searchS = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchS'] ?? $_GET['searchS'] ?? null
);
$status = filter_var(
$_POST['status'] ?? $_GET['status'] ?? 0,
FILTER_VALIDATE_INT
);
if (isset($_POST['search']) || isset($_GET['search'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['template'] = $template;
$centreon->historySearch[$url]['searchH'] = $searchH;
$centreon->historySearch[$url]['searchS'] = $searchS;
$hostStatus = isset($_POST['statusHostFilter']) ? 1 : 0;
$centreon->historySearch[$url]['hostStatus'] = $hostStatus;
$centreon->historySearch[$url]['status'] = $status;
} else {
// restoring saved values
$template = $centreon->historySearch[$url]['template'] ?? 0;
$searchH = $centreon->historySearch[$url]['searchH'] ?? null;
$searchS = $centreon->historySearch[$url]['searchS'] ?? null;
$hostStatus = $centreon->historySearch[$url]['hostStatus'] ?? 0;
$status = $centreon->historySearch[$url]['status'] ?? 0;
}
$searchH_SQL = '';
if ($searchH) {
$searchH_SQL .= "AND (host.host_name LIKE '%" . $pearDB->escape($searchH)
. "%' OR host_alias LIKE '%" . $pearDB->escape($searchH) . "%' OR host_address LIKE '%"
. $pearDB->escape($searchH) . "%')";
}
$searchS_SQL = '';
if ($searchS) {
$searchS_SQL .= "AND (sv.service_alias LIKE '%" . $pearDB->escape($searchS)
. "%' OR sv.service_description LIKE '%" . $pearDB->escape($searchS) . "%')";
}
// Host Status Filter
$hostStatusChecked = '';
$sqlFilterCase2 = "AND host.host_activate = '1'";
if ($hostStatus == 1) {
$hostStatusChecked = 'checked';
$sqlFilterCase2 = '';
}
// Status Filter
$statusFilter = [1 => _('Disabled'), 2 => _('Enabled')];
$sqlFilterCase = '';
if ($status == 2) {
$sqlFilterCase = " AND sv.service_activate = '1' ";
} elseif ($status == 1) {
$sqlFilterCase = " AND sv.service_activate = '0' ";
}
require_once './class/centreonHost.class.php';
// Init Objects
$host_method = new CentreonHost($pearDB);
$service_method = new CentreonService($pearDB);
include './include/common/autoNumLimit.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', _('Host'));
$tpl->assign('headerMenu_desc', _('Service'));
$tpl->assign('headerMenu_retry', _('Scheduling'));
$tpl->assign('headerMenu_parent', _('Template'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
$aclFilter = '';
$distinct = '';
if (! $centreon->user->admin) {
$aclFilter = ' AND host.host_id = acl.host_id '
. 'AND acl.service_id = sv.service_id '
. 'AND acl.group_id IN (' . $acl->getAccessGroupsString() . ') ';
$distinct = ' DISTINCT ';
}
// Host/service list
$queryFieldsToSelect = 'esi.esi_icon_image, sv.service_id, sv.service_description, sv.service_activate, '
. 'sv.service_template_model_stm_id, '
. 'host.host_id, host.host_name, host.host_template_model_htm_id, sv.service_normal_check_interval, '
. 'sv.service_retry_check_interval, sv.service_max_check_attempts ';
$queryTablesToFetch = 'FROM service sv, host'
. ((isset($hostgroups) && $hostgroups) ? ', hostgroup_relation hogr, ' : ', ')
. ($centreon->user->admin ? '' : '`' . $aclDbName . '`' . '.centreon_acl acl, ')
. 'host_service_relation hsr '
. 'LEFT JOIN extended_service_information esi ON esi.service_service_id = hsr.service_service_id ';
$queryWhereClause = "WHERE host.host_register = '1' " . $searchH_SQL . ' ' . $sqlFilterCase2
. ' AND host.host_id = hsr.host_host_id AND hsr.service_service_id = sv.service_id'
. " AND sv.service_register = '1' " . $searchS_SQL . ' ' . $sqlFilterCase
. ((isset($template) && $template) ? " AND service_template_model_stm_id = '{$template}' " : '')
. ((isset($hostgroups) && $hostgroups)
? " AND hogr.hostgroup_hg_id = '{$hostgroups}' AND hogr.host_host_id = host.host_id "
: '')
. $aclFilter;
$rq_body = $queryFieldsToSelect
. $queryTablesToFetch
. $queryWhereClause
. ' ORDER BY host.host_name, service_description';
$dbResult = $pearDB->query(
'SELECT SQL_CALC_FOUND_ROWS ' . $distinct . $rq_body
. ' LIMIT ' . $num * $limit . ', ' . $limit
);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
if (! ($dbResult->rowCount())) {
$dbResult = $pearDB->query(
'SELECT ' . $distinct . $rq_body . ' LIMIT ' . (floor($rows / $limit) * $limit) . ', ' . $limit
);
}
include './include/common/checkPagination.php';
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
// select2 Service template
$route = './api/internal.php?object=centreon_configuration_servicetemplate&action=list';
$attrServicetemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => false, 'defaultDataset' => $template, 'linkedObject' => 'centreonServicetemplates'];
$form->addElement('select2', 'template', '', [], $attrServicetemplates);
// select2 Service Status
$attrServiceStatus = null;
if ($status) {
$statusDefault = [$statusFilter[$status] => $status];
$attrServiceStatus = ['defaultDataset' => $statusDefault];
}
$form->addElement('select2', 'status', '', $statusFilter, $attrServiceStatus);
$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 = [];
$fgHost = ['value' => null, 'print' => null];
$interval_length = $centreon->optGen['interval_length'];
$centreonToken = createCSRFToken();
$statement = $pearDB->prepare(
'SELECT COUNT(*) FROM host_service_relation WHERE service_service_id = :service_id'
);
for ($i = 0; $service = $dbResult->fetch(); $i++) {
// Get Number of Hosts linked to this one.
$statement->bindValue(':service_id', $service['service_id'], PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetch(PDO::FETCH_ASSOC);
$service['nbr'] = $data['COUNT(*)'];
$statement->closeCursor();
unset($data);
/**
* If the name of our Host is in the Template definition, we have to catch it, whatever the level of it :-)
*/
$fgHost['value'] != $service['host_name']
? ($fgHost['print'] = true && $fgHost['value'] = $service['host_name'])
: $fgHost['print'] = false;
$selectedElements = $form->addElement('checkbox', 'select[' . $service['service_id'] . ']');
$moptions = '';
if ($service['service_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&service_id=' . $service['service_id'] . '&o=u&limit='
. $limit . '&num=' . $num . '&hostgroups=' . $hostgroups . "&template={$template}&status=" . $status
. '¢reon_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 . '&service_id=' . $service['service_id'] . '&o=s&limit='
. $limit . '&num=' . $num . '&hostgroups=' . $hostgroups . "&template={$template}&status=" . $status
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='" . _('Enabled') . "'></a>";
}
$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;" onKeyUp="syncInputField(this.name, this.value);" maxlength="3" size="3" '
. "value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $service['service_id'] . "]' />";
/*If the description of our Service is in the Template definition,
we have to catch it, whatever the level of it :-) */
if (! $service['service_description']) {
$service['service_description'] = getMyServiceAlias($service['service_template_model_stm_id']);
} else {
$service['service_description'] = str_replace('#S#', '/', $service['service_description']);
$service['service_description'] = str_replace('#BS#', '\\', $service['service_description']);
}
// TPL List
$tplArr = [];
$tplStr = null;
$tplArr = getMyServiceTemplateModels($service['service_template_model_stm_id']);
if ($tplArr && count($tplArr)) {
foreach ($tplArr as $key => $value) {
$tplStr .= " -> <a href='main.php?p=60206&o=c&service_id=" . $key . "'>" . $value . '</a>';
}
}
// Get service intervals in seconds
$normal_check_interval
= getMyServiceField($service['service_id'], 'service_normal_check_interval') * $interval_length;
$retry_check_interval
= getMyServiceField($service['service_id'], 'service_retry_check_interval') * $interval_length;
if ($normal_check_interval % 60 == 0) {
$normal_units = 'min';
$normal_check_interval = $normal_check_interval / 60;
} else {
$normal_units = 'sec';
}
if ($retry_check_interval % 60 == 0) {
$retry_units = 'min';
$retry_check_interval = $retry_check_interval / 60;
} else {
$retry_units = 'sec';
}
$isHostSvgFile = true;
if ((isset($ehiCache[$service['host_id']]) && $ehiCache[$service['host_id']])) {
$isHostSvgFile = false;
$host_icone = './img/media/' . $mediaObj->getFilename($ehiCache[$service['host_id']]);
} elseif (
$icone = $host_method->replaceMacroInString(
$service['host_id'],
getMyHostExtendedInfoImage($service['host_id'], 'ehi_icon_image', 1)
)
) {
$isHostSvgFile = false;
$host_icone = './img/media/' . $icone;
} else {
$isHostSvgFile = true;
$host_icone = returnSvg('www/img/icons/host.svg', 'var(--icons-fill-color)', 21, 21);
}
$isServiceSvgFile = true;
if (isset($service['esi_icon_image']) && $service['esi_icon_image']) {
$isServiceSvgFile = false;
$svc_icon = './img/media/' . $mediaObj->getFilename($service['esi_icon_image']);
} elseif (
$icone = $mediaObj->getFilename(
getMyServiceExtendedInfoField(
$service['service_id'],
'esi_icon_image'
)
)
) {
$isServiceSvgFile = false;
$svc_icon = './img/media/' . $icone;
} else {
$isServiceSvgFile = true;
$svc_icon = returnSvg('www/img/icons/service.svg', 'var(--icons-fill-color)', 18, 18);
}
$elemArr[$i] = ['MenuClass' => 'list_' . ($service['nbr'] > 1 ? 'three' : $style), 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($service['host_name']), 'RowMenu_icone' => $host_icone, 'RowMenu_sicon' => $svc_icon, 'RowMenu_link' => 'main.php?p=60101&o=c&host_id=' . $service['host_id'], 'RowMenu_link2' => 'main.php?p=' . $p . '&o=c&service_id=' . $service['service_id'], 'RowMenu_parent' => CentreonUtils::escapeSecure($tplStr), 'RowMenu_retry' => CentreonUtils::escapeSecure(
"{$normal_check_interval} {$normal_units} / {$retry_check_interval} {$retry_units}"
), 'RowMenu_desc' => CentreonUtils::escapeSecure($service['service_description']), 'RowMenu_status' => $service['service_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $service['service_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions, 'isHostSvgFile' => $isHostSvgFile, 'isServiceSvgFile' => $isServiceSvgFile];
$fgHost['print'] ? null : $elemArr[$i]['RowMenu_name'] = null;
$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
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "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 == 6 && confirm('"
. _('Are you sure you want to detach the service ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 3 || this.form.elements['"
. $option . "'].selectedIndex == 4 ||this.form.elements['" . $option . "'].selectedIndex == 5){"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "this.form.elements['" . $option . "'].selectedIndex = 0"];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable'), 'dv' => _('Detach')],
$attrs1
);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
// Apply a template definition
if (isset($searchH) && $searchH) {
$searchH = html_entity_decode($searchH);
$searchH = stripslashes(str_replace('"', '"', $searchH));
}
if (isset($searchS) && $searchS) {
$searchS = html_entity_decode($searchS);
$searchS = stripslashes(str_replace('"', '"', $searchS));
}
$tpl->assign('searchH', $searchH);
$tpl->assign('searchS', $searchS);
$tpl->assign('hostgroupsFilter', $hostgroupsFilter);
$tpl->assign('statusHostFilter', $statusHostFilter);
$tpl->assign('hostStatusChecked', $hostStatusChecked);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('Hosts', _('Hosts'));
$tpl->assign('ServiceTemplates', _('Templates'));
$tpl->assign('ServiceStatus', _('Status'));
$tpl->assign('HostStatus', _('Disabled hosts'));
$tpl->assign('Services', _('Services'));
$tpl->display('listService.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/configObject/service/refreshMacroAjax.php | centreon/www/include/configuration/configObject/service/refreshMacroAjax.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . '/www/include/common/common-Func.php';
require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonCommand.class.php';
// Validate the session
session_start();
session_write_close();
$db = new CentreonDB();
try {
if (! CentreonSession::checkSession(session_id(), $db)) {
sendError('bad session id', 401);
}
} catch (Exception $ex) {
sendError('Internal error', 500);
}
$macros = (new CentreonService($db))->ajaxMacroControl($_POST);
header('Content-Type: application/json');
echo json_encode(['macros' => $macros, 'count' => count($macros)]);
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/configObject/service/DB-Func.php | centreon/www/include/configuration/configObject/service/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();
}
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use App\Kernel;
use Centreon\Domain\Log\Logger;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Infrastructure\Common\Api\Router;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Utility\Interfaces\UUIDGeneratorInterface;
require_once _CENTREON_PATH_ . 'www/include/common/vault-functions.php';
/**
* For ACL
*
* @param CentreonDB $db
* @param int $hostId
* @param null|mixed $hostgroupId
* @return null
*/
function setHostChangeFlag($db, $hostId = null, $hostgroupId = null)
{
if (isset($hostId)) {
$table = 'acl_resources_host_relations';
$field = 'host_host_id';
$val = $hostId;
} elseif (isset($hostgroupId)) {
$table = 'acl_resources_hg_relations';
$field = 'hg_hg_id';
$val = $hostgroupId;
} else {
return null;
}
$query = 'UPDATE acl_resources SET changed = 1 '
. 'WHERE acl_res_id IN ('
. "SELECT acl_res_id FROM {$table} WHERE {$field} = :fieldValue)";
$statement = $db->prepare($query);
$statement->bindValue(':fieldValue', (int) $val, PDO::PARAM_INT);
$statement->execute();
return null;
}
/**
* This is a quickform rule for checking if circular inheritance is used
*
* @return bool
*/
function checkCircularInheritance(int $templateId)
{
global $form;
$data = $form->getSubmitValues();
if ((int) $data['service_id'] === $templateId) {
return false;
}
$kernel = Kernel::createForWeb();
$repository = $kernel->getContainer()->get(ReadServiceTemplateRepositoryInterface::class);
$inheritanceArray = $repository->findParents($templateId);
$parentsIds = array_map(
static fn (ServiceTemplateInheritance $inheritancePair): int => $inheritancePair->getParentId(),
$inheritanceArray
);
return ! (in_array((int) $data['service_id'], $parentsIds, true));
}
/**
* Quickform rule that checks whether or not reserved macro are used
*
* @return bool
*/
function serviceMacHandler()
{
global $pearDB;
$macArray = $_POST;
$macTab = [];
foreach ($macArray as $key => $value) {
if (isset($value) && is_string($value) && preg_match('/^macroInput/', $key, $matches)) {
$macTab[] = "'\$_SERVICE" . strtoupper($value) . "\$'";
}
}
if ($macTab !== []) {
$sql = 'SELECT count(*) as nb FROM nagios_macro WHERE macro_name IN (' . implode(',', $macTab) . ')';
$res = $pearDB->query($sql);
$row = $res->fetch();
if (isset($row['nb']) && $row['nb']) {
return false;
}
}
return true;
}
/**
* This is a quickform rule for checking if all the argument fields are filled
*
* @return bool
*/
function argHandler()
{
$argArray = $_POST;
$argTab = [];
foreach ($argArray as $key => $value) {
if (preg_match('/^ARG(\d+)/', $key, $matches)) {
$argTab[$matches[1]] = $value;
}
}
$fill = false;
$nofill = false;
foreach ($argTab as $val) {
if ($val != '') {
$fill = true;
} else {
$nofill = true;
}
}
return ! ($fill === true && $nofill === true);
}
/**
* Returns the formatted string for command arguments
*
* @param $argArray
* @param mixed $conf
* @return string
*/
function getCommandArgs($argArray = [], $conf = [])
{
if (isset($conf['command_command_id_arg'])) {
return $conf['command_command_id_arg'];
}
$argTab = [];
foreach ($argArray as $key => $value) {
if (preg_match('/^ARG(\d+)/', $key, $matches)) {
$argTab[$matches[1]] = $value;
$argTab[$matches[1]] = str_replace("\n", '#BR#', $argTab[$matches[1]]);
$argTab[$matches[1]] = str_replace("\t", '#T#', $argTab[$matches[1]]);
$argTab[$matches[1]] = str_replace("\r", '#R#', $argTab[$matches[1]]);
}
}
ksort($argTab);
$str = '';
foreach ($argTab as $val) {
if ($val != '') {
$str .= '!' . $val;
}
}
if (! strlen($str)) {
return null;
}
return $str;
}
function getHostServiceCombo($service_id = null, $service_description = null)
{
global $pearDB;
if ($service_id == null || $service_description == null) {
return;
}
$query = 'SELECT h.host_name '
. 'FROM host h, host_service_relation hsr '
. 'WHERE h.host_id = hsr.host_host_id '
. "AND hsr.service_service_id = '" . $service_id . "' LIMIT 1";
$DBRES = $pearDB->query($query);
if (! $DBRES->rowCount()) {
$combo = '- / ' . $service_description;
} else {
$row = $DBRES->fetch();
$combo = $row['host_name'] . ' / ' . $service_description;
}
return $combo;
}
function serviceExists($name = null)
{
global $pearDB, $centreon;
$query = 'SELECT service_description FROM service '
. "WHERE service_description = '" . CentreonDB::escape($centreon->checkIllegalChar($name)) . "'";
$dbResult = $pearDB->query($query);
return (bool) ($dbResult->rowCount() >= 1);
}
/**
* Test service template existence
*
* @param string $name
* @param bool $returnId | whether function will return an id instead of boolean
* @return mixed
*/
function testServiceTemplateExistence($name = null, $returnId = false)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('service_id');
}
$query = 'SELECT service_description, service_id FROM service '
. "WHERE service_register = '0' "
. "AND service_description = '" . CentreonDB::escape($centreon->checkIllegalChar($name)) . "'";
$dbResult = $pearDB->query($query);
$service = $dbResult->fetch();
$nbRows = $dbResult->rowCount();
// Modif case
if (isset($id)) {
if ($nbRows >= 1 && $service['service_id'] == $id) {
return true;
}
return ! ($nbRows >= 1 && $service['service_id'] != $id); // Duplicate entry
}
return ! ($nbRows >= 1);
}
/**
* Test service existence
*
* @param string $name
* @param array $hPars
* @param array $hgPars
* @param bool $returnId | whether function will return an id instead of boolean
* @param array $params
* @return mixed
*/
function testServiceExistence($name = null, $hPars = [], $hgPars = [], $returnId = false, $params = [])
{
global $pearDB, $centreon;
global $form;
$id = null;
$hPars = (is_countable($hPars)) ? $hPars : [];
$hgPars = (is_countable($hgPars)) ? $hgPars : [];
if (isset($form) && ! count($hPars) && ! count($hgPars)) {
$arr = count($params) ? $params : $form->getSubmitValues();
if (isset($arr['service_id'])) {
$id = $arr['service_id'];
}
$hPars = $arr['service_hPars'] ?? [];
$hPars = is_array($hPars) ? $hPars : [$hPars];
$hgPars = $arr['service_hgPars'] ?? [];
}
$escapeName = CentreonDB::escape($centreon->checkIllegalChar($name));
$statement = $pearDB->prepare(
<<<'SQL'
SELECT service.service_id
FROM service
INNER JOIN host_service_relation hsr
ON hsr.service_service_id = service.service_id
WHERE hsr.host_host_id = :host_id
AND service.service_description = :service_description
SQL
);
foreach ($hPars as $hostId) {
$statement->bindValue(':host_id', (int) $hostId, PDO::PARAM_INT);
$statement->bindValue(':service_description', $escapeName);
$statement->execute();
$service = $statement->fetch(PDO::FETCH_ASSOC);
// Duplicate entry
if ($statement->rowCount() >= 1 && $service['service_id'] != $id) {
return ($returnId == false) ? false : $service['service_id'];
}
}
$statement = $pearDB->prepare(
<<<'SQL'
SELECT service_id
FROM service
INNER JOIN host_service_relation hsr
ON hsr.service_service_id = service_id
WHERE hsr.hostgroup_hg_id = :hostgroup_hg_id
AND service.service_description = :service_description
SQL
);
foreach ($hgPars as $hostGroupId) {
$statement->bindValue(':hostgroup_hg_id', (int) $hostGroupId, PDO::PARAM_INT);
$statement->bindValue(':service_description', $escapeName);
$statement->execute();
$service = $statement->fetch(PDO::FETCH_ASSOC);
// Duplicate entry
if ($statement->rowCount() >= 1 && $service['service_id'] != $id) {
return ($returnId == false) ? false : $service['service_id'];
}
}
return ($returnId == false) ? true : 0;
}
/**
* Get service id by combination of host or hostgroup relations
*
* @param string $serviceDescription
* @param array $hPars
* @param array $hgPars
* @param mixed $params
* @return int
*/
function getServiceIdByCombination($serviceDescription, $hPars = [], $hgPars = [], $params = [])
{
if (! count($hPars) && ! count($hgPars)) {
return testServiceTemplateExistence($serviceDescription, true);
}
return testServiceExistence($serviceDescription, $hPars, $hgPars, true, $params);
}
function enableServiceInDB($service_id = null, $service_arr = [])
{
if (! $service_id && ! count($service_arr)) {
return;
}
global $pearDB, $centreon;
if ($service_id) {
$service_arr = [$service_id => '1'];
}
$updateStatement = $pearDB->prepare("UPDATE service SET service_activate = '1' WHERE service_id = :serviceId");
$selectStatement = $pearDB->prepare(
'SELECT service_description FROM `service` WHERE service_id = :serviceId LIMIT 1'
);
foreach (array_keys($service_arr) as $serviceId) {
$updateStatement->bindValue(':serviceId', $serviceId, PDO::PARAM_INT);
$updateStatement->execute();
$selectStatement->bindValue(':serviceId', $serviceId, PDO::PARAM_INT);
$selectStatement->execute();
$serviceDescription = $selectStatement->fetchColumn();
signalConfigurationChange('service', (int) $serviceId);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICE,
object_id: $serviceId,
object_name: $serviceDescription,
action_type: ActionLog::ACTION_TYPE_ENABLE
);
}
}
function disableServiceInDB($service_id = null, $service_arr = [])
{
if (! $service_id && ! count($service_arr)) {
return;
}
global $pearDB, $centreon;
if ($service_id) {
$service_arr = [$service_id => '1'];
}
foreach (array_keys($service_arr) as $serviceId) {
$pearDB->query("UPDATE service SET service_activate = '0' WHERE service_id = '" . $serviceId . "'");
$query = "SELECT service_description FROM `service` WHERE service_id = '" . $serviceId . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
signalConfigurationChange('service', (int) $serviceId, [], false);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICE,
object_id: $serviceId,
object_name: $row['service_description'],
action_type: ActionLog::ACTION_TYPE_DISABLE
);
}
}
/**
* @param int $serviceId
*/
function removeRelationLastServiceDependency(int $serviceId): void
{
global $pearDB;
$request = <<<SQL
SELECT
COUNT(dependency_dep_id) AS nb_dependency,
dependency_dep_id AS id
FROM dependency_serviceParent_relation
WHERE dependency_dep_id = (
SELECT dependency_dep_id
FROM dependency_serviceParent_relation
WHERE service_service_id = {$serviceId}
)
GROUP BY dependency_dep_id
SQL;
$statement = $pearDB->query($request);
if (false !== ($result = $statement->fetch())) {
// is last parent
if ($result['nb_dependency'] == 1) {
$pearDB->query('DELETE FROM dependency WHERE dep_id = ' . $result['id']);
}
}
}
/**
* Delete service in DB
*
* Keep this method as service deletion by hostgroup is not supported in APIv2 for the moment.
*
* @param array<int, int> $services The list of service IDs to delete (Ids are the keys)
*/
function deleteServiceInDB(array $services = []): void
{
global $pearDB, $centreon;
$serviceIds = array_keys($services);
$kernel = Kernel::createForWeb();
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
/** @var WriteVaultRepositoryInterface $writeVaultRepository */
$writeVaultRepository = $kernel->getContainer()->get(WriteVaultRepositoryInterface::class);
if ($vaultConfiguration !== null) {
deleteResourceSecretsInVault($writeVaultRepository, [], $serviceIds);
}
$query = 'UPDATE service SET service_template_model_stm_id = NULL WHERE service_id = :service_id';
$statement = $pearDB->prepare($query);
foreach ($serviceIds as $serviceId) {
$previousPollerIds = getPollersForConfigChangeFlagFromServiceId($serviceId);
removeRelationLastServiceDependency((int) $serviceId);
$query = "SELECT service_id FROM service WHERE service_template_model_stm_id = '" . $serviceId . "'";
$dbResult = $pearDB->query($query);
while ($row = $dbResult->fetch()) {
$statement->bindValue(':service_id', (int) $row['service_id'], PDO::PARAM_INT);
$statement->execute();
}
$query = "SELECT service_description FROM `service` WHERE `service_id` = '" . $serviceId . "' LIMIT 1";
$dbResult3 = $pearDB->query($query);
$svcname = $dbResult3->fetch();
$pearDB->query("DELETE FROM service WHERE service_id = '" . $serviceId . "'");
$pearDB->query("DELETE FROM on_demand_macro_service WHERE svc_svc_id = '" . $serviceId . "'");
$pearDB->query("DELETE FROM contact_service_relation WHERE service_service_id = '" . $serviceId . "'");
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICE,
object_id: $serviceId,
object_name: $svcname['service_description'],
action_type: ActionLog::ACTION_TYPE_DELETE
);
signalConfigurationChange('service', (int) $serviceId, $previousPollerIds);
}
$centreon->user->access->updateACL(['type' => 'SERVICE', 'id' => $serviceId, 'action' => 'DELETE']);
}
function divideGroupedServiceInDB($service_id = null, $service_arr = [], $toHost = null)
{
global $pearDB, $pearDBO;
if (! $service_id && ! count($service_arr)) {
return;
}
if ($service_id) {
$service_arr = [$service_id => '1'];
}
foreach ($service_arr as $key => $value) {
$query = 'SELECT count(host_host_id) as nbHost, count(hostgroup_hg_id) as nbHG FROM host_service_relation '
. "WHERE service_service_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$res = $dbResult->fetch();
if ($res['nbHost'] != 0 && $res['nbHG'] == 0) {
divideHostsToHost($key);
} elseif ($toHost) {
divideHostGroupsToHost($key);
} else {
divideHostGroupsToHostGroup($key);
}
// Delete old links for servicegroups
$pearDB->query('DELETE FROM servicegroup_relation WHERE service_service_id = ' . $key);
// Flag service to delete
$svcToDelete[$key] = 1;
}
// Purge Old Service
foreach ($svcToDelete as $svc_id => $flag) {
$pearDB->query("DELETE FROM service WHERE service_id = '" . $svc_id . "'");
$pearDB->query("DELETE FROM host_service_relation WHERE service_service_id = '" . $svc_id . "'");
}
}
function divideHostGroupsToHostGroup($service_id)
{
global $pearDB, $pearDBO;
$query = 'SELECT hostgroup_hg_id FROM host_service_relation '
. "WHERE service_service_id = '" . $service_id . "' AND hostgroup_hg_id IS NOT NULL";
$dbResult3 = $pearDB->query($query);
$query = 'UPDATE index_data
SET service_id = :sv_id
WHERE host_id = :host_id AND service_id = :service_id';
$statement = $pearDBO->prepare($query);
while ($data = $dbResult3->fetch()) {
$sv_id = multipleServiceInDB(
[$service_id => '1'],
[$service_id => '1'],
null,
0,
$data['hostgroup_hg_id'],
[],
[]
);
$hosts = getMyHostGroupHosts($data['hostgroup_hg_id']);
foreach ($hosts as $host_id) {
$statement->bindValue(':sv_id', (int) $sv_id, PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT);
$statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT);
$statement->execute();
setHostChangeFlag($pearDB, $host_id, null);
}
}
$dbResult3->closeCursor();
}
function divideHostGroupsToHost($service_id)
{
global $pearDB, $pearDBO;
$dbResult = $pearDB->query("SELECT * FROM host_service_relation WHERE service_service_id = '" . $service_id . "'");
$query = 'UPDATE index_data
SET service_id = :sv_id
WHERE host_id = :host_id AND service_id = :service_id';
$statement = $pearDBO->prepare($query);
while ($relation = $dbResult->fetch()) {
$hosts = getMyHostGroupHosts($relation['hostgroup_hg_id']);
foreach ($hosts as $host_id) {
$sv_id = multipleServiceInDB(
[$service_id => '1'],
[$service_id => '1'],
$host_id,
0,
null,
[],
[$relation['hostgroup_hg_id'] => null]
);
$statement->bindValue(':sv_id', (int) $sv_id, PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $host_id, PDO::PARAM_INT);
$statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT);
$statement->execute();
setHostChangeFlag($pearDB, $host_id, null);
}
}
$dbResult->closeCursor();
}
function divideHostsToHost($service_id)
{
global $pearDB, $pearDBO;
$dbResult = $pearDB->query("SELECT * FROM host_service_relation WHERE service_service_id = '" . $service_id . "'");
$query = 'UPDATE index_data SET service_id = :sv_id WHERE host_id = :host_id AND service_id = :service_id';
$statement = $pearDBO->prepare($query);
while ($relation = $dbResult->fetch()) {
$sv_id = multipleServiceInDB(
[$service_id => '1'],
[$service_id => '1'],
$relation['host_host_id'],
0,
null,
[],
[$relation['hostgroup_hg_id'] => null]
);
$statement->bindValue(':sv_id', (int) $sv_id, PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $relation['host_host_id'], PDO::PARAM_INT);
$statement->bindValue(':service_id', (int) $service_id, PDO::PARAM_INT);
$statement->execute();
setHostChangeFlag($pearDB, $relation['host_host_id'], null);
}
}
function multipleServiceInDB(
$services = [],
$nbrDup = [],
$host = null,
$descKey = 1,
$hostgroup = null,
$hPars = [],
$hgPars = [],
$params = [],
) {
global $pearDB, $centreon;
/* $descKey param is a flag. If 1, we know we have to rename description because it's a traditionnal
duplication. If 0, we don't have to, beacause we duplicate services for an Host duplication */
// Foreach Service
$maxId['MAX(service_id)'] = null;
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
foreach ($services as $key => $value) {
// Get all information about it
$dbResult = $pearDB->query("SELECT * FROM service WHERE service_id = '" . $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['service_id'] = null;
// Loop on the number of Service we want to duplicate
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
// Create a sentence which contains all the value
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'service_description' && $descKey) {
$service_description = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
} elseif ($key2 == 'service_description') {
$service_description = null;
}
$val ? $val
.= ($value2 != null ? (", '" . $pearDB->escape($value2) . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $pearDB->escape($value2) . "'") : 'NULL');
if ($key2 != 'service_id') {
$fields[$key2] = $value2;
}
if (isset($service_description)) {
$fields['service_description'] = $service_description;
}
}
if (! count($hPars)) {
$hPars = getMyServiceHosts($key);
}
if (! count($hgPars)) {
$hgPars = getMyServiceHostGroups($key);
}
if (
($row['service_register'] && testServiceExistence($service_description, $hPars, $hgPars, $params))
|| (! $row['service_register'] && testServiceTemplateExistence($service_description))
) {
$hPars = [];
$hgPars = [];
$rq = (isset($val) && $val != 'NULL' && $val)
? 'INSERT INTO service VALUES (' . $val . ')'
: null;
if (isset($rq)) {
$dbResult = $pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(service_id) FROM service');
$maxId = $dbResult->fetch();
if (isset($maxId['MAX(service_id)'])) {
// Host duplication case -> Duplicate the Service for the Host we create
if ($host) {
$query = 'INSERT INTO host_service_relation
VALUES (NULL, NULL, :host_id, NULL, :service_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':host_id', (int) $host, PDO::PARAM_INT);
$statement->bindValue(':service_id', (int) $maxId['MAX(service_id)'], PDO::PARAM_INT);
$statement->execute();
setHostChangeFlag($pearDB, $host, null);
} elseif ($hostgroup) {
$query = 'INSERT INTO host_service_relation
VALUES (NULL, :hostgroup_id, NULL,
NULL, :service_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':hostgroup_id', (int) $hostgroup, PDO::PARAM_INT);
$statement->bindValue(':service_id', (int) $maxId['MAX(service_id)'], PDO::PARAM_INT);
$statement->execute();
setHostChangeFlag($pearDB, null, $hostgroup);
} else {
// Service duplication case -> Duplicate the Service for each relation the base Service have
$query = 'SELECT DISTINCT host_host_id, hostgroup_hg_id FROM host_service_relation '
. "WHERE service_service_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['service_hPars'] = '';
$fields['service_hgPars'] = '';
$query = 'INSERT INTO host_service_relation
VALUES (NULL, :hostgroup_hg_id, :host_host_id,
NULL, :service_id)';
$statement = $pearDB->prepare($query);
while ($service = $dbResult->fetch()) {
if ($service['host_host_id']) {
$statement->bindValue(
':hostgroup_hg_id',
null,
PDO::PARAM_NULL
);
$statement->bindValue(
':host_host_id',
(int) $service['host_host_id'],
PDO::PARAM_INT
);
$statement->bindValue(
':service_id',
(int) $maxId['MAX(service_id)'],
PDO::PARAM_INT
);
$statement->execute();
setHostChangeFlag($pearDB, $service['host_host_id'], null);
$fields['service_hPars'] .= $service['host_host_id'] . ',';
} elseif ($service['hostgroup_hg_id']) {
$statement->bindValue(
':hostgroup_hg_id',
(int) $service['hostgroup_hg_id'],
PDO::PARAM_INT
);
$statement->bindValue(
':host_host_id',
null,
PDO::PARAM_NULL
);
$statement->bindValue(
':service_id',
(int) $maxId['MAX(service_id)'],
PDO::PARAM_INT
);
$statement->execute();
setHostChangeFlag($pearDB, null, $service['hostgroup_hg_id']);
$fields['service_hgPars'] .= $service['hostgroup_hg_id'] . ',';
}
}
$fields['service_hPars'] = trim($fields['service_hPars'], ',');
$fields['service_hgPars'] = trim($fields['service_hgPars'], ',');
}
// Contact duplication
$query = 'SELECT DISTINCT contact_id FROM contact_service_relation '
. "WHERE service_service_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['service_cs'] = '';
$query = 'INSERT INTO contact_service_relation VALUES (:service_id,:contact_id )';
$statement = $pearDB->prepare($query);
while ($C = $dbResult->fetch()) {
$statement->bindValue(':service_id', (int) $maxId['MAX(service_id)'], PDO::PARAM_INT);
$statement->bindValue(':contact_id', (int) $C['contact_id'], PDO::PARAM_INT);
$statement->execute();
$fields['service_cs'] .= $C['contact_id'] . ',';
}
$fields['service_cs'] = trim($fields['service_cs'], ',');
// ContactGroup duplication
$query = 'SELECT DISTINCT contactgroup_cg_id FROM contactgroup_service_relation '
. "WHERE service_service_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['service_cgs'] = '';
$query = 'INSERT INTO contactgroup_service_relation
VALUES (:contactgroup_cg_id,:service_id)';
$statement = $pearDB->prepare($query);
while ($Cg = $dbResult->fetch()) {
$statement->bindValue(
':contactgroup_cg_id',
(int) $Cg['contactgroup_cg_id'],
PDO::PARAM_INT
);
$statement->bindValue(':service_id', (int) $maxId['MAX(service_id)'], PDO::PARAM_INT);
$statement->execute();
$fields['service_cgs'] .= $Cg['contactgroup_cg_id'] . ',';
}
$fields['service_cgs'] = trim($fields['service_cgs'], ',');
// Servicegroup duplication
$query = 'SELECT DISTINCT host_host_id, hostgroup_hg_id, servicegroup_sg_id FROM '
. "servicegroup_relation WHERE service_service_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$fields['service_sgs'] = '';
$query = 'INSERT INTO servicegroup_relation (host_host_id, hostgroup_hg_id, '
. 'service_service_id, servicegroup_sg_id)
VALUES (:host_host_id,:hostgroup_hg_id,:service_service_id,:servicegroup_sg_id)';
$statement = $pearDB->prepare($query);
while ($Sg = $dbResult->fetch()) {
$host_id = isset($host) && $host ? $host : $Sg['host_host_id'] ?? null;
$hg_id = isset($hostgroup) && $hostgroup ? $hostgroup : $Sg['hostgroup_hg_id'] ?? null;
$statement->bindValue(
':host_host_id',
$host_id,
PDO::PARAM_INT
);
$statement->bindValue(
':hostgroup_hg_id',
$hg_id,
PDO::PARAM_INT
);
| 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/configObject/service/listServiceByHostGroup.php | centreon/www/include/configuration/configObject/service/listServiceByHostGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
$mediaObj = new CentreonMedia($pearDB);
$searchHG = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['hostgroups'] ?? $_GET['hostgroups'] ?? null
);
$searchS = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchS'] ?? $_GET['searchS'] ?? null
);
$template = filter_var(
$_POST['template'] ?? $_GET['template'] ?? 0,
FILTER_VALIDATE_INT
);
$status = filter_var(
$_POST['status'] ?? $_GET['status'] ?? 0,
FILTER_VALIDATE_INT
);
if (isset($_POST['Search']) || isset($_GET['Search'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['hostgroups'] = $searchHG;
$centreon->historySearch[$url]['search'] = $searchS;
$centreon->historySearch[$url]['template'] = $template;
$centreon->historySearch[$url]['status'] = $status;
} else {
// restoring saved values
$searchHG = $centreon->historySearch[$url]['hostgroups'] ?? null;
$searchS = $centreon->historySearch[$url]['search'] ?? null;
$template = $centreon->historySearch[$url]['template'] ?? null;
$status = $centreon->historySearch[$url]['status'] ?? 0;
}
// Status Filter
$statusFilter = [1 => _('Disabled'), 2 => _('Enabled')];
$sqlFilterCase = '';
if ($status == 2) {
$sqlFilterCase = " AND sv.service_activate = '1' ";
} elseif ($status == 1) {
$sqlFilterCase = " AND sv.service_activate = '0' ";
}
include './include/common/autoNumLimit.php';
$rows = 0;
$tmp = null;
$tmp2 = null;
$searchHG ??= '';
$searchS ??= '';
$aclFrom = '';
$aclCond = '';
$distinct = '';
$aclAccessGroupsParams = [];
if (! $centreon->user->admin) {
$aclAccessGroupList = explode(',', $acl->getAccessGroupsString());
foreach ($aclAccessGroupList as $index => $accessGroupId) {
$aclAccessGroupsParams[':access_' . $index] = str_replace("'", '', $accessGroupId);
}
$queryParams = implode(',', array_keys($aclAccessGroupsParams));
$aclFrom = ", `{$aclDbName}`.centreon_acl acl ";
$aclCond = ' AND sv.service_id = acl.service_id
AND acl.group_id IN (' . $queryParams . ') ';
$distinct = ' DISTINCT ';
}
/*
* Due to Description maybe in the Template definition, we have to search if the description
* could match for each service with a Template.
*/
$templateStr = isset($template) && $template ? ' AND service_template_model_stm_id = :service_template ' : '';
if ($searchS != '' || $searchHG != '') {
$statement = $pearDB->prepare(
'SELECT ' . $distinct . ' hostgroup_hg_id, sv.service_id, sv.service_description, '
. 'service_template_model_stm_id '
. 'FROM service sv, host_service_relation hsr, hostgroup hg ' . $aclFrom
. "WHERE sv.service_register = '1' " . $sqlFilterCase
. ' AND hsr.service_service_id = sv.service_id ' . $aclCond
. ' AND hsr.host_host_id IS NULL '
. ($searchS ? 'AND sv.service_description LIKE :service_description ' : '')
. ($searchHG ? 'AND hsr.hostgroup_hg_id = hg.hg_id AND hg.hg_name LIKE :hg_name ' : '') . $templateStr
);
if (isset($template) && $template) {
$statement->bindValue(
':service_template',
(int) $template,
PDO::PARAM_INT
);
}
foreach ($aclAccessGroupsParams as $key => $accessGroupId) {
$statement->bindValue($key, (int) $accessGroupId, PDO::PARAM_INT);
}
if ($searchS && ! $searchHG) {
$statement->bindValue(':service_description', '%' . $searchS . '%', PDO::PARAM_STR);
$statement->execute();
while ($service = $statement->fetch(PDO::PARAM_INT)) {
if (! isset($tab_buffer[$service['service_id']])) {
$tmp ? $tmp .= ', ' . $service['service_id'] : $tmp = $service['service_id'];
}
$tmp2 ? $tmp2 .= ', ' . $service['hostgroup_hg_id'] : $tmp2 = $service['hostgroup_hg_id'];
$tab_buffer[$service['service_id']] = $service['service_id'];
$rows++;
}
} elseif (! $searchS && $searchHG) {
$statement->bindValue(':hg_name', '%' . $searchHG . '%', PDO::PARAM_STR);
$statement->execute();
while ($service = $statement->fetch(PDO::FETCH_ASSOC)) {
$tmp ? $tmp .= ', ' . $service['service_id'] : $tmp = $service['service_id'];
$tmp2 ? $tmp2 .= ', ' . $service['hostgroup_hg_id'] : $tmp2 = $service['hostgroup_hg_id'];
$rows++;
}
} else {
$statement->bindValue(':service_description', '%' . $searchS . '%', PDO::PARAM_STR);
$statement->bindValue(':hg_name', '%' . $searchHG . '%', PDO::PARAM_STR);
$statement->execute();
while ($service = $statement->fetch(PDO::FETCH_ASSOC)) {
$tmp ? $tmp .= ', ' . $service['service_id'] : $tmp = $service['service_id'];
$tmp2 ? $tmp2 .= ', ' . $service['hostgroup_hg_id'] : $tmp2 = $service['hostgroup_hg_id'];
$rows++;
}
}
} else {
$statement = $pearDB->prepare(
'SELECT ' . $distinct . ' sv.service_description FROM service sv, host_service_relation hsr ' . $aclFrom
. "WHERE service_register = '1' " . $sqlFilterCase . $templateStr
. ' AND hsr.service_service_id = sv.service_id AND hsr.host_host_id IS NULL ' . $aclCond
);
foreach ($aclAccessGroupsParams as $key => $accessGroupId) {
$statement->bindValue($key, (int) $accessGroupId, PDO::PARAM_INT);
}
if (isset($template) && $template) {
$statement->bindValue(
':service_template',
(int) $template,
PDO::PARAM_INT
);
}
$statement->execute();
$rows = $statement->rowCount();
}
// 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);
include './include/common/checkPagination.php';
// start header menu
$tpl->assign('headerMenu_name', _('HostGroup'));
$tpl->assign('headerMenu_desc', _('Service'));
$tpl->assign('headerMenu_retry', _('Scheduling'));
$tpl->assign('headerMenu_parent', _('Template'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// HostGroup/service list
if ($searchS || $searchHG) {
// preparing tmp binds
$tmpIds = explode(',', $tmp);
$tmpQueryBinds = [];
foreach ($tmpIds as $key => $value) {
$tmpQueryBinds[':tmp_id_' . $key] = $value;
}
$tmpBinds = implode(',', array_keys($tmpQueryBinds));
// preparing tmp2 binds
$tmp2Ids = explode(',', $tmp2);
$tmp2QueryBinds = [];
foreach ($tmp2Ids as $key => $value) {
$tmp2QueryBinds[':tmp2_id_' . $key] = $value;
}
$tmp2Binds = implode(',', array_keys($tmp2QueryBinds));
$query = "SELECT {$distinct} @nbr:=(SELECT COUNT(*) FROM host_service_relation "
. 'WHERE service_service_id = sv.service_id GROUP BY sv.service_id ) AS nbr, sv.service_id, '
. 'sv.service_description, sv.service_activate, sv.service_template_model_stm_id, hg.hg_id, hg.hg_name '
. "FROM service sv, hostgroup hg, host_service_relation hsr {$aclFrom} "
. "WHERE sv.service_register = '1' {$sqlFilterCase} AND sv.service_id "
. "IN ({$tmpBinds}) AND hsr.hostgroup_hg_id IN ({$tmp2Binds}) "
. ((isset($template) && $template) ? ' AND service_template_model_stm_id = :template ' : '')
. ' AND hsr.service_service_id = sv.service_id AND hg.hg_id = hsr.hostgroup_hg_id ' . $aclCond
. 'ORDER BY hg.hg_name, sv.service_description LIMIT :offset_, :limit';
$statement = $pearDB->prepare($query);
// tmp bind values
foreach ($tmpQueryBinds as $key => $value) {
$statement->bindValue($key, (int) $value, PDO::PARAM_INT);
}
// tmp bind values
foreach ($tmp2QueryBinds as $key => $value) {
$statement->bindValue($key, (int) $value, PDO::PARAM_INT);
}
} else {
$query = "SELECT {$distinct} @nbr:=(SELECT COUNT(*) FROM host_service_relation "
. 'WHERE service_service_id = sv.service_id GROUP BY sv.service_id ) AS nbr, sv.service_id, '
. 'sv.service_description, sv.service_activate, sv.service_template_model_stm_id, hg.hg_id, hg.hg_name '
. "FROM service sv, hostgroup hg, host_service_relation hsr {$aclFrom} "
. "WHERE sv.service_register = '1' {$sqlFilterCase} "
. ((isset($template) && $template) ? ' AND service_template_model_stm_id = :template ' : '')
. ' AND hsr.service_service_id = sv.service_id AND hg.hg_id = hsr.hostgroup_hg_id ' . $aclCond
. 'ORDER BY hg.hg_name, sv.service_description LIMIT :offset_, :limit';
$statement = $pearDB->prepare($query);
}
$statement->bindValue(':offset_', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
if ((isset($template) && $template)) {
$statement->bindValue(':template', (int) $template, PDO::PARAM_INT);
}
foreach ($aclAccessGroupsParams as $key => $accessGroupId) {
$statement->bindValue($key, (int) $accessGroupId, PDO::PARAM_INT);
}
$statement->execute();
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
// select2 Service template
$route = './api/internal.php?object=centreon_configuration_servicetemplate&action=list';
$attrServicetemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => false, 'defaultDataset' => $template, 'linkedObject' => 'centreonServicetemplates'];
$form->addElement('select2', 'template', '', [], $attrServicetemplates);
// select2 Service Status
$attrServiceStatus = null;
if ($status) {
$statusDefault = [$statusFilter[$status] => $status];
$attrServiceStatus = ['defaultDataset' => $statusDefault];
}
$form->addElement('select2', 'status', '', $statusFilter, $attrServiceStatus);
$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
$interval_length = $centreon->optGen['interval_length'];
$elemArr = [];
$fgHostgroup = ['value' => null, 'print' => null];
$centreonToken = createCSRFToken();
for ($i = 0; $service = $statement->fetch(PDO::FETCH_ASSOC); $i++) {
$moptions = '';
$fgHostgroup['value'] != $service['hg_name']
? ($fgHostgroup['print'] = true && $fgHostgroup['value'] = $service['hg_name'])
: $fgHostgroup['print'] = false;
$selectedElements = $form->addElement('checkbox', 'select[' . $service['service_id'] . ']');
if ($service['service_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&service_id=' . $service['service_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '&template=' . $template . '&status=' . $status
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='" . _('Disabled') . "'>";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&service_id=' . $service['service_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '&template=' . $template . '&status=' . $status
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='" . _('Enabled') . "'>";
}
$moptions .= '</a> ';
$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;\" onKeyUp=\"syncInputField(this.name, this.value);\" maxlength=\"3\" size=\"3\" value='1' "
. "style=\"margin-bottom:0px;\" name='dupNbr[" . $service['service_id'] . "]' />";
/*If the description of our Service is in the Template definition,
we have to catch it, whatever the level of it :-)*/
if (! $service['service_description']) {
$service['service_description'] = getMyServiceAlias($service['service_template_model_stm_id']);
}
// TPL List
$tplArr = [];
$tplStr = null;
$tplArr = getMyServiceTemplateModels($service['service_template_model_stm_id']);
if ($tplArr && count($tplArr)) {
foreach ($tplArr as $key => $value) {
$value = str_replace('#S#', '/', $value);
$value = str_replace('#BS#', '\\', $value);
$tplStr .= " > <a href='main.php?p=60206&o=c&service_id=" . $key . "'>" . $value . '</a>';
}
}
$isServiceSvgFile = true;
if (isset($service['esi_icon_image']) && $service['esi_icon_image']) {
$isServiceSvgFile = false;
$svc_icon = './img/media/' . $mediaObj->getFilename($service['esi_icon_image']);
} elseif (
$icone = $mediaObj->getFilename(
getMyServiceExtendedInfoField(
$service['service_id'],
'esi_icon_image'
)
)
) {
$isServiceSvgFile = false;
$svc_icon = './img/media/' . $icone;
} else {
$isServiceSvgFile = true;
$svc_icon = returnSvg('www/img/icons/service.svg', 'var(--icons-fill-color)', 14, 14);
}
// Get service intervals in seconds
$normal_check_interval
= getMyServiceField($service['service_id'], 'service_normal_check_interval') * $interval_length;
$retry_check_interval
= getMyServiceField($service['service_id'], 'service_retry_check_interval') * $interval_length;
if ($normal_check_interval % 60 == 0) {
$normal_units = 'min';
$normal_check_interval = $normal_check_interval / 60;
} else {
$normal_units = 'sec';
}
if ($retry_check_interval % 60 == 0) {
$retry_units = 'min';
$retry_check_interval = $retry_check_interval / 60;
} else {
$retry_units = 'sec';
}
$elemArr[$i] = [
'MenuClass' => 'list_' . ($service['nbr'] > 1 ? 'three' : $style),
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => CentreonUtils::escapeSecure($service['hg_name']),
'RowMenu_link' => 'configuration/hosts/groups?mode=edit&id=' . $service['hg_id'],
'RowMenu_link2' => 'main.php?p=' . $p . '&o=c&service_id=' . $service['service_id'],
'RowMenu_parent' => CentreonUtils::escapeSecure($tplStr), 'RowMenu_sicon' => $svc_icon,
'RowMenu_retry' => CentreonUtils::escapeSecure("{$normal_check_interval} {$normal_units} / {$retry_check_interval} {$retry_units}"),
'RowMenu_attempts' => CentreonUtils::escapeSecure(getMyServiceField($service['service_id'], 'service_max_check_attempts')),
'RowMenu_desc' => CentreonUtils::escapeSecure($service['service_description']),
'RowMenu_status' => $service['service_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $service['service_activate'] ? 'service_ok' : 'service_critical',
'RowMenu_options' => $moptions,
'isServiceSvgFile' => $isServiceSvgFile,
];
$fgHostgroup['print'] ? null : $elemArr[$i]['RowMenu_name'] = null;
$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 == 6 && confirm('"
. _('Are you sure you want to detach the service ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 7 && confirm('"
. _('Are you sure you want to detach the service ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3 || this.form.elements['o1'].selectedIndex == 4 || "
. "this.form.elements['o1'].selectedIndex == 5){"
. " 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'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable'), 'dv' => _('Detach host group services'), 'mvH' => _("Move host group's services to hosts")],
$attrs1
);
$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 == 6 && confirm('"
. _('Are you sure you want to detach the service ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 7 && confirm('"
. _('Are you sure you want to detach the service ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3 || this.form.elements['o2'].selectedIndex == 4 || "
. "this.form.elements['o2'].selectedIndex == 5){"
. " 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'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable'), 'dv' => _('Detach host group services'), 'mvH' => _("Move host group's services to hosts")],
$attrs2
);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$tpl->assign('limit', $limit);
if (isset($searchHG) && $searchHG) {
$searchHG = html_entity_decode($searchHG);
$searchHG = stripslashes(str_replace('"', '"', $searchHG));
}
if (isset($searchS) && $searchS) {
$searchS = html_entity_decode($searchS);
$searchS = stripslashes(str_replace('"', '"', $searchS));
}
$tpl->assign('hostgroupsFilter', $searchHG);
$tpl->assign('searchS', $searchS);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('HostGroups', _('HostGroups'));
$tpl->assign('Services', _('Services'));
$tpl->assign('ServiceTemplates', _('Templates'));
$tpl->assign('ServiceStatus', _('Status'));
$tpl->display('listService.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/configObject/service/xml/argumentsXmlFunction.php | centreon/www/include/configuration/configObject/service/xml/argumentsXmlFunction.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Function
function myDecodeValue($arg)
{
$arg = str_replace('#S#', '/', $arg ?? '');
$arg = str_replace('#BS#', '\\', $arg);
return html_entity_decode($arg, 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/configuration/configObject/service/xml/argumentsXml.php | centreon/www/include/configuration/configObject/service/xml/argumentsXml.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 __DIR__ . '/argumentsXmlFunction.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonXML.class.php';
// Get session
require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreon.class.php';
if (! isset($_SESSION['centreon'])) {
CentreonSession::start(1);
}
if (isset($_SESSION['centreon'])) {
$oreon = $_SESSION['centreon'];
} else {
exit;
}
// Get language
$locale = $oreon->user->get_lang();
putenv("LANG={$locale}");
setlocale(LC_ALL, $locale);
bindtextdomain('messages', _CENTREON_PATH_ . 'www/locale/');
bind_textdomain_codeset('messages', 'UTF-8');
textdomain('messages');
// start init db
$db = new CentreonDB();
$xml = new CentreonXML();
$xml->startElement('root');
$xml->startElement('main');
$xml->writeElement('argLabel', _('Argument'));
$xml->writeElement('argValue', _('Value'));
$xml->writeElement('argExample', _('Example'));
$xml->writeElement('noArgLabel', _('No argument found for this command'));
$xml->endElement();
if (isset($_GET['cmdId'], $_GET['svcId'], $_GET['svcTplId'], $_GET['o'])) {
$cmdId = CentreonDB::escape($_GET['cmdId']);
$svcId = CentreonDB::escape($_GET['svcId']);
$svcTplId = CentreonDB::escape($_GET['svcTplId']);
$o = CentreonDB::escape($_GET['o']);
$tab = [];
if (! $cmdId && $svcTplId) {
while (1) {
$query4 = "SELECT service_template_model_stm_id, command_command_id, command_command_id_arg
FROM `service`
WHERE service_id = '" . $svcTplId . "'";
$res4 = $db->query($query4);
$row4 = $res4->fetchRow();
if (isset($row4['command_command_id']) && $row4['command_command_id']) {
$cmdId = $row4['command_command_id'];
break;
}
if (! isset($row4['service_template_model_stm_id']) || ! $row4['service_template_model_stm_id']) {
break;
}
if (isset($tab[$row4['service_template_model_stm_id']])) {
break;
}
$svcTplId = $row4['service_template_model_stm_id'];
$tab[$svcTplId] = 1;
}
}
$argTab = [];
$exampleTab = [];
$query2 = 'SELECT command_line, command_example FROM command WHERE command_id = :cmd_id LIMIT 1';
$statement = $db->prepare($query2);
$statement->bindValue(':cmd_id', $cmdId, PDO::PARAM_INT);
$statement->execute();
if ($row2 = $statement->fetch()) {
$cmdLine = $row2['command_line'];
preg_match_all('/\\$(ARG[0-9]+)\\$/', $cmdLine, $matches);
foreach ($matches[1] as $key => $value) {
$argTab[$value] = $value;
}
$exampleTab = preg_split('/\!/', $row2['command_example']);
if (is_array($exampleTab)) {
foreach ($exampleTab as $key => $value) {
$nbTmp = $key;
$exampleTab['ARG' . $nbTmp] = $value;
unset($exampleTab[$key]);
}
}
}
$cmdStatement = $db->prepare('SELECT command_command_id_arg '
. 'FROM service '
. 'WHERE service_id = :svcId LIMIT 1');
$cmdStatement->bindValue(':svcId', (int) $svcId, PDO::PARAM_INT);
$cmdStatement->execute();
if ($cmdStatement->rowCount()) {
$row3 = $cmdStatement->fetchRow();
$valueTab = preg_split('/(?<!\\\)\!/', $row3['command_command_id_arg']);
if (is_array($valueTab)) {
foreach ($valueTab as $key => $value) {
$nbTmp = $key;
$valueTab['ARG' . $nbTmp] = $value;
unset($valueTab[$key]);
}
} else {
$exampleTab = [];
}
}
$macroStatement = $db->prepare('SELECT macro_name, macro_description '
. 'FROM command_arg_description '
. 'WHERE cmd_id = :cmdId ORDER BY macro_name');
$macroStatement->bindValue(':cmdId', (int) $cmdId, PDO::PARAM_INT);
$macroStatement->execute();
while ($row = $macroStatement->fetchRow()) {
$argTab[$row['macro_name']] = $row['macro_description'];
}
$macroStatement->closeCursor();
// Write XML
$style = 'list_two';
$disabled = 0;
$nbArg = 0;
foreach ($argTab as $name => $description) {
$style = $style == 'list_one' ? 'list_two' : 'list_one';
if ($o == 'w') {
$disabled = 1;
}
$xml->startElement('arg');
$xml->writeElement('name', $name, false);
$xml->writeElement('description', $description, false);
$xml->writeElement('value', $valueTab[$name] ?? '', false);
$xml->writeElement('example', isset($exampleTab[$name]) ? myDecodeValue($exampleTab[$name]) : '', false);
$xml->writeElement('style', $style);
$xml->writeElement('disabled', $disabled);
$xml->endElement();
$nbArg++;
}
}
$xml->writeElement('nbArg', $nbArg);
$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/configuration/configObject/service/javascript/argumentJs.php | centreon/www/include/configuration/configObject/service/javascript/argumentJs.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
?>
<script language='javascript' type='text/javascript'>
function mk_pagination(){}
function mk_paginationFF(){}
function set_header_title(){}
var o = '<?php echo $o; ?>';
var _cmdId = '<?php echo $cmdId ?? null; ?>';
var _svcId = '<?php echo isset($cmdId) ? $service_id : null; ?>';
var _svcTplId = '<?php echo isset($cmdId) ? $serviceTplId : null; ?>';
/**
*
*/
function transformForm()
{
var params;
var proc;
var addrXML;
var addrXSL;
params = '?cmdId=' + _cmdId + '&svcId=' + _svcId + '&svcTplId=' + _svcTplId + '&o=' + o;
proc = new Transformation();
addrXML = './include/configuration/configObject/service/xml/argumentsXml.php' + params;
addrXSL = './include/configuration/configObject/service/xsl/arguments.xsl';
proc.setXml(addrXML);
proc.setXslt(addrXSL);
proc.transform("dynamicDiv");
trapId = 0;
}
/**
*
*/
function changeCommand(value)
{
_cmdId = value;
if(document.getElementById('svcTemplate') != null){
_templateId = document.getElementById('svcTemplate').value;
}
transformForm();
}
/**
*
*/
function changeServiceTemplate(value)
{
_svcTplId = value;
if(document.getElementById('checkCommand') != null){
_cmdId = document.getElementById('checkCommand').value;
}
transformForm();
}
</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/command/minHelpCommand.php | centreon/www/include/configuration/configObject/command/minHelpCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 __DIR__ . '/minHelpCommandFunctions.php';
$commandId = filter_var(
$_GET['command_id'] ?? $_POST['command_id'] ?? null,
FILTER_VALIDATE_INT
);
$commandName = htmlspecialchars($_GET['command_name'] ?? $_POST['command_name'] ?? null);
if ($commandId !== false) {
$commandLine = getCommandById($pearDB, (int) $commandId) ?? '';
['commandPath' => $commandPath, 'plugin' => $plugin, 'mode' => $mode] = getCommandElements($commandLine);
$command = replaceMacroInCommandPath($pearDB, $commandPath);
} else {
$command = $centreon->optGen['nagios_path_plugins'] . $commandName;
}
// Secure command
$search = ['#S#', '#BS#', '../', "\t"];
$replace = ['/', '\\', '/', ' '];
$command = str_replace($search, $replace, $command);
// Remove params
$explodedCommand = explode(' ', $command);
$commandPath = realpath($explodedCommand[0]) === false ? $explodedCommand[0] : realpath($explodedCommand[0]);
// Exec command only if located in allowed directories
$msg = 'Command not allowed';
if (isCommandInAllowedResources($pearDB, $commandPath)) {
$command = $commandPath . ' ' . ($plugin ?? '') . ' ' . ($mode ?? '') . ' --help';
$command = escapeshellcmd($command);
$stdout = shell_exec($command . ' 2>&1');
$msg = str_replace("\n", '<br />', $stdout);
}
$attrsText = ['size' => '25'];
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->addElement('header', 'title', _('Plugin Help'));
// Command information
$form->addElement('header', 'information', _('Help'));
$form->addElement('text', 'command_line', _('Command Line'), $attrsText);
$form->addElement('text', 'command_help', _('Output'), $attrsText);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('command_line', CentreonUtils::escapeSecure($command, CentreonUtils::ESCAPE_ALL));
$tpl->assign('msg', CentreonUtils::escapeAllExceptSelectedTags($msg, ['br']));
$tpl->display('minHelpCommand.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/configObject/command/formMacros.php | centreon/www/include/configuration/configObject/command/formMacros.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
require_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonCommand.class.php';
require_once _CENTREON_PATH_ . 'bootstrap.php';
session_start();
session_write_close();
$centreon = $_SESSION['centreon'];
if (! isset($centreon)) {
exit();
}
$centreonLang = new CentreonLang(_CENTREON_PATH_, $centreon);
$centreonLang->bindLang();
if (! isset($pearDB) || is_null($pearDB)) {
$pearDB = new CentreonDB();
global $pearDB;
}
$macros = [];
$macrosServiceDesc = [];
$macrosHostDesc = [];
$nb_arg = 0;
if (isset($_GET['cmd_line']) && $_GET['cmd_line']) {
$str = $_GET['cmd_line'];
$iIdCmd = (int) $_GET['cmdId'];
$oCommande = new CentreonCommand($pearDB);
$macrosHostDesc = $oCommande->matchObject($iIdCmd, $str, '1');
$macrosServiceDesc = $oCommande->matchObject($iIdCmd, $str, '2');
$nb_arg = count($macrosHostDesc) + count($macrosServiceDesc);
$macros = array_merge($macrosServiceDesc, $macrosHostDesc);
}
// FORM
$path = _CENTREON_PATH_ . '/www/include/configuration/configObject/command/';
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '60'];
$attrsAdvSelect = ['style' => 'width: 200px; height: 100px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
// Basic info
$form = new HTML_QuickFormCustom('Form', 'post');
$form->addElement('header', 'title', _('Macro Descriptions'));
$form->addElement('header', 'information', _('Macros'));
$subS = $form->addElement(
'button',
'submitSaveAdd',
_('Save'),
['onClick' => 'setMacrosDescriptions();', 'class' => 'btc bt_success']
);
$subS = $form->addElement(
'button',
'close',
_('Close'),
['onClick' => 'closeBox();', 'class' => 'btc bt_default']
);
// Smarty template
$tpl = new SmartyBC();
$tpl->setTemplateDir($path);
$tpl->setCompileDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/compile');
$tpl->setConfigDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/config');
$tpl->setCacheDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/cache');
$tpl->addPluginsDir(_CENTREON_PATH_ . '/GPL_LIB/smarty-plugins');
$tpl->loadPlugin('smarty_function_eval');
$tpl->setForceCompile(true);
$tpl->setAutoLiteral(false);
$tpl->assign('nb_arg', $nb_arg);
$tpl->assign('macros', $macros);
$tpl->assign('noArgMsg', _('Sorry, your command line does not contain any $_SERVICE$ macro or $_HOST$ macro.'));
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1"></font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('formMacros.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/configObject/command/listCommand.php | centreon/www/include/configuration/configObject/command/listCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_once './include/common/autoNumLimit.php';
$type = filter_var(
$_POST['type'] ?? $_GET['type'] ?? $centreon->historySearch[$url]['type'] ?? null,
FILTER_VALIDATE_INT
);
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchC'] ?? $_GET['searchC'] ?? $centreon->historySearch[$url]['search' . $type] ?? ''
);
$displayLocked = filter_var(
$_POST['displayLocked'] ?? $_GET['displayLocked'] ?? 'off',
FILTER_VALIDATE_BOOLEAN
);
// keep checkbox state if navigating in pagination
// this trick is mandatory cause unchecked checkboxes do not post any data
if (
(isset($centreon->historyPage[$url]) && $centreon->historyPage[$url] > 0 || $num !== 0)
&& isset($centreon->historySearch[$url]['displayLocked'])
) {
$displayLocked = $centreon->historySearch[$url]['displayLocked'];
}
// As the four pages of this menu are generated dynamically from the same ihtml and php files,
// we need to save $type and to overload the $num value set in the pagination.php file to restore each user's filter.
$savedType = $centreon->historySearch[$url]['type'] ?? null;
// As pagination.php will already check if the current page was previously loaded or not,
// we're only checking if the last loaded page have the same $type value (1,2,3 or 4)
if (isset($type) && $type !== $savedType) {
// if so, we reset the pagination and save the current $type
$num = $centreon->historyPage[$url] = 0;
} else {
// saving again the pagination filter
$centreon->historyPage[$url] = $num;
}
// store filters in session
$centreon->historySearch[$url] = [
'search' . $type => $search,
'type' => $type,
'displayLocked' => $displayLocked,
];
// Locked filter
$lockedFilter = $displayLocked ? '' : 'AND command_locked = 0 ';
// Type filter
$typeFilter = $type ? 'AND `command_type` = :command_type ' : '';
$search = tidySearchKey($search, $advanced_search);
$rq = 'SELECT SQL_CALC_FOUND_ROWS `command_id`, `command_name`, `command_line`, `command_type`, '
. '`command_activate` FROM `command` WHERE `command_name` LIKE :search '
. $typeFilter . $lockedFilter . ' ORDER BY `command_name` LIMIT :offset, :limit';
$statement = $pearDB->prepare($rq);
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
$statement->bindValue(':offset', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
if ($type) {
$statement->bindValue(':command_type', (int) $type, PDO::PARAM_INT);
}
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include_once './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);
// Main buttons
$duplicateBtn = "<button id='duplicate_cmd' style='cursor: pointer; background-color: transparent; border: 0; height: 22px; width: 22px;' "
. "onclick=\"javascript:if (confirm('" . _('Do you confirm the duplication ?') . "')) {setO('m'); submit();}\">"
. "<img src='img/icons/content_copy.png' " . "class='ico-22 margin_right' alt='" . _('Duplicate') . "'></button>";
$deleteBtn = "<button id='delete_cmd' style='cursor: pointer; background-color: transparent; border: 0; height: 22px; width: 22px;' "
. "onclick=\"javascript: if (confirm('" . _('Do you confirm the deletion ?') . "')) {setO('d'); submit();}\">"
. "<img src='img/icons/delete_new.png' " . "class='ico-22 margin_right' alt='" . _('Delete') . "'></button>";
$disableBtn = "<button id='disable_cmd' style='cursor: pointer; background-color: transparent; border: 0; height: 22px; width: 22px;' "
. "onclick=\"javascript: setO('md'); submit();\"><img src='img/icons/visibility_off.png' "
. "class='ico-22 margin_right' alt='" . _('Disable') . "'></button>";
$enableBtn = "<button id='enable_cmd' style='cursor: pointer; background-color: transparent; border: 0; height: 22px; width: 22px;' "
. "onclick=\"javascript: setO('me'); submit();\"><img src='img/icons/visibility_on.png' "
. "class='ico-22 margin_right' alt='" . _('Enable') . "'></button>";
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Command Line'));
$tpl->assign('headerMenu_type', _('Type'));
$tpl->assign('headerMenu_huse', _('Host Uses'));
$tpl->assign('headerMenu_suse', _('Services Uses'));
$tpl->assign('headerMenu_options', _('Actions'));
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$addrType = $type ? '&type=' . $type : '';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . $addrType . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Define command Type table
$commandType = ['1' => _('Notification'), '2' => _('Check'), '3' => _('Miscellaneous'), '4' => _('Discovery')];
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $cmd = $statement->fetch(PDO::FETCH_ASSOC); $i++) {
$selectedElements = $form->addElement('checkbox', 'select[' . $cmd['command_id'] . ']');
if ($cmd['command_activate']) {
$optionO = 'di';
$altText = _('Enabled');
$iconValue = 'visibility_on.png';
} else {
$optionO = 'en';
$altText = _('Disabled');
$iconValue = 'visibility_off.png';
}
$state = "<button style='cursor: pointer; background-color: transparent; border: 0; height: 16px; width: 16px;' "
. "onclick=\"javascript: setO('" . $optionO . "'); setCmdId(" . $cmd['command_id'] . '); submit();">'
. "<img src='img/icons/" . $iconValue . "' " . "class='ico-16 margin_right' alt='" . $altText . "'></button>";
$duplicate = "<button style='cursor: pointer; background-color: transparent; border: 0; height: 16px; width: 16px;' "
. "onclick=\"javascript: setO('m'); setCmdId(" . $cmd['command_id'] . '); submit();">'
. "<img src='img/icons/content_copy.png' " . "class='ico-16 margin_right' alt='" . _('Duplicate') . "'></button>";
$delete = "<button style='cursor: pointer; background-color: transparent; border: 0; height: 16px; width: 16px;' "
. "onclick=\"javascript: setO('d'); setCmdId(" . $cmd['command_id'] . '); submit();">'
. "<img src='img/icons/delete_new.png' " . "class='ico-16 margin_right' alt='" . _('Delete') . "'></button>";
if (isset($lockedElements[$cmd['command_id']])) {
$selectedElements->setAttribute('disabled', 'disabled');
$delete = '';
}
$decodedCommand = myDecodeCommand($cmd['command_line']);
$elemArr[$i] = [
'MenuClass' => 'list_' . $style,
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => $cmd['command_name'],
'RowMenu_link' => 'main.php?p=' . $p
. '&o=c&command_id=' . $cmd['command_id'] . '&type=' . $cmd['command_type'],
'RowMenu_desc' => (strlen($decodedCommand) > 50)
? CentreonUtils::escapeSecure(substr($decodedCommand, 0, 50), CentreonUtils::ESCAPE_ALL) . '...'
: CentreonUtils::escapeSecure($decodedCommand, CentreonUtils::ESCAPE_ALL),
'RowMenu_type' => $commandType[$cmd['command_type']],
'RowMenu_huse' => "<a name='#' title='" . _('Host links (host template links)') . "'>"
. getHostNumberUse($cmd['command_id']) . ' (' . getHostTPLNumberUse($cmd['command_id']) . ')</a>',
'RowMenu_suse' => "<a name='#' title='" . _('Service links (service template links)') . "'>"
. getServiceNumberUse($cmd['command_id']) . ' (' . getServiceTPLNumberUse($cmd['command_id']) . ')</a>',
'RowMenu_state' => $state,
'RowMenu_duplicate' => $duplicate,
'RowMenu_delete' => $delete,
];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
if (isset($_GET['type']) && $_GET['type'] != '') {
$type = htmlentities($_GET['type'], ENT_QUOTES, 'UTF-8');
} elseif (! isset($_GET['type'])) {
$type = 2;
}
$tpl->assign(
'msg',
[
'addL' => 'main.php?p=' . $p . '&o=a&type=' . $type,
'addT' => '+ ' . _('ADD'),
]
);
$redirectType = $form->addElement('hidden', 'type');
$redirectType->setValue($type);
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
function setCmdId(_i) {
document.forms['form'].elements['command_id'].value = _i;
}
</script>
<?php
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('limit', $limit);
$tpl->assign('type', $type);
$tpl->assign('searchC', $search);
$tpl->assign('displayLocked', $displayLocked);
$tpl->assign('duplicateBtn', $duplicateBtn);
$tpl->assign('deleteBtn', $deleteBtn);
$tpl->assign('disableBtn', $disableBtn);
$tpl->assign('enableBtn', $enableBtn);
$tpl->display('listCommand.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/configObject/command/help.php | centreon/www/include/configuration/configObject/command/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['command_name'] = dgettext(
'help',
'The command name is used to identify and display this command in contact, host and service definitions.'
);
$help['command_line_help'] = dgettext(
'help',
'The command line specifies the real command line which is actually executed by Monitoring engine. '
. 'Before execution, all valid macros are replaced with their respective values. To use the dollar sign ($) '
. 'on the command line, you have to escape it with another dollar sign ($$). A semicolon (;) '
. 'is used as separator for config file comments and must be worked around by setting a $USER$ macro '
. 'to a semicolon and then referencing it here in place of the semicolon. If you want to pass arguments '
. 'to commands during runtime, you can use $ARGn$ macros in the command line.'
);
$help['enable_shell'] = dgettext(
'help',
'Check this option if your command requires shell features like pipes, redirections, globbing etc. '
. 'Note that commands requiring shell are slowing down the poller server.'
);
$help['arg_example'] = dgettext(
'help',
'The argument example defined here will be displayed together with the command selection and help in '
. 'providing a hint of how to parametrize the command for execution.'
);
$help['command_type'] = dgettext(
'help',
'Define the type of the command. The type will be used to show the command only in the relevant sections.'
);
$help['graph_template'] = dgettext(
'help',
'The optional definition of a graph template will be used as default graph template, when no other is specified.'
);
$help['arg_description'] = dgettext(
'help',
'The argument description provided here will be displayed instead of the technical names like ARGn.'
);
$help['macro_description'] = dgettext(
'help',
'The macro description provided here will be displayed instead of the technical name.'
);
$help['command_comment'] = dgettext('help', 'Comments regarding the command.');
$help['connectors'] = dgettext(
'help',
'Connectors are run in background and execute specific commands without the need to execute a binary, '
. 'thus enhancing performance. This feature is available in Centreon Engine (>= 1.3)'
);
| 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/command/formCommand.php | centreon/www/include/configuration/configObject/command/formCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 $path . 'commandType.php';
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['command_name']);
}
require_once _CENTREON_PATH_ . 'www/include/configuration/configObject/command/javascript/commandJs.php';
const COMMAND_TYPE_CHECK = 2;
const COMMAND_TYPE_MISC = 3;
// Allow type 2 (check) and 3 (miscellaneous) for cloud instance
if (isCloudPlatform() && isset($type) && ($type !== COMMAND_TYPE_CHECK && $type !== COMMAND_TYPE_MISC)) {
$type = COMMAND_TYPE_CHECK;
}
// Database retrieve information for Command
$plugins_list = return_plugin($oreon->optGen['nagios_path_plugins']);
$cmd = [];
$nbRow = '10';
$strArgDesc = '';
if (($o == 'c' || $o == 'w') && $command_id) {
if (isset($lockedElements[$command_id])) {
$o = 'w';
}
$DBRESULT = $pearDB->prepare('SELECT * FROM `command` WHERE `command_id` = :command_id LIMIT 1');
$DBRESULT->bindValue(':command_id', $command_id, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$cmd = array_map('myDecodeCommand', $DBRESULT->fetchRow());
$DBRESULT = $pearDB->prepare('SELECT * FROM `command_arg_description` WHERE `cmd_id` = :command_id');
$DBRESULT->bindValue(':command_id', $command_id, PDO::PARAM_INT);
$DBRESULT->execute();
$strArgDesc = '';
$nbRow = 0;
while ($row = $DBRESULT->fetchRow()) {
$strArgDesc .= $row['macro_name'] . ' : ' . html_entity_decode($row['macro_description']) . "\n";
$nbRow++;
}
}
$oCommande = new CentreonCommand($pearDB);
$aMacroDescription = $oCommande->getMacroDescription($command_id);
$sStrMcro = '';
$nbRowMacro = 0;
if (count($aMacroDescription) > 0) {
foreach ($aMacroDescription as $macro) {
$sStrMcro .= 'MACRO (' . $oCommande->aTypeMacro[$macro['type']] . ') ' . $macro['name'] . ' : '
. $macro['description'] . "\n";
$nbRowMacro++;
}
} elseif ($command_id !== false && array_key_exists('command_line', $cmd)) {
$macrosHostDesc = $oCommande->matchObject($command_id, $cmd['command_line'], '1');
$macrosServiceDesc = $oCommande->matchObject($command_id, $cmd['command_line'], '2');
$aMacroDescription = array_merge($macrosServiceDesc, $macrosHostDesc);
foreach ($aMacroDescription as $macro) {
$sStrMcro .= 'MACRO (' . $oCommande->aTypeMacro[$macro['type']] . ') ' . $macro['name']
. ' : ' . $macro['description'] . "\n";
$nbRowMacro++;
}
}
// Resource Macro
$resource = [];
$query = 'SELECT DISTINCT `resource_name`, `resource_comment` FROM `cfg_resource` ORDER BY `resource_name`';
$DBRESULT = $pearDB->query($query);
while ($row = $DBRESULT->fetchRow()) {
$resource[$row['resource_name']] = $row['resource_name'];
if (isset($row['resource_comment']) && $row['resource_comment'] != '') {
$resource[$row['resource_name']] .= ' (' . $row['resource_comment'] . ')';
}
}
unset($row);
$DBRESULT->closeCursor();
// Connectors
$connectors = [];
$DBRESULT = $pearDB->query("SELECT `id`, `name` FROM `connector` WHERE `enabled` = '1' ORDER BY `name`");
while ($row = $DBRESULT->fetchRow()) {
$connectors[$row['id']] = $row['name'];
}
unset($row);
$DBRESULT->closeCursor();
// Graphs Template comes from DB -> Store in $graphTpls Array
$graphTpls = [null => null];
$DBRESULT = $pearDB->query('SELECT `graph_id`, `name` FROM `giv_graphs_template` ORDER BY `name`');
while ($graphTpl = $DBRESULT->fetchRow()) {
$graphTpls[$graphTpl['graph_id']] = $graphTpl['name'];
}
unset($graphTpl);
$DBRESULT->closeCursor();
// Nagios Macro
$macros = [];
$DBRESULT = $pearDB->query('SELECT `macro_name` FROM `nagios_macro` ORDER BY `macro_name`');
while ($row = $DBRESULT->fetchRow()) {
$macros[$row['macro_name']] = $row['macro_name'];
}
unset($row);
$DBRESULT->closeCursor();
$attrsText = ['size' => '35'];
$attrsTextarea = ['rows' => '9', 'cols' => '80', 'id' => 'command_line'];
$attrsTextarea2 = ['rows' => "{$nbRow}", 'cols' => '100', 'id' => 'listOfArg'];
$attrsTextarea3 = ['rows' => '5', 'cols' => '50', 'id' => 'command_comment'];
$attrsTextarea4 = ['rows' => "{$nbRowMacro}", 'cols' => '100', 'id' => 'listOfMacros'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p . '&type=' . $type);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Command'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Command'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Command'));
}
// Command information
if ($type !== false && isset($tabCommandType[$type]) && $isCloudPlatform === false) {
$form->addElement('header', 'information', $tabCommandType[$type]);
} else {
$form->addElement('header', 'information', _('Information'));
}
$form->addElement('header', 'furtherInfos', _('Additional Information'));
// possibility to change the type of command is only possible out of the Cloud context
if (! $isCloudPlatform) {
foreach ($tabCommandType as $id => $name) {
$cmdType[] = $form->createElement(
'radio',
'command_type',
null,
$name,
$id,
'onChange=checkType(this.value);'
);
}
$form->addGroup($cmdType, 'command_type', _('Command Type'), ' ');
if ($type !== false) {
$form->setDefaults(['command_type' => $type]);
} else {
$form->setDefaults(['command_type' => '2']);
}
}
if (isset($cmd['connector_id']) && is_numeric($cmd['connector_id'])) {
$form->setDefaults(['connectors' => $cmd['connector_id']]);
} else {
$form->setDefaults(['connectors' => '']);
}
$form->addElement('text', 'command_name', _('Command Name'), $attrsText);
$form->addElement('text', 'command_example', _('Argument Example'), $attrsText);
$form->addElement('textarea', 'command_line', _('Command Line'), $attrsTextarea);
$form->addElement('checkbox', 'enable_shell', _('Enable shell'), null, $attrsText);
$form->addElement('textarea', 'listOfArg', _('Argument Descriptions'), $attrsTextarea2)->setAttribute('readonly');
$form->addElement('select', 'graph_id', _('Graph template'), $graphTpls);
$form->addElement('button', 'desc_arg', _('Describe arguments'), ['onClick' => 'goPopup();']);
$form->addElement('button', 'clear_arg', _('Clear arguments'), ['onClick' => 'clearArgs();']);
$form->addElement('textarea', 'command_comment', _('Comment'), $attrsTextarea2);
$form->addElement('button', 'desc_macro', _('Describe macros'), ['onClick' => 'manageMacros();']);
$form->addElement('textarea', 'listOfMacros', _('Macros Descriptions'), $attrsTextarea4)->setAttribute('readonly');
$cmdActivation[] = $form->createElement('radio', 'command_activate', null, _('Enabled'), '1');
$cmdActivation[] = $form->createElement('radio', 'command_activate', null, _('Disabled'), '0');
$form->addGroup($cmdActivation, 'command_activate', _('Status'), ' ');
$form->setDefaults(['command_activate' => '1']);
$form->setDefaults(['listOfArg' => $strArgDesc]);
$form->setDefaults(['listOfMacros' => $sStrMcro]);
$connectors[null] = _('Select a connector...');
$form->addElement('select', 'resource', null, $resource);
$form->addElement('select', 'connectors', _('Connectors'), $connectors);
$form->addElement('select', 'macros', null, $macros);
ksort($plugins_list);
$form->addElement('select', 'plugins', null, $plugins_list);
// Further informations
$form->addElement('hidden', 'command_id');
$redirectType = $form->addElement('hidden', 'type');
$redirectType->setValue($type);
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('command_name', 'myReplace');
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('command_name', _('Compulsory Name'), 'required');
$form->addRule('command_line', _('Compulsory Command Line'), 'required');
$form->registerRule('exist', 'callback', 'testCmdExistence');
$form->addRule('command_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$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);
// Just watch a Command information
if ($o == 'w') {
if ($command_id !== false && $centreon->user->access->page($p) != 2 && ! isset($lockedElements[$command_id])) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p
. '&o=c&command_id=' . $command_id . '&type=' . $type . "'"]
);
}
$form->setDefaults($cmd);
$form->freeze();
} elseif ($o == 'c') {
// Modify a Command information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($cmd);
} elseif ($o == 'a') {
// Add a Command information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('msg', ['comment' => _('Commands definitions can contain Macros but they have to be valid.')]);
$tpl->assign('cmd_help', _('Plugin Help'));
$tpl->assign('is_cloud_platform', $isCloudPlatform);
$valid = false;
$errorMessage = '';
if ($form->validate()) {
try {
$cmdObj = $form->getElement('command_id');
if ($form->getSubmitValue('submitA')) {
$cmdObj->setValue(insertCommandInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateCommandInDB($cmdObj->getValue());
}
$o = null;
$cmdObj = $form->getElement('command_id');
$valid = true;
} catch (Throwable $e) {
$valid = false;
$errorMessage = 'Type of command is undefined';
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: $e->getMessage(),
customContext: ['cmd_id' => $cmdObj->getValue()],
exception: $e
);
}
}
?>
<script type='text/javascript'>
function insertValueQuery(elem) {
var myQuery = document.Form.command_line;
if (elem == 1) {
var myListBox = document.Form.resource;
} else if (elem == 2) {
var myListBox = document.Form.plugins;
} else if (elem == 3) {
var myListBox = document.Form.macros;
}
if (myListBox.options.length > 0) {
var chaineAj = '';
var NbSelect = 0;
for (var i = 0; i < myListBox.options.length; i++) {
if (myListBox.options[i].selected) {
NbSelect++;
if (NbSelect > 1)
chaineAj += ', ';
chaineAj += myListBox.options[i].value;
}
}
if (document.selection) {
// IE support
myQuery.focus();
sel = document.selection.createRange();
sel.text = chaineAj;
document.Form.insert.focus();
} else if (document.Form.command_line.selectionStart ||
document.Form.command_line.selectionStart == '0') {
// MOZILLA/NETSCAPE support
var startPos = document.Form.command_line.selectionStart;
var endPos = document.Form.command_line.selectionEnd;
var chaineSql = document.Form.command_line.value;
myQuery.value =
chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
} else {
myQuery.value += chaineAj;
}
}
}
</script>
<?php
if ($valid) {
require_once $path . 'listCommand.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
if (! empty($errorMessage)) {
$renderer->setErrorTemplate('<font color="red">{$errorMessage}</font><br />{$html}');
} else {
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
}
$form->accept($renderer);
$tpl->assign('errorMessage', $errorMessage);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('macro_desc_label', _('Macros Descriptions'));
if (! $isCloudPlatform) {
$tpl->assign('arg_desc_label', _('Argument Descriptions'));
$tpl->display('formCommandOnPrem.ihtml');
} else {
$tpl->display('formCommandCloud.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/configObject/command/commandType.php | centreon/www/include/configuration/configObject/command/commandType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$tabCommandType = [];
$tabCommandType[1] = _('Notification');
$tabCommandType[2] = _('Check');
$tabCommandType[3] = _('Misc');
$tabCommandType[4] = _('Discovery');
| 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/command/DB-Func.php | centreon/www/include/configuration/configObject/command/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\ActionLog\Domain\Model\ActionLog;
if (! isset($centreon)) {
exit();
}
if (! function_exists('myDecodeCommand')) {
function myDecodeCommand($arg)
{
$arg = str_replace('#BR#', '\\n', $arg ?? '');
$arg = str_replace('#T#', '\\t', $arg);
$arg = str_replace('#R#', '\\r', $arg);
$arg = str_replace('#S#', '/', $arg);
$arg = str_replace('#BS#', '\\', $arg);
$arg = str_replace('#P#', '|', $arg);
return html_entity_decode($arg);
}
}
function getCommandName($command_id)
{
global $pearDB;
$query = 'SELECT `command_name` FROM `command` WHERE `command_id` = ' . $pearDB->escape($command_id);
$dbResult = $pearDB->query($query);
$command = $dbResult->fetch();
return $command['command_name'] ?? null;
}
function testCmdExistence($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('command_id');
}
$query = "SELECT `command_name`, `command_id` FROM `command` WHERE `command_name` = '"
. $pearDB->escape($centreon->checkIllegalChar($name)) . "'";
$dbResult = $pearDB->query($query);
$command = $dbResult->fetch();
if ($dbResult->rowCount() >= 1 && $command['command_id'] == $id) {
// Mofication case
return true;
}
return ! ($dbResult->rowCount() >= 1 && $command['command_id'] != $id);
// Duplicate case
}
function deleteCommandInDB($commands = [])
{
global $pearDB, $centreon;
foreach ($commands as $key => $value) {
$query = "SELECT command_name FROM `command` WHERE `command_id` = '" . (int) $key . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
$pearDB->query("DELETE FROM `command` WHERE `command_id` = '" . (int) $key . "'");
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $key,
object_name: $row['command_name'],
action_type: ActionLog::ACTION_TYPE_DELETE
);
}
}
function multipleCommandInDB($commands = [], $nbrDup = [])
{
global $pearDB, $centreon;
foreach ($commands as $key => $value) {
$dbResult = $pearDB->query("SELECT * FROM `command` WHERE `command_id` = '" . (int) $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['command_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
$key2 == 'command_name' ? ($command_name = $value2 = $value2 . '_' . $i) : null;
if ($key2 == 'command_locked') {
$value2 = '0'; // Duplicate a locked command to edit it
}
$val ? $val .= ($value2 != null ? (", '" . $pearDB->escape($value2) . "'")
: ', NULL') : $val .= ($value2 != null ? ("'" . $pearDB->escape($value2) . "'") : 'NULL');
if ($key2 != 'command_id') {
$fields[$key2] = $pearDB->escape($value2);
}
if (isset($command_name)) {
$fields['command_name'] = $command_name;
}
$fields['command_locked'] = 0;
}
if (isset($command_name) && testCmdExistence($command_name)) {
$rq = $val ? 'INSERT INTO `command` VALUES (' . $val . ')' : null;
$dbResult = $pearDB->query($rq);
// Get Max ID
$dbResult = $pearDB->query('SELECT MAX(command_id) FROM `command`');
$cmd_id = $dbResult->fetch();
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $cmd_id['MAX(command_id)'],
object_name: $command_name,
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
// Duplicate Arguments
duplicateArgDesc($cmd_id['MAX(command_id)'], $key);
}
}
}
}
function updateCommandInDB($cmd_id = null)
{
if (! $cmd_id) {
return;
}
updateCommand($cmd_id);
}
/**
* @param $cmd_id
* @param $params
*
* @throws PDOException
* @throws UnexpectedValueException
* @return void
*/
function updateCommand($cmd_id = null, $params = [])
{
global $form, $pearDB, $centreon, $isCloudPlatform;
if (! $cmd_id) {
return;
}
$ret = [];
$ret = count($params) ? $params : $form->getSubmitValues();
$ret['command_name'] = $centreon->checkIllegalChar($ret['command_name']);
if (! isset($ret['enable_shell'])) {
$ret['enable_shell'] = 0;
}
$rq = 'UPDATE `command` SET `command_name` = :command_name, '
. '`command_line` = :command_line, '
. '`enable_shell` = :enable_shell, '
. '`command_example` = :command_example, '
. '`command_type` = :command_type, '
. '`command_comment` = :command_comment, '
. '`graph_id` = :graph_id, '
. '`connector_id` = :connector_id, '
. '`command_activate` = :command_activate '
. 'WHERE `command_id` = :command_id';
$ret['connectors'] = (isset($ret['connectors']) && ! empty($ret['connectors'])) ? $ret['connectors'] : null;
$ret['command_activate']['command_activate'] ??= null;
if (
($isCloudPlatform && ! isset($ret['type']))
|| (! $isCloudPlatform && ! isset($ret['command_type']) && ! isset($ret['command_type']['command_type']))
) {
throw new UnexpectedValueException('command type is undefined');
}
$type = $isCloudPlatform ? $ret['type'] : $ret['command_type']['command_type'];
$sth = $pearDB->prepare($rq);
$sth->bindParam(':command_name', $ret['command_name'], PDO::PARAM_STR);
$sth->bindParam(':command_line', $ret['command_line'], PDO::PARAM_STR);
$sth->bindParam(':enable_shell', $ret['enable_shell'], PDO::PARAM_INT);
$sth->bindParam(':command_example', $ret['command_example'], PDO::PARAM_STR);
$sth->bindParam(':command_type', $type, PDO::PARAM_INT);
$sth->bindParam(':command_comment', $ret['command_comment'], PDO::PARAM_STR);
$sth->bindParam(':graph_id', $ret['graph_id'], PDO::PARAM_INT);
$sth->bindParam(':connector_id', $ret['connectors'], PDO::PARAM_INT);
$sth->bindParam(':command_activate', $ret['command_activate']['command_activate'], PDO::PARAM_STR);
$sth->bindParam(':command_id', $cmd_id, PDO::PARAM_INT);
$sth->execute();
insertArgDesc($cmd_id, $ret);
insertMacrosDesc($cmd_id, $ret);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $cmd_id,
object_name: $ret['command_name'],
action_type: ActionLog::ACTION_TYPE_CHANGE,
fields: $fields
);
}
function insertCommandInDB($ret = [])
{
return insertCommand($ret);
}
function insertCommand($ret = [])
{
global $form, $pearDB, $centreon, $isCloudPlatform;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$ret['command_name'] = $centreon->checkIllegalChar($ret['command_name']);
if (! isset($ret['enable_shell'])) {
$ret['enable_shell'] = 0;
}
$commandType = $isCloudPlatform ? $ret['type'] : $ret['command_type']['command_type'];
// Insert
$rq = 'INSERT INTO `command` (`command_name`, `command_line`, `enable_shell`, `command_example`, `command_type`,
`graph_id`, `connector_id`, `command_comment`, `command_activate`) ';
$rq .= "VALUES (
'" . $pearDB->escape($ret['command_name']) . "',
'" . $pearDB->escape($ret['command_line']) . "',
" . (int) $ret['enable_shell'] . ",
'" . $pearDB->escape($ret['command_example']) . "',
" . (int) $commandType . ',
' . (! empty($ret['graph_id']) ? (int) $ret['graph_id'] : 'NULL') . ',
' . (! empty($ret['connectors']) ? (int) $ret['connectors'] : 'NULL') . ",
'" . $pearDB->escape($ret['command_comment']) . "',
'" . $pearDB->escape($ret['command_activate']['command_activate']) . "'";
$rq .= ')';
$pearDB->query($rq);
// Get Max ID
$max_id = getMaxID();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $max_id,
object_name: $ret['command_name'],
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
insertArgDesc($max_id, $ret);
insertMacrosDesc($max_id, $ret);
return $max_id;
}
function getMaxID()
{
global $pearDB;
$dbResult = $pearDB->query('SELECT MAX(command_id) FROM `command`');
$row = $dbResult->fetch();
return $row['MAX(command_id)'];
}
function return_plugin($rep)
{
global $centreon;
$plugins = [];
$is_not_a_plugin = ['.' => 1, '..' => 1, 'oreon.conf' => 1, 'oreon.pm' => 1, 'utils.pm' => 1, 'negate' => 1, 'centreon.conf' => 1, 'centreon.pm' => 1];
$handle[$rep] = opendir($rep);
while (false != ($filename = readdir($handle[$rep]))) {
if ($filename != '.' && $filename != '..') {
if (is_dir($rep . $filename)) {
$plg_tmp = return_plugin($rep . '/' . $filename);
$plugins = array_merge($plugins, $plg_tmp);
unset($plg_tmp);
} elseif (! isset($is_not_a_plugin[$filename])
&& ! str_ends_with($filename, '~')
&& ! str_ends_with($filename, '#')
) {
$key = substr($rep . '/' . $filename, strlen($centreon->optGen['nagios_path_plugins']));
$plugins[$key] = $key;
}
}
}
closedir($handle[$rep]);
return $plugins;
}
// Inserts descriptions of arguments
function insertArgDesc($cmd_id, $ret = null)
{
global $pearDB;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$pearDB->query("DELETE FROM `command_arg_description` WHERE cmd_id = '" . (int) $cmd_id . "'");
$query = 'INSERT INTO `command_arg_description` (cmd_id, macro_name, macro_description) VALUES ';
if (isset($ret['listOfArg']) && $ret['listOfArg']) {
$tab1 = preg_split('/\\n/', $ret['listOfArg']);
foreach ($tab1 as $key => $value) {
$tab2 = preg_split("/\ \:\ /", $value, 2);
$query .= "('" . $pearDB->escape($cmd_id) . "', '" . $pearDB->escape($tab2[0]) . "', '"
. $pearDB->escape($tab2[1]) . "'),";
}
$query = trim($query, ',');
$pearDB->query($query);
}
}
/**
* Duplicate The argument description of a command
* @param $cmd_id
* @param $ret
* @param mixed $new_cmd_id
* @return unknown_type
*/
function duplicateArgDesc($new_cmd_id, $cmd_id)
{
global $pearDB;
$query = "INSERT INTO `command_arg_description` (cmd_id, macro_name, macro_description)
SELECT '" . (int) $new_cmd_id . "', macro_name, macro_description
FROM command_arg_description WHERE cmd_id = '" . (int) $cmd_id . "'";
$pearDB->query($query);
}
/**
* Return the number of time a command is used as a host command check
* @param $command_id
* @return unknown_type
*/
function getHostNumberUse($command_id)
{
global $pearDB;
$query = 'SELECT count(*) AS number FROM host '
. "WHERE command_command_id = '" . (int) $command_id . "' AND host_register = '1'";
$dbResult = $pearDB->query($query);
$data = $dbResult->fetch();
return $data['number'];
}
/**
* Return the number of time a command is used as a service command check
* @param $command_id
* @return unknown_type
*/
function getServiceNumberUse($command_id)
{
global $pearDB;
$query = 'SELECT count(*) AS number FROM service '
. "WHERE command_command_id = '" . (int) $command_id . "' AND service_register = '1'";
$dbResult = $pearDB->query($query);
$data = $dbResult->fetch();
return $data['number'];
}
/**
* Return the number of time a command is used as a host command check
* @param $command_id
* @return unknown_type
*/
function getHostTPLNumberUse($command_id)
{
global $pearDB;
$query = 'SELECT count(*) AS number FROM host '
. "WHERE command_command_id = '" . (int) $command_id . "' AND host_register = '0'";
$dbResult = $pearDB->query($query);
$data = $dbResult->fetch();
return $data['number'];
}
/**
* Return the number of time a command is used as a service command check
* @param $command_id
* @return unknown_type
*/
function getServiceTPLNumberUse($command_id)
{
global $pearDB;
$query = 'SELECT count(*) AS number FROM service '
. "WHERE command_command_id = '" . (int) $command_id . "' AND service_register = '0'";
$dbResult = $pearDB->query($query);
$data = $dbResult->fetch();
return $data['number'];
}
/**
* Get command ID by name
*
* @param string $name
* @return int
*/
function getCommandIdByName($name)
{
global $pearDB;
$id = 0;
$res = $pearDB->query("SELECT command_id FROM command WHERE command_name = '" . $pearDB->escape($name) . "'");
if ($res->rowCount()) {
$row = $res->fetch();
$id = $row['command_id'];
}
return $id;
}
/**
* Inserts descriptions of macros rattached to the command
*
* @global type $pearDB
* @param type $cmd
* @param type $ret
*/
function insertMacrosDesc($cmd, $ret)
{
global $pearDB;
$arr = ['HOST' => '1', 'SERVICE' => '2'];
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
if (isset($ret['listOfMacros']) && $ret['listOfMacros']) {
$tab1 = preg_split('/\\n/', $ret['listOfMacros']);
$query = 'DELETE FROM `on_demand_macro_command`
WHERE `command_command_id` = ' . (int) $cmd;
$pearDB->query($query);
foreach ($tab1 as $key => $value) {
$tab2 = preg_split("/\ \:\ /", $value, 2);
$str = trim(substr($tab2[0], 6));
$sDesc = trim(str_replace("\r", '', $tab2[1] ?? ''));
$pos = strpos($str, ')');
if ($pos > 0) {
$sType = substr($str, 1, $pos - 1);
$sName = trim(substr($str, $pos + 1));
} else {
$sType = '1';
$sName = trim($str);
}
if (! empty($sName)) {
$sQueryInsert = 'INSERT INTO `on_demand_macro_command`
(`command_command_id`, `command_macro_name`, `command_macro_desciption`, `command_macro_type`)
VALUES (' . (int) $cmd . ",
'" . $pearDB->escape($sName) . "',
'" . $pearDB->escape($sDesc) . "',
'" . $arr[$sType] . "')";
$pearDB->query($sQueryInsert);
}
}
}
}
/**
* Change status command
*
* @param ini $command_id
* @param array $commands
* @param int $status
*/
function changeCommandStatus($command_id, $commands, $status)
{
global $pearDB, $centreon;
if (isset($command_id)) {
$query = "UPDATE `command` SET command_activate = '" . $pearDB->escape($status) . "' "
. "WHERE command_id = '" . $pearDB->escape($command_id) . "'";
$pearDB->query($query);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $command_id,
object_name: getCommandName($command_id),
action_type: $status ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE
);
} else {
foreach ($commands as $command_id => $flag) {
if (isset($command_id) && $command_id) {
$query = "UPDATE `command` SET command_activate = '" . $pearDB->escape($status) . "' "
. "WHERE command_id = '" . $pearDB->escape($command_id) . "'";
$pearDB->query($query);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_COMMAND,
object_id: $command_id,
object_name: getCommandName($command_id),
action_type: $status ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE
);
}
}
}
}
| 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/command/command.php | centreon/www/include/configuration/configObject/command/command.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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/configuration/configObject/command/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$command_id = filter_var(
$_GET['command_id'] ?? $_POST['command_id'] ?? null,
FILTER_VALIDATE_INT
);
$type = filter_var(
$_POST['command_type']['command_type'] ?? $_GET['type'] ?? $_POST['type'] ?? 2,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] != '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] != '') {
$o = $_POST['o2'];
}
}
// For inline action
if (($o === 'm' || $o === 'd') && count($select) == 0 && $command_id) {
$select[$command_id] = 1;
}
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$commandObj = new CentreonCommand($pearDB);
$lockedElements = $commandObj->getLockedCommands();
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
if ($min) {
switch ($o) {
case 'h': // Show Help Command
default:
require_once $path . 'minHelpCommand.php';
break;
}
} else {
switch ($o) {
case 'a': // Add a Command
case 'w': // Watch a Command
case 'c': // Modify a Command
require_once $path . 'formCommand.php';
break;
case 'm': // Duplicate n Commands
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleCommandInDB(
is_array($select) ? $select : [],
$select
);
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
case 'd': // Delete n Commands
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteCommandInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
case 'me':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
changeCommandStatus(null, is_array($select) ? $select : [], 1);
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
case 'md':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
changeCommandStatus(null, is_array($select) ? $select : [], 0);
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
case 'en':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($command_id !== false) {
changeCommandStatus($command_id, null, 1);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
case 'di':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($command_id !== false) {
changeCommandStatus($command_id, null, 0);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listCommand.php';
break;
default:
require_once $path . 'listCommand.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/command/formArguments.php | centreon/www/include/configuration/configObject/command/formArguments.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';
require_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php';
require_once _CENTREON_PATH_ . 'bootstrap.php';
session_start();
session_write_close();
$centreon = $_SESSION['centreon'];
if (! isset($centreon)) {
exit();
}
$centreonLang = new CentreonLang(_CENTREON_PATH_, $centreon);
$centreonLang->bindLang();
$args = [];
$str = '';
$nb_arg = 0;
if (isset($_GET['cmd_line']) && $_GET['cmd_line']) {
$str = str_replace('$', '@DOLLAR@', $_GET['cmd_line']);
$nb_arg = preg_match_all('/@DOLLAR@ARG([0-9]+)@DOLLAR@/', $str, $matches);
}
if (isset($_GET['textArea']) && $_GET['textArea']) {
$textArea = urldecode($_GET['textArea']);
$tab = preg_split("/\;\;\;/", $textArea);
foreach ($tab as $key => $value) {
$tab2 = preg_split("/\ \:\ /", $value, 2);
$index = str_replace('ARG', '', $tab2[0]);
if (isset($tab2[0]) && $tab2[0]) {
$args[$index] = htmlentities($tab2[1]);
}
}
}
// FORM
$path = _CENTREON_PATH_ . '/www/include/configuration/configObject/command/';
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '60'];
$attrsAdvSelect = ['style' => 'width: 200px; height: 100px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
// Basic info
$form = new HTML_QuickFormCustom('Form', 'post');
$form->addElement('header', 'title', _('Argument Descriptions'));
$form->addElement('header', 'information', _('Arguments'));
$subS = $form->addElement(
'button',
'submitSaveAdd',
_('Save'),
['onClick' => 'setDescriptions();', 'class' => 'btc bt_success']
);
$subS = $form->addElement(
'button',
'close',
_('Close'),
['onClick' => 'closeBox();', 'class' => 'btc bt_default']
);
// Smarty template
$tpl = new SmartyBC();
$tpl->setTemplateDir($path);
$tpl->setCompileDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/compile');
$tpl->setConfigDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/config');
$tpl->setCacheDir(_CENTREON_PATH_ . '/GPL_LIB/SmartyCache/cache');
$tpl->addPluginsDir(_CENTREON_PATH_ . '/GPL_LIB/smarty-plugins');
$tpl->loadPlugin('smarty_function_eval');
$tpl->setForceCompile(true);
$tpl->setAutoLiteral(false);
$tpl->assign('nb_arg', $nb_arg);
$dummyTab = [];
$defaultDesc = [];
for ($i = 1; $i <= $nb_arg; $i++) {
$dummyTab[$i] = $matches[1][$i - 1];
$defaultDesc[$i] = '';
if (isset($args[$dummyTab[$i]]) && $args[$dummyTab[$i]]) {
$defaultDesc[$i] = $args[$dummyTab[$i]];
}
}
$tpl->assign('dummyTab', $dummyTab);
$tpl->assign('defaultDesc', $defaultDesc);
$tpl->assign('noArgMsg', _('Sorry, your command line does not contain any $ARGn$ macro.'));
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <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('args', $args);
$tpl->display('formArguments.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.