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/php-tools/phpstan/src/CustomRules/CentreonRuleTrait.php | php-tools/phpstan/src/CustomRules/CentreonRuleTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules;
use PHPStan\Reflection\ReflectionProvider;
/**
* This trait implements checkIfInUseCase method to check if a file is
* a Use Case.
*/
trait CentreonRuleTrait
{
public function __construct(private ReflectionProvider $reflectionProvider)
{
}
/**
* Tells whether the class FQCN extends an Exception.
*/
private function extendsAnException(?string $classFqcn): bool
{
return ! empty($classFqcn)
&& $this->reflectionProvider->hasClass($classFqcn)
&& $this->reflectionProvider->getClass($classFqcn)
->isSubclassOf(\Exception::class);
}
/**
* Tells whether the class short name or FQCN is valid for a Repository.
*
* @return null|non-empty-string
*/
private function getRepositoryName(string $className): ?string
{
return preg_match('/(?:^|\\\\)([A-Z][a-zA-Z0-9]+)Repository$/', $className, $matches) === 1
? $matches[1] : null;
}
/**
* Tells whether the class short name or FQCN is valid for a Repository Interface.
*
* @return null|non-empty-string
*/
private function getRepositoryInterfaceName(string $className): ?string
{
return preg_match('/(?:^|\\\\)([A-Z][a-zA-Z0-9]+)RepositoryInterface$/', $className, $matches) === 1
? $matches[1] : null;
}
/**
* This method checks if a file is a Use Case.
*/
private function fileIsUseCase(string $filename): bool
{
$slash = '[/\\\\]';
$cleanFilename = preg_replace("#^.*{$slash}(\w+)\.php$#", '$1', $filename);
if (is_null($cleanFilename)) {
return false;
}
$useCase = preg_quote($cleanFilename, '#');
$pattern = '#'
. "{$slash}UseCase"
. "{$slash}(\w+{$slash})*{$useCase}"
. "{$slash}{$useCase}\.php"
. '$#';
return (bool) preg_match($pattern, $filename);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/MiscRules/StringBackquotesCustomRule.php | php-tools/phpstan/src/CustomRules/MiscRules/StringBackquotesCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\MiscRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
/**
* This class implements custom rule for PHPStan to check if variable :db or :dbstg
* are enclosed in backquotes.
*
* @implements Rule<Node\Scalar\String_>
*/
class StringBackquotesCustomRule implements Rule
{
public const CENTREON_CONFIG_DATABASE = ':db';
public const CENTREON_REALTIME_DATABASE = ':dbstg';
private const REGEX = '/(' . self::CENTREON_REALTIME_DATABASE . '|' . self::CENTREON_CONFIG_DATABASE . ')\./';
public function getNodeType(): string
{
return Node\Scalar\String_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if (
! preg_match_all(self::REGEX, $node->value, $matches)
|| empty($matches[1])
) {
return [];
}
// Check rule.
// $matches[0] = [':dbstg.',':db.']
// $matches[1] = [':dbstg',':db']
$errors = [];
foreach ($matches[1] as $match) {
$errors[] = CentreonRuleErrorBuilder::message('(StringBackquotesCustomRule)' . $match . ' must be enclosed in backquotes.')->build();
}
return $errors;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/MiscRules/VariableLengthCustomRule.php | php-tools/phpstan/src/CustomRules/MiscRules/VariableLengthCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\MiscRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
/**
* This class implements custom rule for PHPStan to check if variable name contains more
* than 3 characters.
*
* @implements Rule<Node>
*/
class VariableLengthCustomRule implements Rule
{
/**
* This constant contains an array of variable names to whitelist by custom rule.
*/
private const EXEMPTION_LIST = [
'db', // Database
'ex', // Exception
'id', // Identifier
'e', // Exception
'th', // Throwable
'qb', // Query Builder
'io', // Input Output
];
public function getNodeType(): string
{
return Node::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
$varName = $this->getVariableNameFromNode($node);
// This rule does not apply.
if ($varName === null || in_array($varName, self::EXEMPTION_LIST, true)) {
return [];
}
// Check rule.
if (mb_strlen($varName) < 3) {
return [
CentreonRuleErrorBuilder::message("(VariableLengthCustomRule) {$varName} must contain 3 or more characters.")->build(),
];
}
return [];
}
/**
* This method returns variable name from a scanned node if the node refers to
* variable/property/parameter.
*/
private function getVariableNameFromNode(Node $node): ?string
{
// FIXME Although PHPStan\Node\ClassPropertyNode is covered by backward compatibility promise, this instanceof assumption might break because it's not guaranteed to always stay the same.
// https://phpstan.org/developing-extensions/backward-compatibility-promise
if ($node instanceof \PHPStan\Node\ClassPropertyNode) {
return $node->getName();
}
return match (true) {
$node instanceof Node\Expr\PropertyFetch => is_string($node->name->name ?? null) ? $node->name->name : null,
$node instanceof Node\Expr\Variable => is_string($node->name) ? $node->name : null,
$node instanceof Node\Param => is_string($node->var->name ?? null) ? $node->var->name : null,
default => null,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/MiscRules/CommandHandlerCannotUseCommandBus.php | php-tools/phpstan/src/CustomRules/MiscRules/CommandHandlerCannotUseCommandBus.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\MiscRules;
use App\Shared\Application\Command\AsCommandHandler;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Class_>
*/
final readonly class CommandHandlerCannotUseCommandBus implements Rule
{
public function __construct(
private ReflectionProvider $reflectionProvider,
) {
}
public function getNodeType(): string
{
return Class_::class;
}
/**
* @param Class_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
$reflection = $this->reflectionProvider->getClass((string) $node->namespacedName)->getNativeReflection();
if (! $reflection->getAttributes(AsCommandHandler::class)) {
return [];
}
if (! $constructor = $node->getMethod('__construct')) {
return [];
}
foreach ($constructor->getParams() as $param) {
if (($param->type instanceof Identifier || $param->type instanceof Name) && $param->type->toString() === 'App\Shared\Application\Command\CommandBus') {
return [
RuleErrorBuilder::message('A command handler class cannot use command bus.')
->identifier('command.handler.bus')
->build(),
];
}
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/MiscRules/MarkedClassesHaveTestRule.php | php-tools/phpstan/src/CustomRules/MiscRules/MarkedClassesHaveTestRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\MiscRules;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Class_>
*/
final readonly class MarkedClassesHaveTestRule implements Rule
{
/**
* @param list<class-string> $attributes
* @param list<class-string> $classes
*/
public function __construct(
private ReflectionProvider $reflectionProvider,
private array $attributes = [],
private array $classes = [],
) {
}
public function getNodeType(): string
{
return Class_::class;
}
/**
* @param Class_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
$reflection = $this->reflectionProvider->getClass((string) $node->namespacedName);
if (! $this->isEligible($reflection)) {
return [];
}
$parts = explode('src', $scope->getFile());
$projectPath = trim($parts[0], '/');
$pathFromProject = trim($parts[1], '/');
$classUnderTestPath = \sprintf('/%s/tests/php/%s', $projectPath, $pathFromProject);
$classUnderTestPath = str_replace(
['.php'],
['Test.php'],
$classUnderTestPath,
);
$pathFromTest = \sprintf(
'tests/%s',
ltrim(explode('tests', $classUnderTestPath)[1], '/'),
);
if (file_exists($classUnderTestPath)) {
return [];
}
return [
RuleErrorBuilder::message(\sprintf('The test class %s is missing', $pathFromTest))
->identifier('test.class')
->build(),
];
}
private function isEligible(ClassReflection $reflection): bool
{
foreach ($this->attributes as $attribute) {
if ($reflection->getNativeReflection()->getAttributes($attribute)) {
return true;
}
}
foreach ($this->classes as $class) {
if (! $reflection->isAbstract() && ($reflection->getName() === $class || $reflection->isSubclassOfClass($this->reflectionProvider->getClass($class)))) {
return true;
}
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/Collectors/UseUseCollector.php | php-tools/phpstan/src/CustomRules/Collectors/UseUseCollector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\Collectors;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Collectors\Collector;
/**
* This class implements Collector interface to collect the information about
* 'uses' in codebase.
*
* @implements Collector<Node\UseItem, array{int, string}>
*/
class UseUseCollector implements Collector
{
public function getNodeType(): string
{
return Node\UseItem::class;
}
public function processNode(Node $node, Scope $scope): ?array
{
return [$node->getLine(), (string) $node->name];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/Collectors/MethodCallCollector.php | php-tools/phpstan/src/CustomRules/Collectors/MethodCallCollector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\Collectors;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Collectors\Collector;
/**
* This class implements Collector interface to collect the information about
* method calls in UseCases.
*
* @implements Collector<Node\Expr\MethodCall, string>
*/
class MethodCallCollector implements Collector
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
public function processNode(Node $node, Scope $scope): ?string
{
$name = $node->name->name ?? null;
return is_string($name) ? $name : null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryNameCustomRule.php | php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryNameCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\RepositoryRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\CentreonRuleTrait;
/**
* This class implements a custom rule for PHPStan to check Repository naming requirement
* it must start with data storage prefix, followed by action and context mentions, and finish
* by 'Repository' mention.
*
* @implements Rule<Node\Stmt\Class_>
*/
class RepositoryNameCustomRule implements Rule
{
use CentreonRuleTrait;
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if (
! str_contains($node->name->name ?? '', 'Repository')
|| $this->extendsAnException($node->namespacedName?->toCodeString())
) {
return [];
}
// Rule check.
if (! is_null($this->getRepositoryName($node->name->name ?? ''))) {
return [];
}
return [
CentreonRuleErrorBuilder::message(
"(RepositoryNameCustomRule) Repository name must start with data storage prefix (i.e. 'Db', 'Redis', etc.), "
. "which may be followed by 'Read' or 'Write' and context mention."
)->build(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryImplementsInterfaceCustomRule.php | php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryImplementsInterfaceCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\RepositoryRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\CentreonRuleTrait;
/**
* This class implements a custom rule for PHPStan to check if a Repository implements
* an Interface defined in Application layer.
*
* @implements Rule<Node\Stmt\Class_>
*/
class RepositoryImplementsInterfaceCustomRule implements Rule
{
use CentreonRuleTrait;
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if (
! str_contains($node->name->name ?? '', 'Repository')
|| $node->implements === []
|| $node->isAbstract()
|| $this->extendsAnException($node->namespacedName?->toCodeString())
) {
return [];
}
// Check rule.
foreach ($node->implements as $implementation) {
if (str_contains($implementation->toString(), '\\Application\\')) {
return [];
}
}
return [
CentreonRuleErrorBuilder::message(
'(RepositoryImplementsInterfaceCustomRule) Repositories must implement an Interface defined in Application layer.'
)->build(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryInterfaceNameCustomRule.php | php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryInterfaceNameCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\RepositoryRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\CentreonRuleTrait;
/**
* This class implements a custom rule for PHPStan to check Interface naming requirement.
* It must start with 'Read' or 'Write' mentions and end with 'RepositoryInterface'.
*
* @implements Rule<Node\Stmt\Class_>
*/
class RepositoryInterfaceNameCustomRule implements Rule
{
use CentreonRuleTrait;
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if (
! str_contains($node->name->name ?? '', 'Repository')
|| $node->implements === []
) {
return [];
}
// Rule check.
// If there's no implementation of RepositoryInterface,
// it's RepositoryImplementsInterfaceCustomRule that will return an error.
foreach ($node->implements as $implementation) {
if (! is_null($this->getRepositoryInterfaceName($implementation->toString()))) {
return [];
}
}
return [
CentreonRuleErrorBuilder::message(
"(RepositoryInterfaceNameCustomRule) At least one Interface name must start with 'Read' or 'Write' and end with 'RepositoryInterface'."
)->build(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryNameValidationByInterfaceCustomRule.php | php-tools/phpstan/src/CustomRules/RepositoryRules/RepositoryNameValidationByInterfaceCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\RepositoryRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\CentreonRuleTrait;
/**
* This class implements a custom rule for PHPStan to check Repository naming requirement.
* It must match the implemented Interface name except for data storage prefix
* (in Repository name) and Interface mention (in Interface name).
*
* @implements Rule<Node\Stmt\Class_>
*/
class RepositoryNameValidationByInterfaceCustomRule implements Rule
{
use CentreonRuleTrait;
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if (
! str_contains($node->name->name ?? '', 'Repository')
|| $node->implements === []
) {
return [];
}
// Rule check.
// If there's no implementation of RepositoryInterface,
// it's RepositoryImplementsInterfaceCustomRule that will return an error.
foreach ($node->implements as $implementation) {
$repositoryName = $this->getRepositoryName($node->name->name ?? '');
$interfaceName = $this->getRepositoryInterfaceName($implementation->toString());
if (! is_null($repositoryName) && ! is_null($interfaceName) && str_contains($repositoryName, $interfaceName)) {
return [];
}
}
return [
CentreonRuleErrorBuilder::message(
'(RepositoryNameValidationByInterfaceCustomRule) Repository name should match the implemented Interface name with exception of data storage prefix '
. "and 'Interface' mention."
)->tip(
"For example, Repository name: 'DbReadSessionRepository' and implemented Interface name: "
. "'ReadSessionRepositoryInterface'."
)->build(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/ExceptionInUseCaseCustomRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/ExceptionInUseCaseCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
//
// namespace Tools\PhpStan\CustomRules\ArchitectureRules;
//
// use PhpParser\Node;
// use PhpParser\Node\Stmt\Class_;
// use PhpParser\Node\Stmt\ClassMethod;
// use PhpParser\Node\Stmt\Throw_;
// use PhpParser\Node\Stmt\TryCatch;
// use PHPStan\Analyser\Scope;
// use PHPStan\Rules\Rule;
// use PHPStan\Rules\RuleError;
// use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
// use Tools\PhpStan\CustomRules\CentreonRuleTrait;
//
// /**
// * This class implements a custom rule for PHPStan to check if thrown Exception is in
// * try/catch block and if it is caught.
// *
// * @implements Rule<Node\Stmt\Throw_>
// */
// class ExceptionInUseCaseCustomRule implements Rule
// {
// use CentreonRuleTrait;
//
// public function getNodeType(): string
// {
// return Throw_::class;
// }
//
// public function processNode(Node $node, Scope $scope): array
// {
// // Check if file is UseCase
// if (
// ! $this->fileIsUseCase($scope->getFile())
// || $this->getParentClassMethod($node)->name->name === '__construct'
// || $this->getParentClassMethod($node)->isPrivate() === true
// ) {
// return [];
// }
//
// // check if Exception class is not null and get string representation of Exception class
// $exceptionThrown = ($node->expr->class ?? null) ? $node->expr->class->toCodeString() : '';
// $parentTryCatchNodes = $this->getAllParentTryCatchNodes($node);
// $caughtExceptionTypes = $this->getCaughtExceptionTypes($parentTryCatchNodes);
//
// if ($parentTryCatchNodes === []) {
// return [
// $this->getCentreonCustomExceptionError(),
// ];
// }
//
// foreach ($caughtExceptionTypes as $caughtExceptionType) {
// if (is_a($exceptionThrown, $caughtExceptionType, true)) {
// return [];
// }
// }
//
// return [
// $this->getCentreonCustomExceptionError(),
// ];
// }
//
// /**
// * This method returns the parent ClassMethod node.
// *
// * @param Throw_ $node
// *
// * @return ClassMethod
// */
// private function getParentClassMethod(Throw_ $node): ClassMethod
// {
// while (! $node->getAttribute('parent') instanceof Class_) {
// $node = $node->getAttribute('parent');
// }
//
// return $node;
// }
//
// /**
// * This method gets all the parent TryCatch nodes of a give node and
// * stores then in array.
// *
// * @param Node $node
// *
// * @return TryCatch[]
// */
// private function getAllParentTryCatchNodes(Node $node): array
// {
// $parentTryCatchNodes = [];
// while (! $node->getAttribute('parent') instanceof ClassMethod) {
// if ($node->getAttribute('parent') instanceof TryCatch) {
// $parentTryCatchNodes[] = $node->getAttribute('parent');
// }
// $node = $node->getAttribute('parent');
// }
//
// return $parentTryCatchNodes;
// }
//
// /**
// * This method return an array of Exception types caught in all TryCatch nodes.
// *
// * @param TryCatch[] $parentTryCatchNodes
// *
// * @return string[]
// */
// private function getCaughtExceptionTypes(array $parentTryCatchNodes): array
// {
// $caughtExceptionTypes = [];
// foreach ($parentTryCatchNodes as $parentTryCatchNode) {
// foreach ($parentTryCatchNode->catches as $catch) {
// foreach ($catch->types as $type) {
// $caughtExceptionTypes[] = $type->toCodeString();
// }
// }
// }
//
// return $caughtExceptionTypes;
// }
//
// /**
// * This method returns Centreon Custom error for Exception Custom Rule.
// *
// * @return RuleError
// */
// private function getCentreonCustomExceptionError(): RuleError
// {
// return CentreonRuleErrorBuilder::message(
// '(ExceptionInUseCaseCustomRule) Exception thrown in UseCase should be in a try catch block, and must be caught.'
// )->build();
// }
// }
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/MarkedClassesAreOnlyInvokableRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/MarkedClassesAreOnlyInvokableRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\ArchitectureRules;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Class_>
*/
final readonly class MarkedClassesAreOnlyInvokableRule implements Rule
{
/**
* @param list<class-string> $attributes
* @param list<class-string> $classes
*/
public function __construct(
private ReflectionProvider $reflectionProvider,
private array $attributes = [],
private array $classes = [],
) {
}
public function getNodeType(): string
{
return Class_::class;
}
/**
* @param Class_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
$className = (string) $node->namespacedName;
$reflection = $this->reflectionProvider->getClass($className);
if (! $this->isEligible($reflection)) {
return [];
}
$errors = [];
$hasInvokableMethod = (bool) array_filter(
$node->getMethods(),
static fn (ClassMethod $method): bool => $method->isPublic() && (string) $method->name !== '__invoke',
);
if (! $hasInvokableMethod) {
$errors[] = RuleErrorBuilder::message(\sprintf('The class %s must have "__invoke" method', $className))
->identifier('invokable.missing')
->build();
}
$extraPublicMethodsCount = \count(
array_values(
array_filter(
$node->getMethods(),
static fn (ClassMethod $method): bool => $method->isPublic() && ((string) $method->name !== '__construct' && (string) $method->name !== '__invoke'),
),
),
);
if ($extraPublicMethodsCount !== 0) {
$errors[] = RuleErrorBuilder::message(\sprintf('The class %s has public methods other than "__construct" and "__invoke"', $className))
->identifier('invokable.extra')
->build();
}
return $errors;
}
private function isEligible(ClassReflection $reflection): bool
{
foreach ($this->attributes as $attribute) {
if ($reflection->getNativeReflection()->getAttributes($attribute)) {
return true;
}
}
foreach ($this->classes as $class) {
if (! $reflection->isAbstract() && ($reflection->getName() === $class || $reflection->isSubclassOfClass($this->reflectionProvider->getClass($class)))) {
return true;
}
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/DomainCallNamespacesCustomRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/DomainCallNamespacesCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\ArchitectureRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\CollectedDataNode;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\Collectors\UseUseCollector;
/**
* This class implements a custom rule for PHPStan to check that classes in Domain layer
* do not call namespaces from Application or Infrastructure layers.
*
* @implements Rule<CollectedDataNode>
*/
final class DomainCallNamespacesCustomRule implements Rule
{
/**
* @return class-string<CollectedDataNode>
*/
public function getNodeType(): string
{
return CollectedDataNode::class;
}
/**
* @param CollectedDataNode $node
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
/** @var array<string, list<array{int, string}>> $useUseByFile */
$useUseByFile = $node->get(UseUseCollector::class);
$errors = [];
foreach ($useUseByFile as $file => $useUse) {
// This rule does not apply.
if (! str_contains((string) $file, DIRECTORY_SEPARATOR . 'Domain' . DIRECTORY_SEPARATOR)) {
continue;
}
// Check rule.
foreach ($useUse as [$line, $useNamespace]) {
if (
str_contains($useNamespace, '\\Application\\')
|| str_contains($useNamespace, '\\Infrastructure\\')
) {
$errors[] = CentreonRuleErrorBuilder::message(
'(DomainCallNamespacesCustomRule) Domain must not call Application or Infrastructure namespaces.'
)->line($line)->file($file)->build();
}
}
}
return $errors;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/FinalClassCustomRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/FinalClassCustomRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\ArchitectureRules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Tools\PhpStan\CustomRules\CentreonRuleErrorBuilder;
use Tools\PhpStan\CustomRules\CentreonRuleTrait;
/**
* This class implements a custom rule for PHPStan to check if UseCase, Request, Response
* or Controller classes are final.
*
* @implements Rule<Node\Stmt\Class_>
*/
class FinalClassCustomRule implements Rule
{
use CentreonRuleTrait;
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}
/**
* @return list<\PHPStan\Rules\RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
// This rule does not apply.
if ($node->isFinal()) {
return [];
}
$className = $node->name->name ?? '';
if (
$this->fileIsUseCase($scope->getFile())
|| str_ends_with($className, 'Request')
|| str_ends_with($className, 'Response')
|| str_ends_with($className, 'Controller')
) {
return [
CentreonRuleErrorBuilder::message("(FinalClassCustomRule) Class {$className} must be final.")->build(),
];
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/MarkedClassesAreFinalRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/MarkedClassesAreFinalRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\ArchitectureRules;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Class_>
*/
final readonly class MarkedClassesAreFinalRule implements Rule
{
/**
* @param list<class-string> $attributes
* @param list<class-string> $classes
*/
public function __construct(
private ReflectionProvider $reflectionProvider,
private array $attributes = [],
private array $classes = [],
) {
}
public function getNodeType(): string
{
return Class_::class;
}
/**
* @param Class_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
$className = (string) $node->namespacedName;
$reflection = $this->reflectionProvider->getClass($className);
if (! $this->isEligible($reflection)) {
return [];
}
if ($reflection->isFinal()) {
return [];
}
return [
RuleErrorBuilder::message(\sprintf('The class %s is not final', $className))
->identifier('final.class')
->build(),
];
}
private function isEligible(ClassReflection $reflection): bool
{
if ($reflection->getName() === 'App\Shared\Infrastructure\Doctrine\DoctrineRepository') {
return false;
}
foreach ($this->attributes as $attribute) {
if ($reflection->getNativeReflection()->getAttributes($attribute)) {
return true;
}
}
foreach ($this->classes as $class) {
if ($reflection->getName() === $class || $reflection->isSubclassOfClass($this->reflectionProvider->getClass($class))) {
return true;
}
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/php-tools/phpstan/src/CustomRules/ArchitectureRules/EnumAreSuffixedRule.php | php-tools/phpstan/src/CustomRules/ArchitectureRules/EnumAreSuffixedRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tools\PhpStan\CustomRules\ArchitectureRules;
use PhpParser\Node;
use PhpParser\Node\Stmt\Enum_;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Enum_>
*/
final readonly class EnumAreSuffixedRule implements Rule
{
public function __construct(
private ReflectionProvider $reflectionProvider,
) {
}
public function getNodeType(): string
{
return Enum_::class;
}
/**
* @param Enum_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
$className = (string) $node->namespacedName;
$reflection = $this->reflectionProvider->getClass($className)->getNativeReflection();
if (str_ends_with($reflection->getName(), 'Enum')) {
return [];
}
return [
RuleErrorBuilder::message(\sprintf('The enum %s name must end with "Enum"', $className))
->identifier('enum.suffix')
->build(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/.php-cs-fixer.legacy.www.php | centreon-open-tickets/.php-cs-fixer.legacy.www.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 PhpCsFixer\Finder;
$config = require_once __DIR__ . '/../php-tools/php-cs-fixer/config/base.unstrict.php';
$pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php';
$finder = Finder::create()
->in($pathsConfig['legacy:www']['directories'])
->append($pathsConfig['legacy:www']['files'])
->notPath($pathsConfig['legacy:www']['skip']);
return $config
->setFinder($finder)
->setCacheFile('.php-cs-fixer.legacy.www.cache');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/.php-cs-fixer.conf.php | centreon-open-tickets/.php-cs-fixer.conf.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 [
'legacy:www' => [
'files' => [],
'directories' => [
'config',
'packaging',
'widgets',
'www',
],
'skip' => [],
],
'legacy:src' => [
'files' => [
'.php-cs-fixer.conf.php',
'.php-cs-fixer.diff.php',
'.php-cs-fixer.legacy.src.php',
'.php-cs-fixer.legacy.www.php',
'rector.conf.php',
'rector.diff.php',
'rector.legacy.php',
],
'directories' => [
'src/CentreonOpenTickets',
'tests/php/CentreonOpenTickets',
],
'skip' => [],
],
];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/.php-cs-fixer.diff.php | centreon-open-tickets/.php-cs-fixer.diff.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Tools\PhpCsFixer\Command\RunCsFixerOnDiffCommand;
use Tools\PhpCsFixer\Command\RunCsFixerOnDiffCommandHandler;
require_once __DIR__ . '/../php-tools/vendor/autoload.php';
$pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php';
$args = $_SERVER['argv'] ?? [];
$runCsFixerOnDiffCommand = new RunCsFixerOnDiffCommand(
moduleName: 'centreon-open-tickets',
sections: ['legacy:www', 'legacy:src'],
pathsConfig: $pathsConfig,
args: $args
);
$runCsFixerOnDiffCommandHandler = new RunCsFixerOnDiffCommandHandler();
$runCsFixerOnDiffCommandHandler->run($runCsFixerOnDiffCommand);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/.php-cs-fixer.legacy.src.php | centreon-open-tickets/.php-cs-fixer.legacy.src.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 PhpCsFixer\Finder;
$config = require_once __DIR__ . '/../php-tools/php-cs-fixer/config/base.strict.php';
$pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php';
$finder = Finder::create()
->in($pathsConfig['legacy:src']['directories'])
->append($pathsConfig['legacy:src']['files'])
->notPath($pathsConfig['legacy:src']['skip']);
return $config
->setFinder($finder)
->setCacheFile('.php-cs-fixer.legacy.src.cache');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/rector.diff.php | centreon-open-tickets/rector.diff.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Tools\Rector\Command\RunRectorOnDiffCommand;
use Tools\Rector\Command\RunRectorOnDiffCommandHandler;
require_once __DIR__ . '/../php-tools/vendor/autoload.php';
$pathsConfig = require_once __DIR__ . '/rector.conf.php';
$args = $_SERVER['argv'] ?? [];
$runRectorOnDiffCommand = new RunRectorOnDiffCommand(
moduleName: 'centreon-open-tickets',
sections: ['legacy'],
pathsConfig: $pathsConfig,
args: $args
);
$runRectorOnDiffCommandHandler = new RunRectorOnDiffCommandHandler();
$runRectorOnDiffCommandHandler->run($runRectorOnDiffCommand);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/rector.legacy.php | centreon-open-tickets/rector.legacy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
$rectorConfig = require_once __DIR__ . '/../php-tools/rector/config/base.unstrict.php';
$pathsConfig = require_once __DIR__ . '/rector.conf.php';
return $rectorConfig
->withCache(__DIR__ . '/var/cache/rector.legacy')
->withPaths($pathsConfig['legacy']['paths'])
->withSkip($pathsConfig['legacy']['skip']);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/rector.conf.php | centreon-open-tickets/rector.conf.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 [
'legacy' => [
'paths' => [
// directories
'config',
'src',
'tests',
'widgets',
'www',
// files
'.php-cs-fixer.conf.php',
'.php-cs-fixer.diff.php',
'.php-cs-fixer.legacy.src.php',
'.php-cs-fixer.legacy.www.php',
'rector.conf.php',
'rector.diff.php',
'rector.legacy.php',
],
'skip' => [],
],
];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Routing/RouteLoader.php | centreon-open-tickets/src/CentreonOpenTickets/Routing/RouteLoader.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Routing;
use Core\Common\Infrastructure\Routing\ModuleRouteLoader;
final readonly class RouteLoader extends ModuleRouteLoader
{
public const MODULE_NAME = 'centreon-open-tickets';
public const MODULE_DIRECTORY = 'CentreonOpenTickets';
protected function getModuleName(): string
{
return self::MODULE_NAME;
}
protected function getModuleDirectory(): string
{
return self::MODULE_DIRECTORY;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Resources/Infrastructure/Repository/OpenTicketExtraDataProvider.php | centreon-open-tickets/src/CentreonOpenTickets/Resources/Infrastructure/Repository/OpenTicketExtraDataProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Resources\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\Monitoring\Resource;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Resources\Infrastructure\Repository\ExtraDataProviders\ExtraDataProviderInterface;
/**
* @phpstan-type _TicketData array{
* resource_id:int,
* ticket_value:string,
* subject:string,
* timestamp: int
* }
* @phpstan-type _RuleDetails array{
* macro_ticket_id: ?string,
* url: ?string,
* ...
* }
*/
final class OpenTicketExtraDataProvider extends DatabaseRepository implements ExtraDataProviderInterface
{
use SqlMultipleBindTrait;
private const DATA_PROVIDER_SOURCE_NAME = 'open_tickets';
/**
* @inheritDoc
*/
public function getExtraDataSourceName(): string
{
return self::DATA_PROVIDER_SOURCE_NAME;
}
/**
* @inheritDoc
*/
public function supportsExtraData(ResourceFilter $filter): bool
{
return $filter->getRuleId() !== null;
}
/**
* @inheritDoc
*/
public function getSubFilter(ResourceFilter $filter): string
{
// Only get subRequest is asked and if ruleId is provided
if ($filter->getRuleId() === null) {
return '';
}
$ruleDetails = $this->getRuleDetails($filter->getRuleId());
$macroName = $ruleDetails['macro_ticket_id'];
if ($macroName === null) {
throw new \Exception('Macro name used for rule not found');
}
$onlyOpenedTicketsSubFilter = $filter->getOnlyWithTicketsOpened()
? '(host_tickets.timestamp IS NOT NULL OR service_tickets.timestamp IS NOT NULL)'
: 'host_tickets.timestamp IS NULL AND service_tickets.timestamp IS NULL';
return <<<SQL
AND EXISTS (
SELECT 1 FROM `:dbstg`.hosts h
LEFT JOIN `:dbstg`.services s
ON s.host_id = h.host_id
LEFT JOIN `:dbstg`.customvariables host_customvariables
ON (
h.host_id = host_customvariables.host_id
AND (host_customvariables.service_id IS NULL OR host_customvariables.service_id = 0)
AND host_customvariables.name = '{$macroName}'
)
LEFT JOIN `:dbstg`.mod_open_tickets host_tickets
ON (
host_customvariables.value = host_tickets.ticket_value
AND (host_tickets.timestamp > h.last_time_up OR h.last_time_up IS NULL)
)
LEFT JOIN `:dbstg`.customvariables service_customvariables
ON (
s.service_id = service_customvariables.service_id
AND s.host_id = service_customvariables.host_id
AND service_customvariables.name = '{$macroName}'
)
LEFT JOIN `:dbstg`.mod_open_tickets service_tickets
ON (
service_customvariables.value = service_tickets.ticket_value
AND (service_tickets.timestamp > s.last_time_ok OR s.last_time_ok IS NULL)
)
WHERE (
(h.host_id = resources.parent_id AND s.service_id = resources.id)
OR (h.host_id = resources.id AND s.service_id IS NULL)
)
AND {$onlyOpenedTicketsSubFilter}
LIMIT 1
)
SQL;
}
/**
* @inheritDoc
*/
public function getExtraDataForResources(ResourceFilter $filter, array $resources): array
{
$data = [];
// Provide information only if rule ID is provided and resources is not EMPTY
if ($filter->getRuleId() === null || $resources === []) {
return $data;
}
$ruleDetails = $this->getRuleDetails($filter->getRuleId());
$macroName = $ruleDetails['macro_ticket_id'] ?? null;
if ($macroName === null) {
throw new \Exception('Macro name used for rule not found');
}
$parentResourceIds = [];
$resourceIds = [];
// extract resource id for services and linked hosts
foreach ($this->getServiceResources($resources) as $resource) {
if (
$resource->getResourceId() !== null
&& ! in_array($resource->getResourceId(), $parentResourceIds, true)
) {
$resourceIds[] = $resource->getResourceId();
}
if (
$resource->getParent() !== null
&& $resource->getParent()->getResourceId() !== null
&& ! in_array($resource->getParent()->getResourceId(), $parentResourceIds, true)
) {
$parentResourceIds[] = $resource->getParent()->getResourceId();
}
}
// extract resource ids for hosts
foreach ($this->getHostResources($resources) as $resource) {
if (
$resource->getResourceId() !== null
&& ! in_array($resource->getResourceId(), $parentResourceIds, true)
) {
$parentResourceIds[] = $resource->getResourceId();
}
}
// avoid key re-indexing. index = resource_id
$tickets = $this->getResourceTickets($resourceIds, $macroName)
+ $this->getParentResourceTickets($parentResourceIds, $macroName);
// for each tickets found lets rebuild the link to it using the information from rule details
// if the url has been provided and not empty
return $ruleDetails['url'] !== null
? array_map(
function ($ticket) use ($ruleDetails) {
$ticket['link'] = $this->generateLinkForTicket($ticket['id'], $ruleDetails);
return $ticket;
},
$tickets
)
: $tickets;
}
/**
* @param int $ticketId
* @param _RuleDetails $data
* @return string
*/
private function generateLinkForTicket(int $ticketId, array $data): string
{
$url = $data['url'] ?? '';
if ($url === '') {
return $url;
}
foreach ($data as $key => $value) {
if ($value !== null) {
$pattern = '/\{\$' . preg_quote($key, '/') . '\}/';
/** @var non-empty-string $url */
$url = preg_replace($pattern, (string) $value, $url);
}
}
/** @var non-empty-string $url */
return preg_replace('/\{\$ticket_id\}/', (string) $ticketId, $url) ?? $url;
}
/**
* @param resource[] $resources
* @return resource[]
*/
private function getServiceResources(array $resources): array
{
return array_filter(
$resources,
static fn (Resource $resource) => $resource->getType() === Resource::TYPE_SERVICE
);
}
/**
* @param resource[] $resources
* @return resource[]
*/
private function getHostResources(array $resources): array
{
return array_filter(
$resources,
static fn (Resource $resource) => $resource->getType() === Resource::TYPE_HOST
);
}
/**
* @param int[] $resources
* @param string $macroName
* @return array<int, array{
* id:int,
* subject:string,
* created_at:\DateTimeInterface
* }>|array{}
*/
private function getResourceTickets(array $resources, string $macroName): array
{
if ($resources === []) {
return [];
}
['parameters' => $resourceQueryParameters, 'placeholderList' => $bindQuery] = $this->createMultipleBindParameters(
array_values($resources),
'resource_id',
QueryParameterTypeEnum::INTEGER,
);
$request = <<<SQL
SELECT
r.resource_id,
tickets.ticket_value,
tickets.timestamp,
tickets.user,
tickets_data.subject
FROM `:dbstg`.resources r
LEFT JOIN `:dbstg`.services s
ON s.service_id = r.id
AND s.host_id = r.parent_id
LEFT JOIN `:dbstg`.customvariables cv
ON cv.service_id = s.service_id
AND cv.host_id = s.host_id
AND cv.name = :macroName
LEFT JOIN `:dbstg`.mod_open_tickets tickets
ON tickets.ticket_value = cv.value
AND (tickets.timestamp > s.last_time_ok OR s.last_time_ok IS NULL)
LEFT JOIN `:dbstg`.mod_open_tickets_data tickets_data
ON tickets_data.ticket_id = tickets.ticket_id
WHERE r.resource_id IN ({$bindQuery})
AND tickets.timestamp IS NOT NULL;
SQL;
$queryParameters = [
...$resourceQueryParameters,
QueryParameter::string('macroName', $macroName),
];
$tickets = [];
foreach ($this->connection->iterateAssociative($this->translateDbName($request), QueryParameters::create($queryParameters)) as $record) {
/**
* @var _TicketData $record
*/
$tickets[(int) $record['resource_id']] = [
'id' => (int) $record['ticket_value'],
'subject' => $record['subject'],
'created_at' => (new \DateTimeImmutable())->setTimestamp((int) $record['timestamp']),
];
}
return $tickets;
}
/**
* @param int[] $parentResources
* @param string $macroName
* @return array<int, array{
* id:int,
* subject:string,
* created_at:\DateTimeInterface
* }>|array{}
*/
private function getParentResourceTickets(array $parentResources, string $macroName): array
{
if ($parentResources === []) {
return [];
}
['parameters' => $resourceQueryParameters, 'placeholderList' => $bindQuery] = $this->createMultipleBindParameters(
array_values($parentResources),
'resource_id',
QueryParameterTypeEnum::INTEGER,
);
$request = <<<SQL
SELECT
r.resource_id,
tickets.ticket_value,
tickets.timestamp,
tickets.user,
tickets_data.subject
FROM `:dbstg`.resources r
LEFT JOIN `:dbstg`.hosts h
ON h.host_id = r.id
LEFT JOIN `:dbstg`.customvariables cv
ON cv.host_id = h.host_id
AND (cv.service_id IS NULL OR cv.service_id = 0)
AND cv.name = :macroName
LEFT JOIN `:dbstg`.mod_open_tickets tickets
ON tickets.ticket_value = cv.value
AND (tickets.timestamp > h.last_time_up OR h.last_time_up IS NULL)
LEFT JOIN `:dbstg`.mod_open_tickets_data tickets_data
ON tickets_data.ticket_id = tickets.ticket_id
WHERE r.resource_id IN ({$bindQuery})
AND tickets.timestamp IS NOT NULL;
SQL;
$queryParameters = [
...$resourceQueryParameters,
QueryParameter::string('macroName', $macroName),
];
$tickets = [];
foreach ($this->connection->iterateAssociative($this->translateDbName($request), QueryParameters::create($queryParameters)) as $record) {
/**
* @var _TicketData $record
*/
$tickets[(int) $record['resource_id']] = [
'id' => (int) $record['ticket_value'],
'subject' => $record['subject'],
'created_at' => (new \DateTimeImmutable())->setTimestamp((int) $record['timestamp']),
];
}
return $tickets;
}
/**
* Get the name of the macro configured for the given rule ID.
*
* @param int $ruleId
*
* @return _RuleDetails
*/
private function getRuleDetails(int $ruleId): array
{
$query = <<<'SQL'
SELECT
`uniq_id`,
`value`
FROM `:db`.mod_open_tickets_form_value
WHERE rule_id = :ruleId
SQL;
$queryParameters = QueryParameters::create([
QueryParameter::int('ruleId', $ruleId),
]);
$ruleDetails = [];
foreach ($this->connection->iterateAssociativeIndexed($this->translateDbName($query), $queryParameters) as $key => $data) {
$ruleDetails[$key] = $data['value'];
}
/** @var array{macro_ticket_id: ?string, url: ?string, ...} $ruleDetails */
return $ruleDetails;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Resources/Infrastructure/API/TicketExtraDataFormatter.php | centreon-open-tickets/src/CentreonOpenTickets/Resources/Infrastructure/API/TicketExtraDataFormatter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Resources\Infrastructure\API;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\Resources\Infrastructure\API\ExtraDataNormalizer\ExtraDataNormalizerInterface;
final class TicketExtraDataFormatter implements ExtraDataNormalizerInterface
{
use PresenterTrait;
private const EXTRA_DATA_SOURCE_NAME = 'open_tickets';
/**
* @inheritDoc
*/
public function getExtraDataSourceName(): string
{
return self::EXTRA_DATA_SOURCE_NAME;
}
/**
* @inheritDoc
*/
public function normalizeExtraDataForResource(mixed $data): array
{
/** @var array{id:int, subject:string, created_at:\DateTimeInterface, link:string} $data */
return [
'tickets' => [
'id' => $data['id'],
'subject' => $data['subject'],
'link' => $data['link'],
'created_at' => $this->formatDateToIso8601($data['created_at']),
],
];
}
/**
* @inheritDoc
*/
public function isValidFor(string $providerName): bool
{
return $providerName === self::EXTRA_DATA_SOURCE_NAME;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/ProviderDto.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/ProviderDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Application\UseCase;
final class ProviderDto
{
/**
* @param int $id
* @param string $name
* @param int $typeId
* @param string $typeName
* @param bool $isActivated
*/
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly int $typeId,
public readonly string $typeName,
public readonly bool $isActivated = false,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/FindProviders.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/FindProviders.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Application\UseCase;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use CentreonOpenTickets\Providers\Application\Exception\ProviderException;
use CentreonOpenTickets\Providers\Application\Repository\ReadProviderRepositoryInterface;
use CentreonOpenTickets\Providers\Domain\Model\Provider;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Domain\Exception\RepositoryException;
final class FindProviders
{
use LoggerTrait;
/**
* @param RequestParametersInterface $requestParameters
* @param ReadProviderRepositoryInterface $repository
*/
public function __construct(
private RequestParametersInterface $requestParameters,
private ReadProviderRepositoryInterface $repository,
) {
}
/**
* @return FindProvidersResponse|ResponseStatusInterface
*/
public function __invoke(): FindProvidersResponse|ResponseStatusInterface
{
try {
$providers = $this->repository->findAll($this->requestParameters);
return $this->createResponse($providers);
} catch (RepositoryException $exception) {
$this->error(
$exception->getMessage(),
[
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
);
return new ErrorResponse(ProviderException::errorWhileListingProviders());
}
}
/**
* @param Provider[] $providers
*
* @return FindProvidersResponse
*/
private function createResponse(array $providers): FindProvidersResponse
{
$response = new FindProvidersResponse();
$response->providers = array_map(
static fn (Provider $provider): ProviderDto => new ProviderDto(
id: $provider->getId(),
name: $provider->getName(),
typeId: $provider->getProviderTypeId(),
typeName: $provider->getProviderTypeName(),
isActivated: $provider->isActivated()
),
$providers
);
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/FindProvidersResponse.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/UseCase/FindProvidersResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Application\UseCase;
use Core\Application\Common\UseCase\ListingResponseInterface;
final class FindProvidersResponse implements ListingResponseInterface
{
/** @var ProviderDto[] */
public array $providers;
/**
* @return ProviderDto[]
*/
public function getData(): array
{
return $this->providers;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/Exception/ProviderException.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/Exception/ProviderException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Application\Exception;
class ProviderException extends \Exception
{
/**
* @return self
*/
public static function listingNotAllowed(): self
{
return new self(_('You are not allowed to list ticket providers'));
}
/**
* @return self
*/
public static function errorWhileListingProviders(): self
{
return new self(_('Error while listing ticket providers'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/Repository/ReadProviderRepositoryInterface.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Application/Repository/ReadProviderRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use CentreonOpenTickets\Providers\Domain\Model\Provider;
use Core\Common\Domain\Exception\RepositoryException;
interface ReadProviderRepositoryInterface
{
/**
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return Provider[]
*/
public function findAll(RequestParametersInterface $requestParameters): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Domain/Model/Provider.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Domain/Model/Provider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Provider
{
public const MAX_NAME_LENGTH = 255;
/**
* @param int $id
* @param string $name
* @param int $providerTypeId
* @param string $providerTypeName
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
private int $id,
private string $name,
private int $providerTypeId,
private string $providerTypeName,
private bool $isActivated,
) {
Assertion::positiveInt($this->id, 'Provider::id');
Assertion::notEmptyString($this->name, 'Provider::name');
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, 'Provider::name');
Assertion::positiveInt($this->providerTypeId, 'Provider::providerTypeId');
Assertion::notEmptyString($this->providerTypeName, 'Provider::providerTypeName');
Assertion::maxLength($this->providerTypeName, self::MAX_NAME_LENGTH, 'Provider::providerTypeName');
}
/**
* @return int
*/
public function getProviderTypeId(): int
{
return $this->providerTypeId;
}
/**
* @return string
*/
public function getProviderTypeName(): string
{
return $this->providerTypeName;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Infrastructure/Repository/DbReadProviderRepository.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Infrastructure/Repository/DbReadProviderRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use CentreonOpenTickets\Providers\Application\Repository\ReadProviderRepositoryInterface;
use CentreonOpenTickets\Providers\Domain\Model\Provider;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Common\Infrastructure\RequestParameters\Transformer\SearchRequestParametersTransformer;
/**
* @phpstan-type _Provider array{
* rule_id:int,
* alias:string,
* provider_id:int,
* provider_name:string,
* activate:int
* }
*/
class DbReadProviderRepository extends DatabaseRepository implements ReadProviderRepositoryInterface
{
/**
* @inheritDoc
*/
public function findAll(RequestParametersInterface $requestParameters): array
{
try {
$sqlRequestTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlRequestTranslator->setConcordanceArray(
[
'name' => 'rules.alias',
'is_activated' => 'rules.activate',
]
);
$sqlRequestTranslator->addNormalizer(
'is_activated',
new BoolToEnumNormalizer(),
);
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder->select(
<<<'SQL'
rule_id,
alias,
provider_id,
provider_name,
activate
SQL
)->from('`:db`.mod_open_tickets_rule', 'rules');
if ($requestParameters->getSearch() !== []) {
$sqlRequestTranslator->appendQueryBuilderWithSearchParameter($queryBuilder);
}
if ($requestParameters->getSort() !== []) {
$sqlRequestTranslator->appendQueryBuilderWithSortParameter($queryBuilder);
} else {
$queryBuilder->orderBy('rules.alias', 'ASC');
}
$sqlRequestTranslator->appendQueryBuilderWithPagination($queryBuilder);
$requestParameters = SearchRequestParametersTransformer::reverseToQueryParameters($sqlRequestTranslator->getSearchValues());
$providers = [];
foreach ($this->connection->iterateAssociative($this->translateDbName($queryBuilder->getQuery()), $requestParameters) as $record) {
/** @var _Provider $record */
$providers[] = $this->createProviderFromRecord($record);
}
// get total without pagination
$queryTotal = $queryBuilder
->select('COUNT(*)')
->resetLimit()
->offset(0)
->getQuery();
/**
* @var int|false $total
*/
$total = $this->connection->fetchOne(
$this->translateDbName($queryTotal),
$requestParameters
);
$sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
return $providers;
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while fetching provider rules',
previous: $exception
);
}
}
/**
* @param _Provider $record
*
* @return Provider
*/
private function createProviderFromRecord(array $record): Provider
{
return new Provider(
id: (int) $record['rule_id'],
name: $record['alias'],
providerTypeId: (int) $record['provider_id'],
providerTypeName: $record['provider_name'],
isActivated: (bool) $record['activate'],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/src/CentreonOpenTickets/Providers/Infrastructure/API/FindProviders/FindProvidersController.php | centreon-open-tickets/src/CentreonOpenTickets/Providers/Infrastructure/API/FindProviders/FindProvidersController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonOpenTickets\Providers\Infrastructure\API\FindProviders;
use Centreon\Application\Controller\AbstractController;
use CentreonOpenTickets\Providers\Application\UseCase\FindProviders;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access_editor',
null,
"User doesn't have sufficient rights to get ticket providers information"
)]
final class FindProvidersController extends AbstractController
{
/**
* @param FindProviders $useCase
* @param StandardPresenter $presenter
*
* @return Response
*/
#[Route(
path: '/open-tickets/providers',
name: 'FindProviders',
methods: 'GET'
)]
public function __invoke(
FindProviders $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase();
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString($presenter->present($response));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/tests/php/CentreonOpenTickets/Providers/Application/UseCase/FindProviders/FindProvidersTest.php | centreon-open-tickets/tests/php/CentreonOpenTickets/Providers/Application/UseCase/FindProviders/FindProvidersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\CentreonOpenTickets\Providers\Application\UseCase\FindProviders;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use CentreonOpenTickets\Providers\Application\Exception\ProviderException;
use CentreonOpenTickets\Providers\Application\Repository\ReadProviderRepositoryInterface;
use CentreonOpenTickets\Providers\Application\UseCase\FindProviders;
use CentreonOpenTickets\Providers\Application\UseCase\FindProvidersResponse;
use CentreonOpenTickets\Providers\Domain\Model\Provider;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
beforeEach(closure: function (): void {
$this->useCase = new FindProviders(
requestParameters: $this->requestParameters = $this->createMock(RequestParametersInterface::class),
repository: $this->repository = $this->createMock(ReadProviderRepositoryInterface::class)
);
});
it('should present an ErrorResponse when an exception occurs for ticket provider search', function (): void {
$exception = new RepositoryException('Exception from repository');
$this->repository
->expects($this->once())
->method('findAll')
->willThrowException($exception);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(ProviderException::errorWhileListingProviders()->getMessage());
});
it('should present a FindProvidersResponse when everything goes well', function (): void {
$provider = new Provider(
id: 1,
name: 'glpi',
providerTypeId: 11,
providerTypeName: 'GlpiRestApi',
isActivated: true
);
$this->repository
->expects($this->once())
->method('findAll')
->willReturn([$provider]);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(FindProvidersResponse::class)
->and($response->providers[0]->id)->toBe($provider->getId())
->and($response->providers[0]->name)->toBe($provider->getName())
->and($response->providers[0]->typeId)->toBe($provider->getProviderTypeId())
->and($response->providers[0]->typeName)->toBe($provider->getProviderTypeName())
->and($response->providers[0]->isActivated)->toBe($provider->isActivated());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/tests/php/CentreonOpenTickets/Providers/Infrastructure/API/FindProviders/FindProvidersPresenterStub.php | centreon-open-tickets/tests/php/CentreonOpenTickets/Providers/Infrastructure/API/FindProviders/FindProvidersPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\CentreonOpenTickets\Providers\Infrastructure\API\FindProviders;
use CentreonOpenTickets\Providers\Application\UseCase\FindProvidersResponse;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
final class FindProvidersPresenterStub extends AbstractPresenter
{
public FindProvidersResponse|ResponseStatusInterface $response;
/**
* @param FindProvidersResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindProvidersResponse|ResponseStatusInterface $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/index.php | centreon-open-tickets/widgets/open-tickets/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 '../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
$smartyDir = __DIR__ . '/../../../vendor/smarty/smarty/';
require_once $smartyDir . 'libs/Smarty.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
$widgetId = $_REQUEST['widgetId'];
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/templates/';
$template = SmartyBC::createSmartyTemplate($path, '/');
try {
$db = new CentreonDB();
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = 0;
if (isset($preferences['refresh_interval'])) {
$autoRefresh = $preferences['refresh_interval'];
}
$preferences['rule'] = (! empty($preferences['rule']) ? $preferences['rule'] : null);
$rule = new Centreon_OpenTickets_Rule($db);
$result = $rule->getAliasAndProviderId($preferences['rule']);
if (
! isset($preferences['rule'])
|| is_null($preferences['rule'])
|| $preferences['rule'] == ''
|| ! isset($result['provider_id'])
) {
$template->assign(
'error',
"<center><div class='update' style='text-align:center;width:350px;'>"
. _('Please select a rule first') . '</div></center>'
);
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
} catch (Exception $e) {
$template->assign(
'error',
"<center><div class='update' style='text-align:center;width:350px;'>"
. $e->getMessage() . '</div></center>'
);
}
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
$template->assign('theme', $variablesThemeCSS);
$template->display('index.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/src/export.php | centreon-open-tickets/widgets/open-tickets/src/export.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="open-tickets.csv"');
require_once '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonACL.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonHostcategories.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
$smartyDir = __DIR__ . '/../../../../vendor/smarty/smarty/';
require_once $smartyDir . 'libs/Smarty.class.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
exit();
}
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate($centreon_path . 'www/widgets/open-tickets/src/', './');
// Init Objects
$criticality = new CentreonCriticality($db);
$media = new CentreonMedia($db);
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(INPUT_GET, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
/**
* @var CentreonDB $dbb
*/
$dbb = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
// Set Colors Table
$stateHColors = [
0 => 'host_up',
1 => 'host_down',
2 => 'host_unreachable',
4 => 'host_pending',
];
$stateSColors = [
0 => 'service_ok',
1 => 'service_warning',
2 => 'service_critical',
3 => 'service_unknown',
4 => 'pending',
];
$stateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
$aStateType = ['1' => 'H', '0' => 'S'];
$mainQueryParameters = [];
// Build Query
$query = "SELECT SQL_CALC_FOUND_ROWS h.host_id,
h.name AS hostname,
h.state AS h_state,
s.service_id,
s.description,
s.state AS s_state,
s.last_hard_state,
s.output,
s.scheduled_downtime_depth AS s_scheduled_downtime_depth,
s.acknowledged AS s_acknowledged,
s.notify AS s_notify,
s.active_checks AS s_active_checks,
s.passive_checks AS s_passive_checks,
h.scheduled_downtime_depth AS h_scheduled_downtime_depth,
h.acknowledged AS h_acknowledged,
h.notify AS h_notify,
h.active_checks AS h_active_checks,
h.passive_checks AS h_passive_checks,
s.last_check,
s.last_state_change,
s.last_hard_state_change,
s.check_attempt,
s.max_check_attempts,
h.action_url AS h_action_url,
h.notes_url AS h_notes_url,
s.action_url AS s_action_url,
s.notes_url AS s_notes_url,
cv2.value AS criticality_id,
cv.value AS criticality_level
FROM hosts h, services s
LEFT JOIN customvariables cv ON (
s.service_id = cv.service_id AND s.host_id = cv.host_id AND cv.name = 'CRITICALITY_LEVEL'
)
LEFT JOIN customvariables cv2 ON (
s.service_id = cv2.service_id AND s.host_id = cv2.host_id AND cv2.name = 'CRITICALITY_ID'
)";
if (! $centreon->user->admin) {
$query .= ' , centreon_acl acl ';
}
$query .= " WHERE s.host_id = h.host_id
AND h.name NOT LIKE '_Module_%'
AND s.enabled = 1 ";
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$query = CentreonUtils::conditionBuilder(
$query,
'h.name ' . CentreonUtils::operandToMysqlFormat($op)
. " '" . $dbb->escape($search) . "' "
);
}
}
if (isset($preferences['service_description_search']) && $preferences['service_description_search'] != '') {
$tab = explode(' ', $preferences['service_description_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$query = CentreonUtils::conditionBuilder(
$query,
's.description ' . CentreonUtils::operandToMysqlFormat($op) . " '" . $dbb->escape($search) . "' "
);
}
}
$stateTab = [];
if (isset($preferences['svc_ok']) && $preferences['svc_ok']) {
$stateTab[] = 0;
}
if (isset($preferences['svc_warning']) && $preferences['svc_warning']) {
$stateTab[] = 1;
}
if (isset($preferences['svc_critical']) && $preferences['svc_critical']) {
$stateTab[] = 2;
}
if (isset($preferences['svc_unknown']) && $preferences['svc_unknown']) {
$stateTab[] = 3;
}
if (isset($preferences['svc_pending']) && $preferences['svc_pending']) {
$stateTab[] = 4;
}
if ($stateTab !== []) {
$query = CentreonUtils::conditionBuilder($query, ' s.state IN (' . implode(',', $stateTab) . ')');
}
if (! empty($preferences['hide_disable_notif_host'])) {
$query = CentreonUtils::conditionBuilder($query, ' h.notify != 0 ');
}
if (! empty($preferences['hide_disable_notif_service'])) {
$query = CentreonUtils::conditionBuilder($query, ' s.notify != 0 ');
}
if (! empty($preferences['acknowledgement_filter'])) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$query = CentreonUtils::conditionBuilder($query, ' s.acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$query = CentreonUtils::conditionBuilder(
$query,
' s.acknowledged = 0 AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 '
);
}
}
if (! empty($preferences['downtime_filter'])) {
if ($preferences['downtime_filter'] == 'downtime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth = 0 ');
}
}
if (! empty($preferences['state_type_filter'])) {
if ($preferences['state_type_filter'] == 'hardonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 0 ');
}
}
if (! empty($preferences['poller'])) {
$resultsPoller = explode(',', $preferences['poller']);
$queryPoller = '';
foreach ($resultsPoller as $resultPoller) {
if ($queryPoller != '') {
$queryPoller .= ', ';
}
$queryPoller .= ':instance_id_' . $resultPoller;
$mainQueryParameters[] = [
'parameter' => ':instance_id_' . $resultPoller,
'value' => (int) $resultPoller,
'type' => PDO::PARAM_INT,
];
}
$instanceIdCondition = ' h.instance_id IN (' . $queryPoller . ')';
$query = CentreonUtils::conditionBuilder($query, $instanceIdCondition);
}
if (! empty($preferences['hostgroup'])) {
$results = explode(',', $preferences['hostgroup']);
$queryHG = '';
foreach ($results as $result) {
if ($queryHG !== '') {
$queryHG .= ', ';
}
$queryHG .= ':id_' . $result;
$mainQueryParameters[] = [
'parameter' => ':id_' . $result,
'value' => (int) $result,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostgroup_relation
WHERE hostgroup_hg_id IN (' . $queryHG . ')
)'
);
}
if (! empty($preferences['servicegroup'])) {
$resultsSG = explode(',', $preferences['servicegroup']);
$querySG = '';
foreach ($resultsSG as $resultSG) {
if ($querySG !== '') {
$querySG .= ', ';
}
$querySG .= ':id_' . $resultSG;
$mainQueryParameters[] = [
'parameter' => ':id_' . $resultSG,
'value' => (int) $resultSG,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.service_id IN (
SELECT DISTINCT service_id
FROM services_servicegroups
WHERE servicegroup_id IN (' . $querySG . ')
)'
);
}
if (! empty($preferences['hostcategories'])) {
$resultsHC = explode(',', $preferences['hostcategories']);
$queryHC = '';
foreach ($resultsHC as $resultHC) {
if ($queryHC !== '') {
$queryHC .= ', ';
}
$queryHC .= ':id_' . $resultHC;
$mainQueryParameters[] = [
'parameter' => ':id_' . $resultHC,
'value' => (int) $resultsHC,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostcategories_relation
WHERE hostcategories_hc_id IN (' . $queryHC . ')
)'
);
}
if (isset($preferences['display_severities'])
&& $preferences['display_severities']
&& isset($preferences['criticality_filter'])
&& $preferences['criticality_filter'] != ''
) {
$tab = explode(',', $preferences['criticality_filter']);
$labels = '';
foreach ($tab as $p) {
if ($labels != '') {
$labels .= ',';
}
$labels .= "'" . trim($p) . "'";
}
$res = $db->query('SELECT sc_id FROM service_categories WHERE sc_name IN (' . $labels . ')');
$idC = '';
while ($d1 = $res->fetch()) {
if ($idC != '') {
$idC .= ',';
}
$idC .= $d1['sc_id'];
}
$query .= ' AND cv2.`value` IN (' . $idC . ') ';
}
if (! $centreon->user->admin) {
$pearDB = $db;
$aclObj = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
$groupList = $aclObj->getAccessGroupsString();
$query .= ' AND h.host_id = acl.host_id
AND acl.service_id = s.service_id
AND acl.group_id IN (' . $groupList . ')';
}
$orderby = 'hostname ASC , description ASC';
if (isset($preferences['order_by']) && $preferences['order_by'] != '') {
$orderby = $preferences['order_by'];
}
$query .= "ORDER BY {$orderby}";
$res = $dbb->query($query);
$nbRows = $dbb->numberRows();
$data = [];
$outputLength = $preferences['output_length'] ?: 50;
$commentLength = $preferences['comment_length'] ?: 50;
$hostObj = new CentreonHost($db);
$svcObj = new CentreonService($db);
while ($row = $res->fetch()) {
foreach ($row as $key => $value) {
if ($key == 'last_check') {
$value = date('Y-m-d H:i:s', $value);
} elseif ($key == 'last_state_change' || $key == 'last_hard_state_change') {
$value = time() - $value;
$value = CentreonDuration::toString($value);
} elseif ($key == 'check_attempt') {
$value = $value . '/' . $row['max_check_attempts'];
} elseif ($key == 's_state') {
$data[$row['host_id'] . '_' . $row['service_id']]['color'] = $stateSColors[$value];
$value = $stateLabels[$value];
} elseif ($key == 'h_state') {
$data[$row['host_id'] . '_' . $row['service_id']]['hcolor'] = $stateHColors[$value];
$value = $stateLabels[$value];
} elseif ($key == 'output') {
$value = substr($value, 0, $outputLength);
} elseif (($key == 'h_action_url' || $key == 'h_notes_url') && $value) {
$value = $hostObj->replaceMacroInString($row['hostname'], $value);
} elseif (($key == 's_action_url' || $key == 's_notes_url') && $value) {
$value = $hostObj->replaceMacroInString($row['hostname'], $value);
$value = $svcObj->replaceMacroInString($service_id, $value);
} elseif ($key == 'criticality_id' && $value != '') {
$critData = $criticality->getData($row['criticality_id'], 1);
$value = $critData['hc_name'];
}
$data[$row['host_id'] . '_' . $row['service_id']][$key] = $value;
}
if (isset($preferences['display_last_comment']) && $preferences['display_last_comment']) {
$res2 = $dbb->query(
'SELECT data
FROM comments
WHERE host_id = ' . $row['host_id'] . '
AND service_id = ' . $row['service_id'] . '
ORDER BY entry_time DESC LIMIT 1'
);
if ($row2 = $res2->fetch()) {
$data[$row['host_id'] . '_' . $row['service_id']]['comment'] = substr($row2['data'], 0, $commentLength);
} else {
$data[$row['host_id'] . '_' . $row['service_id']]['comment'] = '-';
}
}
}
$template->assign('preferences', $preferences);
$template->assign('data', $data);
$template->display('export.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/src/action.php | centreon-open-tickets/widgets/open-tickets/src/action.php | <?php
/*
* Copyright 2015-2019 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,*
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonXMLBGRequest.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
session_start();
$centreon_bg = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
?>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/jquery.serialize-object.min.js"></script>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/commonFunc.js"></script>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/dropzone.js"></script>
<link href="./modules/centreon-open-tickets/lib/dropzone.css" rel="stylesheet" type="text/css"/>
<?php
/**
* service_ack: put an ack on a host and service
* @param bool $autoCloseActionPopup set to 1 if you want to automatically close call popup
*/
function service_ack(bool $autoCloseActionPopup)
{
global $cmd, $centreon, $centreon_path;
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
$template->assign('stickyLabel', _('Sticky'));
$template->assign('persistentLabel', _('Persistent'));
$template->assign('authorLabel', _('Author'));
$template->assign('notifyLabel', _('Notify'));
$template->assign('commentLabel', _('Comment'));
$template->assign('forceCheckLabel', _('Force active checks'));
$template->assign('fixedLabel', _('Fixed'));
$template->assign('durationLabel', _('Duration'));
$template->assign('startLabel', _('Start'));
$template->assign('endLabel', _('End'));
$template->assign('selection', $_REQUEST['selection']);
$template->assign('author', $centreon->user->alias);
$template->assign('cmd', $cmd);
$title = _('Service Acknowledgement');
$template->assign('defaultMessage', sprintf(_('Acknowledged by %s'), $centreon->user->alias));
$persistent_checked = '';
if (isset($centreon->optGen['monitoring_ack_persistent']) && $centreon->optGen['monitoring_ack_persistent']) {
$persistent_checked = 'checked';
}
$template->assign('persistent_checked', $persistent_checked);
$sticky_checked = '';
if (isset($centreon->optGen['monitoring_ack_sticky']) && $centreon->optGen['monitoring_ack_sticky']) {
$sticky_checked = 'checked';
}
$template->assign('sticky_checked', $sticky_checked);
$notify_checked = '';
if (isset($centreon->optGen['monitoring_ack_notify']) && $centreon->optGen['monitoring_ack_notify']) {
$notify_checked = 'checked';
}
$template->assign('notify_checked', $notify_checked);
$process_service_checked = '';
if (isset($centreon->optGen['monitoring_ack_svc']) && $centreon->optGen['monitoring_ack_svc']) {
$process_service_checked = 'checked';
}
$template->assign('process_service_checked', $process_service_checked);
$force_active_checked = '';
if (isset($centreon->optGen['monitoring_ack_active_checks']) && $centreon->optGen['monitoring_ack_active_checks']) {
$force_active_checked = 'checked';
}
$template->assign('force_active_checked', $force_active_checked);
$template->assign('titleLabel', $title);
$template->assign('submitLabel', _('Acknowledge'));
$template->assign('autoCloseActionPopup', $autoCloseActionPopup);
$template->display('acknowledge.ihtml');
}
/**
* schedule_check: prepare variables for widget popup when scheduling a check
*
* @param bool $isService set to true if you want to schedule a check on a service
* @param bool $isForced set to true if you want to schedule a forced check
* @param bool $autoCloseActionPopup set to true if you want to automatically close call popup
*/
function schedule_check(bool $isService, bool $isForced, bool $autoCloseActionPopup)
{
global $cmd, $centreon, $centreon_path;
$selection = filter_var($_REQUEST['selection'], FILTER_SANITIZE_STRING);
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
$template->assign('selection', $selection);
$template->assign('titleLabel', _('Scheduling checks'));
$template->assign('forced', $isForced);
$template->assign('isService', $isService);
$template->assign('autoCloseActionPopup', $autoCloseActionPopup ? 'true' : 'false');
$template->display('schedulecheck.ihtml');
}
function format_popup()
{
global $cmd, $widgetId, $rule, $preferences, $centreon, $centreon_path;
$uniq_id = uniqid();
$title = $cmd == 3 ? _('Open Service Ticket') : _('Open Host Ticket');
$result = $rule->getFormatPopupProvider(
$preferences['rule'],
[
'title' => $title,
'user' => [
'name' => $centreon->user->name,
'alias' => $centreon->user->alias,
'email' => $centreon->user->email,
],
],
$widgetId,
$uniq_id,
$_REQUEST['cmd'],
$_REQUEST['selection']
);
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
$provider_infos = $rule->getAliasAndProviderId($preferences['rule']);
$template->assign('provider_id', $provider_infos['provider_id']);
$template->assign('rule_id', $preferences['rule']);
$template->assign('widgetId', $widgetId);
$template->assign('uniqId', $uniq_id);
$template->assign('title', $title);
$template->assign('cmd', $cmd);
$template->assign('selection', $_REQUEST['selection']);
$template->assign('continue', (! is_null($result) && isset($result['format_popup'])) ? 0 : 1);
$template->assign(
'attach_files_enable',
(
! is_null($result)
&& isset($result['attach_files_enable'])
&& $result['attach_files_enable'] === 'yes'
) ? 1 : 0
);
$template->assign(
'formatPopupProvider',
(
! is_null($result)
&& isset($result['format_popup'])
) ? $result['format_popup'] : ''
);
$template->assign('submitLabel', _('Open'));
$template->display('formatpopup.ihtml');
}
function remove_tickets()
{
global $cmd, $widgetId, $rule, $preferences, $centreon, $centreon_path, $centreon_bg;
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$provider_infos = $rule->getAliasAndProviderId($preferences['rule']);
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
$template->assign('title', _('Close Tickets'));
$template->assign('selection', $_REQUEST['selection']);
$template->assign('provider_id', $provider_infos['provider_id']);
$template->assign('rule_id', $preferences['rule']);
$template->display('removetickets.ihtml');
}
try {
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['cmd']) || ! isset($_REQUEST['selection'])) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
throw new Exception('Invalid session');
}
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
$oreon = $centreon;
$cmd = $_REQUEST['cmd'];
$widgetId = $_REQUEST['widgetId'];
$selections = explode(',', $_REQUEST['selection']);
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$rule = new Centreon_OpenTickets_Rule($db);
if ($cmd == 3 || $cmd == 4) {
format_popup();
} elseif ($cmd == 10) {
remove_tickets();
} elseif ($cmd == 70) {
service_ack((bool) $preferences['auto_close_action_popup']);
// schedule service forced check
} elseif ($cmd == 80) {
schedule_check(true, true, (bool) $preferences['auto_close_action_popup']);
// schedule service check
} elseif ($cmd == 81) {
schedule_check(true, false, (bool) $preferences['auto_close_action_popup']);
// schedule host forced check
} elseif ($cmd == 82) {
schedule_check(false, true, (bool) $preferences['auto_close_action_popup']);
// schedule host check
} elseif ($cmd == 83) {
schedule_check(false, false, (bool) $preferences['auto_close_action_popup']);
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/src/toolbar.php | centreon-open-tickets/widgets/open-tickets/src/toolbar.php | <?php
/*
* Copyright 2015-2022 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,*
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonACL.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_POST['widgetId'])) {
exit;
}
$baseUri = (function () {
$scriptName = htmlspecialchars($_SERVER['SCRIPT_NAME']);
$paths = explode('/', $scriptName);
$baseUri = '/' . $paths[1] . '/';
return $baseUri;
})();
$smartyDir = __DIR__ . '/../../../../vendor/smarty/smarty/';
require_once $smartyDir . 'libs/Smarty.class.php';
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
$widgetId = $_POST['widgetId'];
$db = new CentreonDB();
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$pearDB = new CentreonDB();
$admin = $centreon->user->admin;
$canDoAction = false;
if ($admin) {
$canDoAction = true;
}
$toolbar = '';
if ($preferences['toolbar_buttons']) {
if (! isset($preferences['opened_tickets']) || $preferences['opened_tickets'] == 0) {
if ($preferences['action_open_hosts']) {
$toolbar .= "<label id='buttontoolbar_4' style='font-size: 13px; font-weight: bold; cursor:pointer;' "
. "for='host-ticket'>Host <input type='image' title='"
. _('Host: Open ticket') . "' alt='" . _('Host: Open ticket') . "' src='"
. $baseUri
. "/modules/centreon-open-tickets/images/open-ticket.svg' name='host-ticket' "
. "style='border: none; width: 24px; height: 24px; vertical-align: middle;'/> </label> | ";
}
if ($preferences['action_open_services']) {
$toolbar .= "<label id='buttontoolbar_3' style='font-size: 13px; font-weight: bold; cursor:pointer;' "
. "for='service-ticket'> Service <input type='image' title='" . _('Service: Open ticket') . "' alt='"
. _('Service: Open ticket') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/open-ticket.svg' name='service-ticket' "
. "style='border: none; width: 24px; height: 24px; vertical-align: middle;' /> </label> | ";
}
if (
$preferences['action_ack']
&& ($canDoAction || $centreon->user->access->checkAction('service_acknowledgement'))
) {
$toolbar .= "<label id='buttontoolbar_70' style='font-size: 13px; font-weight: bold; cursor:pointer;'' "
. "for='ack-ticket'>Acknowledge <input type='image' title='" . _('Service: Acknowledge') . "' alt='"
. _('Service: Acknowledge') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/acknowledge.png' name='ack-ticket' "
. "style='border: none; height: 22px; vertical-align: middle;' /> </label> | ";
}
if (
$preferences['action_service_forced_check']
&& ($canDoAction || $centreon->user->access->checkAction('service_schedule_forced_check'))
) {
$toolbar .= "<label id='buttontoolbar_80' style='font-size: 13px; font-weight: bold; cursor:pointer;'' "
. "for='schedule-service-forced-check-ticket'>Service: Schedule forced check <input type='image' "
. "title='" . _('Service: Schedule Forced Check') . "' alt='"
. _('Service: Schedule Forced Check') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/schedule_forced_check.png' "
. "name='schedule-service-forced-check-ticket' "
. "style='border: none; height: 22px; vertical-align: middle;' /> </label> | ";
}
if (
$preferences['action_service_check']
&& ($canDoAction || $centreon->user->access->checkAction('service_schedule_check'))
) {
$toolbar .= "<label id='buttontoolbar_81' style='font-size: 13px; font-weight: bold; cursor:pointer;'' "
. "for='schedule-sevice-check-ticket'>Service: Schedule check <input type='image' title='"
. _('Service: Schedule Check') . "' alt='"
. _('Service: Schedule Check') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/schedule_check.png' name='schedule-service-check-ticket' "
. "style='border: none; height: 22px; vertical-align: middle;' /> </label> | ";
}
if (
$preferences['action_host_forced_check']
&& ($canDoAction || $centreon->user->access->checkAction('host_schedule_forced_check'))
) {
$toolbar .= "<label id='buttontoolbar_82' style='font-size: 13px; font-weight: bold; cursor:pointer;'' "
. "for='host-service-forced-check-ticket'>Host: Schedule forced check <input type='image' title='"
. _('Host: Schedule Forced Check') . "' alt='"
. _('Host: Schedule Forced Check') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/schedule_forced_check.png' "
. "name='schedule-host-forced-check-ticket' "
. "style='border: none; height: 22px; vertical-align: middle;' /> </label> | ";
}
if (
$preferences['action_host_check']
&& ($canDoAction || $centreon->user->access->checkAction('host_schedule_check'))
) {
$toolbar .= "<label id='buttontoolbar_83' style='font-size: 13px; font-weight: bold; cursor:pointer;'' "
. "for='schedule-host-check-ticket'>Host: Schedule check <input type='image' title='"
. _('Host: Schedule Check') . "' alt='"
. _('Host: Schedule Check') . "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/schedule_check.png' name='schedule-host-check-ticket' "
. "style='border: none; height: 22px; vertical-align: middle;' /> </label> |";
}
} else {
$toolbar .= "<input type='image' title='" . _('Close Tickets') . "' alt='" . _('Close Tickets')
. "' src='" . $baseUri
. "/modules/centreon-open-tickets/images/close-ticket.svg' id='buttontoolbar_10' "
. "style='cursor:pointer; border: none;width: 24px; height: 24px;' />";
}
} else {
$toolbar .= "<select class='toolbar'>";
$toolbar .= "<option value='0'>-- " . _('More actions') . ' -- </option>';
if (! isset($preferences['opened_tickets']) || $preferences['opened_tickets'] == 0) {
if ($preferences['action_open_hosts']) {
$toolbar .= "<option value='4'>" . _('Host: Open ticket') . '</option>';
}
if ($preferences['action_open_services']) {
$toolbar .= "<option value='3'>" . _('Service: Open ticket') . '</option>';
}
if (
$preferences['action_ack']
&& ($canDoAction || $centreon->user->access->checkAction('service_acknowledgement'))
) {
$toolbar .= "<option value='70'>" . _('Service: Acknowledge') . '</option>';
}
if (
$preferences['action_host_forced_check']
&& ($canDoAction || $centreon->user->access->checkAction('host_schedule_forced_check'))
) {
$toolbar .= "<option value='82'>" . _('Host: Schedule Forced Check') . '</option>';
}
if (
$preferences['action_host_check']
&& ($canDoAction || $centreon->user->access->checkAction('host_schedule_check'))
) {
$toolbar .= "<option value='83'>" . _('Host: Schedule Check') . '</option>';
}
if (
$preferences['action_service_forced_check']
&& ($canDoAction || $centreon->user->access->checkAction('service_schedule_forced_check'))
) {
$toolbar .= "<option value='80'>" . _('Service: Schedule Forced Check') . '</option>';
}
if (
$preferences['action_service_check']
&& ($canDoAction || $centreon->user->access->checkAction('service_schedule_check'))
) {
$toolbar .= "<option value='81'>" . _('Service: Schedule Check') . '</option>';
}
} else {
$toolbar .= "<option value='10'>" . _('Close Tickets') . '</option>';
}
$toolbar .= '</select>';
}
$template->assign('widgetId', $widgetId);
$template->display('toolbar.ihtml');
?>
<script type="text/javascript" src="../../include/common/javascript/centreon/popin.js"></script>
<script type='text/javascript'>
var tab = new Array();
var toolbar = "<?php echo $toolbar; ?>";
var widget_id = "<?php echo $widgetId; ?>";
$(function() {
$("#toolbar_container").html(toolbar);
$(".toolbar").change(function() {
if (jQuery(this).val() != 0) {
var checkValues = $("input:checked").map(function() {
var tmp = $(this).attr('id').split("_");
return tmp[1];
}).get().join(",");
if (checkValues != '') {
var url = "./widgets/open-tickets/src/action.php?widgetId="
+ widget_id + "&selection=" + checkValues + "&cmd=" + jQuery(this).val();
// We delete the old one
// (not really clean. Should be managed by popin itself. Like with a destroy parameters)
parent.jQuery('#OTWidgetPopin').parent().remove();
var popin = parent.jQuery('<div id="OTWidgetPopin">');
popin.centreonPopin({open:true,url:url});
} else {
alert("<?php echo _('Please select one or more items'); ?>");
return false;
}
$(".toolbar").val(0);
}
});
$("[id^=buttontoolbar_]").click(function() {
var checkValues = $("input:checked").map(function() {
var tmp = $(this).attr('id').split("_");
return tmp[1];
}).get().join(",");
if (checkValues != '') {
var tmp = $(this).attr('id').split("_");
var url = "./widgets/open-tickets/src/action.php?widgetId="
+ widget_id + "&selection=" + checkValues + "&cmd=" + tmp[1];
// We delete the old one
// (not really clean. Should be managed by popin itself. Like with a destroy parameters)
parent.jQuery('#OTWidgetPopin').parent().remove();
var popin = parent.jQuery('<div id="OTWidgetPopin">');
popin.centreonPopin({open:true,url:url});
} else {
alert("<?php echo _('Please select one or more items'); ?>");
}
});
});
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/src/index.php | centreon-open-tickets/widgets/open-tickets/src/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 '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonACL.class.php';
require_once $centreon_path . 'www/class/centreonInstance.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonHostcategories.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
$smartyDir = __DIR__ . '/../../../../vendor/smarty/smarty/';
require_once $smartyDir . 'libs/Smarty.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId']) || ! isset($_REQUEST['page'])) {
exit;
}
$db = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $db) == 0) {
exit();
}
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate($centreon_path . 'www/widgets/open-tickets/src/templates/', './');
// Init Objects
$criticality = new CentreonCriticality($db);
$media = new CentreonMedia($db);
$rule = new Centreon_OpenTickets_Rule($db);
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$widgetId = filter_input(INPUT_GET, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
/**
* @var CentreonDB $dbb
*/
$dbb = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
if (! isset($preferences['rule'])) {
exit;
}
$macro_tickets = $rule->getMacroNames($preferences['rule'], $widgetId);
$aColorHost = [
0 => 'host_up',
1 => 'host_down',
2 => 'host_unreachable',
4 => 'host_pending',
];
$aColorService = [
0 => 'service_ok',
1 => 'service_warning',
2 => 'service_critical',
3 => 'service_unknown',
4 => 'pending',
];
$stateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
$aStateType = ['1' => 'H', '0' => 'S'];
$mainQueryParameters = [];
// Build Query
$query = "SELECT SQL_CALC_FOUND_ROWS h.host_id,
h.name AS hostname,
s.latency,
s.execution_time,
h.state AS h_state,
s.service_id,
s.description,
s.state AS s_state,
s.state_type AS state_type,
s.last_hard_state,
s.output,
s.scheduled_downtime_depth AS s_scheduled_downtime_depth,
s.acknowledged AS s_acknowledged,
s.notify AS s_notify,
s.active_checks AS s_active_checks,
s.passive_checks AS s_passive_checks,
h.scheduled_downtime_depth AS h_scheduled_downtime_depth,
h.acknowledged AS h_acknowledged,
h.notify AS h_notify,
h.active_checks AS h_active_checks,
h.passive_checks AS h_passive_checks,
s.last_check,
s.last_state_change,
s.last_hard_state_change,
s.last_time_ok,
s.check_attempt,
s.max_check_attempts,
h.action_url AS h_action_url,
h.notes_url AS h_notes_url,
s.action_url AS s_action_url,
s.notes_url AS s_notes_url,
h.last_hard_state_change AS host_last_hard_state_change,
h.last_time_up AS host_last_time_up,
CAST(mop1.timestamp AS UNSIGNED) AS host_ticket_time,
mop1.ticket_value AS host_ticket_id,
mopd1.subject AS host_ticket_subject,
CAST(mop2.timestamp AS UNSIGNED) AS service_ticket_time,
mopd2.subject AS service_ticket_subject,
mop2.ticket_value AS service_ticket_id,
CONCAT_WS('', mop1.ticket_value, mop2.ticket_value) AS ticket_id,
cv2.value AS criticality_id,
cv.value AS criticality_level,
h.icon_image
FROM hosts h
LEFT JOIN customvariables cv5 ON (
h.host_id = cv5.host_id AND (cv5.service_id IS NULL OR cv5.service_id = 0) AND cv5.name = '" . $macro_tickets['ticket_id'] . "'
)
LEFT JOIN mod_open_tickets mop1 ON (
cv5.value = mop1.ticket_value AND (
mop1.timestamp > h.last_time_up OR h.last_time_up IS NULL
)
)
LEFT JOIN mod_open_tickets_data mopd1 ON (mop1.ticket_id = mopd1.ticket_id), services s
LEFT JOIN customvariables cv ON (
s.service_id = cv.service_id AND s.host_id = cv.host_id AND cv.name = 'CRITICALITY_LEVEL'
)
LEFT JOIN customvariables cv2 ON (
s.service_id = cv2.service_id AND s.host_id = cv2.host_id AND cv2.name = 'CRITICALITY_ID'
)
LEFT JOIN customvariables cv3 ON (
s.service_id = cv3.service_id AND s.host_id = cv3.host_id AND cv3.name = '" . $macro_tickets['ticket_id'] . "'
)
LEFT JOIN mod_open_tickets mop2 ON (
cv3.value = mop2.ticket_value AND (
mop2.timestamp > s.last_time_ok OR s.last_time_ok IS NULL
)
)
LEFT JOIN mod_open_tickets_data mopd2 ON (mop2.ticket_id = mopd2.ticket_id)";
if (! $centreon->user->admin) {
$query .= ' , centreon_acl acl ';
}
$query .= " WHERE s.host_id = h.host_id
AND h.enabled = 1 AND h.name NOT LIKE '_Module_%'
AND s.enabled = 1 ";
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$query = CentreonUtils::conditionBuilder(
$query,
'h.name ' . CentreonUtils::operandToMysqlFormat($op) . " '" . $dbb->escape($search) . "' "
);
}
}
if (isset($preferences['service_description_search']) && $preferences['service_description_search'] != '') {
$tab = explode(' ', $preferences['service_description_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$query = CentreonUtils::conditionBuilder(
$query,
's.description ' . CentreonUtils::operandToMysqlFormat($op) . " '" . $dbb->escape($search) . "' "
);
}
}
$stateTab = [];
if (! empty($preferences['svc_warning'])) {
$stateTab[] = 1;
}
if (! empty($preferences['svc_critical'])) {
$stateTab[] = 2;
}
if (! empty($preferences['svc_unknown'])) {
$stateTab[] = 3;
}
if ($stateTab !== []) {
$query = CentreonUtils::conditionBuilder($query, ' s.state IN (' . implode(',', $stateTab) . ')');
}
if (! empty($preferences['duration_filter'])) {
$tab = explode(' ', $preferences['duration_filter']);
if (
count($tab) >= 2
&& ! empty($tab[0])
&& is_numeric($tab[1])
) {
$op = $tab[0];
if ($op === 'gt') {
$op = 'lt';
} elseif ($op === 'lt') {
$op = 'gt';
} elseif ($op === 'gte') {
$op = 'lte';
} elseif ($op === 'lte') {
$op = 'gte';
}
$op = CentreonUtils::operandToMysqlFormat($op);
$durationValue = time() - $tab[1];
if (! empty($op)) {
$query = CentreonUtils::conditionBuilder(
$query,
's.last_state_change ' . $op . ' ' . $durationValue
);
}
}
}
if (! empty($preferences['hide_down_host'])) {
$query = CentreonUtils::conditionBuilder($query, ' h.state != 1 ');
}
if (! empty($preferences['hide_unreachable_host'])) {
$query = CentreonUtils::conditionBuilder($query, ' h.state != 2 ');
}
if (! empty($preferences['hide_disable_notif_host'])) {
$query = CentreonUtils::conditionBuilder($query, ' h.notify != 0 ');
}
if (! empty($preferences['hide_disable_notif_service'])) {
$query = CentreonUtils::conditionBuilder($query, ' s.notify != 0 ');
}
// For Open Tickets
if (! isset($preferences['opened_tickets']) || $preferences['opened_tickets'] == 0) {
$query .= ' AND mop1.timestamp IS NULL ';
$query .= ' AND mop2.timestamp IS NULL ';
} else {
$query .= ' AND (mop1.timestamp IS NOT NULL ';
$query .= ' OR mop2.timestamp IS NOT NULL) ';
}
if (! empty($preferences['acknowledgement_filter'])) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$query = CentreonUtils::conditionBuilder($query, ' s.acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$query = CentreonUtils::conditionBuilder(
$query,
' s.acknowledged = 0 AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 '
);
}
}
if (! empty($preferences['downtime_filter'])) {
if ($preferences['downtime_filter'] == 'downtime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth = 0 ');
}
}
if (! empty($preferences['state_type_filter'])) {
if ($preferences['state_type_filter'] == 'hardonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 0 ');
}
}
if (! empty($preferences['poller'])) {
$resultsPoller = explode(',', $preferences['poller']);
$queryPoller = '';
foreach ($resultsPoller as $resultPoller) {
if ($queryPoller !== '') {
$queryPoller .= ', ';
}
$queryPoller .= ':instance_id_' . $resultPoller;
$mainQueryParameters[] = [
'parameter' => ':instance_id_' . $resultPoller,
'value' => (int) $resultPoller,
'type' => PDO::PARAM_INT,
];
}
$instanceIdCondition = ' h.instance_id IN (' . $queryPoller . ')';
$query = CentreonUtils::conditionBuilder($query, $instanceIdCondition);
}
if (! empty($preferences['hostgroup'])) {
$results = explode(',', $preferences['hostgroup']);
$queryHG = '';
foreach ($results as $result) {
if ($queryHG !== '') {
$queryHG .= ', ';
}
$queryHG .= ':id_' . $result;
$mainQueryParameters[] = [
'parameter' => ':id_' . $result,
'value' => (int) $result,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostgroup_relation
WHERE hostgroup_hg_id IN (' . $queryHG . ')
)'
);
}
if (! empty($preferences['servicegroup'])) {
$resultsSG = explode(',', $preferences['servicegroup']);
$querySG = '';
foreach ($resultsSG as $resultSG) {
if ($querySG !== '') {
$querySG .= ', ';
}
$querySG .= ':id_' . $resultSG;
$mainQueryParameters[] = [
'parameter' => ':id_' . $resultSG,
'value' => (int) $resultSG,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.service_id IN (
SELECT DISTINCT service_id
FROM services_servicegroups
WHERE servicegroup_id IN (' . $querySG . ')
)'
);
}
if (! empty($preferences['hostcategories'])) {
$resultsHC = explode(',', $preferences['hostcategories']);
$queryHC = '';
foreach ($resultsHC as $resultHC) {
if ($queryHC !== '') {
$queryHC .= ', ';
}
$queryHC .= ':id_' . $resultHC;
$mainQueryParameters[] = [
'parameter' => ':id_' . $resultHC,
'value' => (int) $resultHC,
'type' => PDO::PARAM_INT,
];
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostcategories_relation
WHERE hostcategories_hc_id IN (' . $queryHC . ')
)'
);
}
if (isset($preferences['display_severities'])
&& $preferences['display_severities']
&& isset($preferences['criticality_filter'])
&& $preferences['criticality_filter'] != ''
) {
$tab = explode(',', $preferences['criticality_filter']);
$labels = '';
foreach ($tab as $p) {
if ($labels != '') {
$labels .= ',';
}
$labels .= "'" . trim($p) . "'";
}
$query2 = 'SELECT sc_id FROM service_categories WHERE sc_name IN (' . $labels . ')';
$RES = $db->query($query2);
$idC = '';
while ($d1 = $RES->fetch()) {
if ($idC != '') {
$idC .= ',';
}
$idC .= $d1['sc_id'];
}
$query .= " AND cv2.`value` IN ({$idC}) ";
}
if (! $centreon->user->admin) {
$pearDB = $db;
$acls = new CentreonAclLazy($centreon->user->user_id);
if (! $acls->getAccessGroups()->isEmpty()) {
$groupList = implode(', ', $acls->getAccessGroups()->getIds());
$query .= " AND h.host_id = acl.host_id AND acl.service_id = s.service_id AND acl.group_id IN ({$groupList})";
} else {
// make the request return nothing if no ACL groups linked to the user
$query .= ' AND 1 = 0';
}
}
if (isset($preferences['output_search']) && $preferences['output_search'] != '') {
$tab = explode(' ', $preferences['output_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$query = CentreonUtils::conditionBuilder(
$query,
's.output ' . CentreonUtils::operandToMysqlFormat($op) . " '" . $dbb->escape($search) . "' "
);
}
}
if (isset($preferences['ticket_id_search']) && $preferences['ticket_id_search'] != '') {
$query .= " AND (mop1.ticket_value LIKE '" . $dbb->escape($preferences['ticket_id_search'])
. "' OR mop2.ticket_value LIKE '" . $dbb->escape($preferences['ticket_id_search']) . "') ";
}
if (isset($preferences['ticket_subject_search']) && $preferences['ticket_subject_search'] != '') {
$query .= " AND (mopd1.subject LIKE '" . $dbb->escape($preferences['ticket_subject_search'])
. "' OR mopd2.subject LIKE '" . $dbb->escape($preferences['ticket_subject_search']) . "') ";
}
$orderBy = 'hostname ASC , description ASC';
if (isset($preferences['order_by']) && $preferences['order_by'] != '') {
$aOrder = explode(' ', $preferences['order_by']);
if (in_array('last_state_change', $aOrder) || in_array('last_hard_state_change', $aOrder)) {
$order = $aOrder[1] == 'DESC' ? 'ASC' : 'DESC';
$orderBy = $aOrder[0] . ' ' . $order;
} else {
$orderBy = $preferences['order_by'];
}
if (isset($preferences['order_by2']) && $preferences['order_by2'] != '') {
$aOrder = explode(' ', $preferences['order_by2']);
$orderBy .= ', ' . $aOrder[0] . ' ' . $aOrder[1];
}
}
$query .= 'ORDER BY ' . $orderBy;
$query .= ' LIMIT ' . ($page * $preferences['entries']) . ',' . $preferences['entries'];
$res = $dbb->prepare($query);
foreach ($mainQueryParameters as $parameter) {
$res->bindValue($parameter['parameter'], $parameter['value'], $parameter['type']);
}
unset($parameter, $mainQueryParameters);
$res->execute();
$nbRows = $dbb->query('SELECT FOUND_ROWS()')->fetchColumn();
$data = [];
$outputLength = $preferences['output_length'] ?: 50;
$hostObj = new CentreonHost($db);
$svcObj = new CentreonService($db);
$gmt = new CentreonGMT();
$gmt->getMyGMTFromSession(session_id());
while ($row = $res->fetch()) {
foreach ($row as $key => $value) {
if ($key == 'last_check') {
$value = $gmt->getDate('Y-m-d H:i:s', $value);
} elseif ($key == 'last_state_change' || $key == 'last_hard_state_change') {
$value = time() - $value;
$value = CentreonDuration::toString($value);
} elseif ($key == 'check_attempt') {
$value = $value . '/' . $row['max_check_attempts'] . ' (' . $aStateType[$row['state_type']] . ')';
} elseif ($key == 's_state') {
$data[$row['host_id'] . '_' . $row['service_id']]['color'] = $aColorService[$value];
$value = $stateLabels[$value];
} elseif ($key == 'h_state') {
$data[$row['host_id'] . '_' . $row['service_id']]['hcolor'] = $aColorHost[$value];
$value = $stateLabels[$value];
} elseif ($key == 'output') {
$value = substr($value, 0, $outputLength);
} elseif (($key == 'h_action_url' || $key == 'h_notes_url') && $value) {
$value = CentreonUtils::escapeSecure($hostObj->replaceMacroInString($row['hostname'], $value));
if (preg_match("/^.\/include\/configuration\/configKnowledge\/proxy\/proxy.php(.*)/i", $value)) {
$value = '../../' . $value;
}
} elseif (($key == 's_action_url' || $key == 's_notes_url') && $value) {
$value = $hostObj->replaceMacroInString($row['hostname'], $value);
$value = CentreonUtils::escapeSecure($svcObj->replaceMacroInString($row['service_id'], $value));
if (preg_match("/^.\/include\/configuration\/configKnowledge\/proxy\/proxy.php(.*)/i", $value)) {
$value = '../../' . $value;
}
} elseif ($key == 'criticality_id' && $value != '') {
$critData = $criticality->getData($row['criticality_id'], 1);
$value = "<img src='../../img/media/" . $media->getFilename($critData['icon_id'])
. "' title='" . $critData['sc_name'] . "' width='16' height='16'>";
}
$data[$row['host_id'] . '_' . $row['service_id']][$key] = $value;
}
$data[$row['host_id'] . '_' . $row['service_id']]['encoded_description'] = urlencode(
$data[$row['host_id'] . '_' . $row['service_id']]['description']
);
$data[$row['host_id'] . '_' . $row['service_id']]['encoded_hostname'] = urlencode(
$data[$row['host_id'] . '_' . $row['service_id']]['hostname']
);
if ($row['host_ticket_time'] > $row['host_last_time_up']
&& isset($row['host_ticket_id']) && ! is_null($row['host_ticket_id']) && $row['host_ticket_id'] != ''
) {
$ticket_id = $row['host_ticket_id'];
$url = $rule->getUrl($preferences['rule'], $ticket_id, $row, $widgetId);
if (! is_null($url) && $url != '') {
$ticket_id = '<a href="' . $url . '" target="_blank">' . $ticket_id . '</a>';
}
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_id'] = $ticket_id;
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_time'] = $gmt->getDate(
'Y-m-d H:i:s',
$row['host_ticket_time']
);
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_subject'] = $row['host_ticket_subject'];
} elseif ($row['service_ticket_time'] > $row['last_time_ok']
&& isset($row['service_ticket_id'])
&& ! is_null($row['service_ticket_id'])
&& $row['service_ticket_id'] != ''
) {
$ticket_id = $row['service_ticket_id'];
$url = $rule->getUrl($preferences['rule'], $ticket_id, $row, $widgetId);
if (! is_null($url) && $url != '') {
$ticket_id = '<a href="' . $url . '" target="_blank">' . $ticket_id . '</a>';
}
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_id'] = $ticket_id;
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_time'] = $gmt->getDate(
'Y-m-d H:i:s',
$row['service_ticket_time']
);
$data[$row['host_id'] . '_' . $row['service_id']]['ticket_subject'] = $row['service_ticket_subject'];
}
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$data[$row['host_id'] . '_' . $row['service_id']]['h_details_uri'] = $useDeprecatedPages
? '../../main.php?p=0202&o=hd&host_name=' . $row['hostname']
: $resourceController->buildHostDetailsUri($row['host_id']);
$data[$row['host_id'] . '_' . $row['service_id']]['s_details_uri'] = $useDeprecatedPages
? '../../main.php?p=0202&o=hd&host_name=' . $row['hostname']
. '&service_description=' . $row['description']
: $resourceController->buildServiceDetailsUri($row['host_id'], $row['service_id']);
}
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $preferences['refresh_interval']);
$template->assign('preferences', $preferences);
$template->assign('page', $page);
$template->assign('dataJS', count($data));
$template->assign('nbRows', $nbRows);
$template->assign('preferences', $preferences);
$template->assign('data', $data);
$template->display('table.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/widgets/open-tickets/src/ajax/callforwardmodule.php | centreon-open-tickets/widgets/open-tickets/src/ajax/callforwardmodule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 $centreon_path . 'www/modules/centreon-open-tickets/views/rules/ajax/call.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/centreon-open-tickets.conf.php | centreon-open-tickets/www/modules/centreon-open-tickets/centreon-open-tickets.conf.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 dirname(__DIR__, 3) . '/bootstrap.php';
if (empty($centreon_path)) {
$centreon_path = dirname(__DIR__, 3) . '/';
}
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/request.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/providers/register.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/conf.php | centreon-open-tickets/www/modules/centreon-open-tickets/conf.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$module_conf['centreon-open-tickets']['rname'] = 'Centreon Open Tickets';
$module_conf['centreon-open-tickets']['name'] = 'centreon-open-tickets';
$module_conf['centreon-open-tickets']['mod_release'] = '26.01.0';
$module_conf['centreon-open-tickets']['infos'] = 'Centreon Open Tickets is a community module developed to '
. "create tickets to your favorite ITSM tools using API.
Once done provider configuration, the module allows for an operator to create tickets for hosts and services '
. 'in a non-ok state using a dedicated widget. Indeed, a button associated with each host or service allows '
. 'you to connect to the API and create the ticket while offering the possibility to acknowledge at the same '
. 'time the object.
Regarding the widget configuration, it is possible to see the created tickets by presenting tickets ID and "
. 'date of creation of these.
';
$module_conf['centreon-open-tickets']['is_removeable'] = '1';
$module_conf['centreon-open-tickets']['author'] = 'Centreon';
$module_conf['centreon-open-tickets']['stability'] = 'stable';
$module_conf['centreon-open-tickets']['last_update'] = '2025-11-18';
$module_conf['centreon-open-tickets']['images'] = [
'images/image1.png',
'images/image2.png',
'images/image3.png',
];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/next/php/upgrade.php | centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/next/php/upgrade.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
require_once __DIR__ . '/../../../providers/register.php';
$version = 'xx.xx.x';
$errorMessage = '';
/**
* @var ConnectionInterface|CentreonDB $pearDB
* @var ConnectionInterface $pearDBO
*/
$addProviderNameColumn = function () use ($pearDB, &$errorMessage): void {
$errorMessage = 'Failed to add `provider_name` column to mod_open_tickets_rule table';
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - adding `provider_name` column to configuration table mod_open_tickets_rule'
);
if ($pearDB->columnExists($pearDB->getConnectionConfig()->getDatabaseNameConfiguration(), 'mod_open_tickets_rule', 'provider_name')) {
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - nothing to do, column provider_name already defined in mod_open_tickets_rule table'
);
return;
}
$pearDB->executeStatement(
query: <<<'SQL'
ALTER TABLE `mod_open_tickets_rule` ADD COLUMN `provider_name` VARCHAR(255) NOT NULL AFTER `provider_id`
SQL
);
};
$migrateExistingRules = function () use ($pearDB, &$errorMessage, $register_providers): void {
$errorMessage = 'Failed to update provider names for existing rules';
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - finding rules to migrate (adding provider name regarding provider id configured)'
);
$rules = $pearDB->fetchAllAssociativeIndexed(
query: <<<'SQL'
SELECT rule_id, provider_id FROM mod_open_tickets_rule
SQL
);
if ($rules === []) {
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - nothing to do as no rules were configured'
);
}
foreach ($rules as $ruleId => $provider) {
$providerId = $provider['provider_id'];
if (! in_array($providerId, $register_providers)) {
CentreonLog::create()->warning(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - provider not found in registry, skipping rule',
customContext: [
'rule_id' => $ruleId,
'provider_id' => $providerId,
]
);
continue;
}
$providerName = array_search($providerId, $register_providers);
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: 'UPGRADE Open Tickets - updating provider name for rule',
customContext: [
'rule_id' => $ruleId,
'provider_id' => $providerId,
'provider_name' => $providerName,
]
);
$pearDB->update(
query: <<<'SQL'
UPDATE mod_open_tickets_rule SET provider_name = :providerName WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId), QueryParameter::string('providerName', $providerName)])
);
}
};
try {
$addProviderNameColumn();
if (! $pearDB->isTransactionActive()) {
$pearDB->startTransaction();
}
$migrateExistingRules();
$pearDB->commitTransaction();
} catch (Throwable $throwable) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: "UPGRADE Open Tickets - {$version}: " . $errorMessage,
exception: $throwable
);
try {
if ($pearDB->isTransactionActive()) {
$pearDB->rollBackTransaction();
}
} catch (ConnectionException $rollbackException) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: "UPGRADE Open Tickets - {$version}: error while rolling back the upgrade operation for : {$errorMessage}",
exception: $rollbackException
);
throw new RuntimeException(
message: "UPGRADE Open Tickets - {$version}: error while rolling back the upgrade operation for : {$errorMessage}",
previous: $rollbackException
);
}
throw new RuntimeException(
message: "UPGRADE Open Tickets - {$version}: " . $errorMessage,
previous: $throwable
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/25.11.0/php/upgrade.php | centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/25.11.0/php/upgrade.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/25.01.1/php/upgrade.php | centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/25.01.1/php/upgrade.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Regenerate routes. Should be present in the
// upgrade scripts of all versions.
require __DIR__ . '/../../../php/generate_routes.php';
// error specific content
$errorMessage = '';
$versionOfTheUpgrade = 'UPGRADE - 25.01.1: ';
/**
* @param CentreonDB $pearDB
*
* @throws CentreonDbException
* @return void
*/
$reOrderAndChangeType = function (CentreonDB $pearDB) use (&$errorMessage): void {
$errorMessage = 'Unable to update table topology to re order and change type of Create Ticket menu access';
$pearDB->executeQuery(
<<<'SQL'
UPDATE `topology`
SET `readonly` = '1', `topology_order` = 20, `topology_group` = 8, topology_name = 'Create Ticket'
WHERE `topology_page` = 60421
SQL
);
$errorMessage = 'Unable to update table acl_topology_relations (radio to checkbox ACL configuration)';
$pearDB->executeQuery(
<<<'SQL'
UPDATE acl_topology_relations AS t1
INNER JOIN topology AS t2 ON t1.topology_topology_id = t2.topology_id
SET t1.access_right = 0
WHERE t1.access_right = 2 AND t2.topology_page = 60421
SQL
);
};
try {
if (! $pearDB->inTransaction()) {
$pearDB->beginTransaction();
}
$reOrderAndChangeType($pearDB);
$pearDB->commit();
} catch (Exception $e) {
if ($pearDB->inTransaction()) {
try {
$pearDB->rollBack();
} catch (PDOException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: "{$versionOfTheUpgrade} error while rolling back the upgrade operation",
customContext: ['error_message' => $e->getMessage(), 'trace' => $e->getTraceAsString()],
exception: $e
);
}
}
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_UPGRADE,
message: $versionOfTheUpgrade . $errorMessage,
customContext: ['error_message' => $e->getMessage(), 'trace' => $e->getTraceAsString()],
exception: $e
);
throw new Exception($versionOfTheUpgrade . $errorMessage, (int) $e->getCode(), $e);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/24.09.0/php/upgrade.php | centreon-open-tickets/www/modules/centreon-open-tickets/upgrade/24.09.0/php/upgrade.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
require __DIR__ . '/../../../php/generate_routes.php';
require_once __DIR__ . '/../../../../../class/centreonLog.class.php';
$centreonLog = new CentreonLog();
// error specific content
$versionOfTheUpgrade = 'UPGRADE - 24.09.0';
$errorMessage = '';
$insertSubmitTicketTopology = function (CentreonDB $pearDB) use (&$errorMessage): void {
$errorMessage = 'Could not insert SubmitTicket form topology';
$statement = $pearDB->query('SELECT 1 FROM topology WHERE topology_page = 60421');
if ((bool) $statement->fetchColumn() === false) {
$pearDB->query(
<<<'SQL'
INSERT INTO topology
(
topology_name,
topology_parent,
topology_page,
topology_url,
topology_show,
readonly
) VALUES (
'Submit Ticket',
604,
60421,
'./modules/centreon-open-tickets/views/rules/submitTicket/action.php',
'0',
'0'
)
SQL
);
}
};
try {
if (! $pearDB->inTransaction()) {
$pearDB->beginTransaction();
}
$insertSubmitTicketTopology($pearDB);
$pearDB->commit();
} catch (Exception $e) {
if ($pearDB->inTransaction()) {
$pearDB->rollBack();
}
$centreonLog->insertLog(
4,
$versionOfTheUpgrade . $errorMessage
. ' - Code : ' . (int) $e->getCode()
. ' - Error : ' . $e->getMessage()
. ' - Trace : ' . $e->getTraceAsString()
);
throw new Exception($versionOfTheUpgrade . $errorMessage, (int) $e->getCode(), $e);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/webServices/rest/centreon_openticket.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/webServices/rest/centreon_openticket.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/api/class/webService.class.php';
define('CENTREON_OPENTICKET_PATH', _CENTREON_PATH_ . '/www/modules/centreon-open-tickets');
require_once CENTREON_OPENTICKET_PATH . '/class/rule.php';
require_once CENTREON_OPENTICKET_PATH . '/class/automatic.class.php';
class CentreonOpenticket extends CentreonWebService
{
/** @var Centreon */
public $centreon;
/** @var CentreonDB */
public $pearDBMonitoring;
/**
* @global Centreon $centreon
*/
public function __construct()
{
global $centreon;
$this->centreon = $centreon;
$this->pearDBMonitoring = new CentreonDB('centstorage');
parent::__construct();
}
public function postTestProvider()
{
if (! isset($this->arguments['service'])) {
throw new RestBadRequestException('Missing service argument');
}
$service = $this->arguments['service'];
if (! file_exists(
CENTREON_OPENTICKET_PATH . '/providers/' . $service . '/' . $service . 'Provider.class.php'
)) {
throw new RestBadRequestException('The service provider does not exists.');
}
include_once CENTREON_OPENTICKET_PATH . '/providers/Abstract/AbstractProvider.class.php';
include_once CENTREON_OPENTICKET_PATH . '/providers/' . $service . '/' . $service . 'Provider.class.php';
$className = $service . 'Provider';
if (! method_exists($className, 'test')) {
throw new RestBadRequestException('The service provider has no test function.');
}
try {
if (! $className::test($this->arguments)) {
throw new RestForbiddenException('Fail.');
}
return true;
} catch (Exception $e) {
throw new RestBadRequestException($e->getMessage());
}
}
/**
* Webservice to open a ticket for a service
*
* @return array
*/
public function postOpenService()
{
/* {
* "rule_name": "mail",
* "contact_name": "test",
* "contact_alias": "test2",
* "contact_email": "test@localhost",
* "host_id": 10,
* "service_id": 199,
* "host_name": "testhost", [$HOSTNAME$]
* "host_alias": "testhost", [$HOSTALIAS$]
* "service_description": "service1", [$SERVICEDESC$]
* "service_output": "output example", [$SERVICEOUTPUT$]
* "service_state": "CRITICAL" [$SERVICESTATE$]
* "last_service_state_change": 1498125177, [$LASTSERVICESTATECHANGE$]
* "extra_properties": {
* "custom_message": "my message"
* },
* "select": {
* "test": "26",
* "test2": "my value"
* }
* }
*/
if (
! isset($this->arguments['rule_name'])
|| ! isset($this->arguments['host_id'])
|| ! isset($this->arguments['service_id'])
|| ! isset($this->arguments['service_state'])
|| ! isset($this->arguments['service_output'])
) {
throw new RestBadRequestException('Parameters missing');
}
$rule = new Centreon_OpenTickets_Rule($this->pearDB);
$automatic = new Automatic(
$rule,
_CENTREON_PATH_,
CENTREON_OPENTICKET_PATH . '/',
$this->centreon,
$this->pearDBMonitoring,
$this->pearDB
);
try {
$rv = $automatic->openService($this->arguments);
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
return $rv;
}
/**
* Webservice to open a ticket for a host
*
* @return array
*/
public function postOpenHost()
{
/* {
* "rule_name": "mail",
* "contact_name": "test",
* "contact_alias": "test2",
* "contact_email": "test@localhost",
* "host_id": 10,
* "host_name": "testhost", [$HOSTNAME$]
* "host_alias": "testhost", [$HOSTALIAS$]
* "host_output": "output example", [$HOSTOUTPUT$]
* "host_state": "UP" [$HOSTSTATE$]
* "last_host_state_change": 1498125177, [$LASTHOSTSTATECHANGE$]
* "extra_properties": {
* "custom_message": "my message"
* },
* "select": {
* "test": "26",
* "test2": "my value"
* }
* }
*/
if (
! isset($this->arguments['rule_name'])
|| ! isset($this->arguments['host_id'])
|| ! isset($this->arguments['host_state'])
|| ! isset($this->arguments['host_output'])
) {
throw new RestBadRequestException('Parameters missing');
}
$rule = new Centreon_OpenTickets_Rule($this->pearDB);
$automatic = new Automatic(
$rule,
_CENTREON_PATH_,
CENTREON_OPENTICKET_PATH . '/',
$this->centreon,
$this->pearDBMonitoring,
$this->pearDB
);
try {
$rv = $automatic->openHost($this->arguments);
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
return $rv;
}
/**
* Webservice to close a ticket for a host
*
* @return array
*/
public function postCloseHost()
{
/* {
* "rule_name": "mail",
* "host_id": 10
*/
if (
! isset($this->arguments['rule_name'])
|| ! isset($this->arguments['host_id'])
) {
throw new RestBadRequestException('Parameters missing');
}
$rule = new Centreon_OpenTickets_Rule($this->pearDB);
$automatic = new Automatic(
$rule,
_CENTREON_PATH_,
CENTREON_OPENTICKET_PATH . '/',
$this->centreon,
$this->pearDBMonitoring,
$this->pearDB
);
try {
$rv = $automatic->closeHost($this->arguments);
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
return $rv;
}
/**
* Webservice to close a ticket for a service
*
* @return array
*/
public function postCloseService()
{
/* {
* "rule_name": "mail",
* "host_id": 10,
* "service_id": 30
*/
if (
! isset($this->arguments['rule_name'])
|| ! isset($this->arguments['service_id'])
|| ! isset($this->arguments['host_id'])
) {
throw new RestBadRequestException('Parameters missing');
}
$rule = new Centreon_OpenTickets_Rule($this->pearDB);
$automatic = new Automatic(
$rule,
_CENTREON_PATH_,
CENTREON_OPENTICKET_PATH . '/',
$this->centreon,
$this->pearDBMonitoring,
$this->pearDB
);
try {
$rv = $automatic->closeService($this->arguments);
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
return $rv;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/webServices/rest/centreon_openticket_history.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/webServices/rest/centreon_openticket_history.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/api/class/webService.class.php';
class CentreonOpenticketHistory extends CentreonWebService
{
/** @var Centreon */
public $centreon;
/** @var CentreonDB */
public $pearDBMonitoring;
/** @var CentreonDB|null */
protected $pearDB;
/**
* @global Centreon $centreon
*/
public function __construct()
{
global $centreon;
$this->centreon = $centreon;
$this->pearDBMonitoring = new CentreonDB('centstorage');
parent::__construct();
}
public function postSaveHistory()
{
/* {
* "ticket_id": "199",
* "timestamp": 1498125177,
* "user": "toto",
* "subject": "mon sujet",
* "links": [
* { "hostname": "plop", "service_description": "caca", "service_state": "1" },
* { "hostname": "plop", "service_description": "caca2", "service_state": "2" }
* ]
* }
*/
$result = ['code' => 0, 'message' => 'history saved'];
if (! isset($this->arguments['ticket_id'])
|| ! isset($this->arguments['user'])
|| ! isset($this->arguments['subject'])
|| ! is_array($this->arguments['links'])
) {
return ['code' => 1, 'message' => 'parameters missing'];
}
$timestamp = time();
if (isset($this->arguments['timestamp'])) {
$timestamp = $this->arguments['timestamp'];
}
$links_ok = [];
$stmt_host = $this->pearDBMonitoring->prepare('SELECT host_id FROM hosts WHERE name = ?');
$stmt_service = $this->pearDBMonitoring->prepare(
'SELECT hosts.host_id, services.service_id
FROM hosts, services
WHERE hosts.name = ?
AND hosts.host_id = services.host_id
AND services.description = ?'
);
foreach ($this->arguments['links'] as $link) {
if (isset($link['hostname'], $link['service_description'])) {
$res = $this->pearDBMonitoring->execute(
$stmt_service,
[$link['hostname'], $link['service_description']]
);
if ($row = $stmt_service->fetch()) {
$links_ok[] = array_merge(
$link,
['service_id' => $row['service_id'], 'host_id' => $row['host_id']]
);
}
} elseif (isset($link['hostname'])) {
$res = $this->pearDBMonitoring->execute($stmt_host, [$link['hostname']]);
if ($row = $stmt_host->fetch()) {
$links_ok[] = array_merge($link, ['host_id' => $row['host_id']]);
}
}
}
if (count($links_ok) == 0) {
return ['code' => 1, 'message' => 'links parameters missing or wrong'];
}
// Insert data
$this->pearDBMonitoring->beginTransaction();
$res = $this->pearDBMonitoring->query(
'INSERT INTO mod_open_tickets (`timestamp`, `user`, `ticket_value`) VALUES ('
. $this->pearDBMonitoring->quote($timestamp) . ', '
. $this->pearDBMonitoring->quote($this->arguments['user']) . ', '
. $this->pearDBMonitoring->quote($this->arguments['ticket_id'])
. ')'
);
if (PEAR::isError($res) === true) {
return ['code' => 1, 'message' => 'cannot insert in database'];
}
// Get Autoincrement
$res = $this->pearDBMonitoring->query('SELECT LAST_INSERT_ID() AS last_id');
if (PEAR::isError($res) === true || ! ($row = $res->fetch())) {
return ['code' => 1, 'message' => 'database issue'];
}
$auto_ticket = $row['last_id'];
// Insert data
$res = $this->pearDBMonitoring->query(
'INSERT INTO mod_open_tickets_data (`ticket_id`, `subject`) VALUES ('
. $this->pearDBMonitoring->quote($auto_ticket) . ', '
. $this->pearDBMonitoring->quote($this->arguments['subject'])
. ')'
);
if (PEAR::isError($res) === true) {
return ['code' => 1, 'message' => 'cannot insert in database'];
}
// Insert data
foreach ($links_ok as $link_ok) {
$names = '';
$values = '';
$append = '';
foreach ($link_ok as $key => $value) {
$names .= $append . $key;
$values .= $append . $this->pearDBMonitoring->quote($value);
$append = ', ';
}
$res = $this->pearDBMonitoring->query(
"INSERT INTO mod_open_tickets_link (`ticket_id`, {$names}) VALUES ("
. $this->pearDBMonitoring->quote($auto_ticket) . ', '
. $values
. ')'
);
if (PEAR::isError($res) === true) {
return ['code' => 1, 'message' => 'cannot insert in database'];
}
}
$this->pearDBMonitoring->commit();
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/index.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/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 './modules/centreon-open-tickets/centreon-open-tickets.conf.php';
// Smarty template initialization
$path = './modules/centreon-open-tickets/views/logs/templates/';
$tpl = SmartyBC::createSmartyTemplate($path);
// Form begin
$form = new HTML_QuickFormCustom('FormTicketLogs', 'get', '?p=' . $p);
$periods = ['' => '', '10800' => _('Last 3 Hours'), '21600' => _('Last 6 Hours'), '43200' => _('Last 12 Hours'), '86400' => _('Last 24 Hours'), '172800' => _('Last 2 Days'), '302400' => _('Last 4 Days'), '604800' => _('Last 7 Days'), '1209600' => _('Last 14 Days'), '2419200' => _('Last 28 Days'), '2592000' => _('Last 30 Days'), '2678400' => _('Last 31 Days'), '5184000' => _('Last 2 Months'), '10368000' => _('Last 4 Months'), '15552000' => _('Last 6 Months'), '31104000' => _('Last Year')];
$form->addElement(
'select',
'period',
_('Log Period'),
$periods
);
$form->addElement(
'text',
'StartDate',
'',
['id' => 'StartDate', 'class' => 'datepicker', 'size' => 8]
);
$form->addElement(
'text',
'StartTime',
'',
['id' => 'StartTime', 'class' => 'timepicker', 'size' => 5]
);
$form->addElement(
'text',
'EndDate',
'',
['id' => 'EndDate', 'class' => 'datepicker', 'size' => 8]
);
$form->addElement(
'text',
'EndTime',
'',
['id' => 'EndTime', 'class' => 'timepicker', 'size' => 5]
);
$form->addElement(
'text',
'subject',
_('Subject'),
['id' => 'subject', 'style' => 'width: 203px;', 'size' => 15, 'value' => '']
);
$form->addElement(
'text',
'ticket_id',
_('Ticket ID'),
['id' => 'ticket_id', 'style' => 'width: 203px;', 'size' => 15, 'value' => '']
);
$form->addElement(
'submit',
'graph',
_('Apply'),
['onclick' => 'return applyForm();', 'class' => 'btc bt_success']
);
$attrHosts = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_host&action=list', 'multiple' => true];
$attrHost1 = array_merge($attrHosts);
$form->addElement(
'select2',
'host_filter',
_('Hosts'),
[],
$attrHost1
);
$attrService = ['datasourceOrigin' => 'ajax', 'allowClear' => false, 'availableDatasetRoute' => './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_service&action=list', 'multiple' => true];
$attrService1 = array_merge($attrService);
$form->addElement(
'select2',
'service_filter',
_('Services'),
[],
$attrService1
);
$form->setDefaults(['period' => '10800']);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('viewLog.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/call.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/call.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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__ . '/../../../centreon-open-tickets.conf.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/ticketLog.php';
require_once $centreon_path . 'www/class/centreonXMLBGRequest.class.php';
$centreon_open_tickets_path = $centreon_path . 'www/modules/centreon-open-tickets/';
session_start();
$centreon_bg = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
$db = $dependencyInjector['configuration_db'];
$dbStorage = $dependencyInjector['realtime_db'];
$ticket_log = new Centreon_OpenTickets_Log($db, $dbStorage);
if (isset($_SESSION['centreon'])) {
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
} else {
exit;
}
require_once $centreon_path . 'www/include/common/common-Func.php';
$resultat = ['code' => 0, 'msg' => ''];
$actions = ['get-logs' => __DIR__ . '/actions/getLogs.php', 'export-csv' => __DIR__ . '/actions/exportCSV.php', 'export-xml' => __DIR__ . '/actions/exportXML.php'];
if (! isset($_POST['data'])) {
if (! isset($_GET['action'])) {
$resultat = ['code' => 1, 'msg' => "POST 'data' needed."];
} else {
include $actions[$_GET['action']];
}
} else {
$get_information = json_decode($_POST['data'], true);
if (! isset($get_information['action'])
|| ! isset($actions[$get_information['action']])) {
$resultat = ['code' => 1, 'msg' => 'Action not good.'];
} else {
include $actions[$get_information['action']];
}
}
header('Content-type: text/plain');
echo json_encode($resultat);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/getLogs.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/getLogs.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function set_pagination($tpl, $pagination, $current_page, $rows)
{
$tpl->assign('pagination', $pagination);
$tpl->assign('current_page', $current_page);
$num_page = (int) (($rows / $pagination) + 1);
$tpl->assign('num_page', $num_page);
$total = 10;
$bottom = $current_page - 1;
$top = $current_page + 1;
$bottom_display = [];
$top_display = [];
$arrow_first_display = 1;
$arrow_last_display = 1;
for (; $bottom > 0 && count($bottom_display) < 6; $bottom--) {
$bottom_display[] = $bottom;
$total--;
}
sort($bottom_display, SORT_NUMERIC);
if ($bottom <= 0) {
$arrow_first_display = 0;
}
for (; $top <= $num_page && $total >= 0; $top++) {
$top_display[] = $top;
$total--;
}
sort($top_display, SORT_NUMERIC);
if ($top > (($rows / $pagination) + 1)) {
$arrow_last_display = 0;
}
$tpl->assign('bottom_display', $bottom_display);
$tpl->assign('top_display', $top_display);
$tpl->assign('arrow_first_display', $arrow_first_display);
$tpl->assign('arrow_last_display', $arrow_last_display);
}
$resultat = ['code' => 0, 'msg' => 'ok', 'data' => null, 'pagination' => null];
// $fp = fopen('/tmp/debug.txt', 'a+');
// fwrite($fp, print_r($get_information, true));
$_SESSION['OT_form_logs'] = $get_information['form'];
try {
$tickets = $ticket_log->getLog($get_information['form'], $centreon_bg, $get_information['pagination'], $get_information['current_page']);
// fwrite($fp, print_r($tickets, true));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($centreon_open_tickets_path, 'views/logs/templates');
$tpl->assign('tickets', $tickets['tickets']);
$resultat['data'] = $tpl->fetch('data.ihtml');
// Get Pagination
set_pagination($tpl, $get_information['pagination'], $get_information['current_page'], $tickets['rows']);
$resultat['pagination'] = $tpl->fetch('pagination.ihtml');
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/exportCSV.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/exportCSV.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
header('Content-Type: application/csv-tab-delimited-table');
header('Content-disposition: filename=TicketLogs.csv');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
// $fp = fopen('/tmp/debug.txt', 'a+');
// fwrite($fp, print_r($_SESSION['OT_form_logs'], true));
try {
$tickets = $ticket_log->getLog($_SESSION['OT_form_logs'], $centreon_bg, null, null, true);
// fwrite($fp, print_r($tickets, true));
echo _('Begin date') . '; ' . _('End date') . ";\n";
echo $centreon_bg->GMT->getDate('m/d/Y (H:i:s)', intval($tickets['start'])) . ';' . $centreon_bg->GMT->getDate('m/d/Y (H:i:s)', intval($tickets['end'])) . "\n";
echo "\n";
echo _('Day') . ';' . _('Time') . ';' . _('Host') . ';' . _('Service') . ';' . _('Ticket ID') . ';' . _('User') . ';' . _('Subject') . "\n";
foreach ($tickets['tickets'] as $ticket) {
echo $centreon_bg->GMT->getDate('Y/m/d', $ticket['timestamp']) . ';' . $centreon_bg->GMT->getDate('H:i:s', $ticket['timestamp']) . ';' . $ticket['host_name'] . ';' . $ticket['service_description'] . ';' . $ticket['ticket_id'] . ';' . $ticket['user'] . ';' . $ticket['subject'] . "\n";
}
} catch (Exception $e) {
}
exit(1);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/exportXML.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/logs/ajax/actions/exportXML.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename=TicketLogs.xml');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
// $fp = fopen('/tmp/debug.txt', 'a+');
// fwrite($fp, print_r($_SESSION['OT_form_logs'], true));
try {
$tickets = $ticket_log->getLog($_SESSION['OT_form_logs'], $centreon_bg, null, null, true);
// fwrite($fp, print_r($tickets, true));
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<root>';
echo '<info>';
echo '<start>' . $centreon_bg->GMT->getDate('m/d/Y (H:i:s)', intval($tickets['start'])) . '</start><end>' . $centreon_bg->GMT->getDate('m/d/Y (H:i:s)', intval($tickets['end'])) . '</end>';
echo '</info>';
echo '<data>';
foreach ($tickets['tickets'] as $ticket) {
echo '<line>';
echo '<day>' . $centreon_bg->GMT->getDate('Y/m/d', $ticket['timestamp']) . '</day><time>' . $centreon_bg->GMT->getDate('H:i:s', $ticket['timestamp']) . '</time><host_name>' . $ticket['host_name'] . '</host_name><service_description>' . $ticket['service_description'] . '</service_description><ticket_id>' . $ticket['ticket_id'] . '</ticket_id><user>' . $ticket['user'] . '</user><subject>' . $ticket['subject'] . '</subject>';
echo '</line>';
}
echo '</data>';
echo '</root>';
} catch (Exception $e) {
}
exit(1);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/list.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/list.php | <?php
/*
* Copyright 2015-2019 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,*
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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;
// Smarty template initialization
$path = './modules/centreon-open-tickets/views/rules/';
$tpl = SmartyBC::createSmartyTemplate($path);
$rows = 0;
$nbRule = 0;
require './include/common/autoNumLimit.php';
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
$query = 'FROM mod_open_tickets_rule r';
$params = [];
if ($search) {
$query .= ' WHERE r.alias LIKE :search';
$params[] = QueryParameter::string('search', '%' . $search . '%');
}
$countQuery = 'SELECT COUNT(*) AS total ' . $query;
$query = 'SELECT r.rule_id, r.activate, r.alias ' . $query . ' ORDER BY r.alias';
$query .= ' LIMIT :offset, :limit';
try {
$rows = (int) $db->fetchOne(
$countQuery,
QueryParameters::create($params)
);
$params[] = QueryParameter::int('offset', $num * $limit);
$params[] = QueryParameter::int('limit', $limit);
$res = $db->fetchAllAssociative(
$query,
QueryParameters::create($params)
);
} catch (ConnectionException|RepositoryException|CollectionException|ValueObjectException $exception) {
$rows = 0;
$res = [];
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching open ticket rules: ' . $exception->getMessage(),
['search' => $search],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while fetching open ticket rules');
}
$elemArr = [];
$tdStyle = 'list_one';
$ruleStr = '';
foreach ($res as $row) {
$selectedElements = $form->addElement('checkbox', 'select[' . $row['rule_id'] . ']');
$elemArr[$row['rule_id']]['select'] = $selectedElements->toHtml();
$elemArr[$row['rule_id']]['url_edit'] = './main.php?p=' . $p . '&o=c&rule_id=' . $row['rule_id'];
$elemArr[$row['rule_id']]['name'] = $row['alias'];
$elemArr[$row['rule_id']]['status'] = $row['activate'] ? _('Enabled') : _('Disabled');
$elemArr[$row['rule_id']]['style'] = $tdStyle;
$dupElements = $form->addElement(
'text',
'duplicateNb[' . $row['rule_id'] . ']',
null,
['id' => 'duplicateNb[' . $row['rule_id'] . ']', 'size' => '3', 'value' => '1']
);
$moptions = '';
if ($row['activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&o=ds&rule_id=' . $row['rule_id'] . '&limit=' . $limit
. '&num=' . $num . "'><img class='ico-14' src='img/icons/disabled.png' border='0' alt='"
. _('Disabled') . "'></a>";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&o=e&rule_id=' . $row['rule_id'] . '&limit='
. $limit . '&num=' . $num . "'><img class='ico-14' src='img/icons/enabled.png' border='0' alt='"
. _('Enabled') . "'></a>";
}
$elemArr[$row['rule_id']]['dup'] = $moptions . ' ' . $dupElements->toHtml();
$tdStyle = $tdStyle == 'list_one' ? 'list_two' : 'list_one';
if ($ruleStr) {
$ruleStr .= ',';
}
$ruleStr .= "'" . $row['rule_id'] . "'";
$nbRule++;
}
$tpl->assign(
'msg',
['addL' => '?p=' . $p . '&o=a', 'add' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?'), 'img' => './modules/centreon-autodiscovery-server/images/add2.png']
);
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o1'].value = _i;
document.forms['form'].elements['o2'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('" . _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 4) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'd' => _('Delete'), 'e' => _('Enable'), 'ds' => _('Disable'), 'dp' => _('Duplicate')],
$attrs1
);
$attrs2 = ['onchange' => 'javascript: '
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('" . _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 4) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'd' => _('Delete'), 'e' => _('Enable'), 'ds' => _('Disable'), 'dp' => _('Duplicate')],
$attrs2
);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('elemArr', $elemArr);
$tpl->assign('searchLabel', _('Search'));
$tpl->assign('statusLabel', _('Status'));
$tpl->assign('ruleLabel', _('Rules'));
$tpl->assign('optionLabel', _('Options'));
$tpl->assign('search', $search);
$tpl->assign('nbRule', $nbRule);
$tpl->assign('no_rule_defined', _('No rule found'));
$tpl->assign('limit', $limit);
$tpl->display('list.ihtml');
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/index.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/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 './modules/centreon-open-tickets/centreon-open-tickets.conf.php';
$db = new CentreonDBManager();
$request = new CentreonOpenTicketsRequest();
$rule = new Centreon_OpenTickets_Rule($db);
$o = $request->getParam('o');
if (! $o) {
$o = $request->getParam('o1');
}
if (! $o) {
$o = $request->getParam('o2');
}
$ruleId = $request->getParam('rule_id');
$select = $request->getParam('select');
$duplicateNb = $request->getParam('duplicateNb');
$p = $request->getParam('p');
$num = $request->getParam('num');
$limit = $request->getParam('limit');
$search = $request->getParam('searchRule');
try {
switch ($o) {
case 'a':
require_once 'form.php';
break;
case 'd':
$rule->delete($select);
require_once 'list.php';
break;
case 'c':
require_once 'form.php';
break;
case 'l':
require_once 'list.php';
break;
case 'dp':
$rule->duplicate($select, $duplicateNb);
require_once 'list.php';
break;
case 'e':
if (empty($select) && $ruleId === null) {
throw new Exception('Please provide at least one rule to enable');
}
$rule->enable(! empty($select) ? $select : [$ruleId => '1']);
require_once 'list.php';
break;
case 'ds':
if (empty($select) && $ruleId === null) {
throw new Exception('Please provide at least one rule to disable');
}
$rule->disable(! empty($select) ? $select : [$ruleId => '1']);
require_once 'list.php';
break;
default:
require_once 'list.php';
break;
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/form.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/form.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Smarty template initialization
$path = './modules/centreon-open-tickets/views/rules/';
$tpl = SmartyBC::createSmartyTemplate($path);
$required_field = ' <font color="red" size="1">*</font>';
$tpl->assign('host', ['label' => _('Hosts')]);
$tpl->assign('rule', ['label' => _('Rules')]);
$tpl->assign('img_wrench', './modules/centreon-open-tickets/images/wrench.png');
$tpl->assign('img_info', './modules/centreon-open-tickets/images/information.png');
$tpl->assign('sort1', _('General'));
$tpl->assign('sort2', _('Advanced'));
$tpl->assign('header', ['title' => _('Rules'), 'general' => _('General information')]);
$result_rule = $rule->getAliasAndProviderId($ruleId);
$tpl->assign('page', $p);
$tpl->assign('rule_id', $ruleId);
$rule_alias_html = '<input size="30" name="rule_alias" type="text" value="'
. (htmlspecialchars($result_rule['alias'] ?? '', ENT_QUOTES, 'UTF-8')) . '" />';
$provider_html = '<select id="provider_id" name="provider_id"><option value=""></option>';
ksort($register_providers);
foreach ($register_providers as $name => $value) {
$selected = '';
if (isset($result_rule['provider_id']) && $result_rule['provider_id'] == $value) {
$selected = ' selected ';
}
$provider_html .= '<option value="' . $value . '"' . $selected . '>' . $name . '</option>';
}
$provider_html .= '</select>';
$array_rule_form = [
'rule_alias' => ['label' => _('Rule name') . $required_field, 'html' => $rule_alias_html],
'rule_provider' => ['label' => _('Provider') . $required_field, 'html' => $provider_html],
];
$tpl->assign('form', $array_rule_form);
$tpl->display('form.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/call.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/call.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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__ . '/../../../centreon-open-tickets.conf.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/providers/register.php';
require_once $centreon_path . 'www/class/centreonXMLBGRequest.class.php';
$centreon_open_tickets_path = $centreon_path . 'www/modules/centreon-open-tickets/';
require_once $centreon_open_tickets_path . 'providers/Abstract/AbstractProvider.class.php';
session_start();
$centreon_bg = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
$db = $dependencyInjector['configuration_db'];
$rule = new Centreon_OpenTickets_Rule($db);
if (isset($_SESSION['centreon'])) {
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
} else {
exit;
}
require_once $centreon_path . 'www/include/common/common-Func.php';
$resultat = ['code' => 0, 'msg' => ''];
$actions = ['get-form-config' => __DIR__ . '/actions/getFormConfig.php', 'save-form-config' => __DIR__ . '/actions/saveFormConfig.php', 'validate-format-popup' => __DIR__ . '/actions/validateFormatPopup.php', 'submit-ticket' => __DIR__ . '/actions/submitTicket.php', 'close-ticket' => __DIR__ . '/actions/closeTicket.php', 'service-ack' => __DIR__ . '/actions/serviceAck.php', 'upload-file' => __DIR__ . '/actions/uploadFile.php', 'remove-file' => __DIR__ . '/actions/removeFile.php', 'schedule-check' => __DIR__ . '/actions/scheduleCheck.php'];
if (! isset($_POST['data']) && ! isset($_REQUEST['action'])) {
$resultat = ['code' => 1, 'msg' => "POST 'data' needed."];
} else {
$get_information = isset($_POST['data']) ? json_decode($_POST['data'], true) : null;
$action = ! is_null($get_information) && isset($get_information['action'])
? $get_information['action'] : ($_REQUEST['action'] ?? 'none');
if (! isset($actions[$action])) {
$resultat = ['code' => 1, 'msg' => 'Action not good.'];
} else {
include $actions[$action];
}
}
header('Content-type: text/plain');
echo json_encode($resultat);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/removeFile.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/removeFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = ['code' => 0, 'msg' => 'ok'];
$temp_dir = sys_get_temp_dir();
unlink($temp_dir . '/opentickets/' . $get_information['uniqId'] . '__' . $get_information['filename']);
unset($_SESSION['ot_upload_files'][$get_information['uniqId']]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/getFormConfig.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/getFormConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = ['code' => 0, 'msg' => 'ok'];
// Load provider class
if (is_null($get_information['provider_id'])) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set provider_id';
return;
}
$provider_name = null;
foreach ($register_providers as $name => $id) {
if ($id == $get_information['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)
|| ! file_exists(
$centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php'
)
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set a provider';
return;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$centreon_provider = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$get_information['rule_id'],
null,
$get_information['provider_id'],
$provider_name
);
try {
$resultat['result'] = $centreon_provider->getConfig();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/submitTicket.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/submitTicket.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function get_contact_information()
{
global $db, $centreon_bg;
$result = ['alias' => '', 'email' => '', 'name' => ''];
$dbResult = $db->query(
"SELECT
contact_name as `name`,
contact_alias as `alias`,
contact_email as email
FROM contact
WHERE contact_id = '" . $centreon_bg->user_id . "' LIMIT 1"
);
if (($row = $dbResult->fetch())) {
$result = $row;
}
return $result;
}
function get_provider_class($rule_id)
{
global
$register_providers,
$centreon_open_tickets_path,
$rule,
$centreon_path,
$get_information;
$provider = $rule->getAliasAndProviderId($rule_id);
$provider_name = null;
foreach ($register_providers as $name => $id) {
if (isset($provider['provider_id']) && $id == $provider['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)) {
return null;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name
. '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$provider_class = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$rule_id,
$get_information['form'],
$provider['provider_id'],
$provider_name
);
return $provider_class;
}
function do_chain_rules($rule_list, $db_storage, $contact_infos, $selected)
{
$loop_check = [];
while (($provider = array_shift($rule_list))) {
$provider_class = get_provider_class($provider['Provider']);
if (is_null($provider_class)) {
continue;
}
if (isset($loop_check[$provider['Provider']])) {
continue;
}
$loop_check[$provider['Provider']] = 1;
$provider_class->submitTicket(
$db_storage,
$contact_infos,
$selected['host_selected'],
$selected['service_selected']
);
array_unshift($rule_list, $provider_class->getChainRuleList());
}
}
$resultat = ['code' => 0, 'msg' => 'ok'];
// Load provider class
if (is_null($get_information['provider_id']) || is_null($get_information['form'])) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set provider_id or form';
return;
}
$provider_name = null;
foreach ($register_providers as $name => $id) {
if ($id == $get_information['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)
|| ! file_exists(
$centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php'
)
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set a provider';
return;
}
if (! isset($get_information['form']['widgetId'])
|| is_null($get_information['form']['widgetId'])
|| $get_information['form']['widgetId'] == ''
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set widgetId';
return;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$centreon_provider = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$get_information['rule_id'],
$get_information['form'],
$get_information['provider_id'],
$provider_name
);
$centreon_provider->setWidgetId($get_information['form']['widgetId']);
$centreon_provider->setUniqId($get_information['form']['uniqId']);
// We get Host or Service
require_once $centreon_path . 'www/class/centreonDuration.class.php';
$selected_values = explode(',', $get_information['form']['selection']);
$db_storage = new CentreonDBManager('centstorage');
$selected = $rule->loadSelection(
$db_storage,
(string) $get_information['form']['cmd'],
(string) $get_information['form']['selection']
);
$sticky = ! empty($centreon->optGen['monitoring_ack_sticky']) ? 2 : 1;
$notify = ! empty($centreon->optGen['monitoring_ack_notify']) ? 1 : 0;
$persistent = ! empty($centreon->optGen['monitoring_ack_persistent']) ? 1 : 0;
try {
$contact_infos = get_contact_information();
$resultat['result'] = $centreon_provider->submitTicket(
$db_storage,
$contact_infos,
$selected['host_selected'],
$selected['service_selected']
);
if ($resultat['result']['ticket_is_ok'] == 1) {
do_chain_rules($centreon_provider->getChainRuleList(), $db_storage, $contact_infos, $selected);
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
$oreon = $_SESSION['centreon'];
$external_cmd = new CentreonExternalCommand();
$method_external_name = 'set_process_command';
if (method_exists($external_cmd, $method_external_name) == false) {
$method_external_name = 'setProcessCommand';
}
foreach ($selected['host_selected'] as $value) {
$command = 'CHANGE_CUSTOM_HOST_VAR;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['name'],
$centreon_provider->getMacroTicketId(),
$resultat['result']['ticket_id']
),
$value['instance_id'],
]
);
if ($centreon_provider->doAck()) {
$command = 'ACKNOWLEDGE_HOST_PROBLEM;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['name'],
$sticky,
$notify,
$persistent,
$contact_infos['alias'],
'open ticket: ' . $resultat['result']['ticket_id']
),
$value['instance_id'],
]
);
}
if ($centreon_provider->doesScheduleCheck()) {
$command = 'SCHEDULE_FORCED_HOST_CHECK;%s;%d';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['name'],
time()
),
$value['instance_id'],
]
);
}
}
foreach ($selected['service_selected'] as $value) {
$command = 'CHANGE_CUSTOM_SVC_VAR;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['host_name'],
$value['description'],
$centreon_provider->getMacroTicketId(),
$resultat['result']['ticket_id']
),
$value['instance_id'],
]
);
if ($centreon_provider->doAck()) {
$command = 'ACKNOWLEDGE_SVC_PROBLEM;%s;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['host_name'],
$value['description'],
$sticky,
$notify,
$persistent,
$contact_infos['alias'],
'open ticket: ' . $resultat['result']['ticket_id']
),
$value['instance_id'],
]
);
}
if ($centreon_provider->doesScheduleCheck()) {
$command = 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;%d';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$value['host_name'],
$value['description'],
time()
),
$value['instance_id'],
]
);
}
}
$external_cmd->write();
}
$centreon_provider->clearUploadFiles();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/serviceAck.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/serviceAck.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = [
'code' => 0,
'msg' => 'ok',
];
// We get Host or Service
$selected_values = explode(',', $get_information['form']['selection']);
$db_storage = new CentreonDBManager('centstorage');
$problems = [];
// check services and hosts
$selected_str = '';
$selected_str_append = '';
$hosts_selected_str = '';
$hosts_selected_str_append = '';
$hosts_done = [];
$services_done = [];
foreach ($selected_values as $value) {
$str = explode(';', $value);
$selected_str .= $selected_str_append . 'services.host_id = ' . $str[0] . ' AND services.service_id = ' . $str[1];
$selected_str_append = ' OR ';
if (! isset($hosts_done[$str[0]])) {
$hosts_selected_str .= $hosts_selected_str_append . $str[0];
$hosts_selected_str_append = ', ';
$hosts_done[$str[0]] = 1;
}
}
$query = '(SELECT DISTINCT services.description, hosts.name as host_name, hosts.instance_id FROM services, hosts
WHERE (' . $selected_str . ') AND services.host_id = hosts.host_id';
if (! $centreon_bg->is_admin) {
$query .= ' AND EXISTS(
SELECT * FROM centreon_acl WHERE centreon_acl.group_id IN ('
. $centreon_bg->grouplistStr . '
)
AND hosts.host_id = centreon_acl.host_id
AND services.service_id = centreon_acl.service_id
)';
}
$query .= ') UNION ALL (
SELECT DISTINCT NULL as description, hosts.name as host_name, hosts.instance_id
FROM hosts
WHERE hosts.host_id IN ('
. $hosts_selected_str . '
)';
if (! $centreon_bg->is_admin) {
$query .= ' AND EXISTS(
SELECT * FROM centreon_acl
WHERE centreon_acl.group_id IN ('
. $centreon_bg->grouplistStr . '
)
AND hosts.host_id = centreon_acl.host_id
)';
}
$query .= ') ORDER BY `host_name`, `description`';
$hosts_done = [];
$dbResult = $db_storage->query($query);
while (($row = $dbResult->fetch())) {
if (isset($hosts_done[$row['host_name'] . ';' . $row['description']])) {
continue;
}
$problems[] = $row;
$hosts_done[$row['host_name'] . ';' . $row['description']] = 1;
}
$persistent = 0;
$sticky = 0;
$notify = 0;
$forceCheck = false;
if (isset($get_information['form']['persistent'])) {
$persistent = 1;
}
if (isset($get_information['form']['sticky'])) {
$sticky = 2;
}
if (isset($get_information['form']['notify'])) {
$notify = 1;
}
if (isset($get_information['form']['forcecheck'])) {
$forceCheck = true;
}
try {
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
$oreon = $_SESSION['centreon'];
$external_cmd = new CentreonExternalCommand();
$method_external_name = 'set_process_command';
if (method_exists($external_cmd, $method_external_name) == false) {
$method_external_name = 'setProcessCommand';
}
$error_msg = [];
foreach ($problems as $row) {
if (is_null($row['description']) || $row['description'] == '') {
$command = 'ACKNOWLEDGE_HOST_PROBLEM;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$row['host_name'],
$sticky,
$notify,
$persistent,
$get_information['form']['author'],
$get_information['form']['comment']
),
$row['instance_id'],
]
);
if ($forceCheck) {
$command = 'SCHEDULE_FORCED_HOST_CHECK;%s;%d';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$row['host_name'],
time()
),
$row['instance_id'],
]
);
}
continue;
}
$command = 'ACKNOWLEDGE_SVC_PROBLEM;%s;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$row['host_name'],
$row['description'],
$sticky,
$notify,
$persistent,
$get_information['form']['author'],
$get_information['form']['comment']
),
$row['instance_id'],
]
);
if ($forceCheck) {
$command = 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;%d';
call_user_func_array(
[$external_cmd, $method_external_name],
[
sprintf(
$command,
$row['host_name'],
$row['description'],
time()
),
$row['instance_id'],
]
);
}
}
$external_cmd->write();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
$db->rollback();
}
$resultat['msg'] = 'successfully sent acknowledgement';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/validateFormatPopup.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/validateFormatPopup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = ['code' => 0, 'msg' => 'ok'];
// Load provider class
if (is_null($get_information['provider_id']) || is_null($get_information['form'])) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set provider_id or form';
return;
}
$provider_name = null;
foreach ($register_providers as $name => $id) {
if ($id == $get_information['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)
|| ! file_exists(
$centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php'
)
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set a provider';
return;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$centreon_provider = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$get_information['rule_id'],
$get_information['form'],
$get_information['provider_id'],
$provider_name
);
try {
$resultat['result'] = $centreon_provider->validateFormatPopup();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
$db->rollback();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/scheduleCheck.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/scheduleCheck.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$result = [
'code' => 0,
'msg' => 'ok',
];
// We get Host or Service
$selected_values = explode(',', $get_information['form']['selection']);
$forced = $get_information['form']['forced'];
$isService = $get_information['form']['isService'];
$db_storage = new CentreonDBManager('centstorage');
$problems = [];
// check services and hosts
$selected_str = '';
$selected_str_append = '';
$hosts_selected_str = '';
$hosts_selected_str_append = '';
$hostsDone = [];
$servicesDone = [];
foreach ($selected_values as $value) {
$str = explode(';', $value);
$selected_str .= $selected_str_append . 'services.host_id = ' . $str[0] . ' AND services.service_id = ' . $str[1];
$selected_str_append = ' OR ';
if (! isset($hosts_done[$str[0]])) {
$hosts_selected_str .= $hosts_selected_str_append . $str[0];
$hosts_selected_str_append = ', ';
$hosts_done[$str[0]] = 1;
}
}
$query = '(SELECT DISTINCT services.description, hosts.name as host_name, hosts.instance_id
FROM hosts
INNER JOIN services
ON services.host_id = hosts.host_id
WHERE (' . $selected_str . ')';
if (! $centreon_bg->is_admin) {
$query .= " AND EXISTS (
SELECT *
FROM centreon_acl
WHERE centreon_acl.group_id IN ({$centreon_bg->grouplistStr})
AND hosts.host_id = centreon_acl.host_id
AND services.service_id = centreon_acl.service_id
)";
}
$query .= ") UNION ALL (
SELECT DISTINCT NULL as description, hosts.name as host_name, hosts.instance_id
FROM hosts
WHERE hosts.host_id IN ({$hosts_selected_str})";
if (! $centreon_bg->is_admin) {
$query .= " AND EXISTS (
SELECT * FROM centreon_acl
WHERE centreon_acl.group_id IN ({$centreon_bg->grouplistStr})
AND hosts.host_id = centreon_acl.host_id
)";
}
$query .= ') ORDER BY `host_name`, `description`';
$hosts_done = [];
$dbResult = $db_storage->query($query);
while (($row = $dbResult->fetch())) {
if (isset($hosts_done[$row['host_name'] . ';' . $row['description']])) {
continue;
}
$problems[] = $row;
$hosts_done[$row['host_name'] . ';' . $row['description']] = 1;
}
try {
// fwrite($fp, print_r($problems, true) . "===\n");
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
$oreon = $_SESSION['centreon'];
$external_cmd = new CentreonExternalCommand();
$method_external_name = 'set_process_command';
if (method_exists($external_cmd, $method_external_name) == false) {
$method_external_name = 'setProcessCommand';
}
$error_msg = [];
foreach ($problems as $row) {
// host check action and service description from database is empty (meaning entry is about a host)
if (! $isService && (is_null($row['description']) || $row['description'] == '')) {
$command = $forced ? 'SCHEDULE_FORCED_HOST_CHECK;%s;%s' : 'SCHEDULE_HOST_CHECK;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf(
$command,
$row['host_name'],
time()
), $row['instance_id']]
);
continue;
// servuce check action and service description from database is empty (meaning entry is about a host)
}
if ($isService && (is_null($row['description']) || $row['description'] == '')) {
continue;
}
if ($isService) {
$command = $forced ? 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;%s' : 'SCHEDULE_SVC_CHECK;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf(
$command,
$row['host_name'],
$row['description'],
time()
), $row['instance_id']]
);
}
}
$external_cmd->write();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
$db->rollback();
}
$resultat['msg'] = 'Successfully scheduled the check';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/saveFormConfig.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/saveFormConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = ['code' => 0, 'msg' => 'ok'];
// Load provider class
if (is_null($get_information['provider_id']) || is_null($get_information['form'])) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set provider_id or form';
return;
}
if (! isset($get_information['form']['rule_alias'])
|| is_null($get_information['form']['rule_alias'])
|| $get_information['form']['rule_alias'] == ''
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set rule name';
return;
}
$provider_name = null;
foreach ($register_providers as $name => $id) {
if ($id == $get_information['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)
|| ! file_exists(
$centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php'
)
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set a provider';
return;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$centreon_provider = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$get_information['rule_id'],
$get_information['form'],
$get_information['provider_id'],
$provider_name
);
try {
$resultat['result'] = $centreon_provider->saveConfig();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
// rollback if transaction started
if ($db->inTransaction()) {
$db->rollback();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/uploadFile.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/uploadFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$resultat = ['code' => 0, 'msg' => 'ok'];
$uniq_id = $_REQUEST['uniqId'];
foreach ($_FILES as $file) {
$dir = dirname($file['tmp_name']);
$file_dst = $dir . '/opentickets/' . $uniq_id . '__' . $file['name'];
@mkdir($dir . '/opentickets', 0750);
if (rename($file['tmp_name'], $file_dst)) {
if (! isset($_SESSION['ot_upload_files'])) {
$_SESSION['ot_upload_files'] = [];
}
if (! isset($_SESSION['ot_upload_files'][$uniq_id])) {
$_SESSION['ot_upload_files'][$uniq_id] = [];
}
$_SESSION['ot_upload_files'][$uniq_id][$file_dst] = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/closeTicket.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/ajax/actions/closeTicket.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Exception\ConnectionException;
$resultat = ['code' => 0, 'msg' => 'ok'];
// Load provider class
if (is_null($get_information['provider_id']) || is_null($get_information['form'])) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set provider_id or form';
return;
}
$provider_name = null;
foreach ($register_providers as $name => $id) {
if ($id == $get_information['provider_id']) {
$provider_name = $name;
break;
}
}
if (is_null($provider_name)
|| ! file_exists(
$centreon_open_tickets_path . 'providers/' . $provider_name . '/' . $provider_name . 'Provider.class.php'
)
) {
$resultat['code'] = 1;
$resultat['msg'] = 'Please set a provider';
return;
}
require_once $centreon_open_tickets_path . 'providers/' . $provider_name
. '/' . $provider_name . 'Provider.class.php';
$classname = $provider_name . 'Provider';
$centreon_provider = new $classname(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$get_information['rule_id'],
$get_information['form'],
$get_information['provider_id'],
$provider_name
);
// We get Host or Service
$selected_values = explode(',', $get_information['form']['selection']);
$db_storage = new CentreonDBManager('centstorage');
$problems = [];
$tickets = [];
// check services and hosts
$selected_str = '';
$selected_str_append = '';
$hosts_selected_str = '';
$hosts_selected_str_append = '';
$hosts_done = [];
$services_done = [];
foreach ($selected_values as $value) {
$str = explode(';', $value);
$selected_str .= $selected_str_append . 'services.host_id = '
. $str[0] . ' AND services.service_id = ' . $str[1];
$selected_str_append = ' OR ';
if (! isset($hosts_done[$str[0]])) {
$hosts_selected_str .= $hosts_selected_str_append . $str[0];
$hosts_selected_str_append = ', ';
$hosts_done[$str[0]] = 1;
}
}
$query = '(SELECT DISTINCT
services.description, hosts.name as host_name, hosts.instance_id, mot.ticket_value, mot.timestamp
FROM services, hosts, mod_open_tickets_link as motl, mod_open_tickets as mot
WHERE (' . $selected_str . ') AND services.host_id = hosts.host_id';
if (! $centreon_bg->is_admin) {
$query .= ' AND EXISTS(
SELECT * FROM centreon_acl WHERE centreon_acl.group_id IN ('
. $centreon_bg->grouplistStr . '
)
AND hosts.host_id = centreon_acl.host_id
AND services.service_id = centreon_acl.service_id)';
}
$query .= ' AND motl.host_id = hosts.host_id
AND motl.service_id = services.service_id
AND motl.ticket_id = mot.ticket_id
) UNION ALL (
SELECT DISTINCT
NULL as description,
hosts.name as host_name,
hosts.instance_id,
mot.ticket_value,
mot.timestamp
FROM hosts, mod_open_tickets_link as motl, mod_open_tickets as mot
WHERE hosts.host_id IN (' . $hosts_selected_str . ')';
if (! $centreon_bg->is_admin) {
$query .= ' AND EXISTS(
SELECT * FROM centreon_acl
WHERE centreon_acl.group_id IN (
' . $centreon_bg->grouplistStr . '
) AND hosts.host_id = centreon_acl.host_id)';
}
$query .= ' AND motl.host_id = hosts.host_id
AND motl.service_id IS NULL
AND motl.ticket_id = mot.ticket_id
) ORDER BY `host_name`, `description`, `timestamp` DESC';
$hosts_done = [];
try {
$dbResult = $db_storage->fetchAllAssociative($query);
} catch (ConnectionException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching tickets to close: ' . $e->getMessage(),
exception: $e
);
$resultat['code'] = 1;
$resultat['msg'] = 'Error while fetching tickets to close: ' . $e->getMessage();
return;
}
foreach ($dbResult as $row) {
if (isset($hosts_done[$row['host_name'] . ';' . $row['description']])) {
continue;
}
$problems[] = $row;
$tickets[$row['ticket_value']] = ['status' => 0, 'msg_error' => null];
$hosts_done[$row['host_name'] . ';' . $row['description']] = 1;
}
try {
$centreon_provider->closeTicket($tickets);
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
$oreon = $_SESSION['centreon'];
$external_cmd = new CentreonExternalCommand();
$method_external_name = 'set_process_command';
if (method_exists($external_cmd, $method_external_name) == false) {
$method_external_name = 'setProcessCommand';
}
$removed_tickets = [];
$error_msg = [];
foreach ($problems as $row) {
// an error in ticket close
if (isset($tickets[$row['ticket_value']]) && $tickets[$row['ticket_value']]['status'] == -1) {
$error_msg[] = $tickets[$row['ticket_value']]['msg_error'];
// We close in centreon if ContinueOnError is ok
if ($centreon_provider->doCloseTicket()
&& $centreon_provider->doCloseTicketContinueOnError() == 0) {
continue;
}
}
// ticket is really closed
if ($tickets[$row['ticket_value']]['status'] == 2 && ! isset($removed_tickets[$row['ticket_value']])) {
$removed_tickets[$row['ticket_value']] = 1;
}
if (is_null($row['description']) || $row['description'] == '') {
$command = 'CHANGE_CUSTOM_HOST_VAR;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf($command, $row['host_name'], $centreon_provider->getMacroTicketId(), ''), $row['instance_id']]
);
$command = 'REMOVE_HOST_ACKNOWLEDGEMENT;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf($command, $row['host_name']), $row['instance_id']]
);
continue;
}
$command = 'CHANGE_CUSTOM_SVC_VAR;%s;%s;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf($command, $row['host_name'], $row['description'], $centreon_provider->getMacroTicketId(), ''), $row['instance_id']]
);
if ($centreon_provider->doAck()) {
$command = 'REMOVE_SVC_ACKNOWLEDGEMENT;%s;%s';
call_user_func_array(
[$external_cmd, $method_external_name],
[sprintf($command, $row['host_name'], $row['description']), $row['instance_id']]
);
}
}
$external_cmd->write();
} catch (Exception $e) {
$resultat['code'] = 1;
$resultat['msg'] = $e->getMessage();
$db->rollback();
}
$resultat['msg'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">' . _('Close Tickets') . '</td>
</tr>
<tr>
<td class="FormRowField" style="padding-left:15px;">Tickets closed: '
. join(',', array_keys($removed_tickets)) . '.</td>
</tr>';
if ($centreon_provider->doCloseTicket() && count($error_msg) > 0) {
$resultat['msg'] .= '<tr>
<td class="FormRowField" style="padding-left:15px; color: red">Issue to close tickets: '
. join('<br/>', $error_msg) . '.</td>
</tr>';
}
$resultat['msg'] .= '</table>';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/closeTicket/action.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/closeTicket/action.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once __DIR__ . '/../../../centreon-open-tickets.conf.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/providers/register.php';
require_once $centreon_path . 'www/class/centreonXMLBGRequest.class.php';
$centreon_open_tickets_path = $centreon_path . 'www/modules/centreon-open-tickets/';
require_once $centreon_open_tickets_path . 'providers/Abstract/AbstractProvider.class.php';
session_start();
/**
* Function that will check the selection payload.
*
* @param string $selection
*
* @return bool
*/
function isSelectionValid(string $selection): bool
{
preg_match('/^(\d+;?\d+,?)+$/', $selection, $matches);
return $matches !== [];
}
if (isset($_SESSION['centreon'])) {
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
} else {
$resultat = ['code' => 1, 'msg' => 'Invalid session'];
header('Content-type: text/plain');
echo json_encode($resultat);
exit;
}
$centreon_bg = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
$db = $dependencyInjector['configuration_db'];
$rule = new Centreon_OpenTickets_Rule($db);
$request = Symfony\Component\HttpFoundation\Request::createFromGlobals();
$payload = json_decode($request->getContent(), true);
$data = $payload['data'] ?? null;
if ($data === null) {
$resultat = ['code' => 1, 'msg' => 'POST data key missing'];
header('Content-type: text/plain');
echo json_encode($resultat);
exit;
}
if (
! isset($data['rule_id'])
|| (int) $data['rule_id'] <= 0
) {
$resultat = ['code' => 1, 'msg' => 'Rule ID should be provided as an integer'];
header('Content-type: text/plain');
echo json_encode($resultat);
exit;
}
$ruleInformation = $rule->getAliasAndProviderId($data['rule_id']);
if (
! isset($data['selection'])
|| ! isSelectionValid($data['selection'])
) {
$resultat = ['code' => 1, 'msg' => 'Resource selection not provided or not well formatted'];
header('Content-type: text/plain');
echo json_encode($resultat);
exit;
}
// re-create payload sent from the widget directly from this file
$get_information = [
'action' => 'close-ticket',
'rule_id' => $data['rule_id'],
'provider_id' => $ruleInformation['provider_id'],
'form' => [
'rule_id' => $data['rule_id'],
'provider_id' => $ruleInformation['provider_id'],
'selection' => $data['selection'],
],
];
require_once __DIR__ . '/../ajax/actions/closeTicket.php';
header('Content-type: text/plain');
echo json_encode($resultat);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/submitTicket/action.php | centreon-open-tickets/www/modules/centreon-open-tickets/views/rules/submitTicket/action.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../../../../../vendor/autoload.php');
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonXMLBGRequest.class.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
session_start();
$centreon_bg = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
?>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/jquery.serialize-object.min.js"></script>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/commonFunc.js"></script>
<script type="text/javascript" src="./modules/centreon-open-tickets/lib/dropzone.js"></script>
<link href="./modules/centreon-open-tickets/lib/dropzone.css" rel="stylesheet" type="text/css"/>
<?php
const SERVICE_OPEN_TICKET_COMMAND_ID = 3;
const HOST_OPEN_TICKET_COMMAND_ID = 4;
function format_popup(): void
{
global $cmd,
$rule,
$centreon,
$centreon_path,
$db;
$rules = [];
$statement = $db->query('SELECT rule_id, alias, provider_id FROM mod_open_tickets_rule');
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$rules[$row['rule_id']] = $row;
}
$uniqId = uniqid();
$title = $cmd === SERVICE_OPEN_TICKET_COMMAND_ID
? _('Open Service Ticket')
: _('Open Host Ticket');
$result = null;
if (isset($_GET['rule_id'])) {
$selection = $_GET['selection'] ?? $_GET['host_id'] . ';' . $_GET['service_id'];
$result = $rule->getFormatPopupProvider(
$_GET['rule_id'],
[
'title' => $title,
'user' => [
'name' => $centreon->user->name,
'alias' => $centreon->user->alias,
'email' => $centreon->user->email,
],
],
0,
$uniqId,
$_GET['cmd'],
$selection
);
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/open-tickets/src/';
$template = SmartyBC::createSmartyTemplate($path . 'templates/', './');
if (isset($_GET['rule_id'])) {
$template->assign('provider_id', $rules[$_GET['rule_id']]['provider_id']);
$template->assign('rule_id', $_GET['rule_id']);
$template->assign('widgetId', 0);
$template->assign('uniqId', $uniqId);
$template->assign('title', $title);
$template->assign('cmd', $cmd);
$template->assign('selection', $selection);
$template->assign('continue', (! is_null($result) && isset($result['format_popup'])) ? 0 : 1);
$template->assign(
'attach_files_enable',
(
! is_null($result)
&& isset($result['attach_files_enable'])
&& $result['attach_files_enable'] === 'yes'
) ? 1 : 0
);
$template->assign(
'formatPopupProvider',
(
! is_null($result)
&& isset($result['format_popup'])
) ? $result['format_popup'] : ''
);
$template->assign('submitLabel', _('Open'));
} else {
$template->assign('rules', $rules);
$template->assign('submitRule', _('Select'));
}
$template->display(__DIR__ . '/submitTicket.ihtml');
}
try {
if (! isset($_SESSION['centreon']) || ! isset($_GET['cmd'])) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) === 0) {
throw new Exception('Invalid session');
}
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
$oreon = $centreon->user;
$cmd = filter_input(INPUT_GET, 'cmd', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$widgetId = filter_input(INPUT_GET, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$selections = explode(',', $_REQUEST['selection']);
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$rule = new Centreon_OpenTickets_Rule($db);
if (
$cmd === SERVICE_OPEN_TICKET_COMMAND_ID
|| $cmd === HOST_OPEN_TICKET_COMMAND_ID
) {
format_popup();
} else {
throw new Exception('Unhandled data provided for cmd parameter');
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/widgets/Params/Connector/OpenTicketsRule.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/widgets/Params/Connector/OpenTicketsRule.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once __DIR__ . '/../../../../../class/centreonWidget/Params/List.class.php';
class CentreonWidgetParamsConnectorOpenTicketsRule extends CentreonWidgetParamsList
{
/**
* @param HTML_QuickForm $quickform
* @param mixed $db
* @param mixed $userId
*/
public function __construct($db, $quickform, $userId)
{
parent::__construct($db, $quickform, $userId);
}
public function getListValues($paramId)
{
static $tab;
if (! isset($tab)) {
$res = $this->db->query(
"SELECT rule_id, `alias` FROM mod_open_tickets_rule WHERE `activate` = '1' ORDER BY `alias`"
);
$tab = [null => null];
while ($row = $res->fetch()) {
$tab[$row['rule_id']] = $row['alias'];
}
}
return $tab;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/register.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/register.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$register_providers = [];
// provider name and the ID. For specific use id > 1000.
$register_providers['Mail'] = 1;
$register_providers['Glpi'] = 2;
$register_providers['Otrs'] = 3;
$register_providers['Simple'] = 4;
$register_providers['BmcItsm'] = 5;
$register_providers['Serena'] = 6;
$register_providers['BmcFootprints11'] = 7;
$register_providers['EasyvistaSoap'] = 8;
$register_providers['ServiceNow'] = 9;
$register_providers['Jira'] = 10;
$register_providers['GlpiRestApi'] = 11;
$register_providers['RequestTracker2'] = 12;
$register_providers['Itop'] = 13;
$register_providers['EasyVistaRest'] = 14;
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/MailProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/MailProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use PHPMailer\PHPMailer\Exception as MailerException;
use PHPMailer\PHPMailer\PHPMailer;
require_once __DIR__ . '/library/PHPMailer.php';
require_once __DIR__ . '/library/Exception.php';
class MailProvider extends AbstractProvider
{
protected $attach_files = 1;
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain(1);
}
protected function setDefaultValueExtra()
{
$this->default_data['from'] = '{$user.email}';
$this->default_data['subject']
= 'Issue {$ticket_id} - {include file="file:$centreon_open_tickets_path'
. '/providers/Abstract/templates/display_title.ihtml"}';
$this->default_data['clones']['headerMail'] = [];
$this->default_data['ishtml'] = 'yes';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('from', "Please set 'From' value");
$this->checkFormValue('to', "Please set 'To' value");
$this->checkFormValue('subject', "Please set 'Subject' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/Mail/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['mail' => _('Mail')]);
// Form
$from_html = '<input size="50" name="from" type="text" value="' . $this->getFormValue('from') . '" />';
$to_html = '<input size="50" name="to" type="text" value="' . $this->getFormValue('to') . '" />';
$subject_html = '<input size="50" name="subject" type="text" value="'
. $this->getFormValue('subject')
. '" />';
$ishtml_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="ishtml" name="ishtml" value="yes" '
. ($this->getFormValue('ishtml') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="ishtml"></label></div>';
$array_form = ['from' => ['label' => _('From') . $this->required_field, 'html' => $from_html], 'to' => ['label' => _('To') . $this->required_field, 'html' => $to_html], 'subject' => ['label' => _('Subject') . $this->required_field, 'html' => $subject_html], 'header' => ['label' => _('Headers')], 'ishtml' => ['label' => _('Use html'), 'html' => $ishtml_html]];
// Clone part
$headerMailName_html = '<input id="headerMailName_#index#" size="20" name="headerMailName[#index#]" '
. 'type="text" />';
$headerMailValue_html = '<input id="headerMailValue_#index#" size="20" name="headerMailValue[#index#]" '
. 'type="text" />';
$array_form['headerMail'] = [['label' => _('Name'), 'html' => $headerMailName_html], ['label' => _('Value'), 'html' => $headerMailValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['headerMail'] = $this->getCloneValue('headerMail');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['clones']['headerMail'] = $this->getCloneSubmitted('headerMail', ['Name', 'Value']);
$this->save_config['simple']['from'] = $this->submitted_config['from'];
$this->save_config['simple']['to'] = $this->submitted_config['to'];
$this->save_config['simple']['subject'] = $this->submitted_config['subject'];
$this->save_config['simple']['ishtml'] = (
isset($this->submitted_config['ishtml'])
&& $this->submitted_config['ishtml'] == 'yes'
) ? $this->submitted_config['ishtml'] : '';
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
/**
* @phpstan-ignore-next-line
* FIXME $contact['name'] => Offset 'name' does not exist on string => $contact is a string or an array ??
*/
$values = "('" . $result['ticket_time'] . "', '" . $db_storage->escape($contact['name']) . "')";
try {
$db_storage->query("INSERT INTO mod_open_tickets (`timestamp`, `user`) VALUES {$values}");
$result['ticket_id'] = $db_storage->lastinsertId('mod_open_tickets');
} catch (Exception $e) {
$result['ticket_error_message'] = $e->getMessage();
return $result;
}
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$tpl->assign('ticket_id', $result['ticket_id']);
$this->assignSubmittedValues($tpl);
// We send the mail
$tpl->assign('string', $this->rule_data['from']);
$from = $tpl->fetch('eval.ihtml');
$tpl->assign('string', $this->rule_data['subject']);
$subject = $tpl->fetch('eval.ihtml');
$mail = new PHPMailer(true);
try {
$mail->CharSet = 'utf-8';
$mail->setFrom($from);
$mail->addAddress($this->rule_data['to']);
if (isset($this->rule_data['ishtml']) && $this->rule_data['ishtml'] == 'yes') {
$mail->isHTML(true);
}
$attach_files = $this->getUploadFiles();
foreach ($attach_files as $file) {
$mail->addAttachment($file['filepath'], $file['filename']);
}
$headers = 'From: ' . $from;
if (isset($this->rule_data['clones']['headerMail'])) {
foreach ($this->rule_data['clones']['headerMail'] as $values) {
$mail->addCustomHeader($values['Name'], $values['Value']);
$headers .= "\r\n" . $values['Name'] . ':' . $values['Value'];
}
}
$mail->Subject = $subject;
$mail->Body = $this->body;
$mail->send();
$this->saveHistory(
$db_storage,
$result,
[
'no_create_ticket_id' => true,
'contact' => $contact,
'host_problems' => $host_problems,
'service_problems' => $service_problems,
'subject' => $subject,
'data_type' => self::DATA_TYPE_JSON,
'data' => json_encode(
[
'mail' => $mail->getSentMIMEMessage(),
]
),
]
);
} catch (MailerException $e) {
$result['ticket_error_message'] = 'Mailer Error: ' . $mail->ErrorInfo;
} catch (Exception $e) {
$result['ticket_error_message'] = 'Mailer Error: ' . $e->getMessage();
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/library/PHPMailer.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/library/PHPMailer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace PHPMailer\PHPMailer;
/**
* PHPMailer - PHP email creation and transport class.
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
*/
class PHPMailer
{
public const CHARSET_ASCII = 'us-ascii';
public const CHARSET_ISO88591 = 'iso-8859-1';
public const CHARSET_UTF8 = 'utf-8';
public const CONTENT_TYPE_PLAINTEXT = 'text/plain';
public const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
public const CONTENT_TYPE_TEXT_HTML = 'text/html';
public const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
public const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
public const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
public const ENCODING_7BIT = '7bit';
public const ENCODING_8BIT = '8bit';
public const ENCODING_BASE64 = 'base64';
public const ENCODING_BINARY = 'binary';
public const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
public const ENCRYPTION_STARTTLS = 'tls';
public const ENCRYPTION_SMTPS = 'ssl';
public const ICAL_METHOD_REQUEST = 'REQUEST';
public const ICAL_METHOD_PUBLISH = 'PUBLISH';
public const ICAL_METHOD_REPLY = 'REPLY';
public const ICAL_METHOD_ADD = 'ADD';
public const ICAL_METHOD_CANCEL = 'CANCEL';
public const ICAL_METHOD_REFRESH = 'REFRESH';
public const ICAL_METHOD_COUNTER = 'COUNTER';
public const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
/**
* The PHPMailer Version number.
*
* @var string
*/
public const VERSION = '6.6.0';
/**
* Error severity: message only, continue processing.
*
* @var int
*/
public const STOP_MESSAGE = 0;
/**
* Error severity: message, likely ok to continue processing.
*
* @var int
*/
public const STOP_CONTINUE = 1;
/**
* Error severity: message, plus full stop, critical error reached.
*
* @var int
*/
public const STOP_CRITICAL = 2;
/**
* The SMTP standard CRLF line break.
* If you want to change line break format, change static::$LE, not this.
*/
public const CRLF = "\r\n";
/**
* "Folding White Space" a white space string used for line folding.
*/
public const FWS = ' ';
/**
* The maximum line length supported by mail().
*
* Background: mail() will sometimes corrupt messages
* with headers headers longer than 65 chars, see #818.
*
* @var int
*/
public const MAIL_MAX_LINE_LENGTH = 63;
/**
* The maximum line length allowed by RFC 2822 section 2.1.1.
*
* @var int
*/
public const MAX_LINE_LENGTH = 998;
/**
* The lower maximum line length allowed by RFC 2822 section 2.1.1.
* This length does NOT include the line break
* 76 means that lines will be 77 or 78 chars depending on whether
* the line break format is LF or CRLF; both are valid.
*
* @var int
*/
public const STD_LINE_LENGTH = 76;
/**
* Email priority.
* Options: null (default), 1 = High, 3 = Normal, 5 = low.
* When null, the header is not set at all.
*
* @var int|null
*/
public $Priority;
/**
* The character set of the message.
*
* @var string
*/
public $CharSet = self::CHARSET_ISO88591;
/**
* The MIME Content-type of the message.
*
* @var string
*/
public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
/**
* The message encoding.
* Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
*
* @var string
*/
public $Encoding = self::ENCODING_8BIT;
/**
* Holds the most recent mailer error message.
*
* @var string
*/
public $ErrorInfo = '';
/**
* The From email address for the message.
*
* @var string
*/
public $From = '';
/**
* The From name of the message.
*
* @var string
*/
public $FromName = '';
/**
* The envelope sender of the message.
* This will usually be turned into a Return-Path header by the receiver,
* and is the address that bounces will be sent to.
* If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
*
* @var string
*/
public $Sender = '';
/**
* The Subject of the message.
*
* @var string
*/
public $Subject = '';
/**
* An HTML or plain text message body.
* If HTML then call isHTML(true).
*
* @var string
*/
public $Body = '';
/**
* The plain-text message body.
* This body can be read by mail clients that do not have HTML email
* capability such as mutt & Eudora.
* Clients that can read HTML will view the normal Body.
*
* @var string
*/
public $AltBody = '';
/**
* An iCal message part body.
* Only supported in simple alt or alt_inline message types
* To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
*
* @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
* @see http://kigkonsult.se/iCalcreator/
*
* @var string
*/
public $Ical = '';
/**
* Word-wrap the message body to this number of chars.
* Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
*
* @see static::STD_LINE_LENGTH
*
* @var int
*/
public $WordWrap = 0;
/**
* Which method to use to send mail.
* Options: "mail", "sendmail", or "smtp".
*
* @var string
*/
public $Mailer = 'mail';
/**
* The path to the sendmail program.
*
* @var string
*/
public $Sendmail = '/usr/sbin/sendmail';
/**
* Whether mail() uses a fully sendmail-compatible MTA.
* One which supports sendmail's "-oi -f" options.
*
* @var bool
*/
public $UseSendmailOptions = true;
/**
* The email address that a reading confirmation should be sent to, also known as read receipt.
*
* @var string
*/
public $ConfirmReadingTo = '';
/**
* The hostname to use in the Message-ID header and as default HELO string.
* If empty, PHPMailer attempts to find one with, in order,
* $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
* 'localhost.localdomain'.
*
* @see PHPMailer::$Helo
*
* @var string
*/
public $Hostname = '';
/**
* An ID to be used in the Message-ID header.
* If empty, a unique id will be generated.
* You can set your own, but it must be in the format "<id@domain>",
* as defined in RFC5322 section 3.6.4 or it will be ignored.
*
* @see https://tools.ietf.org/html/rfc5322#section-3.6.4
*
* @var string
*/
public $MessageID = '';
/**
* The message Date to be used in the Date header.
* If empty, the current date will be added.
*
* @var string
*/
public $MessageDate = '';
/**
* SMTP hosts.
* Either a single hostname or multiple semicolon-delimited hostnames.
* You can also specify a different port
* for each host by using this format: [hostname:port]
* (e.g. "smtp1.example.com:25;smtp2.example.com").
* You can also specify encryption type, for example:
* (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
* Hosts will be tried in order.
*
* @var string
*/
public $Host = 'localhost';
/**
* The default SMTP server port.
*
* @var int
*/
public $Port = 25;
/**
* The SMTP HELO/EHLO name used for the SMTP connection.
* Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
* one with the same method described above for $Hostname.
*
* @see PHPMailer::$Hostname
*
* @var string
*/
public $Helo = '';
/**
* What kind of encryption to use on the SMTP connection.
* Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
*
* @var string
*/
public $SMTPSecure = '';
/**
* Whether to enable TLS encryption automatically if a server supports it,
* even if `SMTPSecure` is not set to 'tls'.
* Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
*
* @var bool
*/
public $SMTPAutoTLS = true;
/**
* Whether to use SMTP authentication.
* Uses the Username and Password properties.
*
* @see PHPMailer::$Username
* @see PHPMailer::$Password
*
* @var bool
*/
public $SMTPAuth = false;
/**
* Options array passed to stream_context_create when connecting via SMTP.
*
* @var array
*/
public $SMTPOptions = [];
/**
* SMTP username.
*
* @var string
*/
public $Username = '';
/**
* SMTP password.
*
* @var string
*/
public $Password = '';
/**
* SMTP auth type.
* Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
*
* @var string
*/
public $AuthType = '';
/**
* The SMTP server timeout in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
*
* @var int
*/
public $Timeout = 300;
/**
* Comma separated list of DSN notifications
* 'NEVER' under no circumstances a DSN must be returned to the sender.
* If you use NEVER all other notifications will be ignored.
* 'SUCCESS' will notify you when your mail has arrived at its destination.
* 'FAILURE' will arrive if an error occurred during delivery.
* 'DELAY' will notify you if there is an unusual delay in delivery, but the actual
* delivery's outcome (success or failure) is not yet decided.
*
* @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
*/
public $dsn = '';
/**
* SMTP class debug output mode.
* Debug output level.
* Options:
* @see SMTP::DEBUG_OFF: No output
* @see SMTP::DEBUG_CLIENT: Client messages
* @see SMTP::DEBUG_SERVER: Client and server messages
* @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
* @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
*
* @see SMTP::$do_debug
*
* @var int
*/
public $SMTPDebug = 0;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
* By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
*
* ```php
* $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* ```
*
* Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
* level output is used:
*
* ```php
* $mail->Debugoutput = new myPsr3Logger;
* ```
*
* @see SMTP::$Debugoutput
*
* @var string|callable|\Psr\Log\LoggerInterface
*/
public $Debugoutput = 'echo';
/**
* Whether to keep the SMTP connection open after each message.
* If this is set to true then the connection will remain open after a send,
* and closing the connection will require an explicit call to smtpClose().
* It's a good idea to use this if you are sending multiple messages as it reduces overhead.
* See the mailing list example for how to use it.
*
* @var bool
*/
public $SMTPKeepAlive = false;
/**
* Whether to split multiple to addresses into multiple messages
* or send them all in one message.
* Only supported in `mail` and `sendmail` transports, not in SMTP.
*
* @var bool
*
* @deprecated 6.0.0 PHPMailer isn't a mailing list manager!
*/
public $SingleTo = false;
/**
* Whether to generate VERP addresses on send.
* Only applicable when sending via SMTP.
*
* @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
* @see http://www.postfix.org/VERP_README.html Postfix VERP info
*
* @var bool
*/
public $do_verp = false;
/**
* Whether to allow sending messages with an empty body.
*
* @var bool
*/
public $AllowEmpty = false;
/**
* DKIM selector.
*
* @var string
*/
public $DKIM_selector = '';
/**
* DKIM Identity.
* Usually the email address used as the source of the email.
*
* @var string
*/
public $DKIM_identity = '';
/**
* DKIM passphrase.
* Used if your key is encrypted.
*
* @var string
*/
public $DKIM_passphrase = '';
/**
* DKIM signing domain name.
*
* @example 'example.com'
*
* @var string
*/
public $DKIM_domain = '';
/**
* DKIM Copy header field values for diagnostic use.
*
* @var bool
*/
public $DKIM_copyHeaderFields = true;
/**
* DKIM Extra signing headers.
*
* @example ['List-Unsubscribe', 'List-Help']
*
* @var array
*/
public $DKIM_extraHeaders = [];
/**
* DKIM private key file path.
*
* @var string
*/
public $DKIM_private = '';
/**
* DKIM private key string.
*
* If set, takes precedence over `$DKIM_private`.
*
* @var string
*/
public $DKIM_private_string = '';
/**
* Callback Action function name.
*
* The function that handles the result of the send email action.
* It is called out by send() for each email sent.
*
* Value can be any php callable: http://www.php.net/is_callable
*
* Parameters:
* bool $result result of the send action
* array $to email addresses of the recipients
* array $cc cc email addresses
* array $bcc bcc email addresses
* string $subject the subject
* string $body the email body
* string $from email address of sender
* string $extra extra information of possible use
* "smtp_transaction_id' => last smtp transaction id
*
* @var string
*/
public $action_function = '';
/**
* What to put in the X-Mailer header.
* Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
*
* @var string|null
*/
public $XMailer = '';
/**
* Which validator to use by default when validating email addresses.
* May be a callable to inject your own validator, but there are several built-in validators.
* The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
*
* @see PHPMailer::validateAddress()
*
* @var string|callable
*/
public static $validator = 'php';
/**
* Value-array of "method" in Contenttype header "text/calendar"
*
* @var string[]
*/
protected static $IcalMethods = [
self::ICAL_METHOD_REQUEST,
self::ICAL_METHOD_PUBLISH,
self::ICAL_METHOD_REPLY,
self::ICAL_METHOD_ADD,
self::ICAL_METHOD_CANCEL,
self::ICAL_METHOD_REFRESH,
self::ICAL_METHOD_COUNTER,
self::ICAL_METHOD_DECLINECOUNTER,
];
/**
* The complete compiled MIME message body.
*
* @var string
*/
protected $MIMEBody = '';
/**
* The complete compiled MIME message headers.
*
* @var string
*/
protected $MIMEHeader = '';
/**
* Extra headers that createHeader() doesn't fold in.
*
* @var string
*/
protected $mailHeader = '';
/**
* An implementation of the PHPMailer OAuthTokenProvider interface.
*
* @var OAuthTokenProvider
*/
protected $oauth;
/**
* Storage for addresses when SingleTo is enabled.
*
* @var array
*/
protected $SingleToArray = [];
/**
* An instance of the SMTP sender class.
*
* @var SMTP
*/
protected $smtp;
/**
* The array of 'to' names and addresses.
*
* @var array
*/
protected $to = [];
/**
* The array of 'cc' names and addresses.
*
* @var array
*/
protected $cc = [];
/**
* The array of 'bcc' names and addresses.
*
* @var array
*/
protected $bcc = [];
/**
* The array of reply-to names and addresses.
*
* @var array
*/
protected $ReplyTo = [];
/**
* An array of all kinds of addresses.
* Includes all of $to, $cc, $bcc.
*
* @see PHPMailer::$to
* @see PHPMailer::$cc
* @see PHPMailer::$bcc
*
* @var array
*/
protected $all_recipients = [];
/**
* An array of names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $all_recipients
* and one of $to, $cc, or $bcc.
* This array is used only for addresses with IDN.
*
* @see PHPMailer::$to
* @see PHPMailer::$cc
* @see PHPMailer::$bcc
* @see PHPMailer::$all_recipients
*
* @var array
*/
protected $RecipientsQueue = [];
/**
* An array of reply-to names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $ReplyTo.
* This array is used only for addresses with IDN.
*
* @see PHPMailer::$ReplyTo
*
* @var array
*/
protected $ReplyToQueue = [];
/**
* The array of attachments.
*
* @var array
*/
protected $attachment = [];
/**
* The array of custom headers.
*
* @var array
*/
protected $CustomHeader = [];
/**
* The most recent Message-ID (including angular brackets).
*
* @var string
*/
protected $lastMessageID = '';
/**
* The message's MIME type.
*
* @var string
*/
protected $message_type = '';
/**
* The array of MIME boundary strings.
*
* @var array
*/
protected $boundary = [];
/**
* The array of available text strings for the current language.
*
* @var array
*/
protected $language = [];
/**
* The number of errors encountered.
*
* @var int
*/
protected $error_count = 0;
/**
* The S/MIME certificate file path.
*
* @var string
*/
protected $sign_cert_file = '';
/**
* The S/MIME key file path.
*
* @var string
*/
protected $sign_key_file = '';
/**
* The optional S/MIME extra certificates ("CA Chain") file path.
*
* @var string
*/
protected $sign_extracerts_file = '';
/**
* The S/MIME password for the key.
* Used only if the key is encrypted.
*
* @var string
*/
protected $sign_key_pass = '';
/**
* Whether to throw exceptions for errors.
*
* @var bool
*/
protected $exceptions = false;
/**
* Unique ID used for message ID and boundaries.
*
* @var string
*/
protected $uniqueid = '';
/**
* SMTP RFC standard line ending; Carriage Return, Line Feed.
*
* @var string
*/
protected static $LE = self::CRLF;
/**
* Constructor.
*
* @param bool $exceptions Should we throw external exceptions?
*/
public function __construct($exceptions = null)
{
if ($exceptions !== null) {
$this->exceptions = (bool) $exceptions;
}
// Pick an appropriate debug output format automatically
$this->Debugoutput = (str_contains(PHP_SAPI, 'cli') ? 'echo' : 'html');
}
/**
* Destructor.
*/
public function __destruct()
{
// Close any open SMTP connection nicely
$this->smtpClose();
}
/**
* Sets message type to HTML or plain.
*
* @param bool $isHtml True for HTML mode
*/
public function isHTML($isHtml = true): void
{
$this->ContentType = $isHtml ? static::CONTENT_TYPE_TEXT_HTML : static::CONTENT_TYPE_PLAINTEXT;
}
/**
* Send messages using SMTP.
*/
public function isSMTP(): void
{
$this->Mailer = 'smtp';
}
/**
* Send messages using PHP's mail() function.
*/
public function isMail(): void
{
$this->Mailer = 'mail';
}
/**
* Send messages using $Sendmail.
*/
public function isSendmail(): void
{
$ini_sendmail_path = ini_get('sendmail_path');
$this->Sendmail = stripos($ini_sendmail_path, 'sendmail') === false ? '/usr/sbin/sendmail' : $ini_sendmail_path;
$this->Mailer = 'sendmail';
}
/**
* Send messages using qmail.
*/
public function isQmail(): void
{
$ini_sendmail_path = ini_get('sendmail_path');
$this->Sendmail = stripos($ini_sendmail_path, 'qmail') === false ? '/var/qmail/bin/qmail-inject' : $ini_sendmail_path;
$this->Mailer = 'qmail';
}
/**
* Add a "To" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addAddress($address, $name = '')
{
return $this->addOrEnqueueAnAddress('to', $address, $name);
}
/**
* Add a "CC" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('cc', $address, $name);
}
/**
* Add a "BCC" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addBCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('bcc', $address, $name);
}
/**
* Add a "Reply-To" address.
*
* @param string $address The email address to reply to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addReplyTo($address, $name = '')
{
return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
}
/**
* Parse and validate a string containing one or more RFC822-style comma-separated email addresses
* of the form "display name <address>" into an array of name/address pairs.
* Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
* Note that quotes in the name part are removed.
*
* @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
*
* @param string $addrstr The address list string
* @param bool $useimap Whether to use the IMAP extension to parse the list
* @param string $charset the charset to use when decoding the address list string
*
* @return array
*/
public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591)
{
$addresses = [];
if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
// Use this built-in parser if it's available
$list = imap_rfc822_parse_adrlist($addrstr, '');
// Clear any potential IMAP errors to get rid of notices being thrown at end of script.
imap_errors();
foreach ($list as $address) {
if (
$address->host !== '.SYNTAX-ERROR.'
&& static::validateAddress($address->mailbox . '@' . $address->host)
) {
// Decode the name part if it's present and encoded
if (
property_exists($address, 'personal')
// Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
&& defined('MB_CASE_UPPER')
&& preg_match('/^=\?.*\?=$/s', $address->personal)
) {
$origCharset = mb_internal_encoding();
mb_internal_encoding($charset);
// Undo any RFC2047-encoded spaces-as-underscores
$address->personal = str_replace('_', '=20', $address->personal);
// Decode the name
$address->personal = mb_decode_mimeheader($address->personal);
mb_internal_encoding($origCharset);
}
$addresses[] = [
'name' => (property_exists($address, 'personal') ? $address->personal : ''),
'address' => $address->mailbox . '@' . $address->host,
];
}
}
} else {
// Use this simpler parser
$list = explode(',', $addrstr);
foreach ($list as $address) {
$address = trim($address);
// Is there a separate name part?
if (! str_contains($address, '<')) {
// No separate name, just use the whole thing
if (static::validateAddress($address)) {
$addresses[] = [
'name' => '',
'address' => $address,
];
}
} else {
[$name, $email] = explode('<', $address);
$email = trim(str_replace('>', '', $email));
$name = trim($name);
if (static::validateAddress($email)) {
// Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
// If this name is encoded, decode it
if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) {
$origCharset = mb_internal_encoding();
mb_internal_encoding($charset);
// Undo any RFC2047-encoded spaces-as-underscores
$name = str_replace('_', '=20', $name);
// Decode the name
$name = mb_decode_mimeheader($name);
mb_internal_encoding($origCharset);
}
$addresses[] = [
// Remove any surrounding quotes and spaces from the name
'name' => trim($name, '\'" '),
'address' => $email,
];
}
}
}
}
return $addresses;
}
/**
* Set the From and FromName properties.
*
* @param string $address
* @param string $name
* @param bool $auto Whether to also set the Sender address, defaults to true
*
* @throws Exception
*
* @return bool
*/
public function setFrom($address, $name = '', $auto = true)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); // Strip breaks and trim
// Don't validate now addresses with IDN. Will be done in send().
$pos = strrpos($address, '@');
if (
($pos === false)
|| ((! $this->has8bitChars(substr($address, ++$pos)) || ! static::idnSupported())
&& ! static::validateAddress($address))
) {
$error_message = sprintf(
'%s (From): %s',
$this->lang('invalid_address'),
$address
);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto && empty($this->Sender)) {
$this->Sender = $address;
}
return true;
}
/**
* Return the Message-ID header of the last email.
* Technically this is the value from the last time the headers were created,
* but it's also the message ID of the last sent message except in
* pathological cases.
*
* @return string
*/
public function getLastMessageID()
{
return $this->lastMessageID;
}
/**
* Check that a string looks like an email address.
* Validation patterns supported:
* * `auto` Pick best pattern automatically;
* * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
* * `pcre` Use old PCRE implementation;
* * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
* * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
* * `noregex` Don't use a regex: super fast, really dumb.
* Alternatively you may pass in a callable to inject your own validator, for example:
*
* ```php
* PHPMailer::validateAddress('user@example.com', function($address) {
* return (strpos($address, '@') !== false);
* });
* ```
*
* You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
*
* @param string $address The email address to check
* @param string|callable $patternselect Which pattern to use
*
* @return bool
*/
public static function validateAddress($address, $patternselect = null)
{
if ($patternselect === null) {
$patternselect = static::$validator;
}
// Don't allow strings as callables, see SECURITY.md and CVE-2021-3603
if (is_callable($patternselect) && ! is_string($patternselect)) {
return call_user_func($patternselect, $address);
}
// Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
if (str_contains($address, "\n") || str_contains($address, "\r")) {
return false;
}
switch ($patternselect) {
case 'pcre': // Kept for BC
case 'pcre8':
/*
* A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
* is based.
* In addition to the addresses allowed by filter_var, also permits:
* * dotless domains: `a@b`
* * comments: `1234 @ local(blah) .machine .example`
* * quoted elements: `'"test blah"@example.org'`
* * numeric TLDs: `a@b.123`
* * unbracketed IPv4 literals: `a@192.168.0.1`
* * IPv6 literals: 'first.last@[IPv6:a1::]'
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/library/Exception.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Mail/library/Exception.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace PHPMailer\PHPMailer;
/**
* PHPMailer exception handler.
*
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class Exception extends \Exception
{
/**
* Prettify error message output.
*
* @return string
*/
public function errorMessage()
{
return '<strong>' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "</strong><br />\n";
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/help.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/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['ca_cert_path'] = dgettext(
'help',
'Shall only be available when SSL Verify Peer option is enabled.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/CentreonCommon.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/CentreonCommon.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function smarty_function_host_get_hostgroups($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['host_id'])) {
$smarty->assign('host_get_hostgroups_result', []);
return;
}
$db = new CentreonDBManager('centstorage');
$result = [];
$dbResult = $db->query(
'SELECT hostgroups.* FROM hosts_hostgroups, hostgroups
WHERE hosts_hostgroups.host_id = ' . $params['host_id'] . '
AND hosts_hostgroups.hostgroup_id = hostgroups.hostgroup_id'
);
while (($row = $dbResult->fetch())) {
$result[$row['hostgroup_id']] = $row['name'];
}
$smarty->assign('host_get_hostgroups_result', $result);
}
function smarty_function_host_get_severity($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['host_id'])) {
$smarty->assign('host_get_severity_result', []);
return;
}
$db = new CentreonDBManager();
$result = [];
$dbResult = $db->query(
'SELECT
hc_id, hc_name, level
FROM hostcategories_relation, hostcategories
WHERE hostcategories_relation.host_host_id = ' . $params['host_id'] . "
AND hostcategories_relation.hostcategories_hc_id = hostcategories.hc_id
AND level IS NOT NULL AND hc_activate = '1'
ORDER BY level DESC
LIMIT 1"
);
while (($row = $dbResult->fetch())) {
$result[$row['hc_id']] = ['name' => $row['hc_name'], 'level' => $row['level']];
}
$smarty->assign('host_get_severity_result', $result);
}
/*
* Smarty example:
* {host_get_hostcategories host_id="104"}
* host categories linked:
* {foreach from=$host_get_hostcategories_result key=hc_id item=i}
* id: {$hc_id} name = {$i.name}
* {/foreach}
*
*/
function smarty_function_host_get_hostcategories($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['host_id'])) {
$smarty->assign('host_get_hostcategories_result', []);
return;
}
$db = new CentreonDBManager();
$loop = [];
$array_stack = [$params['host_id']];
$result = [];
while ($host_id = array_shift($array_stack)) {
if (isset($loop[$host_id])) {
continue;
}
$loop[$host_id] = 1;
$dbResult = $db->query(
"SELECT htr.host_tpl_id, hcr.hostcategories_hc_id, hostcategories.hc_name
FROM host
LEFT JOIN host_template_relation htr ON host.host_id = htr.host_host_id
LEFT JOIN hostcategories_relation hcr ON htr.host_host_id = hcr.host_host_id
LEFT JOIN hostcategories ON hostcategories.hc_id = hcr.hostcategories_hc_id
AND hostcategories.hc_activate = '1'
WHERE host.host_id = " . $host_id . ' ORDER BY `order` ASC'
);
while (($row = $dbResult->fetch())) {
if (! is_null($row['host_tpl_id']) && $row['host_tpl_id'] != '') {
array_unshift($array_stack, $row['host_tpl_id']);
}
if (! is_null($row['hostcategories_hc_id']) && $row['hostcategories_hc_id'] != '') {
$result[$row['hostcategories_hc_id']] = ['name' => $row['hc_name']];
}
}
}
$smarty->assign('host_get_hostcategories_result', $result);
}
/*
* Smarty example:
* {service_get_servicecategories service_id="1928"}
* service categories linked:
* {foreach from=$service_get_servicecategories_result key=sc_id item=i}
* id: {$sc_id} name = {$i.name}, description = {$i.description}
* {/foreach}
*
*/
function smarty_function_service_get_servicecategories($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['service_id'])) {
$smarty->assign('service_get_servicecategories_result', []);
return;
}
$db = new CentreonDBManager();
$loop = [];
$array_stack = [$params['service_id']];
$result = [];
while ($service_id = array_shift($array_stack)) {
if (isset($loop[$service_id])) {
continue;
}
$loop[$service_id] = 1;
$dbResult = $db->query(
"SELECT service.service_template_model_stm_id, sc.sc_id, sc.sc_name, sc.sc_description
FROM service
LEFT JOIN service_categories_relation scr ON service.service_id = scr.service_service_id
LEFT JOIN service_categories sc ON sc.sc_id = scr.sc_id AND sc.sc_activate = '1'
WHERE service.service_id = " . $service_id
);
while (($row = $dbResult->fetch())) {
if (! is_null($row['service_template_model_stm_id']) && $row['service_template_model_stm_id'] != '') {
array_unshift($array_stack, $row['service_template_model_stm_id']);
}
if (! is_null($row['sc_id']) && $row['sc_id'] != '') {
$result[$row['sc_id']] = ['name' => $row['sc_name'], 'description' => $row['sc_description']];
}
}
}
$smarty->assign('service_get_servicecategories_result', $result);
}
/*
* Smarty example:
* {service_get_servicegroups host_id="104" service_id="1928"}
* service groups linked:
* {foreach from=$service_get_servicegroups_result key=sg_id item=i}
* id: {$sg_id} name = {$i.name}, alias = {$i.alias}
* {/foreach}
*
*/
function smarty_function_service_get_servicegroups($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['service_id'])) {
$smarty->assign('service_get_servicegroups_result', []);
return;
}
$db = new CentreonDBManager();
$result = [];
$service_id_tpl = $params['service_id'];
if (isset($params['host_id'])) {
$dbResult = $db->query(
"SELECT service.service_template_model_stm_id, sg.sg_id, sg.sg_name, sg.sg_alias
FROM servicegroup_relation sgr
LEFT JOIN servicegroup sg ON sgr.servicegroup_sg_id = sg.sg_id
AND sg.sg_activate = '1'
LEFT JOIN service ON service.service_id = sgr.service_service_id
WHERE sgr.host_host_id = " . $params['host_id'] . '
AND sgr.service_service_id = ' . $params['service_id']
);
while (($row = $dbResult->fetch())) {
$service_id_tpl = $row['service_template_model_stm_id'];
if (! is_null($row['sg_id']) && $row['sg_id'] != '') {
$result[$row['sg_id']] = ['name' => $row['sg_name'], 'alias' => $row['sg_alias']];
}
}
}
$loop_array = [];
while (! is_null($service_id_tpl) && $service_id_tpl != '') {
if (isset($loop_array[$service_id_tpl])) {
break;
}
$loop_array[$service_id_tpl] = 1;
$dbResult = $db->query(
"SELECT service.service_template_model_stm_id, sg.sg_id, sg.sg_name, sg.sg_alias
FROM servicegroup_relation sgr
LEFT JOIN servicegroup sg ON sgr.servicegroup_sg_id = sg.sg_id
AND sg.sg_activate = '1'
LEFT JOIN service ON service.service_id = sgr.service_service_id
WHERE sgr.service_service_id = " . $service_id_tpl
);
while (($row = $dbResult->fetch())) {
$service_id_tpl = $row['service_template_model_stm_id'];
if (! is_null($row['sg_id']) && $row['sg_id'] != '') {
$result[$row['sg_id']] = ['name' => $row['sg_name'], 'alias' => $row['sg_alias']];
}
}
}
$smarty->assign('service_get_servicegroups_result', $result);
}
function smarty_function_host_get_macro_value_in_config($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['host_id'])) {
$smarty->assign('host_get_macro_value_in_config_result', '');
return;
}
if (! isset($params['macro_name'])) {
$smarty->assign('host_get_macro_value_in_config_result', '');
return;
}
$db = new CentreonDBManager();
// Look macro in current host
$dbResult = $db->query(
'SELECT host_macro_value
FROM on_demand_macro_host
WHERE host_host_id = ' . $params['host_id'] . "
AND host_macro_name = '\$_HOST" . $params['macro_name'] . "\$'"
);
if (($row = $dbResult->fetch())) {
$smarty->assign('host_get_macro_value_in_config_result', $row['host_macro_value']);
return;
}
// Look macro in host template relation
$loop = [];
$array_stack = [['host_id' => $params['host_id'], 'macro_value' => null]];
$result = '';
while (($host_entry = array_pop($array_stack))) {
if (isset($loop[$host_entry['host_id']])) {
continue;
}
if (! is_null($host_entry['macro_value'])) {
$result = $host_entry['macro_value'];
break;
}
$loop[$host_entry['host_id']] = 1;
$dbResult = $db->query(
"SELECT
host_tpl_id, macro.host_macro_value
FROM host_template_relation
LEFT JOIN on_demand_macro_host macro ON macro.host_host_id = host_template_relation.host_tpl_id
AND macro.host_macro_name = '\$_HOST" . $params['macro_name'] . "\$'
WHERE host_template_relation.host_host_id = " . $host_entry['host_id'] . '
ORDER BY `order` DESC'
);
while (($row = $dbResult->fetch())) {
$entry = ['host_id' => $row['host_tpl_id'], 'macro_value' => null];
if (! is_null($row['host_macro_value'])) {
$entry['macro_value'] = $row['host_macro_value'];
}
array_push($array_stack, $entry);
}
}
$smarty->assign('host_get_macro_value_in_config_result', $result);
}
function smarty_function_host_get_macro_values_in_config($params, &$smarty)
{
include_once __DIR__ . '/../../centreon-open-tickets.conf.php';
include_once __DIR__ . '/../../class/centreonDBManager.class.php';
if (! isset($params['host_id'])) {
$smarty->assign('host_get_macro_values_in_config_result', []);
return;
}
if (! isset($params['macro_name'])) {
$smarty->assign('host_get_macro_values_in_config_result', []);
return;
}
$db = new CentreonDBManager();
$result = [];
// Get level 1
$dbresult1 = $db->query(
"SELECT
host_tpl_id, macro.host_macro_value
FROM host_template_relation
LEFT JOIN on_demand_macro_host macro ON macro.host_host_id = host_template_relation.host_tpl_id
AND macro.host_macro_name = '\$_HOST" . $params['macro_name'] . "\$'
WHERE host_template_relation.host_host_id = " . $params['host_id'] . '
ORDER BY `order` ASC'
);
while (($row_entry_level1 = $dbresult1->fetch())) {
$loop = [];
$array_stack = [['host_id' => $row_entry_level1['host_tpl_id'], 'macro_value' => $row_entry_level1['host_macro_value']]];
while (($host_entry = array_pop($array_stack))) {
if (isset($loop[$host_entry['host_id']])) {
continue;
}
if (! is_null($host_entry['macro_value'])) {
$result[] = $host_entry['macro_value'];
break;
}
$loop[$host_entry['host_id']] = 1;
$dbResult = $db->query(
"SELECT
host_tpl_id, macro.host_macro_value
FROM host_template_relation
LEFT JOIN on_demand_macro_host macro ON macro.host_host_id = host_template_relation.host_tpl_id
AND macro.host_macro_name = '\$_HOST" . $params['macro_name'] . "\$'
WHERE host_template_relation.host_host_id = " . $host_entry['host_id'] . '
ORDER BY `order` DESC'
);
while (($row = $dbResult->fetch())) {
$entry = ['host_id' => $row['host_tpl_id'], 'macro_value' => null];
if (! is_null($row['host_macro_value'])) {
$entry['macro_value'] = $row['host_macro_value'];
}
array_push($array_stack, $entry);
}
}
}
$smarty->assign('host_get_macro_values_in_config_result', $result);
}
function smarty_function_sortgroup($params, &$smarty)
{
asort($params['group']);
$smarty->assign('sortgroup_result', $params['group']);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/AbstractProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Abstract/AbstractProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once __DIR__ . '/CentreonCommon.php';
abstract class AbstractProvider
{
public const HOSTGROUP_TYPE = 0;
public const HOSTCATEGORY_TYPE = 1;
public const HOSTSEVERITY_TYPE = 2;
public const SERVICEGROUP_TYPE = 3;
public const SERVICECATEGORY_TYPE = 4;
public const SERVICESEVERITY_TYPE = 5;
public const SERVICECONTACTGROUP_TYPE = 6;
public const CUSTOM_TYPE = 7;
public const BODY_TYPE = 8;
public const DATA_TYPE_JSON = 0;
public const DATA_TYPE_XML = 1;
/** @var array<mixed> */
protected $rule_data;
/** @var array<mixed> */
protected $default_data;
/** @var array<int, string> */
protected $rule_list;
/** @var Centreon_OpenTickets_Rule */
protected $rule;
/** @var int */
protected $rule_id;
/** @var string */
protected $centreon_path;
/** @var string */
protected $centreon_open_tickets_path;
/** @var array<mixed> */
protected $config = ['container1_html' => '', 'container2_html' => '', 'clones' => []];
/** @var string */
protected $required_field = ' <font color="red" size="1">*</font>';
/** @var mixed */
protected $submitted_config = null;
/** @var string */
protected $check_error_message = '';
/** @var string */
protected $check_error_message_append = '';
/** @var string */
protected $body = '';
/** @var array<mixed> */
protected $save_config = [];
/** @var int|null */
protected $widget_id;
/** @var string|null */
protected $uniq_id;
/** @var int */
protected $attach_files = 0;
/** @var int */
protected $close_advanced = 0;
/** @var int */
protected $proxy_enabled = 0;
/** @var string */
protected $provider_name = '';
/**
* constructor
*
* @param Centreon_OpenTickets_Rule $rule
* @param string $centreon_path
* @param string $centreon_open_tickets_path
* @param int $rule_id
* @param mixed $submitted_config
* @param int $provider_id
* @param string $provider_name
*
* @return void
*/
public function __construct(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$rule_id,
$submitted_config,
$provider_id,
$provider_name,
) {
$this->rule = $rule;
$this->centreon_path = $centreon_path;
$this->centreon_open_tickets_path = $centreon_open_tickets_path;
$this->rule_id = $rule_id;
$this->submitted_config = $submitted_config;
$this->rule_data = $rule->get($rule_id);
$this->rule_list = $rule->getRuleList();
if (
is_null($rule_id)
|| ! isset($this->rule_data['provider_id'])
|| $provider_id != $this->rule_data['provider_id']
) {
$this->default_data = [];
$this->default_data['clones'] = [];
$this->setDefaultValueMain();
$this->setDefaultValueExtra();
}
// We reset value. We have changed provider on same form
if (
isset($this->rule_data['provider_id'])
&& $provider_id != $this->rule_data['provider_id']
) {
$this->rule_data = [];
}
$this->widget_id = null;
$this->uniq_id = null;
$this->provider_name = $provider_name;
}
/**
* Validate the popup for submit a ticket
*
* @return array The status of validation (
* 'code' => int,
* 'message' => string
* )
*/
abstract public function validateFormatPopup();
/**
* @param int $widget_id
* @return void
*/
public function setWidgetId($widget_id): void
{
$this->widget_id = $widget_id;
}
/**
* @param ?string $uniq_id
* @return void
*/
public function setUniqId($uniq_id): void
{
$this->uniq_id = $uniq_id;
}
/**
* Set form values
*
* @param mixed $form
* @return void
*/
public function setForm($form): void
{
$this->submitted_config = $form;
}
/**
* @return void
*/
public function clearUploadFiles(): void
{
$upload_files = $this->getUploadFiles();
foreach ($upload_files as $file) {
unlink($file['filepath']);
}
unset($_SESSION['ot_upload_files'][$this->uniq_id]);
}
/**
* Build the config form
*
* @return array<mixed>
*/
public function getConfig()
{
$this->getConfigContainer1Extra();
$this->getConfigContainer1Main();
$this->getConfigContainer2Main();
$this->getConfigContainer2Extra();
return $this->config;
}
/**
* @return mixed
*/
public function getChainRuleList()
{
$result = [];
if (isset($this->rule_data['clones']['chainruleList'])) {
$result = $this->rule_data['clones']['chainruleList'];
}
return $result;
}
/**
* @return mixed
*/
public function getMacroTicketId()
{
return $this->rule_data['macro_ticket_id'];
}
/**
* @return void
*/
public function saveConfig(): void
{
$this->checkConfigForm();
$this->save_config = ['clones' => [], 'simple' => []];
$this->saveConfigMain();
$this->saveConfigExtra();
$this->rule->save($this->rule_id, $this->save_config);
}
/**
* Check select lists requirement
*
* @return array
*/
public function automateValidateFormatPopupLists()
{
$rv = ['code' => 0, 'lists' => []];
if (isset($this->rule_data['clones']['groupList'])) {
foreach ($this->rule_data['clones']['groupList'] as $values) {
if (
$values['Mandatory'] == 1
&& ! isset($this->submitted_config['select_' . $values['Id']])
) {
$rv['code'] = 1;
$rv['lists'][] = $values['Id'];
}
}
}
return $rv;
}
/**
* @param array<mixed> $args
* @param bool $addGroups
* @return array<mixed>|null
*/
public function getFormatPopup($args, $addGroups = false)
{
if (
! isset($this->rule_data['format_popup'])
|| is_null($this->rule_data['format_popup'])
|| $this->rule_data['format_popup'] == ''
) {
return null;
}
$result = ['format_popup' => null];
$tpl = $this->initSmartyTemplate();
$groups = $this->assignFormatPopupTemplate($tpl, $args);
$tpl->assign('string', $this->rule_data['format_popup']);
$result['format_popup'] = $tpl->fetch('eval.ihtml');
$result['attach_files_enable'] = $this->rule_data['attach_files'] ?? 0;
if ($addGroups === true) {
$result['groups'] = $groups;
}
return $result;
}
/**
* @return 0|1
*/
public function doAck()
{
if (isset($this->rule_data['ack']) && $this->rule_data['ack'] == 'yes') {
return 1;
}
return 0;
}
/**
* Check if schedule check is needed
*
* @return bool
*/
public function doesScheduleCheck(): bool
{
return
isset($this->rule_data['schedule_check'])
&& $this->rule_data['schedule_check'] === 'yes';
}
/**
* @return 0|1
*/
public function doCloseTicket()
{
if (isset($this->rule_data['close_ticket_enable']) && $this->rule_data['close_ticket_enable'] == 'yes') {
return 1;
}
return 0;
}
/**
* @return 0|1
*/
public function doCloseTicketContinueOnError()
{
if (isset($this->rule_data['error_close_centreon']) && $this->rule_data['error_close_centreon'] == 'yes') {
return 1;
}
return 0;
}
/**
* @param CentreonDB $db_storage
* @param string $contact
* @param array<mixed> $host_problems
* @param array<mixed> $service_problems
* @return array<mixed>
*/
public function submitTicket($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['confirm_popup' => null];
$submit_result = $this->doSubmit($db_storage, $contact, $host_problems, $service_problems);
$result['confirm_message'] = $this->setConfirmMessage($host_problems, $service_problems, $submit_result);
$result['ticket_id'] = $submit_result['ticket_id'];
$result['ticket_is_ok'] = $submit_result['ticket_is_ok'];
$result['ticket_time'] = $submit_result['ticket_time'];
$result['confirm_autoclose'] = $this->rule_data['confirm_autoclose'];
return $result;
}
/**
* @param int|string $ticket_id
* @param array<mixed> $data
* @return false|string
*/
public function getUrl($ticket_id, $data)
{
$tpl = $this->initSmartyTemplate();
foreach ($data as $label => $value) {
$tpl->assign($label, $value);
}
foreach ($this->rule_data as $label => $value) {
$tpl->assign($label, $value);
}
$tpl->assign('ticket_id', $ticket_id);
$tpl->assign('string', $this->rule_data['url']);
return $tpl->fetch('eval.ihtml');
}
/**
* @param array<mixed> $tickets
* @return void
*/
public function closeTicket(&$tickets): void
{
// By default, yes tickets are removed (even no). -1 means a error
foreach ($tickets as $k => $v) {
$tickets[$k]['status'] = 1;
}
}
/**
* Set the default extra data
* @return void
*/
abstract protected function setDefaultValueExtra();
/**
* Check the configuration form
* @return void
*/
abstract protected function checkConfigForm();
/**
* Prepare the extra configuration block
* @return void
*/
abstract protected function getConfigContainer1Extra();
/**
* Prepare the extra configuration block
* @return void
*/
abstract protected function getConfigContainer2Extra();
/**
* Add specific configuration field
* @return void
*/
abstract protected function saveConfigExtra();
/**
* Create a ticket
*
* @param CentreonDB $db_storage The centreon_storage database connection
* @param string $contact The contact who open the ticket
* @param array $host_problems The list of host issues link to the ticket
* @param array $service_problems The list of service issues link to the ticket
* @return array The status of action (
* 'code' => int,
* 'message' => string
* )
*/
abstract protected function doSubmit($db_storage, $contact, $host_problems, $service_problems);
/**
* @param string $path
* @return SmartyBC
*/
protected function initSmartyTemplate($path = 'providers/Abstract/templates')
{
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($this->centreon_open_tickets_path, $path);
$tpl->loadPlugin('smarty_function_host_get_hostgroups');
$tpl->loadPlugin('smarty_function_host_get_severity');
$tpl->loadPlugin('smarty_function_host_get_hostcategories');
$tpl->loadPlugin('smarty_function_host_get_macro_value_in_config');
$tpl->loadPlugin('smarty_function_host_get_macro_values_in_config');
$tpl->loadPlugin('smarty_function_service_get_servicecategories');
$tpl->loadPlugin('smarty_function_service_get_servicegroups');
$tpl->loadPlugin('smarty_function_sortgroup');
return $tpl;
}
/**
* @return void
*/
protected function clearSession()
{
if (
! is_null($this->uniq_id)
&& isset($_SESSION['ot_save_' . $this->uniq_id])
) {
unset($_SESSION['ot_save_' . $this->uniq_id]);
}
}
/**
* @param int|string $key
* @param mixed $value
* @return void
*/
protected function saveSession($key, $value)
{
if (! is_null($this->uniq_id)) {
if (! isset($_SESSION['ot_save_' . $this->uniq_id])) {
$_SESSION['ot_save_' . $this->uniq_id] = [];
}
$_SESSION['ot_save_' . $this->uniq_id][$key] = $value;
}
}
/**
* @return array<mixed>
*/
protected function getUploadFiles()
{
$upload_files = [];
if (isset($_SESSION['ot_upload_files'][$this->uniq_id])) {
foreach (array_keys($_SESSION['ot_upload_files'][$this->uniq_id]) as $filepath) {
$filename = basename($filepath);
if (preg_match('/^.*?__(.*)/', $filename, $matches)) {
$upload_files[] = ['filepath' => $filepath, 'filename' => $matches[1]];
}
}
}
return $upload_files;
}
/**
* @param int|string $key
* @return mixed|null
*/
protected function getSession($key)
{
if (! is_null($key) && ! is_null($this->uniq_id) && isset($_SESSION['ot_save_' . $this->uniq_id][$key])) {
return $_SESSION['ot_save_' . $this->uniq_id][$key];
}
return null;
}
/**
* @param ?string $value
* @return null|string|false
*/
protected function to_utf8($value)
{
$encoding = mb_detect_encoding($value);
if ($encoding == 'UTF-8') {
return $value;
}
return mb_convert_encoding($value, 'UTF-8', $encoding);
}
/**
* @param bool|int $body_html
* @return void
*/
protected function setDefaultValueMain($body_html = 0)
{
$this->default_data['macro_ticket_id'] = 'TICKET_ID';
$this->default_data['ack'] = 'yes';
$this->default_data['schedule_check'] = 'no';
$this->default_data['format_popup'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
<tr>
<td class="FormRowField" style="padding-left:15px;">{$custom_message.label}</td>
<td class="FormRowValue" style="padding-left:15px;">
<textarea id="custom_message" name="custom_message" cols="50" rows="6"></textarea>
</td>
</tr>
{include file="file:$centreon_open_tickets_path/providers/Abstract/templates/groups.ihtml"}
<!--<tr>
<td class="FormRowField" style="padding-left:15px;">Add graphs</td>
<td class="FormRowValue" style="padding-left:15px;"><input type="checkbox" name="add_graph" value="1" /></td>
</tr>-->
</table>
';
$this->default_data['message_confirm'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
{if $ticket_is_ok == 1}
<tr><td class="FormRowField" style="padding-left:15px;">New ticket opened: {$ticket_id}.</td></tr>
{else}
<tr><td class="FormRowField" style="padding-left:15px;">Error to open the ticket: {$ticket_error_message}.</td></tr>
{/if}
</table>
';
$this->default_data['format_popup'] = $this->default_data['format_popup'];
$this->default_data['message_confirm'] = $this->default_data['message_confirm'];
if ($body_html == 1) {
$default_body = '
<html>
<body>
<p>{$user.alias} open ticket at {$smarty.now|date_format:"%d/%m/%y %H:%M:%S"}</p>
<p>{$custom_message}</p>
<p>
{include file="file:$centreon_open_tickets_path/providers/Abstract/templates/display_selected_lists.ihtml" separator="<br/>"}
</p>
{assign var="table_style" value="border-collapse: collapse; border: 1px solid black;"}
{assign var="cell_title_style" value="background-color: #D2F5BB; border: 1px solid black; text-align: center; padding: 10px; text-transform:uppercase; font-weight:bold;"}
{assign var="cell_style" value="border-bottom: 1px solid black; padding: 5px;"}
{if $host_selected|@count gt 0}
<table cellpading="0" cellspacing="0" style="{$table_style}">
<tr>
<td style="{$cell_title_style}">Host</td>
<td style="{$cell_title_style}">State</td>
<td style="{$cell_title_style}">Duration</td>
<td style="{$cell_title_style}">Output</td>
</tr>
{foreach from=$host_selected item=host}
<tr>
<td style="{$cell_style}">{$host.name}</td>
<td style="{$cell_style}">{$host.state_str}</td>
<td style="{$cell_style}">{$host.last_hard_state_change_duration}</td>
<td style="{$cell_style}">{$host.output|substr:0:255}</td>
</tr>
{/foreach}
</table>
{/if}
{if $service_selected|@count gt 0}
<table cellpading="0" cellspacing="0" style="{$table_style}">
<tr>
<td style="{$cell_title_style}">Host</td>
<td style="{$cell_title_style}">Service</td>
<td style="{$cell_title_style}">State</td>
<td style="{$cell_title_style}">Duration</td>
<td style="{$cell_title_style}">Output</td>
</tr>
{foreach from=$service_selected item=service}
<tr>
<td style="{$cell_style}">{$service.host_name}</td>
<td style="{$cell_style}">{$service.description}</td>
<td style="{$cell_style}">{$service.state_str}</td>
<td style="{$cell_style}">{$service.last_hard_state_change_duration}</td>
<td style="{$cell_style}">{$service.output|substr:0:255}</td>
</tr>
{/foreach}
</table>
{/if}
{assign var="centreon_url" value="localhost"}
{assign var="centreon_username" value="admin"}
{assign var="centreon_token" value="token"}
{assign var="centreon_end" value="`$smarty.now`"}
{assign var="centreon_start" value=$centreon_end-86400}
{if isset($add_graph) && $add_graph == 1}
{if $service_selected|@count gt 0}
{foreach from=$service_selected item=service}
{if $service.num_metrics > 0}
<br /><img src="http://{$centreon_url}/centreon/include/views/graphs/generateGraphs/generateImage.php?username={$centreon_username}&token={$centreon_token}&start={$centreon_start}&end={$centreon_end}&hostname={$service.host_name}&service={$service.description}" />
{/if}
{/foreach}
{/if}
{/if}
</body>
</html>';
} else {
$default_body = '
{$user.alias} open ticket at {$smarty.now|date_format:"%d/%m/%y %H:%M:%S"}
{$custom_message}
{include file="file:$centreon_open_tickets_path/providers/Abstract/templates/display_selected_lists.ihtml" separator=""}
{if $host_selected|@count gt 0}
{foreach from=$host_selected item=host}
Host: {$host.name}
State: {$host.state_str}
Duration: {$host.last_hard_state_change_duration}
Output: {$host.output|substr:0:1024}
{/foreach}
{/if}
{if $service_selected|@count gt 0}
{foreach from=$service_selected item=service}
Host: {$service.host_name}
Service: {$service.description}
State: {$service.state_str}
Duration: {$service.last_hard_state_change_duration}
Output: {$service.output|substr:0:1024}
{/foreach}
{/if}
';
}
$this->default_data['clones']['bodyList'] = [['Name' => 'Default', 'Value' => $default_body, 'Default' => '1']];
$this->default_data['peer_verify'] = 'yes';
$this->default_data['ca_cert_path'] = '';
}
/**
* Get a form clone value
*
* @param string $uniq_id
* @return array<mixed>
*/
protected function getCloneValue($uniq_id)
{
$format_values = [];
if (isset($this->rule_data['clones'][$uniq_id]) && is_array($this->rule_data['clones'][$uniq_id])) {
foreach ($this->rule_data['clones'][$uniq_id] as $values) {
$format = [];
foreach ($values as $label => $value) {
$format[$uniq_id . $label . '_#index#'] = $value;
}
$format_values[] = $format;
}
} elseif (isset($this->default_data['clones'][$uniq_id])) {
foreach ($this->default_data['clones'][$uniq_id] as $values) {
$format = [];
foreach ($values as $label => $value) {
$format[$uniq_id . $label . '_#index#'] = $value;
}
$format_values[] = $format;
}
}
return ['clone_values' => json_encode($format_values), 'clone_count' => count($format_values)];
}
/**
* Get a form value
*
* @param string $uniq_id
* @param bool $htmlentities
* @return string
*/
protected function getFormValue($uniq_id, $htmlentities = true)
{
$value = '';
if (isset($this->rule_data[$uniq_id]) && ! is_null($this->rule_data[$uniq_id])) {
$value = $this->rule_data[$uniq_id];
} elseif (isset($this->default_data[$uniq_id])) {
$value = $this->default_data[$uniq_id];
}
if ($htmlentities) {
$value = htmlentities($value, ENT_QUOTES);
}
return $value;
}
/**
* @return void
*/
protected function checkLists()
{
$groupList = $this->getCloneSubmitted(
'groupList',
['Id', 'Label', 'Type', 'Filter', 'Mandatory', 'Sort']
);
$duplicate_id = [];
foreach ($groupList as $values) {
if (preg_match('/[^A-Za-z0-9_]/', $values['Id'])) {
$this->check_error_message .= $this->check_error_message_append
. "List id '" . $values['Id'] . "' must contains only alphanumerics or underscore characters";
$this->check_error_message_append = '<br/>';
}
if (isset($duplicate_id[$values['Id']])) {
$this->check_error_message .= $this->check_error_message_append
. "List id '" . $values['Id'] . "' already exits";
$this->check_error_message_append = '<br/>';
}
$duplicate_id[$values['Id']] = 1;
}
}
/**
* @param string $uniq_id
* @param string $error_msg
* @return void
*/
protected function checkFormInteger($uniq_id, $error_msg)
{
if (
isset($this->submitted_config[$uniq_id])
&& $this->submitted_config[$uniq_id] != ''
&& preg_match('/[^0-9]/', $this->submitted_config[$uniq_id])
) {
$this->check_error_message .= $this->check_error_message_append . $error_msg;
$this->check_error_message_append = '<br/>';
}
}
/**
* @param string $uniq_id
* @param string $error_msg
* @return void
*/
protected function checkFormValue($uniq_id, $error_msg)
{
if (! isset($this->submitted_config[$uniq_id]) || $this->submitted_config[$uniq_id] == '') {
$this->check_error_message .= $this->check_error_message_append . $error_msg;
$this->check_error_message_append = '<br/>';
}
}
/**
* Build the main config: url, ack, message confirm, lists
*
* @return void
*/
protected function getConfigContainer1Main()
{
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign(
'header',
[
'common' => _('Common'),
'close_ticket' => _('Close Ticket'),
]
);
// Form
$url_html = '<input size="50" name="url" type="text" value="' . $this->getFormValue('url') . '" />';
$message_confirm_html = '<textarea rows="8" cols="70" name="message_confirm">'
. $this->getFormValue('message_confirm') . '</textarea>';
$ack_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="ack" name="ack" value="yes" '
. ($this->getFormValue('ack') === 'yes' ? 'checked' : '')
. '/><label class="empty-label" for="ack"></label></div>';
$scheduleCheckHtml = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="schedule_check" name="schedule_check" value="yes" '
. ($this->getFormValue('schedule_check') === 'yes' ? 'checked' : '')
. '/><label class="empty-label" for="schedule_check"></label></div>';
$close_ticket_enable_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="close_ticket" name="close_ticket_enable" value="yes" '
. ($this->getFormValue('close_ticket_enable') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="close_ticket"></label></div>';
$error_close_centreon_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="error_close_centreon" name="error_close_centreon" value="yes" '
. ($this->getFormValue('error_close_centreon') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="error_close_centreon"></label></div>';
$array_form = [
'url' => ['label' => _('Url'), 'html' => $url_html],
'message_confirm' => ['label' => _('Confirm message popup'), 'html' => $message_confirm_html],
'ack' => ['label' => _('Acknowledge'), 'html' => $ack_html],
'schedule_check' => ['label' => _('Schedule check'), 'html' => $scheduleCheckHtml],
'close_ticket_enable' => [
'label' => _('Enable'),
'enable' => $this->close_advanced,
'html' => $close_ticket_enable_html,
],
'error_close_centreon' => [
'label' => _('On error continue close Centreon'),
'html' => $error_close_centreon_html,
],
'grouplist' => ['label' => _('Lists')],
'customlist' => ['label' => _('Custom list definition')],
'bodylist' => ['label' => _('Body list definition')],
];
$extra_group_options = '';
$method_name = 'getGroupListOptions';
if (method_exists($this, $method_name)) {
$extra_group_options = $this->{$method_name}();
}
// Group list clone
$groupListId_html = '<input id="groupListId_#index#" name="groupListId[#index#]" size="20" type="text" />';
$groupListLabel_html = '<input id="groupListLabel_#index#" name="groupListLabel[#index#]" '
. 'size="20" type="text" />';
$groupListType_html = '<select id="groupListType_#index#" name="groupListType[#index#]" type="select-one">'
. $extra_group_options
. '<option value="' . self::HOSTGROUP_TYPE . '">Host group</options>'
. '<option value="' . self::HOSTCATEGORY_TYPE . '">Host category</options>'
. '<option value="' . self::HOSTSEVERITY_TYPE . '">Host severity</options>'
. '<option value="' . self::SERVICEGROUP_TYPE . '">Service group</options>'
. '<option value="' . self::SERVICECATEGORY_TYPE . '">Service category</options>'
. '<option value="' . self::SERVICESEVERITY_TYPE . '">Service severity</options>'
. '<option value="' . self::SERVICECONTACTGROUP_TYPE . '">Contact group</options>'
. '<option value="' . self::BODY_TYPE . '">Body</options>'
. '<option value="' . self::CUSTOM_TYPE . '">Custom</options>'
. '</select>';
$groupListFilter_html = '<input id="groupListFilter_#index#" name="groupListFilter[#index#]" '
. 'size="20" type="text" />';
$groupListMandatory_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input id="groupListMandatory_#index#" name="groupListMandatory[#index#]" '
. 'type="checkbox" value="1" /><label class="empty-label" for="groupListMandatory_#index#"></label></div>';
$groupListSort_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input id="groupListSort_#index#" name="groupListSort[#index#]" type="checkbox" />'
. '<label class="empty-label" for="groupListSort_#index#"></label></div>';
$array_form['groupList'] = [
['label' => _('Id'), 'html' => $groupListId_html],
['label' => _('Label'), 'html' => $groupListLabel_html],
['label' => _('Type'), 'html' => $groupListType_html],
['label' => _('Filter'), 'html' => $groupListFilter_html],
['label' => _('Mandatory'), 'html' => $groupListMandatory_html],
['label' => _('Sort'), 'html' => $groupListSort_html],
];
// Custom list clone
$customListId_html = '<input id="customListId_#index#" name="customListId[#index#]" size="20" type="text" />';
$customListValue_html = '<input id="customListValue_#index#" name="customListValue[#index#]" size="20" '
. 'type="text" />';
$customListLabel_html = '<input id="customListLabel_#index#" name="customListLabel[#index#]" size="20" '
. 'type="text" />';
$customListDefault_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input id="customListDefault_#index#" name="customListDefault[#index#]" '
. 'type="checkbox" value="1" /><label class="empty-label" for="customListDefault_#index#"></label></div>';
$array_form['customList'] = [
['label' => _('Id'), 'html' => $customListId_html],
['label' => _('Value'), 'html' => $customListValue_html],
['label' => _('Label'), 'html' => $customListLabel_html],
['label' => _('Default'), 'html' => $customListDefault_html],
];
// Body list clone
$bodyListName_html = '<input id="bodyListName_#index#" name="bodyListName[#index#]" size="20" '
. 'type="text" />';
$bodyListValue_html = '<textarea type="textarea" id="bodyListValue_#index#" rows="8" cols="70" '
. 'name="bodyListValue[#index#]"></textarea>';
$bodyListDefault_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input id="bodyListDefault_#index#" name="bodyListDefault[#index#]" '
. 'type="checkbox" value="1" /><label class="empty-label" for="bodyListDefault_#index#"></label></div>';
$array_form['bodyList'] = [
['label' => _('Name'), 'html' => $bodyListName_html],
['label' => _('Value'), 'html' => $bodyListValue_html],
['label' => _('Default'), 'html' => $bodyListDefault_html],
];
// SSL Peer verify
$peerVerifyHtml = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="peer_verify" name="peer_verify" value="yes" '
. ($this->getFormValue('peer_verify') === 'yes' ? 'checked' : '')
. '/><label class="empty-label" for="peer_verify"></label></div>';
$caCertPathHtml = '<input size="50" name="ca_cert_path" type="text" value="' . $this->getFormValue('ca_cert_path') . '" />';
$array_form['peer_verify'] = ['label' => _('SSL Verify Peer'), 'html' => $peerVerifyHtml];
$array_form['ca_cert_path'] = ['label' => _('Certificate Authority Info'), 'html' => $caCertPathHtml];
$tpl->assign('form', $array_form);
// prepare help texts
$helptext = '';
include_once __DIR__ . '/help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$this->config['container1_html'] .= $tpl->fetch('conf_container1main.ihtml');
$this->config['clones']['groupList'] = $this->getCloneValue('groupList');
$this->config['clones']['customList'] = $this->getCloneValue('customList');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Serena/SerenaProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Serena/SerenaProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class SerenaProvider extends AbstractProvider
{
use LoggerTrait;
public const ARG_PROJECT_ID = 1;
public const ARG_SUBJECT = 2;
public const ARG_CONTENT = 3;
public const ARG_CATEGORY = 4;
public const ARG_SUB_CATEGORY = 5;
public const ARG_SUB_CATEGORY_DETAILS = 6;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_PROJECT_ID => 'project_id', self::ARG_SUBJECT => 'subject', self::ARG_CONTENT => 'content', self::ARG_CATEGORY => 'category', self::ARG_SUB_CATEGORY => 'subcategory', self::ARG_SUB_CATEGORY_DETAILS => 'subcategory_details'];
/** @var string */
protected $ws_error;
/** @var string */
protected $_ticket_number;
/** @var mixed */
protected $otrs_call_response;
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['endpoint'] = 'http://127.0.0.1//gsoap/gsoap_ssl.dll?XXXXXX';
$this->default_data['namespace'] = 'XXXXXXX';
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_SUBJECT, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers/'
. 'Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_CONTENT, 'Value' => '{$body}'], ['Arg' => self::ARG_PROJECT_ID, 'Value' => '1']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['message_confirm'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
{if $ticket_is_ok == 1}
<tr><td class="FormRowField" style="padding-left:15px;">New ticket opened: {$ticket_id}.</td></tr>
{else}
<tr>
<td class="FormRowField" style="padding-left:15px;">Error to open the ticket: <xmp>{$ticket_error_message}</xmp>
</td></tr>
{/if}
</table>
';
$this->default_data['message_confirm'] = $this->default_data['message_confirm'];
$this->default_data['url'] = '';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('endpoint', "Please set 'Endpoint' value");
$this->checkFormValue('namespace', "Please set 'Namespace' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/Serena/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['serena' => _('Serena')]);
// Form
$endpoint_html = '<input size="50" name="endpoint" type="text" value="'
. $this->getFormValue('endpoint') . '" />';
$namespace_html = '<input size="50" name="namespace" type="text" value="'
. $this->getFormValue('namespace') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['endpoint' => ['label' => _('Endpoint') . $this->required_field, 'html' => $endpoint_html], 'namespace' => ['label' => _('Namespace'), 'html' => $namespace_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_PROJECT_ID . '">' . _('Project ID') . '</options>'
. '<option value="' . self::ARG_SUBJECT . '">' . _('Subject') . '</options>'
. '<option value="' . self::ARG_CONTENT . '">' . _('Content') . '</options>'
. '<option value="' . self::ARG_CATEGORY . '">' . _('Category') . '</options>'
. '<option value="' . self::ARG_SUB_CATEGORY . '">' . _('Sub-Category') . '</options>'
. '<option value="' . self::ARG_SUB_CATEGORY_DETAILS . '">' . _('Sub-Category Details') . '</options>'
. '</select>';
$mappingTicketArg_html .= '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['endpoint'] = $this->submitted_config['endpoint'];
$this->save_config['simple']['namespace'] = $this->submitted_config['namespace'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
$code = $this->createTicketSerena($ticket_arguments);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->_ticket_number, 'subject' => $ticket_arguments[
$this->internal_arg_name[self::ARG_SUBJECT]
], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments]
)]
);
return $result;
}
/**
* REST API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
/**
* @param array $ticket_arguments
* @return int
*/
protected function createTicketSerena($ticket_arguments)
{
$extended_fields = '';
$listing = [$this->internal_arg_name[self::ARG_SUB_CATEGORY_DETAILS] => ['dbName' => 'OT_SUB_CATEGORY_DETAILS', 'displayName' => 'Sub-category details'], $this->internal_arg_name[self::ARG_SUB_CATEGORY] => ['dbName' => 'OT_SUB_CATEGORY', 'displayName' => 'Sub-category'], $this->internal_arg_name[self::ARG_CATEGORY] => ['dbName' => 'OT_CATEGORY', 'displayName' => 'OT_CATEGORY']];
foreach ($ticket_arguments as $ticket_argument => $value) {
if (isset($listing[$ticket_argument])) {
$extended_fields .= '
<ae:extendedField>
<ae:id>
<ae:displayName>' . $listing[$ticket_argument]['displayName'] . '</ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:dbName>' . $listing[$ticket_argument]['dbName'] . '</ae:dbName>
</ae:id>
<ae:setValueBy>DISPLAY-VALUE</ae:setValueBy>
<ae:setValueMethod>REPLACE-VALUES</ae:setValueMethod>
<ae:value>
<ae:displayValue>' . $value . '</ae:displayValue>
<ae:internalValue></ae:internalValue>
<ae:uuid></ae:uuid>
</ae:value>
</ae:extendedField>
';
}
}
$data = '<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ae:CreatePrimaryItem xmlns:ae="urn:' . $this->rule_data['namespace'] . '">
<ae:auth>
<ae:userId>' . $this->rule_data['username'] . '</ae:userId>
<ae:password><![CDATA[' . $this->rule_data['password'] . ']]></ae:password>
<ae:hostname></ae:hostname>
<ae:loginAsUserId></ae:loginAsUserId>
</ae:auth>
<ae:project>
<ae:displayName></ae:displayName>
<ae:id>' . $ticket_arguments[$this->internal_arg_name[self::ARG_PROJECT_ID]] . '</ae:id>
<ae:uuid></ae:uuid>
<ae:fullyQualifiedName></ae:fullyQualifiedName>
</ae:project>
<ae:parentItem></ae:parentItem>
<ae:item>
<ae:id>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:tableId></ae:tableId>
<ae:tableIdItemId></ae:tableIdItemId>
<ae:issueId></ae:issueId>
</ae:id>
<ae:itemType></ae:itemType>
<ae:project>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:fullyQualifiedName></ae:fullyQualifiedName>
</ae:project>
<ae:title><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_SUBJECT]] . ']]></ae:title>
<ae:description><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_CONTENT]] . ']]></ae:description>
<ae:createdBy>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:loginId></ae:loginId>
</ae:createdBy>
<ae:createDate></ae:createDate>
<ae:modifiedBy>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:loginId></ae:loginId>
</ae:modifiedBy>
<ae:modifiedDate></ae:modifiedDate>
<ae:activeInactive></ae:activeInactive>
<ae:state>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:isClosed></ae:isClosed>
</ae:state>
<ae:owner>
<ae:displayName></ae:displayName>
<ae:id></ae:id>
<ae:uuid></ae:uuid>
<ae:loginId></ae:loginId>
</ae:owner>
<ae:url/>
<ae:subtasks/>
' . $extended_fields . '
</ae:item>
</ae:CreatePrimaryItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
';
if ($this->callSOAP($data) == 1) {
return -1;
}
return 0;
}
/**
* @param array|string $data
* @return int
*/
protected function callSOAP($data)
{
$this->otrs_call_response = null;
$base_url = $this->rule_data['endpoint'];
$ch = curl_init($base_url);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
$payload = is_string($data) ? $data : json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
['Content-Type: text/xml;charset=UTF-8', 'SOAPAction: ae:CreatePrimaryItem', 'Content-Length: ' . strlen($payload)]
);
$optionsToLog = [
'apiAddress' => $base_url,
'method' => 'POST',
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// log the curl options
$this->debug('Serena API request options', [
'options' => $optionsToLog,
]);
$result = curl_exec($ch);
curl_close($ch);
if ($result == false) {
$this->setWsError(curl_error($ch));
return 1;
}
/*
* OK:
* <SOAP-ENV:Body>
* <ae:CreatePrimaryItemResponse>
* <ae:return><ae:id xsi:type="ae:ItemIdentifier"><ae:displayName>INC_003915</ae:displayName>
* NOK:
* <SOAP-ENV:Body>
* <SOAP-ENV:Fault>
* <faultcode>SOAP-ENV:Client</faultcode><faultstring>Invalid project 0.</faultstring>
*/
if (! preg_match('/<ae:id xsi:type="ae:ItemIdentifier">.*?<ae:displayName>(.*?)</', $result, $matches)) {
$this->setWsError($result);
return 1;
}
$this->_ticket_number = $matches[1];
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Glpi/GlpiProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Glpi/GlpiProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
class GlpiProvider extends AbstractProvider
{
public const GPLI_ENTITIES_TYPE = 10;
public const GPLI_GROUPS_TYPE = 11;
public const GLPI_ITIL_CATEGORIES_TYPE = 12;
public const ARG_CONTENT = 1;
public const ARG_ENTITY = 2;
public const ARG_URGENCY = 3;
public const ARG_IMPACT = 4;
public const ARG_CATEGORY = 5;
public const ARG_USER = 6;
public const ARG_USER_EMAIL = 7;
public const ARG_GROUP = 8;
public const ARG_GROUP_ASSIGN = 9;
public const ARG_TITLE = 10;
protected $glpi_connected = 0;
protected $glpi_session = null;
/** @var null|array */
protected $glpi_call_response;
/** @var string */
protected $rpc_error;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_CONTENT => 'content', self::ARG_ENTITY => 'entity', self::ARG_URGENCY => 'urgency', self::ARG_IMPACT => 'impact', self::ARG_CATEGORY => 'category', self::ARG_USER => 'user', self::ARG_USER_EMAIL => 'user_email', self::ARG_GROUP => 'group', self::ARG_GROUP_ASSIGN => 'groupassign', self::ARG_TITLE => 'title'];
public function __destruct()
{
$this->logoutGlpi();
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['path'] = '/glpi/plugins/webservices/xmlrpc.php';
$this->default_data['https'] = 0;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_TITLE, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_CONTENT, 'Value' => '{$body}'], ['Arg' => self::ARG_ENTITY, 'Value' => '{$select.gpli_entity.id}'], ['Arg' => self::ARG_CATEGORY, 'Value' => '{$select.glpi_itil_category.id}'], ['Arg' => self::ARG_GROUP_ASSIGN, 'Value' => '{$select.glpi_group.id}'], ['Arg' => self::ARG_USER_EMAIL, 'Value' => '{$user.email}'], ['Arg' => self::ARG_URGENCY, 'Value' => '{$select.urgency.value}'], ['Arg' => self::ARG_IMPACT, 'Value' => '{$select.impact.value}']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = 'http://{$address}/glpi/front/ticket.form.php?id={$ticket_id}';
$this->default_data['clones']['groupList'] = [['Id' => 'gpli_entity', 'Label' => _('Entity'), 'Type' => self::GPLI_ENTITIES_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'glpi_group', 'Label' => _('Glpi group'), 'Type' => self::GPLI_GROUPS_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'glpi_itil_category', 'Label' => _('Itil category'), 'Type' => self::GLPI_ITIL_CATEGORIES_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'urgency', 'Label' => _('Urgency'), 'Type' => self::CUSTOM_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'impact', 'Label' => _('Impact'), 'Type' => self::CUSTOM_TYPE, 'Filter' => '', 'Mandatory' => '']];
$this->default_data['clones']['customList'] = [['Id' => 'urgency', 'Value' => '1', 'Default' => ''], ['Id' => 'urgency', 'Value' => '2', 'Default' => ''], ['Id' => 'urgency', 'Value' => '3', 'Default' => ''], ['Id' => 'urgency', 'Value' => '4', 'Default' => ''], ['Id' => 'urgency', 'Value' => '5', 'Default' => ''], ['Id' => 'impact', 'Value' => '1', 'Default' => ''], ['Id' => 'impact', 'Value' => '2', 'Default' => ''], ['Id' => 'impact', 'Value' => '3', 'Default' => ''], ['Id' => 'impact', 'Value' => '4', 'Default' => ''], ['Id' => 'impact', 'Value' => '5', 'Default' => '']];
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/Glpi/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['glpi' => _('Glpi')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$path_html = '<input size="50" name="path" type="text" value="'
. $this->getFormValue('path') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$https_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="https" name="https" value="yes" '
. ($this->getFormValue('https') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="https"></label></div>';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'path' => ['label' => _('Path'), 'html' => $path_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'https' => ['label' => _('Use https'), 'html' => $https_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_TITLE . '">' . _('Title') . '</options>'
. '<option value="' . self::ARG_CONTENT . '">' . _('Content') . '</options>'
. '<option value="' . self::ARG_ENTITY . '">' . _('Entity') . '</options>'
. '<option value="' . self::ARG_URGENCY . '">' . _('Urgency') . '</options>'
. '<option value="' . self::ARG_IMPACT . '">' . _('Impact') . '</options>'
. '<option value="' . self::ARG_CATEGORY . '">' . _('Category') . '</options>'
. '<option value="' . self::ARG_USER . '">' . _('User') . '</options>'
. '<option value="' . self::ARG_USER_EMAIL . '">' . _('User email') . '</options>'
. '<option value="' . self::ARG_GROUP . '">' . _('Group') . '</options>'
. '<option value="' . self::ARG_GROUP_ASSIGN . '">' . _('Group assign') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['path'] = $this->submitted_config['path'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['https'] = (
isset($this->submitted_config['https'])
&& $this->submitted_config['https'] == 'yes'
) ? $this->submitted_config['https'] : '';
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
protected function getGroupListOptions()
{
return '<option value="' . self::GPLI_ENTITIES_TYPE . '">Glpi entities</options>'
. '<option value="' . self::GPLI_GROUPS_TYPE . '">Glpi groups</options>'
. '<option value="' . self::GLPI_ITIL_CATEGORIES_TYPE . '">Glpi itil categories</options>';
}
protected function assignGlpiEntities($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listEntitiesGlpi();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->rpc_error;
return 0;
}
$result = [];
foreach ($this->glpi_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['completename']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['completename'])) {
$result[$row['id']] = $this->to_utf8($row['completename']);
}
}
$this->saveSession('glpi_entities', $this->glpi_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignGlpiGroups($entry, &$groups_order, &$groups)
{
$filter = null;
if (isset($entry['Filter']) && ! is_null($entry['Filter']) && $entry['Filter'] != '') {
$filter = $entry['Filter'];
}
$code = $this->listGroupsGlpi($filter);
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->rpc_error;
return 0;
}
$result = [];
foreach ($this->glpi_call_response['response'] as $row) {
$result[$row['id']] = $this->to_utf8($row['completename']);
}
$this->saveSession('glpi_groups', $this->glpi_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignItilCategories($entry, &$groups_order, &$groups)
{
$filter = null;
if (isset($entry['Filter']) && ! is_null($entry['Filter']) && $entry['Filter'] != '') {
$filter = $entry['Filter'];
}
$code = $this->listItilCategoriesGlpi($filter);
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->rpc_error;
return 0;
}
$result = [];
foreach ($this->glpi_call_response['response'] as $row) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
$this->saveSession('glpi_itil_categories', $this->glpi_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::GPLI_ENTITIES_TYPE) {
$this->assignGlpiEntities($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GPLI_GROUPS_TYPE) {
$this->assignGlpiGroups($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_ITIL_CATEGORIES_TYPE) {
$this->assignItilCategories($entry, $groups_order, $groups);
}
}
protected function assignSubmittedValuesSelectMore($select_input_id, $selected_id)
{
$session_name = null;
foreach ($this->rule_data['clones']['groupList'] as $value) {
if ($value['Id'] == $select_input_id) {
if ($value['Type'] == self::GPLI_ENTITIES_TYPE) {
$session_name = 'glpi_entities';
} elseif ($value['Type'] == self::GPLI_GROUPS_TYPE) {
$session_name = 'glpi_groups';
} elseif ($value['Type'] == self::GLPI_ITIL_CATEGORIES_TYPE) {
$session_name = 'glpi_itil_categories';
}
}
}
if (is_null($session_name) && $selected_id == -1) {
return [];
}
if ($selected_id == -1) {
return ['id' => null, 'value' => null];
}
$result = $this->getSession($session_name);
if (is_null($result)) {
return [];
}
foreach ($result as $value) {
if ($value['id'] == $selected_id) {
return $value;
}
}
return [];
}
protected function doSubmit(
$db_storage,
$contact,
$host_problems,
$service_problems,
$extra_ticket_arguments = [],
) {
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = $extra_ticket_arguments;
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
// Old version of GLPI use 'recipient' depiste groupassign
if ($value['Arg'] == self::ARG_GROUP_ASSIGN) {
$ticket_arguments['recipient'] = $result_str;
}
}
}
$code = $this->createTicketGlpi($ticket_arguments);
if ($code == -1) {
$result['ticket_error_message'] = $this->rpc_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->glpi_call_response['response']['id'], 'subject' => $ticket_arguments[self::ARG_TITLE], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode($ticket_arguments)]
);
return $result;
}
/**
* XML-RPC Calls
*
* @param string $error
* @return void
*/
protected function setRpcError($error)
{
$this->rpc_error = $error;
}
protected function requestRpc($method, $args = null)
{
$array_result = ['code' => -1];
if (is_null($args)) {
$args = [];
}
foreach ($args as $key => $value) {
if (is_null($value)) {
unset($args[$key]);
}
}
$proto = 'http';
if (isset($this->rule_data['https']) && $this->rule_data['https'] == 'yes') {
$proto = 'https';
}
$host = $this->rule_data['address'];
$url = '/';
if (! is_null($this->rule_data['path']) || $this->rule_data['path'] != '') {
$url = $this->rule_data['path'];
}
if ($this->glpi_connected == 1) {
$url .= '?session=' . $this->glpi_session;
}
$request = xmlrpc_encode_request($method, $args, ['encoding' => 'utf-8', 'escaping' => 'markup']);
$context = stream_context_create(
['http' => ['method' => 'POST', 'header' => 'Content-Type: text/xml', 'timeout' => $this->rule_data['timeout'], 'content' => $request]]
);
$file = file_get_contents("{$proto}://{$host}/{$url}", false, $context);
if (! $file) {
$this->setRpcError("webservice '{$method}': no response");
return $array_result;
}
$response = xmlrpc_decode($file);
if (! is_array($response)) {
$this->setRpcError("webservice '{$method}': bad response");
return $array_result;
}
if (xmlrpc_is_fault($response)) {
$this->setRpcError("webservice '{$method}' error (" . $response['faultCode'] . '): '
. $this->to_utf8($response['faultString']));
return $array_result;
}
$array_result['response'] = $response;
$array_result['code'] = 0;
return $array_result;
}
protected function listEntitiesGlpi()
{
if ($this->glpi_connected == 0) {
if ($this->loginGlpi() == -1) {
return -1;
}
}
$this->glpi_call_response = $this->requestRpc('glpi.listEntities', ['start' => 0, 'limit' => 100]);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function listGroupsGlpi($filter = null)
{
if ($this->glpi_connected == 0) {
if ($this->loginGlpi() == -1) {
return -1;
}
}
$this->glpi_call_response = $this->requestRpc(
'glpi.listGroups',
['start' => 0, 'limit' => 100, 'name' => $filter]
);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function listItilCategoriesGlpi($filter = null)
{
if ($this->glpi_connected == 0) {
if ($this->loginGlpi() == -1) {
return -1;
}
}
$this->glpi_call_response = $this->requestRpc(
'glpi.listObjects',
['start' => 0, 'limit' => 100, 'name' => $filter, 'itemtype' => 'itilcategory', 'show_label' => 1]
);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function createTicketGlpi($arguments)
{
if ($this->glpi_connected == 0) {
if ($this->loginGlpi() == -1) {
return -1;
}
}
$this->glpi_call_response = $this->requestRpc('glpi.createTicket', $arguments);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function listObjects($arguments)
{
if ($this->glpi_connected == 0) {
if ($this->loginGlpi() == -1) {
return -1;
}
}
$this->glpi_call_response = $this->requestRpc('glpi.listObjects', $arguments);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function logoutGlpi()
{
if ($this->glpi_connected == 0) {
return 0;
}
$this->glpi_call_response = $this->requestRpc('glpi.doLogout');
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
return 0;
}
protected function loginGlpi()
{
if ($this->glpi_connected == 1) {
return 0;
}
if (! extension_loaded('xmlrpc')) {
$this->setRpcError('cannot load xmlrpc extension');
return -1;
}
$this->glpi_call_response = $this->requestRpc(
'glpi.doLogin',
['login_name' => $this->rule_data['username'], 'login_password' => $this->rule_data['password']]
);
if ($this->glpi_call_response['code'] == -1) {
return -1;
}
$this->glpi_session = $this->glpi_call_response['response']['session'];
$this->glpi_connected = 1;
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/BmcItsm/BmcItsmProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/BmcItsm/BmcItsmProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class BmcItsmProvider extends AbstractProvider
{
use LoggerTrait;
protected $_set_empty_xml = 1;
protected $_itsm_fields = ['Assigned_Group', 'Assigned_Group_Shift_Name', 'Assigned_Support_Company', 'Assigned_Support_Organization', 'Assignee', 'Categorization_Tier_1', 'Categorization_Tier_2', 'Categorization_Tier_3', 'CI_Name', 'Closure_Manufacturer', 'Closure_Product_Category_Tier1', 'Closure_Product_Category_Tier2', 'Closure_Product_Category_Tier3', 'Closure_Product_Model_Version', 'Closure_Product_Name', 'Department', 'First_Name', 'Impact', 'Last_Name', 'Lookup_Keyword', 'Manufacturer', 'Product_Categorization_Tier_1', 'Product_Categorization_Tier_2', 'Product_Categorization_Tier_3', 'Product_Model_Version', 'Product_Name', 'Reported_Source', 'Resolution', 'Resolution_Category_Tier_1', 'Resolution_Category_Tier_2', 'Resolution_Category_Tier_3', 'Service_Type', 'Status', 'z1D_Action', 'Flag_Create_Request', 'Description', 'Detailed_Decription', 'Urgency', 'z1D_WorklogDetails', 'z1D_Details', 'z1D_Activity_Type', 'z1D_ActivityDate_tab', 'z1D_CommunicationSource', 'z1D_Secure_Log', 'z1D_View_Access', 'AccessMode', 'AppInstanceServer', 'AppInterfaceForm', 'AppLogin', 'AppPassword', 'Area_Business', 'Assigned_Group_ID', 'Assigned_To', 'Assignee_Groups', 'Assignee_Login_ID', 'Attachment_4_attachmentName', 'Attachment_4_attachmentData', 'Attachment_4_attachmentOrigSize', 'Attachment_5_attachmentName', 'Attachment_5_attachmentData', 'Attachment_5_attachmentOrigSize', 'Attachment_6_attachmentName', 'Attachment_6_attachmentData', 'Attachment_6_attachmentOrigSize', 'Attachment_7_attachmentName', 'Attachment_7_attachmentData', 'Attachment_7_attachmentOrigSize', 'Attachment_8_attachmentName', 'Attachment_8_attachmentData', 'Attachment_8_attachmentOrigSize', 'Attachment_9_attachmentName', 'Attachment_9_attachmentData', 'Attachment_9_attachmentOrigSize', 'BiiARS_01', 'BiiARS_02', 'BiiARS_03', 'BiiARS_04', 'BiiARS_05', 'bOrphanedRoot', 'CC_Business', 'cell_name', 'Client_Sensitivity', 'Client_Type', 'ClientLocale', 'Company', 'Component_ID', 'Contact_Company', 'Created_By', 'Created_From_flag', 'DatasetId', 'DataTags', 'Default_City', 'Default_Country', 'Desk_Location', 'Direct_Contact_Company', 'Direct_Contact_Department', 'Direct_Contact_First_Name', 'Direct_Contact_Internet_E-mail', 'Direct_Contact_Last_Name', 'Direct_Contact_Middle_Initial', 'Direct_Contact_Organization', 'Direct_Contact_Phone_Number', 'Direct_Contact_Site', 'Extension_Business', 'first_name2', 'Generic_Categorization_Tier_1', 'Global_OR_Custom_Mapping', 'Impact_OR_Root', 'Incident_Number', 'Incident_Entry_ID', 'InstanceId', 'Internet_E-mail', 'last_name2', 'Local_Business', 'Login_ID', 'Mail_Station', 'MaxRetries', 'mc_ueid', 'Middle_Initial', 'OptionForClosingIncident', 'Organization', 'Person_ID', 'Phone_Number', 'policy_name', 'PortNumber', 'Priority', 'Priority_Weight', 'Protocol', 'ReconciliationIdentity', 'Region', 'Reported_Date', 'Required_Resolution_DateTime', 'Resolution_Method', 'root_component_id_list', 'root_incident_id_list', 'Schema_Name', 'Short_Description', 'Site', 'Site_Group', 'Site_ID', 'SRID', 'SRInstanceID', 'SRMS_Registry_Instance_ID', 'SRMSAOIGuid', 'status_incident', 'Status_Reason', 'status_reason2', 'Submitter', 'TemplateID', 'TemplateID2', 'Unavailability_Type', 'Unavailability_Priority', 'Unknown_User', 'use_case', 'Vendor_Group', 'Vendor_Group_ID', 'Vendor_Name', 'Vendor_Organization', 'Vendor_Ticket_Number', 'VIP', 'z1D_Char01', 'z1D_Permission_Group_ID', 'z1D_Permission_Group_List', 'z1D_Char02', 'z1D_CIUAAssignGroup', 'z1D_CIUASupportCompany', 'z1D_CIUASupportOrg', 'z1D_Command', 'z1D_SRMInteger', 'z1D_SupportGroupID', 'z1D_UAAssignmentMethod', 'z2AF_Act_Attachment_1_attachmentName', 'z2AF_Act_Attachment_1_attachmentData', 'z2AF_Act_Attachment_1_attachmentOrigSize', 'z2Attachment_2_attachmentName', 'z2Attachment_2_attachmentData', 'z2Attachment_2_attachmentOrigSize', 'z2Attachment_3_attachmentName', 'z2Attachment_3_attachmentData', 'z2Attachment_3_attachmentOrigSize', 'zTmpEventGUID'];
protected $internal_arguments = ['Action' => ['id' => 1, 'soap' => 'z1D_Action'], 'Service Type' => ['id' => 2, 'soap' => 'Service_Type'], 'Subject' => ['id' => 3, 'soap' => 'Description'], 'Content' => ['id' => 4, 'soap' => 'Detailed_Decription'], 'Urgency' => ['id' => 5, 'soap' => 'Urgency'], 'Impact' => ['id' => 6, 'soap' => 'Impact'], 'First Name' => ['id' => 7, 'soap' => 'First_Name'], 'Last Name' => ['id' => 8, 'soap' => 'Last_Name'], 'Dataset ID' => ['id' => 9, 'soap' => 'DatasetId'], 'Status' => ['id' => 10, 'soap' => 'Status'], 'Source' => ['id' => 11, 'soap' => 'Reported_Source'], 'Type Service' => ['id' => 12, 'soap' => 'Service_Type'], 'Assigned Group' => ['id' => 13, 'soap' => 'Assigned_Group']];
/** @var string */
protected $ws_error;
/** @var null|array */
protected $otrs_call_response;
/** @var string */
protected $_ticket_number;
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['endpoint'] = 'http://127.0.0.1/arsys/services/'
. 'ARService?server=XXXX&webService=HPD_IncidentInterface_Create_WS';
$this->default_data['namespace'] = 'IncidentInterface_Create_WS';
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => $this->internal_arguments['Subject']['id'], 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}'], ['Arg' => $this->internal_arguments['Content']['id'], 'Value' => '{$body}'], ['Arg' => $this->internal_arguments['Action']['id'], 'Value' => 'CREATE'], ['Arg' => $this->internal_arguments['Status']['id'], 'Value' => 'Assigned'], ['Arg' => $this->internal_arguments['Source']['id'], 'Value' => 'Supervision'], ['Arg' => $this->internal_arguments['Type Service']['id'], 'Value' => 'Infrastructure Event']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['message_confirm'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
{if $ticket_is_ok == 1}
<tr>
<td class="FormRowField" style="padding-left:15px;">New ticket opened: {$ticket_id}.</td>
</tr>
{else}
<tr>
<td class="FormRowField" style="padding-left:15px;">Error to open the ticket: <xmp>{$ticket_error_message}</xmp>
</td>
</tr>
{/if}
</table>
';
$this->default_data['message_confirm'] = $this->default_data['message_confirm'];
$this->default_data['url'] = 'http://{$address}/index.pl?Action=AgentTicketZoom;TicketNumber={$ticket_id}';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('endpoint', "Please set 'Endpoint' value");
$this->checkFormValue('namespace', "Please set 'Namespace' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/BmcItsm/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['bmcitsm' => _('BMC ITSM')]);
// Form
$endpoint_html = '<input size="50" name="endpoint" type="text" value="'
. $this->getFormValue('endpoint') . '" />';
$namespace_html = '<input size="50" name="namespace" type="text" value="'
. $this->getFormValue('namespace') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['endpoint' => ['label' => _('Endpoint') . $this->required_field, 'html' => $endpoint_html], 'namespace' => ['label' => _('Namespace'), 'html' => $namespace_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">';
ksort($this->internal_arguments);
foreach ($this->internal_arguments as $label => $array) {
$mappingTicketArg_html .= '<option value="' . $array['id'] . '">' . _($label) . '</options>';
}
$mappingTicketArg_html .= '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['endpoint'] = $this->submitted_config['endpoint'];
$this->save_config['simple']['namespace'] = $this->submitted_config['namespace'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
foreach ($this->internal_arguments as $arg) {
if ($arg['id'] == $value['Arg']) {
$ticket_arguments[$arg['soap']] = $result_str;
break;
}
}
}
}
$code = $this->createTicketBmcItsm($ticket_arguments);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->_ticket_number, 'subject' => $ticket_arguments['Description'], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments]
)]
);
return $result;
}
/**
* REST API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
protected function createTicketBmcItsm($ticket_arguments)
{
$data = '<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:'
. $this->rule_data['namespace'] . '">
<soapenv:Header>
<urn:AuthenticationInfo>
<urn:userName>' . $this->rule_data['username'] . '</urn:userName>
<urn:password>' . $this->rule_data['password'] . '</urn:password>
<!--Optional:-->
<urn:authentication></urn:authentication>
<!--Optional:-->
<urn:locale></urn:locale>
<!--Optional:-->
<urn:timeZone></urn:timeZone>
</urn:AuthenticationInfo>
</soapenv:Header>
<soapenv:Body>
<urn:HelpDesk_Submit_Service>
';
foreach ($this->_itsm_fields as $field) {
if (isset($ticket_arguments[$field]) && $ticket_arguments[$field] != '') {
$data .= '<urn:' . $field . '>' . $ticket_arguments[$field] . '</urn:' . $field . '>';
} elseif ($this->_set_empty_xml == 1) {
$data .= '<urn:' . $field . '></urn:' . $field . '>';
}
}
$data .= '</urn:HelpDesk_Submit_Service>
</soapenv:Body>
</soapenv:Envelope>
';
if ($this->callSOAP($data) == 1) {
return -1;
}
return 0;
}
protected function callSOAP($data)
{
$this->otrs_call_response = null;
$base_url = $this->rule_data['endpoint'];
$ch = curl_init($base_url);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
['Content-Type: text/xml;charset=UTF-8', 'SOAPAction: urn:' . $this->rule_data['namespace'] . '/HelpDesk_Submit_Service', 'Content-Length: ' . strlen($data)]
);
$optionsToLog = [
'apiAddress' => $base_url,
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// log the curl options
$this->debug('BmcItsm API request options', [
'options' => $optionsToLog,
]);
$result = curl_exec($ch);
curl_close($ch);
if ($result == false) {
$this->setWsError(curl_error($ch));
return 1;
}
/*
* OK:
* <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns0:HelpDesk_Submit_ServiceResponse xmlns:ns0="urn:HPD_IncidentInterface_Create_WS" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
* <ns0:Incident_Number>INC000001907092</ns0:Incident_Number>
* </ns0:HelpDesk_Submit_ServiceResponse></soapenv:Body></soapenv:Envelope>
* NOK:
* <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body>
* <soapenv:Fault><faultcode>soapenv:Server.userException</faultcode><faultstring>java.lang.NullPointerException</faultstring><detail><ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">xxxx.localdomain</ns1:hostname></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>
*/
if (! preg_match('/Incident_Number>(.*?)</', $result, $matches)) {
$this->setWsError($result);
return 1;
}
$this->_ticket_number = $matches[1];
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyvistaSoap/EasyvistaSoapProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyvistaSoap/EasyvistaSoapProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class EasyvistaSoapProvider extends AbstractProvider
{
use LoggerTrait;
public const ARG_ACCOUNT = 1;
public const ARG_CATALOG_GUID = 2;
public const ARG_CATALOG_CODE = 3;
public const ARG_ASSET_ID = 4;
public const ARG_ASSET_TAG = 5;
public const ARG_ASSET_NAME = 6;
public const ARG_URGENCY_ID = 7;
public const ARG_SEVERITY_ID = 8;
public const ARG_EXTERNAL_REFERENCE = 9;
public const ARG_PHONE = 10;
public const ARG_REQUESTOR_IDENTIFICATION = 11;
public const ARG_REQUESTOR_MAIL = 12;
public const ARG_REQUESTOR_NAME = 13;
public const ARG_LOCATION_ID = 14;
public const ARG_LOCATION_CODE = 15;
public const ARG_DEPARTMENT_ID = 16;
public const ARG_DEPARTMENT_CODE = 17;
public const ARG_RECIPIENT_ID = 18;
public const ARG_RECIPIENT_IDENTIFICATION = 19;
public const ARG_RECIPIENT_MAIL = 20;
public const ARG_RECIPIENT_NAME = 21;
public const ARG_ORIGIN = 22;
public const ARG_DESCRIPTION = 23;
public const ARG_PARENT_REQUEST = 24;
public const ARG_CI_ID = 25;
public const ARG_CI_ASSET_TAG = 26;
public const ARG_CI_NAME = 27;
public const ARG_SUBMIT_DATE = 28;
protected $proxy_enabled = 1;
protected $attach_files = 1;
/** @var array<int, array<mixed>> */
protected $internal_arg_name = [self::ARG_ACCOUNT => ['formid' => 'Account', 'soapname' => 'Account'], self::ARG_CATALOG_GUID => ['formid' => 'CatalogGUID', 'soapname' => 'Catalog_GUID'], self::ARG_CATALOG_CODE => ['formid' => 'CatalogCode', 'soapname' => 'Catalog_Code'], self::ARG_ASSET_ID => ['formid' => 'AssetID', 'soapname' => 'AssetID'], self::ARG_ASSET_TAG => ['formid' => 'AssetTag', 'soapname' => 'AssetTag'], self::ARG_ASSET_NAME => ['formid' => 'AssetName', 'soapname' => 'ASSET_NAME'], self::ARG_URGENCY_ID => ['formid' => 'UrgencyId', 'soapname' => 'Urgency_ID'], self::ARG_SEVERITY_ID => ['formid' => 'SeverityId', 'soapname' => 'Severity_ID'], self::ARG_EXTERNAL_REFERENCE => ['formid' => 'ExternalReference', 'soapname' => 'External_reference'], self::ARG_PHONE => ['formid' => 'Phone', 'soapname' => 'Phone'], self::ARG_REQUESTOR_IDENTIFICATION => ['formid' => 'RequestorIdentification', 'soapname' => 'Requestor_Identification'], self::ARG_REQUESTOR_MAIL => ['formid' => 'RequestorMail', 'soapname' => 'Requestor_Mail'], self::ARG_REQUESTOR_NAME => ['formid' => 'RequestorName', 'soapname' => 'Requestor_Name'], self::ARG_LOCATION_ID => ['formid' => 'LocationID', 'soapname' => 'Location_ID'], self::ARG_LOCATION_CODE => ['formid' => 'LocationCode', 'soapname' => 'Location_Code'], self::ARG_DEPARTMENT_ID => ['formid' => 'DepartmentID', 'soapname' => 'Department_ID'], self::ARG_DEPARTMENT_CODE => ['formid' => 'DepartmentCode', 'soapname' => 'Department_Code'], self::ARG_RECIPIENT_ID => ['formid' => 'RecipientID', 'soapname' => 'Recipient_ID'], self::ARG_RECIPIENT_IDENTIFICATION => ['formid' => 'RecipientIdentification', 'soapname' => 'Recipient_Identification'], self::ARG_RECIPIENT_MAIL => ['formid' => 'RecipientMail', 'soapname' => 'Recipient_Mail'], self::ARG_RECIPIENT_NAME => ['formid' => 'RecipientName', 'soapname' => 'Recipient_Name'], self::ARG_ORIGIN => ['formid' => 'Origin', 'soapname' => 'Origin'], self::ARG_DESCRIPTION => ['formid' => 'Description', 'soapname' => 'Description'], self::ARG_PARENT_REQUEST => ['formid' => 'ParentRequest', 'soapname' => 'ParentRequest'], self::ARG_CI_ID => ['formid' => 'CiID', 'soapname' => 'CI_ID'], self::ARG_CI_ASSET_TAG => ['formid' => 'CiAssetTag', 'soapname' => 'CI_ASSET_TAG'], self::ARG_CI_NAME => ['formid' => 'CiName', 'soapname' => 'CI_NAME'], self::ARG_SUBMIT_DATE => ['formid' => 'SubmitDate', 'soapname' => 'SUBMIT_DATE']];
/** @var string */
protected $ws_error;
/** @var null|array */
protected $soap_result;
/** @var string */
protected $_ticket_number;
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['wspath'] = '/WebService/SmoBridge.php';
$this->default_data['https'] = 0;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_ACCOUNT, 'Value' => 'Account name'], ['Arg' => self::ARG_DESCRIPTION, 'Value' => '{$body}'], ['Arg' => self::ARG_CATALOG_GUID, 'Value' => 'Catalog_GUID']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = 'http://{$address}/TicketNumber={$ticket_id}';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('wspath', "Please set 'Webservice Path' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkFormInteger('proxy_port', "'Proxy port' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/EasyvistaSoap/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['easyvista' => _('Easyvista')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$wspath_html = '<input size="50" name="wspath" type="text" value="'
. $this->getFormValue('wspath') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$https_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="https" name="https" value="yes" '
. ($this->getFormValue('https') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="https"></label></div>';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'wspath' => ['label' => _('Webservice Path') . $this->required_field, 'html' => $wspath_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'https' => ['label' => _('Use https'), 'html' => $https_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_ACCOUNT . '">' . _('Account') . '</options>'
. '<option value="' . self::ARG_DESCRIPTION . '">' . _('Description') . '</options>'
. '<option value="' . self::ARG_CATALOG_GUID . '">' . _('Catalog GUID') . '</options>'
. '<option value="' . self::ARG_CATALOG_CODE . '">' . _('Catalog Code') . '</options>'
. '<option value="' . self::ARG_URGENCY_ID . '">' . _('Urgency ID') . '</options>'
. '<option value="' . self::ARG_SEVERITY_ID . '">' . _('Severity ID') . '</options>'
. '<option value="' . self::ARG_ASSET_ID . '">' . _('Asset ID') . '</options>'
. '<option value="' . self::ARG_ASSET_TAG . '">' . _('Asset Tag') . '</options>'
. '<option value="' . self::ARG_ASSET_NAME . '">' . _('Asset Name') . '</options>'
. '<option value="' . self::ARG_EXTERNAL_REFERENCE . '">' . _('External Reference') . '</options>'
. '<option value="' . self::ARG_PHONE . '">' . _('Phone') . '</options>'
. '<option value="' . self::ARG_REQUESTOR_IDENTIFICATION . '">' . _('Requestor Identification') . '</options>'
. '<option value="' . self::ARG_REQUESTOR_MAIL . '">' . _('Requestor Mail') . '</options>'
. '<option value="' . self::ARG_REQUESTOR_NAME . '">' . _('Requestor Name') . '</options>'
. '<option value="' . self::ARG_LOCATION_ID . '">' . _('Location ID') . '</options>'
. '<option value="' . self::ARG_LOCATION_CODE . '">' . _('Location Code') . '</options>'
. '<option value="' . self::ARG_DEPARTMENT_ID . '">' . _('Department ID') . '</options>'
. '<option value="' . self::ARG_DEPARTMENT_CODE . '">' . _('Department Code') . '</options>'
. '<option value="' . self::ARG_RECIPIENT_ID . '">' . _('Recipient ID') . '</options>'
. '<option value="' . self::ARG_RECIPIENT_IDENTIFICATION . '">' . _('Recipient Identification') . '</options>'
. '<option value="' . self::ARG_RECIPIENT_MAIL . '">' . _('Recipient Mail') . '</options>'
. '<option value="' . self::ARG_RECIPIENT_NAME . '">' . _('Recipient Name') . '</options>'
. '<option value="' . self::ARG_ORIGIN . '">' . _('Origin') . '</options>'
. '<option value="' . self::ARG_PARENT_REQUEST . '">' . _('Parent Request') . '</options>'
. '<option value="' . self::ARG_CI_ID . '">' . _('CI ID') . '</options>'
. '<option value="' . self::ARG_CI_ASSET_TAG . '">' . _('CI Asset Tag') . '</options>'
. '<option value="' . self::ARG_CI_NAME . '">' . _('CI Name') . '</options>'
. '<option value="' . self::ARG_SUBMIT_DATE . '">' . _('Submit Date') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
$tpl = $this->initSmartyTemplate('providers/EasyvistaSoap/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['easyvista' => _('Easyvista')]);
$updatefields_html = '<input size="50" name="ez_updatefields" type="text" value="'
. $this->getFormValue('ez_updatefields') . '" />';
$array_form = ['ez_updatefields' => ['label' => _('Update fields'), 'html' => $updatefields_html]];
$tpl->assign('form', $array_form);
$this->config['container2_html'] .= $tpl->fetch('conf_container2extra.ihtml');
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['wspath'] = $this->submitted_config['wspath'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['https'] = (
isset($this->submitted_config['https']) && $this->submitted_config['https'] == 'yes'
) ? $this->submitted_config['https'] : '';
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['simple']['ez_updatefields'] = $this->submitted_config['ez_updatefields'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]['formid']] = $result_str;
}
}
$code = $this->createTicket($ticket_arguments);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->attachFiles($ticket_arguments);
if (isset($this->rule_data['ez_updatefields']) && $this->rule_data['ez_updatefields'] != '') {
$tpl->assign('string', $this->rule_data['ez_updatefields']);
$this->rule_data['ez_updatefields'] = $tpl->fetch('eval.ihtml');
$this->updateTicket($ticket_arguments);
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->_ticket_number, 'subject' => $ticket_arguments['CatalogGUID'], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments]
)]
);
return $result;
}
/**
* SOAP API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
protected function updateTicket($ticket_arguments)
{
$data = '<?xml version="1.0"?>
<soap:Envelope
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<tns:EZV_UpdateRequest xmlns:tns="https://na1.easyvista.com/WebService">
<tns:Account><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_ACCOUNT]['formid']] . ']]></tns:Account>
<tns:Login><![CDATA[' . $this->rule_data['username'] . ']]></tns:Login>
<tns:Password><![CDATA[' . $this->rule_data['password'] . ']]></tns:Password>
<tns:RFC_Number><![CDATA[' . $this->_ticket_number . ']]></tns:RFC_Number>
<tns:fields_to_update><![CDATA[' . $this->rule_data['ez_updatefields'] . ']]></tns:fields_to_update>
<tns:Request_id />
<tns:External_reference />
</tns:EZV_UpdateRequest>
</soap:Body>
</soap:Envelope>
';
$this->callSOAP($data, 'tns:EZV_UpdateRequest');
}
protected function attachFiles($ticket_arguments)
{
$attach_files = $this->getUploadFiles();
foreach ($attach_files as $file) {
$base64_content = base64_encode(file_get_contents($file['filepath']));
$data = '<?xml version="1.0"?>
<soap:Envelope
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<tns:EZV_AttachDocToRequest xmlns:tns="https://na1.easyvista.com/WebService">
<tns:Account><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_ACCOUNT]['formid']] . ']]></tns:Account>
<tns:Login><![CDATA[' . $this->rule_data['username'] . ']]></tns:Login>
<tns:Password><![CDATA[' . $this->rule_data['password'] . ']]></tns:Password>
<tns:path_docname><![CDATA[' . $file['filename'] . ']]></tns:path_docname>
<tns:BinaryStream><![CDATA[' . $base64_content . ']]></tns:BinaryStream>
<tns:RFC_Number><![CDATA[' . $this->_ticket_number . ']]></tns:RFC_Number>
<tns:External_reference />
<tns:Description />
</tns:EZV_AttachDocToRequest>
</soap:Body>
</soap:Envelope>
';
$this->callSOAP($data, 'tns:EZV_AttachDocToRequest');
}
}
protected function createTicket($ticket_arguments)
{
$attributes = '';
$account = '';
foreach ($this->internal_arg_name as $key => $value) {
if ($value['soapname'] == 'Account') {
$account = '<tns:Account><![CDATA[' . $ticket_arguments[$value['formid']] . ']]></tns:Account>';
continue;
}
$attributes .= (isset($ticket_arguments[$value['formid']])
? '<tns:' . $value['soapname'] . '><![CDATA[' . $ticket_arguments[$value['formid']]
. ']]></tns:' . $value['soapname'] . '>' : '<tns:' . $value['soapname'] . '/>');
}
$data = '<?xml version="1.0"?>
<soap:Envelope
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<tns:EZV_CreateRequest xmlns:tns="https://na1.easyvista.com/WebService">'
. $account . '
<tns:Login><![CDATA[' . $this->rule_data['username'] . ']]></tns:Login>
<tns:Password><![CDATA[' . $this->rule_data['password'] . ']]></tns:Password>'
. $attributes . '
</tns:EZV_CreateRequest>
</soap:Body>
</soap:Envelope>
';
if ($this->callSOAP($data, 'tns:EZV_CreateRequest') == 1) {
return -1;
}
/*
* OK:
* TODO
*
* NOK:
* <?xml version="1.0" encoding="UTF-8"?>
* <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
* xmlns:xsd="http://www.w3.org/2001/XMLSchema"
* xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
* xmlns:si="http://soapinterop.org/xsd"><SOAP-ENV:Body>
* <ns1:EZV_CreateRequestResponse xmlns:ns1="https://na1.easyvista.com/WebService">
* <return xsi:type="xsd:string">-1</return>
* </ns1:EZV_CreateRequestResponse>
* </SOAP-ENV:Body></SOAP-ENV:Envelope>
*/
if (! preg_match('/<return.*?>(.*?)<\/return>/msi', $this->soap_result, $matches)) {
$this->setWsError('');
return -1;
}
$return_value = $matches[1];
if (preg_match('/^-[0-9]+/', $return_value)) {
$map_error = ['-1' => 'invalid Account value', '-2' => 'Login/Password invalid', '-3' => 'invalid parameter', -4 => 'workflow not found'];
$msg_error = 'unknown error';
if (isset($map_error[$return_value])) {
$msg_error = $map_error[$return_value];
}
$this->setWsError($msg_error);
return -1;
}
$this->_ticket_number = $return_value;
return 0;
}
protected function callSOAP($data, $soap_action)
{
$proto = 'http';
if (isset($this->rule_data['https']) && $this->rule_data['https'] == 'yes') {
$proto = 'https';
}
$endpoint = $proto . '://' . $this->rule_data['address'] . $this->rule_data['wspath'];
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
$ch = curl_init($endpoint);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
self::setProxy(
$ch,
['proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
['Content-Type: text/xml;charset=UTF-8', 'SOAPAction: ' . $soap_action, 'Content-Length: ' . strlen($data)]
);
$optionsToLog = [
'apiAddress' => $endpoint,
'soapAction' => $soap_action,
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// log the curl options
$this->debug('Easyvista Soap request options', [
'options' => $optionsToLog,
]);
$this->soap_result = curl_exec($ch);
if ($this->soap_result == false) {
$this->setWsError(curl_error($ch));
curl_close($ch);
return 1;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
$this->setWsError($this->soap_result);
return 1;
}
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/RequestTracker2/RequestTracker2Provider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/RequestTracker2/RequestTracker2Provider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class RequestTracker2Provider extends AbstractProvider
{
use LoggerTrait;
public const RT_QUEUE_TYPE = 10;
public const RT_CUSTOMFIELD_TYPE = 11;
public const ARG_QUEUE = 1;
public const ARG_SUBJECT = 2;
public const ARG_REQUESTOR = 3;
public const ARG_CC = 4;
public const ARG_CONTENT = 5;
protected $proxy_enabled = 1;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_QUEUE => 'Queue', self::ARG_SUBJECT => 'Priority', self::ARG_REQUESTOR => 'Requestor', self::ARG_CC => 'Cc', self::ARG_CONTENT => 'Content'];
/** @var string */
protected $ws_error;
/** @var null|array */
protected $call_response;
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['path'] = '/REST/2.0/';
$this->default_data['https'] = 0;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_SUBJECT, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers/'
. 'Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_CONTENT, 'Value' => '{$body}'], ['Arg' => self::ARG_REQUESTOR, 'Value' => '{$user.email}'], ['Arg' => self::ARG_QUEUE, 'Value' => '{$select.rt_queue.value}']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain(0);
$this->default_data['url'] = 'http://{$address}/SelfService/Display.html?id={$ticket_id}';
$this->default_data['clones']['groupList'] = [['Id' => 'rt_queue', 'Label' => _('Rt queue'), 'Type' => self::RT_QUEUE_TYPE, 'Filter' => '', 'Mandatory' => '1']];
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('path', "Please set 'Path' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('token', "Please set 'Token' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specific config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/RequestTracker2/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['rt' => _('RequestTracker')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$path_html = '<input size="50" name="path" type="text" value="'
. $this->getFormValue('path') . '" />';
$token_html = '<input size="50" name="token" type="password" value="'
. $this->getFormValue('token') . '" autocomplete="off" />';
$https_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="https" name="https" value="yes" '
. ($this->getFormValue('https') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="https"></label></div>';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'path' => ['label' => _('Path') . $this->required_field, 'html' => $path_html], 'token' => ['label' => _('Token') . $this->required_field, 'html' => $token_html], 'https' => ['label' => _('Use https'), 'html' => $https_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')], 'mappingticketdynamicfield' => ['label' => _('Mapping ticket dynamic field')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_QUEUE . '">' . _('Queue') . '</options>'
. '<option value="' . self::ARG_SUBJECT . '">' . _('Subject') . '</options>'
. '<option value="' . self::ARG_REQUESTOR . '">' . _('Requestor') . '</options>'
. '<option value="' . self::ARG_CC . '">' . _('Cc') . '</options>'
. '<option value="' . self::ARG_CONTENT . '">' . _('Content') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
// mapping Ticket DynamicField
$mappingTicketDynamicFieldName_html = '<input id="mappingTicketDynamicFieldName_#index#" '
. 'name="mappingTicketDynamicFieldName[#index#]" size="30" type="text" />';
$mappingTicketDynamicFieldValue_html = '<input id="mappingTicketDynamicFieldValue_#index#" '
. 'name="mappingTicketDynamicFieldValue[#index#]" size="30" type="text" />';
$array_form['mappingTicketDynamicField'] = [['label' => _('Name'), 'html' => $mappingTicketDynamicFieldName_html], ['label' => _('Value'), 'html' => $mappingTicketDynamicFieldValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
$this->config['clones']['mappingTicketDynamicField'] = $this->getCloneValue('mappingTicketDynamicField');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['path'] = $this->submitted_config['path'];
$this->save_config['simple']['token'] = $this->submitted_config['token'];
$this->save_config['simple']['https'] = (isset($this->submitted_config['https'])
&& $this->submitted_config['https'] == 'yes')
? $this->submitted_config['https'] : '';
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
$this->save_config['clones']['mappingTicketDynamicField'] = $this->getCloneSubmitted(
'mappingTicketDynamicField',
['Name', 'Value']
);
}
/**
* @return string
*/
protected function getGroupListOptions()
{
return '<option value="' . self::RT_QUEUE_TYPE . '">Rt queue</options>'
. '<option value="' . self::RT_CUSTOMFIELD_TYPE . '">Rt custom field</options>';
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignRtQueue($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
[$code, $items] = $this->listQueueRt();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($items as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['Name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['Name'])) {
$result[$row['id']] = $this->to_utf8($row['Name']);
}
}
$saveResults = ['results' => $items];
$this->saveSession($entry['Id'], $saveResults);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignRtCustomField($entry, &$groups_order, &$groups)
{
// $entry['Filter']: to get the custom list
[$code, $items] = $this->listCustomFieldRt($entry['Filter']);
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($items as $row) {
$result[$row['id']] = $this->to_utf8($row['value']);
}
$saveResults = ['results' => $items];
$this->saveSession($entry['Id'], $saveResults);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::RT_QUEUE_TYPE) {
$this->assignRtQueue($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::RT_CUSTOMFIELD_TYPE) {
$this->assignRtCustomField($entry, $groups_order, $groups);
}
}
/**
* @param int|string $select_input_id
* @param int $selected_id
* @return mixed
*/
protected function assignSubmittedValuesSelectMore($select_input_id, $selected_id)
{
$session_name = null;
foreach ($this->rule_data['clones']['groupList'] as $value) {
if ($value['Id'] == $select_input_id) {
$session_name = $value['Id'];
}
}
if (is_null($session_name) && $selected_id == -1) {
return [];
}
if ($selected_id == -1) {
return ['id' => null, 'value' => null];
}
$result = $this->getSession($session_name);
if (is_null($result)) {
return [];
}
foreach ($result['results'] as $value) {
if ($value['id'] == $selected_id) {
return $value;
}
}
return [];
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
$ticket_dynamic_fields = [];
if (isset($this->rule_data['clones']['mappingTicketDynamicField'])) {
foreach ($this->rule_data['clones']['mappingTicketDynamicField'] as $value) {
if ($value['Name'] == '' || $value['Value'] == '') {
continue;
}
$array_tmp = [];
$tpl->assign('string', $value['Name']);
$array_tmp = ['Name' => $tpl->fetch('eval.ihtml')];
$tpl->assign('string', $value['Value']);
$array_tmp['Value'] = $tpl->fetch('eval.ihtml');
$ticket_dynamic_fields[] = $array_tmp;
}
}
$code = $this->createTicketRt($ticket_arguments, $ticket_dynamic_fields);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->call_response['id'], 'subject' => $ticket_arguments['Subject'], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments, 'dynamic_fields' => $ticket_dynamic_fields]
)]
);
return $result;
}
/**
* REST API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
/**
* @return array{int, array}
*/
protected function listQueueRt()
{
$items = [];
$page = 1;
$per_page = 100;
while (1) {
$query = 'queues/all?fields=id,Name&per_page=' . $per_page . '&page=' . $page;
if ($this->callRest($query) == 1) {
return [-1, $items];
}
$items = array_merge($items, $this->call_response['items']);
if ($this->call_response['total'] < ($page * $per_page)) {
break;
}
$page++;
}
return [0, $items];
}
/**
* @param ?string $filter
* @return array
*/
protected function listCustomFieldRt($filter)
{
$items = [];
if (is_null($filter) || $filter === '') {
$this->setWsError('please set filter for the list');
return [-1, $items];
}
$argument = [['field' => 'Name', 'operator' => 'LIKE', 'value' => $filter]];
if ($this->callRest('customfields?fields=Name', $argument) == 1) {
return [-1, $items];
}
$customField = array_shift($this->call_response['items']);
/*
* Format:
* {
* "id": 17,
* "type": "customfield",
* "Name": "Site"
* }
*/
if (is_null($customField)) {
$this->setWsError("cannot get a custom field with filter '{$filter}'");
return [-1, $items];
}
if ($this->callRest('customfield/' . $customField['id']) == 1) {
return [-1, $items];
}
$duplicated = [];
foreach ($this->call_response['Values'] as $value) {
if (isset($duplicated[$value])) {
continue;
}
$items[] = ['id' => $value, 'value' => $value, 'customFieldId' => $customField['id']];
$duplicated[$value] = 1;
}
return [0, $items];
}
/**
* @param array $ticket_arguments
* @param array $ticket_dynamic_fields
* @return int
*/
protected function createTicketRt($ticket_arguments, $ticket_dynamic_fields)
{
$argument = ['Queue' => $ticket_arguments[$this->internal_arg_name[self::ARG_QUEUE]], 'Subject' => $ticket_arguments[$this->internal_arg_name[self::ARG_SUBJECT]], 'Requestor' => $ticket_arguments[$this->internal_arg_name[self::ARG_REQUESTOR]], 'Content' => $ticket_arguments[$this->internal_arg_name[self::ARG_CONTENT]]];
if (
isset($ticket_arguments[$this->internal_arg_name[self::ARG_CC]])
&& $ticket_arguments[$this->internal_arg_name[self::ARG_CC]] != ''
) {
$argument['Cc'] = $ticket_arguments[$this->internal_arg_name[self::ARG_CC]];
}
if (count($ticket_dynamic_fields) > 0) {
$argument['CustomFields'] = [];
foreach ($ticket_dynamic_fields as $field) {
$argument['CustomFields'][$field['Name']] = $field['Value'];
}
}
$fp = fopen('/var/opt/rh/rh-php71/log/php-fpm/debug.txt', 'a+');
fwrite($fp, print_r($argument, true));
fclose($fp);
if ($this->callRest('ticket', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @param string $function
* @param null|array $argument
* @return int
*/
protected function callRest($function, $argument = null)
{
if (! extension_loaded('curl')) {
$this->setWsError('cannot load curl extension');
return 1;
}
$this->call_response = null;
$proto = 'http';
if (isset($this->rule_data['https']) && $this->rule_data['https'] == 'yes') {
$proto = 'https';
}
$base_url = $proto . '://' . $this->rule_data['address'] . $this->rule_data['path'] . $function;
$ch = curl_init($base_url);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
$method = 'GET';
$headers = ['Content-Type: application/json', 'Accept: application/json'];
$headers[] = 'Authorization: token ' . $this->getFormValue('token', false);
if (! is_null($argument)) {
$argument_json = json_encode($argument);
curl_setopt($ch, CURLOPT_POSTFIELDS, $argument_json);
$headers[] = 'Content-Length: ' . strlen($argument_json);
$method = 'POST';
}
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
self::setProxy(
$ch,
['proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
$optionsToLog = [
'apiAddress' => $base_url,
'method' => $method,
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
if ($peerVerify && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// log the curl options
$this->debug('Request tracker API request options', [
'options' => $optionsToLog,
]);
$result = curl_exec($ch);
if ($result == false) {
$this->setWsError(curl_error($ch));
curl_close($ch);
return 1;
}
// 401 it's an error (unauthorized maybe)
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (! preg_match_all('/^2/', $http_code)) {
curl_close($ch);
$this->setWsError($http_code . ' code error');
return 1;
}
$decoded_result = json_decode($result, true);
if (is_null($decoded_result) || $decoded_result == false) {
$this->setWsError($result);
return 1;
}
curl_close($ch);
$this->call_response = $decoded_result;
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/ServiceNow/ServiceNowProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/ServiceNow/ServiceNowProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
/**
* @phpstan-type TokenInfo array{
* instance: string,
* client_id: string,
* client_secret: string,
* username: string,
* password: string,
* proxy_address: string,
* proxy_port: string,
* proxy_username: string,
* proxy_password: string,
* }
*/
class ServiceNowProvider extends AbstractProvider
{
public const SERVICENOW_LIST_CATEGORY = 20;
public const SERVICENOW_LIST_SUBCATEGORY = 21;
public const SERVICENOW_LIST_IMPACT = 22;
public const SERVICENOW_LIST_URGENCY = 23;
public const SERVICENOW_LIST_ASSIGNMENT_GROUP = 24;
public const SERVICENOW_LIST_ASSIGNED_TO = 25;
public const SERVICENOW_LIST_SEVERITY = 26;
public const ARG_SHORT_DESCRIPTION = 1;
public const ARG_COMMENTS = 2;
public const ARG_IMPACT = 3;
public const ARG_URGENCY = 4;
public const ARG_CATEGORY = 5;
public const ARG_SUBCATEGORY = 6;
public const ARG_ASSIGNED_TO = 7;
public const ARG_ASSIGNMENT_GROUP = 8;
public const ARG_SEVERITY = 9;
protected $proxy_enabled = 1;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_SHORT_DESCRIPTION => 'ShortDescription', self::ARG_COMMENTS => 'Comments', self::ARG_IMPACT => 'Impact', self::ARG_URGENCY => 'Urgency', self::ARG_CATEGORY => 'Category', self::ARG_SEVERITY => 'Severity', self::ARG_SUBCATEGORY => 'Subcategory', self::ARG_ASSIGNED_TO => 'AssignedTo', self::ARG_ASSIGNMENT_GROUP => 'AssignmentGroup'];
/**
* Validate the popup for submit a ticket
*/
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Test the service
*
* @param TokenInfo $info The post information from webservice
* @return bool
*/
public static function test($info)
{
// Test arguments
if (
! isset($info['instance'])
|| ! isset($info['clientId'])
|| ! isset($info['clientSecret'])
|| ! isset($info['username'])
|| ! isset($info['password'])
) {
throw new Exception('Missing arguments.');
}
try {
$tokens = self::getAccessToken(
[
'instance' => $info['instance'],
'client_id' => $info['clientId'],
'client_secret' => $info['clientSecret'],
'username' => $info['username'],
'password' => $info['password'],
'proxy_address' => $info['proxyAddress'],
'proxy_port' => $info['proxyPort'],
'proxy_username' => $info['proxyUsername'],
'proxy_password' => $info['proxyPassword'],
]
);
return true;
} catch (Exception $e) {
return false;
}
}
/**
* Set the default extra data
*/
protected function setDefaultValueExtra()
{
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_SHORT_DESCRIPTION, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers/'
. 'Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_COMMENTS, 'Value' => '{$body}'], ['Arg' => self::ARG_ASSIGNED_TO, 'Value' => '{$select.servicenow_assigned_to.value}'], ['Arg' => self::ARG_ASSIGNMENT_GROUP, 'Value' => '{$select.servicenow_assignment_group.value}'], ['Arg' => self::ARG_IMPACT, 'Value' => '{$select.servicenow_impact.value}'], ['Arg' => self::ARG_URGENCY, 'Value' => '{$select.servicenow_urgency.value}'], ['Arg' => self::ARG_SEVERITY, 'Value' => '{$select.servicenow_severity.value}'], ['Arg' => self::ARG_CATEGORY, 'Value' => '{$select.servicenow_category.value}'], ['Arg' => self::ARG_SUBCATEGORY, 'Value' => '{$select.servicenow_subcategory.value}']];
}
/**
* Add default data
* @param mixed $body_html
*/
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = 'https://{$instance_name}.service-now.com/'
. 'nav_to.do?uri=incident.do?sys_id={$ticket_id}';
$this->default_data['clones']['groupList'] = [['Id' => 'servicenow_category', 'Label' => _('Category'), 'Type' => self::SERVICENOW_LIST_CATEGORY, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'servicenow_subcategory', 'Label' => _('Subcategory'), 'Type' => self::SERVICENOW_LIST_SUBCATEGORY, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'servicenow_impact', 'Label' => _('Impact'), 'Type' => self::SERVICENOW_LIST_IMPACT, 'Filter' => '', 'Mandatory' => true], ['Id' => 'servicenow_urgency', 'Label' => _('Urgency'), 'Type' => self::SERVICENOW_LIST_URGENCY, 'Filter' => '', 'Mandatory' => true], ['Id' => 'servicenow_severity', 'Label' => _('Severity'), 'Type' => self::SERVICENOW_LIST_SEVERITY, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'servicenow_assignment_group', 'Label' => _('Assignment group'), 'Type' => self::SERVICENOW_LIST_ASSIGNMENT_GROUP, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'servicenow_assigned_to', 'Label' => _('Assigned to'), 'Type' => self::SERVICENOW_LIST_ASSIGNED_TO, 'Filter' => '', 'Mandatory' => '']];
}
/**
* Check the configuration form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('instance_name', 'Please set a instance.');
$this->checkFormValue('client_id', 'Please set a OAuth2 client id.');
$this->checkFormValue('client_secret', 'Please set a OAuth2 client secret.');
$this->checkFormValue('username', 'Please set a OAuth2 username.');
$this->checkFormValue('password', 'Please set a OAuth2 password.');
$this->checkFormInteger('proxy_port', "'Proxy port' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Prepare the extra configuration block
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/ServiceNow/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['servicenow' => _('Service Now')]);
$tpl->assign('webServiceUrl', './api/internal.php');
// Form
$instance_name_html = '<input size="50" name="instance_name" type="text" value="'
. $this->getFormValue('instance_name') . '" />';
$client_id_html = '<input size="50" name="client_id" type="text" value="'
. $this->getFormValue('client_id') . '" />';
$client_secret_html = '<input size="50" name="client_secret" type="password" value="'
. $this->getFormValue('client_secret') . '" autocomplete="off" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$array_form = ['instance_name' => ['label' => _('Instance name')
. $this->required_field, 'html' => $instance_name_html], 'client_id' => ['label' => _('OAuth Client ID')
. $this->required_field, 'html' => $client_id_html], 'client_secret' => ['label' => _('OAuth client secret')
. $this->required_field, 'html' => $client_secret_html], 'username' => ['label' => _('OAuth username')
. $this->required_field, 'html' => $username_html], 'password' => ['label' => _('OAuth password')
. $this->required_field, 'html' => $password_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_SHORT_DESCRIPTION . '">' . _('Short description') . '</options>'
. '<option value="' . self::ARG_COMMENTS . '">' . _('Comments') . '</options>'
. '<option value="' . self::ARG_IMPACT . '">' . _('Impact') . '</options>'
. '<option value="' . self::ARG_URGENCY . '">' . _('Urgency') . '</options>'
. '<option value="' . self::ARG_SEVERITY . '">' . _('Severity') . '</options>'
. '<option value="' . self::ARG_CATEGORY . '">' . _('Category') . '</options>'
. '<option value="' . self::ARG_SUBCATEGORY . '">' . _('Subcategory') . '</options>'
. '<option value="' . self::ARG_ASSIGNED_TO . '">' . _('Assigned To') . '</options>'
. '<option value="' . self::ARG_ASSIGNMENT_GROUP . '">' . _('Assignment Group') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
protected function getConfigContainer2Extra()
{
}
/**
* Add specific configuration field
*/
protected function saveConfigExtra()
{
$this->save_config['simple']['instance_name'] = $this->submitted_config['instance_name'];
$this->save_config['simple']['client_id'] = $this->submitted_config['client_id'];
$this->save_config['simple']['client_secret'] = $this->submitted_config['client_secret'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
/**
* Append additional list
*
* @return string
*/
protected function getGroupListOptions()
{
return '<option value="' . self::SERVICENOW_LIST_CATEGORY . '">ServiceNow category</options>'
. '<option value="' . self::SERVICENOW_LIST_SUBCATEGORY . '">ServiceNow subcategory</options>'
. '<option value="' . self::SERVICENOW_LIST_IMPACT . '">ServiceNow impact</options>'
. '<option value="' . self::SERVICENOW_LIST_URGENCY . '">ServiceNow urgency</options>'
. '<option value="' . self::SERVICENOW_LIST_SEVERITY . '">ServiceNow severity</options>'
. '<option value="' . self::SERVICENOW_LIST_ASSIGNMENT_GROUP . '">ServiceNow assignment group</options>'
. '<option value="' . self::SERVICENOW_LIST_ASSIGNED_TO . '">ServiceNow assigned to</options>';
}
protected function assignOtherServiceNow($entry, $method, &$groups_order, &$groups)
{
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
try {
$listValues = $this->getCache($entry['Id']);
if (is_null($listValues)) {
$listValues = $this->callServiceNow($method, ['Filter' => $entry['Filter']]);
$this->setCache($entry['Id'], $listValues, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
return 0;
}
$groups[$entry['Id']]['values'] = $listValues;
return $listValues;
}
/**
* Add field in popin for create a ticket
* @param mixed $entry
* @param mixed $groups_order
* @param mixed $groups
*/
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::SERVICENOW_LIST_ASSIGNED_TO) {
$listValues = $this->assignOtherServiceNow($entry, 'getListSysUser', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_ASSIGNMENT_GROUP) {
$listValues = $this->assignOtherServiceNow($entry, 'getListSysUserGroup', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_IMPACT) {
$listValues = $this->assignOtherServiceNow($entry, 'getListImpact', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_URGENCY) {
$listValues = $this->assignOtherServiceNow($entry, 'getListUrgency', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_SEVERITY) {
$listValues = $this->assignOtherServiceNow($entry, 'getListSeverity', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_CATEGORY) {
$listValues = $this->assignOtherServiceNow($entry, 'getListCategory', $groups_order, $groups);
} elseif ($entry['Type'] == self::SERVICENOW_LIST_SUBCATEGORY) {
$listValues = $this->assignOtherServiceNow($entry, 'getListSubcategory', $groups_order, $groups);
}
}
/**
* Create a ticket
*
* @param CentreonDB $db_storage The centreon_storage database connection
* @param string $contact The contact who open the ticket
* @param array $host_problems The list of host issues link to the ticket
* @param array $service_problems The list of service issues link to the ticket
* @return array The status of action (
* 'code' => int,
* 'message' => string
* )
*/
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
// Create ticket
try {
$data = $this->submitted_config;
$data['ticket_arguments'] = $ticket_arguments;
$resultInfo = $this->callServiceNow('createTicket', $data);
} catch (Exception $e) {
$result['ticket_error_message'] = 'Error during create ServiceNow ticket';
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $resultInfo['sysTicketId'] ?? null, 'subject' => $ticket_arguments[
$this->internal_arg_name[self::ARG_SHORT_DESCRIPTION]
], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode($data)]
);
return $result;
}
/**
* Get an access token
*
* @param TokenInfo $info
* @return array The tokens
*/
protected static function getAccessToken($info)
{
$url = 'https://' . $info['instance'] . '.service-now.com/oauth_token.do';
$postfields = 'grant_type=password';
$postfields .= '&client_id=' . urlencode($info['client_id']);
$postfields .= '&client_secret=' . urlencode($info['client_secret']);
$postfields .= '&username=' . urlencode($info['username']);
$postfields .= '&password=' . urlencode($info['password']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
self::setProxy($ch, $info);
$returnJson = curl_exec($ch);
if ($returnJson === false) {
throw new Exception(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status !== 200) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
$return = json_decode($returnJson, true);
return ['accessToken' => $return['access_token'], 'refreshToken' => $return['refresh_token']];
}
/**
* Refresh the access token
*
* @param mixed $refreshToken
*
* @throws Exception
* @return array<string, mixed> The access token
*/
protected function refreshToken($refreshToken)
{
$instance = $this->getFormValue('instance_name', false);
$url = 'https://' . $instance . '.service-now.com/oauth_token.do';
$postfields = 'grant_type=refresh_token';
$postfields .= '&client_id=' . urlencode(
$this->getFormValue('client_id', false)
);
$postfields .= '&client_secret=' . urlencode(
$this->getFormValue('client_secret', false)
);
$postfields .= '&refresh_token=' . $refreshToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
self::setProxy(
$ch,
['proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
$returnJson = curl_exec($ch);
if ($returnJson === false) {
throw new Exception(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status !== 200) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
$return = json_decode($returnJson, true);
return ['accessToken' => $return['access_token'], 'refreshToken' => $return['refresh_token']];
}
/**
* Call a service now Rest webservices
* @param mixed $methodName
* @param mixed $params
*/
protected function callServiceNow($methodName, $params = [])
{
$accessToken = $this->getCache('accessToken');
$refreshToken = $this->getCache('refreshToken');
if (is_null($refreshToken)) {
$tokens = self::getAccessToken(
['instance' => $this->getFormValue('instance_name', false), 'client_id' => $this->getFormValue('client_id', false), 'client_secret' => $this->getFormValue('client_secret', false), 'username' => $this->getFormValue('username', false), 'password' => $this->getFormValue('password', false), 'proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
$accessToken = $tokens['accessToken'];
$this->setCache('accessToken', $tokens['accessToken'], 1600);
$this->setCache('refreshToken', $tokens['refreshToken'], 8400);
} elseif (is_null($accessToken)) {
$tokens = $this->refreshToken($refreshToken);
$accessToken = $tokens['accessToken'];
$this->setCache('accessToken', $tokens['accessToken'], 1600);
$this->setCache('refreshToken', $tokens['refreshToken'], 8400);
}
return $this->{$methodName}($params, $accessToken);
}
/**
* Execute the http request
*
* @param string $uri The URI to call
* @param string $accessToken The OAuth access token
* @param string $method The http method
* @param string $data The data to send, used in method POST, PUT, PATCH
*/
protected function runHttpRequest($uri, $accessToken, $method = 'GET', $data = null)
{
$instance = $this->getFormValue('instance_name', false);
$url = 'https://' . $instance . '.service-now.com' . $uri;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $accessToken]
);
self::setProxy(
$ch,
['proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method !== 'GET') {
curl_setopt($ch, CURLOPT_POST, 1);
if (! is_null($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
}
$returnJson = curl_exec($ch);
if ($returnJson === false) {
throw new Exception(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status < 200 && $status >= 300) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
return json_decode($returnJson, true);
}
/**
* Get the list of user from ServiceNow for Assigned to
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of user
*/
protected function getListSysUser($params, $accessToken)
{
$uri = '/api/now/table/sys_user?sysparm_fields=sys_id,active,name';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['active'] === 'true') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['sys_id']] = $entry['name'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['name'])) {
$selected[$entry['sys_id']] = $entry['name'];
}
}
}
return $selected;
}
/**
* Get the list of user group from ServiceNow for Assigned to
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of user group
*/
protected function getListSysUserGroup($params, $accessToken)
{
$uri = '/api/now/table/sys_user_group?sysparm_fields=sys_id,active,name';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['active'] === 'true') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['sys_id']] = $entry['name'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['name'])) {
$selected[$entry['sys_id']] = $entry['name'];
}
}
}
return $selected;
}
/**
* Getting the list of impact from ServiceNow
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of impact
*/
protected function getListImpact($params, $accessToken)
{
$uri = '/api/now/table/sys_choice?sysparm_fields=value,label,inactive'
. '&sysparm_query=nameSTARTSWITHtask%5EelementSTARTSWITHimpact';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['inactive'] === 'false') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['value']] = $entry['label'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['label'])) {
$selected[$entry['value']] = $entry['label'];
}
}
}
return $selected;
}
/**
* Getting the list of urgency from ServiceNow
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of urgency
*/
protected function getListUrgency($params, $accessToken)
{
$uri = '/api/now/table/sys_choice?sysparm_fields=value,label,inactive'
. '&sysparm_query=nameSTARTSWITHincident%5EelementSTARTSWITHurgency';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['inactive'] === 'false') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['value']] = $entry['label'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['label'])) {
$selected[$entry['value']] = $entry['label'];
}
}
}
return $selected;
}
/**
* Getting the list of severity from ServiceNow
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of urgency
*/
protected function getListSeverity($params, $accessToken)
{
$uri = '/api/now/table/sys_choice?sysparm_fields=value,label,inactive'
. '&sysparm_query=nameSTARTSWITHincident%5EelementSTARTSWITHseverity';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['inactive'] === 'false') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['value']] = $entry['label'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['label'])) {
$selected[$entry['value']] = $entry['label'];
}
}
}
return $selected;
}
/**
* Getting the list of category from ServiceNow
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of category
*/
protected function getListCategory($params, $accessToken)
{
$uri = '/api/now/table/sys_choice?sysparm_fields=value,label,inactive'
. '&sysparm_query=nameSTARTSWITHincident%5EelementSTARTSWITHcategory';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['inactive'] === 'false') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['value']] = $entry['label'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['label'])) {
$selected[$entry['value']] = $entry['label'];
}
}
}
return $selected;
}
/**
* Getting the list of subcategory from ServiceNow
*
* @param array $params The parameters for filter (no used)
* @param string $accessToken The access token
* @return array The list of subcategory
*/
protected function getListSubcategory($params, $accessToken)
{
$uri = '/api/now/table/sys_choice?sysparm_fields=value,label,inactive'
. '&sysparm_query=nameSTARTSWITHincident%5EelementSTARTSWITHsubcategory';
$result = $this->runHttpRequest($uri, $accessToken);
$selected = [];
foreach ($result['result'] as $entry) {
if ($entry['inactive'] === 'false') {
if (! isset($params['Filter']) || is_null($params['Filter']) || $params['Filter'] == '') {
$selected[$entry['value']] = $entry['label'];
}
if (preg_match('/' . $params['Filter'] . '/', $entry['label'])) {
$selected[$entry['value']] = $entry['label'];
}
}
}
return $selected;
}
protected function createTicket($params, $accessToken)
{
$uri = '/api/now/v1/table/incident';
$impacts = explode('_', $params['ticket_arguments'][$this->internal_arg_name[self::ARG_IMPACT]], 2);
$urgencies = explode('_', $params['ticket_arguments'][$this->internal_arg_name[self::ARG_URGENCY]], 2);
$severities = explode('_', $params['ticket_arguments'][$this->internal_arg_name[self::ARG_SEVERITY]], 2);
$data = ['impact' => $impacts[0], 'urgency' => $urgencies[0], 'severity' => $severities[0], 'short_description' => $params['ticket_arguments'][
$this->internal_arg_name[self::ARG_SHORT_DESCRIPTION]
]];
if (isset($params['ticket_arguments'][$this->internal_arg_name[self::ARG_CATEGORY]])) {
$category = explode(
'_',
$params['ticket_arguments'][$this->internal_arg_name[self::ARG_CATEGORY]],
2
);
$data['category'] = $category[0];
}
if (isset($params['ticket_arguments'][$this->internal_arg_name[self::ARG_SUBCATEGORY]])) {
$subcategory = explode(
'_',
$params['ticket_arguments'][$this->internal_arg_name[self::ARG_SUBCATEGORY]],
2
);
$data['subcategory'] = $subcategory[0];
}
if (isset($params['ticket_arguments'][$this->internal_arg_name[self::ARG_ASSIGNED_TO]])) {
$assignedTo = explode(
'_',
$params['ticket_arguments'][$this->internal_arg_name[self::ARG_ASSIGNED_TO]],
2
);
$data['assigned_to'] = $assignedTo[0];
}
if (isset($params['ticket_arguments'][$this->internal_arg_name[self::ARG_ASSIGNMENT_GROUP]])) {
$assignmentGroup = explode(
'_',
$params['ticket_arguments'][$this->internal_arg_name[self::ARG_ASSIGNMENT_GROUP]],
2
);
$data['assignment_group'] = $assignmentGroup[0];
}
if (isset($params['ticket_arguments'][$this->internal_arg_name[self::ARG_COMMENTS]])) {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Jira/JiraProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Jira/JiraProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class JiraProvider extends AbstractProvider
{
use LoggerTrait;
public const JIRA_PROJECT = 30;
public const JIRA_ASSIGNEE = 31;
public const JIRA_ISSUETYPE = 32;
public const JIRA_PRIORITY = 33;
public const ARG_PROJECT = 1;
public const ARG_SUMMARY = 2;
public const ARG_DESCRIPTION = 3;
public const ARG_ASSIGNEE = 4;
public const ARG_ISSUETYPE = 5;
public const ARG_PRIORITY = 6;
protected $proxy_enabled = 1;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_PROJECT => 'Project', self::ARG_SUMMARY => 'Summary', self::ARG_DESCRIPTION => 'Description', self::ARG_ASSIGNEE => 'Assignee', self::ARG_PRIORITY => 'Priority', self::ARG_ISSUETYPE => 'IssueType'];
/** @var string */
protected $ws_error;
/** @var null|array */
protected $jira_call_response;
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = 'xxx.atlassian.net';
$this->default_data['rest_api_resource'] = '/rest/api/latest/';
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_SUMMARY, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers/'
. 'Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_DESCRIPTION, 'Value' => '{$body}'], ['Arg' => self::ARG_PROJECT, 'Value' => '{$select.jira_project.id}'], ['Arg' => self::ARG_ASSIGNEE, 'Value' => '{$select.jira_assignee.id}'], ['Arg' => self::ARG_PRIORITY, 'Value' => '{$select.jira_priority.id}'], ['Arg' => self::ARG_ISSUETYPE, 'Value' => '{$select.jira_issuetype.id}']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
// $this->default_data['url'] = 'http://{$address}/index.pl?Action=AgentTicketZoom;TicketNumber={$ticket_id}';
$this->default_data['clones']['groupList'] = [['Id' => 'jira_project', 'Label' => _('Jira project'), 'Type' => self::JIRA_PROJECT, 'Filter' => '', 'Mandatory' => '1'], ['Id' => 'jira_priority', 'Label' => _('Jira priority'), 'Type' => self::JIRA_PRIORITY, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'jira_assignee', 'Label' => _('Jira assignee'), 'Type' => self::JIRA_ASSIGNEE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'jira_issuetype', 'Label' => _('Jira issue type'), 'Type' => self::JIRA_ISSUETYPE, 'Filter' => '', 'Mandatory' => '1']];
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('rest_api_resource', "Please set 'Rest Api Resource' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('user_token', "Please set 'User Token' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/Jira/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['jira' => _('Jira')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$rest_api_resource_html = '<input size="50" name="rest_api_resource" type="text" value="'
. $this->getFormValue('rest_api_resource') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$user_token_html = '<input size="50" name="user_token" type="password" value="'
. $this->getFormValue('user_token') . '" autocomplete="off" />';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'rest_api_resource' => ['label' => _('Rest Api Resource') . $this->required_field, 'html' => $rest_api_resource_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'user_token' => ['label' => _('User Token') . $this->required_field, 'html' => $user_token_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_PROJECT . '">' . _('Project') . '</options>'
. '<option value="' . self::ARG_SUMMARY . '">' . _('Summary') . '</options>'
. '<option value="' . self::ARG_DESCRIPTION . '">' . _('Description') . '</options>'
. '<option value="' . self::ARG_ASSIGNEE . '">' . _('Assignee') . '</options>'
. '<option value="' . self::ARG_PRIORITY . '">' . _('Priority') . '</options>'
. '<option value="' . self::ARG_ISSUETYPE . '">' . _('Issue Type') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['rest_api_resource'] = $this->submitted_config['rest_api_resource'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['user_token'] = $this->submitted_config['user_token'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
protected function getGroupListOptions()
{
return '<option value="' . self::JIRA_PROJECT . '">Jira project</options>'
. '<option value="' . self::JIRA_ASSIGNEE . '">Jira assignee</options>'
. '<option value="' . self::JIRA_ISSUETYPE . '">Jira issue type</options>'
. '<option value="' . self::JIRA_PRIORITY . '">Jira priority</options>';
}
protected function assignJiraProject($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listProjectJira();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->jira_call_response as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('jira_project', $this->jira_call_response);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignJiraPriority($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listPriorityJira();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->jira_call_response as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('jira_priority', $this->jira_call_response);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignJiraIssuetype($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listIssuetypeJira();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->jira_call_response as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('jira_issuetype', $this->jira_call_response);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignJiraUser($entry, &$groups_order, &$groups, $label_session)
{
$code = $this->listUserJira($entry['Filter']);
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->jira_call_response as $row) {
$result[$row['accountId']] = $this->to_utf8($row['displayName']);
}
$this->saveSession($label_session, $this->jira_call_response);
$groups[$entry['Id']]['values'] = $result;
}
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::JIRA_PROJECT) {
$this->assignJiraProject($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::JIRA_ASSIGNEE) {
$this->assignJiraUser($entry, $groups_order, $groups, 'jira_assignee');
} elseif ($entry['Type'] == self::JIRA_ISSUETYPE) {
$this->assignJiraIssuetype($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::JIRA_PRIORITY) {
$this->assignJiraPriority($entry, $groups_order, $groups);
}
}
protected function assignSubmittedValuesSelectMore($select_input_id, $selected_id)
{
$session_name = null;
foreach ($this->rule_data['clones']['groupList'] as $value) {
if ($value['Id'] == $select_input_id) {
if ($value['Type'] == self::JIRA_PROJECT) {
$session_name = 'jira_project';
} elseif ($value['Type'] == self::JIRA_ASSIGNEE) {
$session_name = 'jira_assignee';
} elseif ($value['Type'] == self::JIRA_ISSUETYPE) {
$session_name = 'jira_issuetype';
} elseif ($value['Type'] == self::JIRA_PRIORITY) {
$session_name = 'jira_priority';
}
}
}
if (is_null($session_name) && $selected_id == -1) {
return [];
}
if ($selected_id == -1) {
return ['id' => null, 'value' => null];
}
$result = $this->getSession($session_name);
if (is_null($result)) {
return [];
}
foreach ($result as $value) {
if ($value['id'] == $selected_id) {
return $value;
}
}
return [];
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
$code = $this->createTicketJira($ticket_arguments);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
// Array ( [id] => 41261 [key] => TES-2 [self] => https://centreon.atlassian.net/rest/api/latest/issue/41261 )
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->jira_call_response['key'], 'subject' => $ticket_arguments[$this->internal_arg_name[self::ARG_SUMMARY]], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['ticket_key' => $this->jira_call_response['key'], 'arguments' => $ticket_arguments]
)]
);
return $result;
}
/**
* REST API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
protected function listProjectJira()
{
if ($this->callRest('project') == 1) {
return -1;
}
return 0;
}
protected function listPriorityJira()
{
if ($this->callRest('priority') == 1) {
return -1;
}
return 0;
}
protected function listIssuetypeJira()
{
if ($this->callRest('issuetype') == 1) {
return -1;
}
return 0;
}
protected function listUserJira($filter)
{
$search = 'query=';
if (isset($filter)) {
$search .= urlencode($filter);
}
if ($this->callRest('user/search?' . $search) == 1) {
return -1;
}
return 0;
}
protected function createTicketJira($ticket_arguments)
{
$argument = ['fields' => ['project' => ['id' => $ticket_arguments[$this->internal_arg_name[self::ARG_PROJECT]]], 'summary' => $ticket_arguments[$this->internal_arg_name[self::ARG_SUMMARY]], 'description' => $ticket_arguments[$this->internal_arg_name[self::ARG_DESCRIPTION]]]];
if (
isset($ticket_arguments[$this->internal_arg_name[self::ARG_ASSIGNEE]])
&& $ticket_arguments[$this->internal_arg_name[self::ARG_ASSIGNEE]] != ''
) {
$argument['fields']['assignee'] = ['accountId' => $ticket_arguments[$this->internal_arg_name[self::ARG_ASSIGNEE]]];
}
if (
isset($ticket_arguments[$this->internal_arg_name[self::ARG_PRIORITY]])
&& $ticket_arguments[$this->internal_arg_name[self::ARG_PRIORITY]] != ''
) {
$argument['fields']['priority'] = ['id' => $ticket_arguments[$this->internal_arg_name[self::ARG_PRIORITY]]];
}
if (
isset($ticket_arguments[$this->internal_arg_name[self::ARG_ISSUETYPE]])
&& $ticket_arguments[$this->internal_arg_name[self::ARG_ISSUETYPE]] != ''
) {
$argument['fields']['issuetype'] = ['id' => $ticket_arguments[$this->internal_arg_name[self::ARG_ISSUETYPE]]];
}
if ($this->callRest('issue', $argument) == 1) {
return -1;
}
return 0;
}
protected function callRest($function, $argument = null)
{
$this->jira_call_response = null;
$proto = 'https';
$base_url = $proto . '://' . $this->rule_data['address'] . $this->rule_data['rest_api_resource']
. '/' . $function;
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
$ch = curl_init($base_url);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
$method = 'GET';
$headers = ['Content-Type: application/json', 'Accept: application/json'];
if (! is_null($argument)) {
$argument_json = json_encode($argument);
curl_setopt($ch, CURLOPT_POSTFIELDS, $argument_json);
$headers[] = 'Content-Length: ' . strlen($argument_json);
$method = 'POST';
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt(
$ch,
CURLOPT_USERPWD,
$this->getFormValue('username', false) . ':' . $this->getFormValue('user_token', false)
);
self::setProxy(
$ch,
['proxy_address' => $this->getFormValue('proxy_address', false), 'proxy_port' => $this->getFormValue('proxy_port', false), 'proxy_username' => $this->getFormValue('proxy_username', false), 'proxy_password' => $this->getFormValue('proxy_password', false)]
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$optionsToLog = [
'apiAddress' => $base_url,
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// log the curl options
$this->debug('Jira API request options', [
'options' => $optionsToLog,
]);
$result = curl_exec($ch);
if ($result == false) {
$this->setWsError(curl_error($ch));
curl_close($ch);
return 1;
}
// 401 it's an error (unauthorized maybe)
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (! preg_match_all('/^2/', $http_code)) {
curl_close($ch);
$this->setWsError($http_code . ' code error');
return 1;
}
$decoded_result = json_decode($result, true);
if (is_null($decoded_result) || $decoded_result == false) {
$this->setWsError($result);
return 1;
}
curl_close($ch);
$this->jira_call_response = $decoded_result;
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Simple/SimpleProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Simple/SimpleProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
class SimpleProvider extends AbstractProvider
{
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
protected function setDefaultValueExtra()
{
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['format_popup'] = '';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems]
);
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Itop/ItopProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Itop/ItopProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class ItopProvider extends AbstractProvider
{
use LoggerTrait;
public const ITOP_ORGANIZATION_TYPE = 10;
public const ITOP_CALLER_TYPE = 11;
public const ITOP_SERVICE_TYPE = 12;
public const ITOP_SERVICE_SUBCATEGORY_TYPE = 13;
public const ARG_CONTENT = 1;
public const ARG_TITLE = 2;
public const ARG_ORGANIZATION = 3;
public const ARG_CALLER = 4;
public const ARG_ORIGIN = 5;
public const ARG_SERVICE = 6;
public const ARG_SERVICE_SUBCATEGORY = 7;
public const ARG_IMPACT = 8;
public const ARG_URGENCY = 9;
protected $proxy_enabled = 1;
protected $close_advanced = 1;
protected $internal_arg_name = [
self::ARG_CONTENT => 'content',
self::ARG_TITLE => 'title',
self::ARG_ORGANIZATION => 'organization',
self::ARG_CALLER => 'caller',
self::ARG_ORIGIN => 'origin',
self::ARG_SERVICE => 'service',
self::ARG_SERVICE_SUBCATEGORY => 'service_subcategory',
self::ARG_IMPACT => 'impact',
self::ARG_URGENCY => 'urgency',
];
/*
* checks if all mandatory fields have been filled
*
* @return {array} telling us if there is a missing parameter
*/
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/*
* test if we can reach Itop webservice with the given Configuration
*
* @param {array} $info required information to reach the itop api
*
* @return {bool}
*
* throw \Exception if there are some missing parameters
* throw \Exception if the connection failed
*/
public static function test($info)
{
// this is called through our javascript code. Those parameters are already checked in JS code.
// but since this function is public, we check again because anyone could use this function
if (
! isset($info['address'])
|| ! isset($info['api_version'])
|| ! isset($info['username'])
|| ! isset($info['password'])
|| ! isset($info['protocol'])
) {
throw new Exception('missing arguments', 13);
}
// check if php curl is installed
if (! extension_loaded('curl')) {
throw new Exception("couldn't find php curl", 10);
}
$curl = curl_init();
$apiAddress = $info['protocol'] . '://' . $info['address'] . '/webservices/rest.php?version='
. $info['api_version'];
$data = ['operation' => 'list_operations'];
$query = ['auth_user' => $info['username'], 'auth_pwd' => $info['password'], 'json_data' => json_encode($data)];
// ssl peer verify
$peerVerify = (bool) ($info['peer_verify'] ?? true);
$caCertPath = $info['ca_cert_path'] ?? '';
// initiate our curl options
curl_setopt($curl, CURLOPT_URL, $apiAddress);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $peerVerify ? 2 : 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_TIMEOUT, $info['timeout']);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($query));
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($curl, CURLOPT_CAINFO, $caCertPath);
}
// execute curl and get status information
$curlResult = json_decode(curl_exec($curl), true);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode >= 400) {
// return false;
throw new Exception('curl result: ' . $curlResult . '|| HTTP return code: ' . $httpCode, 1);
}
if ($curlResult['code'] !== 0) {
throw new Exception($curlResult['message']);
}
return true;
}
/*
* get callers from itop
*
* $param {array} $data selected organization and ITOP_CALLER_TYPE group data
*
* @return {array} $listCallers list of callers
*
* throw \Exception if we can't get callers data
*/
public function getCallers($data)
{
$key = "SELECT Person WHERE status='active'";
if (preg_match('/(.*?)___(.*)/', $data['organization_value'], $matches)) {
$key .= " AND org_id='" . $matches[1] . "'";
} else {
throw new Exception('No organization found', 1);
}
$filter = $data['groups']['itop_caller']['filter'];
if (isset($filter) && $filter != '') {
$key .= " AND friendlyname LIKE '%" . $filter . "%'";
}
$data = ['operation' => 'core/get', 'class' => 'Person', 'key' => $key, 'output_fields' => 'friendlyname'];
try {
$listCallers = $this->getCache('itop_caller_' . $matches[1]);
if (is_null($listCallers)) {
// if no callers were found in cache, get them from itop and put them in cache for 8 hours
$listCallers = $this->curlQuery($data);
$this->setCache('itop_caller_' . $matches[1], $listCallers, 8 * 3600);
}
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return $listCallers;
}
/*
* get services from itop
*
* $param {array} $data selected organization and ITOP_SERVICE_TYPE group data
*
* @return {array} $listServices list of services
*
* throw \Exception if we can't get services data
*/
public function getServices($data)
{
$key = 'SELECT Service';
if (preg_match('/(.*?)___(.*)/', $data['organization_value'], $matches)) {
$key .= " WHERE org_id='" . $matches[1] . "'";
} else {
throw new Exception('No organization found', 1);
}
$filter = $data['groups']['itop_service']['filter'];
if (isset($filter) && $filter != '') {
$key .= " AND friendlyname LIKE '%" . $filter . "%'";
}
$data = ['operation' => 'core/get', 'class' => 'Service', 'key' => $key, 'output_fields' => 'friendlyname'];
try {
$listServices = $this->getCache('itop_service_' . $matches[1]);
if (is_null($listServices)) {
// if no callers were found in cache, get them from itop and put them in cache for 8 hours
$listServices = $this->curlQuery($data);
$this->setCache('itop_service_' . $matches[1], $listServices, 8 * 3600);
}
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return $listServices;
}
/*
* get service subcategories from itop
*
* $param {array} $data selected service and ITOP_SERVICE_SUBCATEGORY_TYPE group data
*
* @return {array} $listServiceSubcategories list of service subcategories
*
* throw \Exception if we can't get service subcategories data
*/
public function getServiceSubcategories($data)
{
$key = 'SELECT ServiceSubcategory';
if (preg_match('/(.*?)___(.*)/', $data['service_value'], $matches)) {
$key .= " WHERE service_id='" . $matches[1] . "'";
} else {
throw new Exception('No service found', 1);
}
$filter = $data['groups']['itop_service_subcategory']['filter'];
if (isset($filter) && $filter != '') {
$key .= " AND friendlyname LIKE '%" . $filter . "%'";
}
$data = ['operation' => 'core/get', 'class' => 'ServiceSubcategory', 'key' => $key, 'output_fields' => 'friendlyname'];
try {
$listServiceSubcategories = $this->getCache('itop_service_subcategory_' . $matches[1]);
if (is_null($listServiceSubcategories)) {
// if no callers were found in cache, get them from itop and put them in cache for 8 hours
$listServiceSubcategories = $this->curlQuery($data);
$this->setCache('itop_service_subcategory_' . $matches[1], $listServiceSubcategories, 8 * 3600);
}
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return $listServiceSubcategories;
}
/*
* check if the close option is enabled, if so, try to close every selected ticket
*
* @param {array} $tickets
*
* @return void
*/
public function closeTicket(&$tickets): void
{
if ($this->doCloseTicket()) {
foreach ($tickets as $k => $v) {
try {
$this->closeTicketItop($k);
$tickets[$k]['status'] = 2;
} catch (Exception $e) {
$tickets[$k]['status'] = -1;
$tickets[$k]['msg_error'] = $e->getMessage();
}
}
} else {
parent::closeTicket($tickets);
}
}
// Set default values for our rule form options
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '10.30.2.22/itop/web';
$this->default_data['api_version'] = '1.4';
$this->default_data['username'] = '';
$this->default_data['password'] = '';
$this->default_data['protocol'] = 'https';
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_CONTENT, 'Value' => '{$body}'], ['Arg' => self::ARG_TITLE, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_ORGANIZATION, 'Value' => '{$select.itop_organization.id}'], ['Arg' => self::ARG_CALLER, 'Value' => '{$select.itop_caller.id}'], ['Arg' => self::ARG_ORIGIN, 'Value' => '{$select.itop_origin.value}'], ['Arg' => self::ARG_SERVICE, 'Value' => '{$select.itop_service.id}'], ['Arg' => self::ARG_SERVICE_SUBCATEGORY, 'Value' => '{$select.itop_service_subcategory.id}'], ['Arg' => self::ARG_IMPACT, 'Value' => '{$select.itop_impact.value}'], ['Arg' => self::ARG_URGENCY, 'Value' => '{$select.itop_urgency.value}']];
}
/*
* Set default values for the widget popup when opening a ticket
*
* @return void
*/
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html = 0);
$this->default_data['url'] = '{$protocol}://{$address}/pages/UI.php?operation=details'
. '&class=UserRequest&id={$ticket_id}';
$this->default_data['format_popup'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
<tr>
<td class="FormRowField" style="padding-left:15px;">{$custom_message.label}</td>
<td class="FormRowValue" style="padding-left:15px;">
<textarea id="custom_message" name="custom_message" cols="50" rows="6"></textarea>
</td>
</tr>
{include file="file:$centreon_open_tickets_path/providers/Abstract/templates/groups.ihtml"}
{include file="file:$centreon_open_tickets_path/providers/Itop/templates/format_popup_requiredFields.ihtml"}
</table>
';
$this->default_data['clones']['groupList'] = [['Id' => 'itop_organization', 'Label' => _('Organization'), 'Type' => self::ITOP_ORGANIZATION_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_caller', 'Label' => _('Caller'), 'Type' => self::ITOP_CALLER_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_service', 'Label' => _('Service'), 'Type' => self::ITOP_SERVICE_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_service_subcategory', 'Label' => _('Service Subcategory'), 'Type' => self::ITOP_SERVICE_SUBCATEGORY_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_origin', 'Label' => _('Origin'), 'Type' => self::CUSTOM_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_urgency', 'Label' => _('Urgency'), 'Type' => self::CUSTOM_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'itop_impact', 'Label' => _('Impact'), 'Type' => self::CUSTOM_TYPE, 'Filter' => '', 'Mandatory' => '']];
$this->default_data['clones']['customList'] = [['Id' => 'itop_origin', 'Value' => 'mail', 'Label' => 'email', 'Default' => ''], ['Id' => 'itop_origin', 'Value' => 'monitoring', 'Label' => 'monitoring', 'Default' => ''], ['Id' => 'itop_origin', 'Value' => 'phone', 'Label' => 'phone', 'Default' => ''], ['Id' => 'itop_origin', 'Value' => 'portal', 'Label' => 'portal', 'Default' => ''], ['Id' => 'itop_origin', 'Value' => 'mail', 'Label' => 'email', 'Default' => ''], ['Id' => 'itop_impact', 'Value' => '1', 'Label' => 'A department', 'Default' => ''], ['Id' => 'itop_impact', 'Value' => '2', 'Label' => 'A service', 'Default' => ''], ['Id' => 'itop_impact', 'Value' => '3', 'Label' => 'A person', 'Default' => ''], ['Id' => 'itop_urgency', 'Value' => '1', 'Label' => 'critical', 'Default' => ''], ['Id' => 'itop_urgency', 'Value' => '2', 'Label' => 'high', 'Default' => ''], ['Id' => 'itop_urgency', 'Value' => '3', 'Label' => 'medium', 'Default' => ''], ['Id' => 'itop_urgency', 'Value' => '4', 'Label' => 'low', 'Default' => '']];
}
/*
* Verify if every mandatory form field is filled with data
*
* @throw \Exception when a form field is not set
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', 'Please set the "Address" value');
$this->checkFormValue('api_version', 'Please set the "API version" value');
$this->checkFormValue('username', 'Please set the "Username" value');
$this->checkFormValue('password', 'Please set the "Password" value');
$this->checkFormValue('protocol', 'Please set the "Protocol" value');
$this->checkFormInteger('timeout', '"Timeout" must be an integer');
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
// Initiate your html configuration and lets Smarty display it in the rule form
protected function getConfigContainer1Extra()
{
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($this->centreon_open_tickets_path, 'providers/Itop/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['Itop' => _('Itop Rest Api')]);
$tpl->assign('webServiceUrl', './api/internal.php');
// we create the html that is going to be displayed
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" />';
$api_version_html = '<input size="50" name="api_version" type="text" value ="'
. $this->getFormValue('api_version') . '" />';
$protocol_html = '<input size="2" name="protocol" type="text" value="'
. $this->getFormValue('protocol') . '" />';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
// this array is here to link a label with the html code that we've wrote above
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'api_version' => ['label' => _('API version') . $this->required_field, 'html' => $api_version_html], 'protocol' => ['label' => _('Protocol'), 'html' => $protocol_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')]];
// html code for a dropdown list where we will be able to select something from the following list
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" '
. 'name="mappingTicketValue[#index#]" size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" '
. 'name="mappingTicketArg[#index#]" type="select-one">'
. '<option value="' . self::ARG_CONTENT . '">' . _('Content') . '</options>'
. '<option value="' . self::ARG_TITLE . '">' . _('Title') . '</options>'
. '<option value="' . self::ARG_ORGANIZATION . '">' . _('Organization') . '</options>'
. '<option value="' . self::ARG_SERVICE . '">' . _('Service') . '</options>'
. '<option value="' . self::ARG_SERVICE_SUBCATEGORY . '">' . _('Service Subcategory') . '</options>'
. '<option value="' . self::ARG_ORIGIN . '">' . _('Origin') . '</options>'
. '<option value="' . self::ARG_IMPACT . '">' . _('Impact') . '</options>'
. '<option value="' . self::ARG_URGENCY . '">' . _('Urgency') . '</options>'
. '<option value="' . self::ARG_CALLER . '">' . _('Caller') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
protected function getConfigContainer2Extra()
{
}
// Saves the rule form in the database
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['api_version'] = $this->submitted_config['api_version'];
$this->save_config['simple']['protocol'] = $this->submitted_config['protocol'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
}
/*
* Adds new types to the list of types
*
* @return {string} $str html code that add an option to a select
*/
protected function getGroupListOptions()
{
return '<option value="' . self::ITOP_SERVICE_TYPE . '">Service</option>'
. '<option value="' . self::ITOP_CALLER_TYPE . '">Caller</option>'
. '<option value="' . self::ITOP_ORGANIZATION_TYPE . '">Organization</option>'
. '<option value="' . self::ITOP_SERVICE_SUBCATEGORY_TYPE . '">Service subcategory</option>';
}
/*
* configure variables with the data provided by the itop api
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from itop
*
* @return void
*/
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::ITOP_ORGANIZATION_TYPE) {
$this->assignItopOrganizations($entry, $groups_order, $groups);
} elseif (
$entry['Type'] == self::ITOP_CALLER_TYPE
|| $entry['Type'] == self::ITOP_SERVICE_TYPE
|| $entry['Type'] == self::ITOP_SERVICE_SUBCATEGORY_TYPE
) {
$this->assignItopAjax($entry, $groups_order, $groups);
}
}
/*
* handle gathered organizations
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from itop
*
* @return void
*
* throw \Exception if we can't get organizations from itop
*/
protected function assignItopOrganizations($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
try {
$listOrganizations = $this->getCache($entry['Id']);
if (is_null($listOrganizations)) {
// if no organizations were found in cache, get them from itop and put them in cache for 8 hours
$listOrganizations = $this->getOrganizations();
$this->setCache($entry['Id'], $listOrganizations, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listOrganizations['objects'] ?? [] as $organization) {
// foreach organization found, if we don't have any filter configured,
// we just put the id and the name of the organization inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$organization['key']] = $this->to_utf8($organization['fields']['name']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the organization inside the result array
if (preg_match('/' . $entry['Filter'] . '/', $organization['fields']['name'])) {
$result[$organization['key']] = $this->to_utf8($organization['fields']['name']);
}
}
$groups[$entry['Id']]['values'] = $result;
}
/*
* initiate information for dynamic (ajax) fields like callers, services or service subcategories
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from itop
*
* @return void
*/
protected function assignItopAjax($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0), 'filter' => $entry['Filter']];
$groups_order[] = $entry['Id'];
$groups[$entry['Id']]['values'] = '';
}
/*
* brings all parameters together in order to build the ticket arguments and save
* ticket data in the database
*
* @param {object} $db_storage centreon storage database informations
* @param {array} $contact centreon contact informations
* @param {array} $host_problems centreon host information
* @param {array} $service_problems centreon service information
* @param {array} $extraTicketArguments
*
* @return {array} $result will tell us if the submit ticket action resulted in a ticket being opened
*/
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems, $extraTicketArguments = [])
{
// initiate a result array
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
// assign submitted values from the widget to the template
$this->assignSubmittedValues($tpl);
$ticketArguments = $extraTicketArguments;
if (isset($this->rule_data['clones']['mappingTicket'])) {
// for each ticket argument in the rule form, we retrieve its value
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$resultString = $tpl->fetch('eval.ihtml');
if ($resultString == '') {
$resultstring = null;
}
$ticketArguments[$this->internal_arg_name[$value['Arg']]] = $resultString;
}
}
// we try to open the ticket
try {
$ticketId = $this->createTicket($ticketArguments);
} catch (Exception $e) {
$result['ticket_error_message'] = $e->getMessage();
return $result;
}
// we save ticket data in our database
$this->saveHistory($db_storage, $result, ['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $ticketId, 'subject' => $ticketArguments[self::ARG_TITLE], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode($ticketArguments)]);
return $result;
}
/*
* handle every query that we need to do
*
* @param {array} $info required information to reach the itop api
*
* @return {array} $curlResult the json decoded data gathered from itop
*
* throw \Exception 10 if php-curl is not installed
* throw \Exception 11 if itop api fails
*/
protected function curlQuery($data)
{
// check if php curl is installed
if (! extension_loaded('curl')) {
throw new Exception("couldn't find php curl", 10);
}
$query = ['auth_user' => $this->getFormValue('username'), 'auth_pwd' => $this->getFormValue('password'), 'json_data' => json_encode($data)];
$curl = curl_init();
$apiAddress = $this->getFormValue('protocol') . '://' . $this->getFormValue('address')
. '/webservices/rest.php?version=' . $this->getFormValue('api_version');
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
// initiate our curl options
curl_setopt($curl, CURLOPT_URL, $apiAddress);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($query));
curl_setopt($curl, CURLOPT_TIMEOUT, $this->getFormValue('timeout'));
$optionsToLog = [
'apiAddress' => $apiAddress,
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($curl, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// if proxy is set, we add it to curl
if (
$this->getFormValue('proxy_address') != ''
&& $this->getFormValue('proxy_port') != ''
) {
curl_setopt(
$curl,
CURLOPT_PROXY,
$this->getFormValue('proxy_address') . ':' . $this->getFormValue('proxy_port')
);
// if proxy authentication configuration is set, we add it to curl
if (
$this->getFormValue('proxy_username') != ''
&& $this->getFormValue('proxy_password') != ''
) {
curl_setopt(
$curl,
CURLOPT_PROXYUSERPWD,
$this->getFormValue('proxy_username') . ':' . $this->getFormValue('proxy_password')
);
}
}
// log the curl options
$this->debug('Itop API request options', [
'options' => $optionsToLog,
]);
// execute curl and get status information
$curlResult = json_decode(curl_exec($curl), true);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode >= 400) {
throw new Exception('ERROR: ' . $curlResult . ' || HTTP ERROR: ' . $httpCode, 11);
}
if ($curlResult['code'] !== 0) {
throw new Exception($curlResult['message'], $curlResult['code']);
}
return $curlResult;
}
/*
* get organizations from itop
*
* @return {array} $organizations list of organizations
*
* throw \Exception if we can't get organizations data
*/
protected function getOrganizations()
{
$key = "SELECT Organization WHERE status='active'";
$data = ['operation' => 'core/get', 'class' => 'Organization', 'key' => $key, 'output_fields' => 'name'];
try {
$organizations = $this->curlQuery($data);
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return $organizations;
}
/**
* @param array $ticketArguments
* @return mixed
*/
protected function createTicket($ticketArguments)
{
$data = ['operation' => 'core/create', 'class' => 'UserRequest', 'output_fields' => 'id', 'comment' => 'Opened from Centreon', 'fields' => ['description' => $ticketArguments['content'], 'title' => $ticketArguments['title']]];
if (isset($ticketArguments['organization'])
&& $ticketArguments['organization'] != ''
&& $ticketArguments['organization'] != -1) {
$data['fields']['org_id'] = $ticketArguments['organization'];
}
if (isset($ticketArguments['service'])
&& $ticketArguments['service'] != ''
&& $ticketArguments['service'] != -1) {
$data['fields']['service_id'] = $ticketArguments['service'];
}
if (isset($ticketArguments['service_subcategory'])
&& $ticketArguments['service_subcategory'] != ''
&& $ticketArguments['service_subcategory'] != -1) {
$data['fields']['servicesubcategory_id'] = $ticketArguments['service_subcategory'];
}
if (isset($ticketArguments['caller'])
&& $ticketArguments['caller'] != ''
&& $ticketArguments['caller'] != -1) {
$data['fields']['caller_id'] = $ticketArguments['caller'];
}
if (isset($ticketArguments['urgency'])
&& $ticketArguments['urgency'] != '') {
$data['fields']['urgency'] = $ticketArguments['urgency'];
}
if (isset($ticketArguments['origin'])
&& $ticketArguments['origin'] != '') {
$data['fields']['origin'] = $ticketArguments['origin'];
}
if (isset($ticketArguments['impact'])
&& $ticketArguments['impact'] != '') {
$data['fields']['impact'] = $ticketArguments['impact'];
}
$result = $this->curlQuery($data);
foreach ($result['objects'] as $ticket) {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Itop/ajax/call.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Itop/ajax/call.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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__ . '/../../../centreon-open-tickets.conf.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/providers/register.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
$centreon_open_tickets_path = $centreon_path . 'www/modules/centreon-open-tickets/';
require_once $centreon_open_tickets_path . 'providers/Abstract/AbstractProvider.class.php';
session_start();
$db = new CentreonDBManager();
$rule = new Centreon_OpenTickets_Rule($db);
if (isset($_SESSION['centreon'])) {
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
} else {
exit;
}
define('SMARTY_DIR', "{$centreon_path}/vendor/smarty/smarty/libs/");
require_once SMARTY_DIR . 'Smarty.class.php';
require_once $centreon_path . 'www/include/common/common-Func.php';
// check if there is data in POST
if (! isset($_POST['data'])) {
$result = ['code' => 1, 'msg' => "POST 'data' is required."];
} else {
$getInformation = isset($_POST['data']) ? json_decode($_POST['data'], true) : null;
$result = ['code' => 0, 'msg' => 'ok'];
// check if there is the provider id in the data
if (is_null($getInformation['provider_id'])) {
$result['code'] = 1;
$result['msg'] = 'Please set the provider_id';
return;
}
// check if there is a provider method that we have to call
if (is_null($getInformation['methods'])) {
$result['code'] = 1;
$result['msg'] = 'Please use a provider function';
return;
}
foreach ($register_providers as $name => $id) {
if ($id == $getInformation['provider_id']) {
$providerName = $name;
break;
}
}
// check if provider exists
if (is_null($providerName) || ! file_exists($centreon_open_tickets_path . 'providers/' . $providerName . '/'
. $providerName . 'Provider.class.php')) {
$result['code'] = 1;
$result['msg'] = 'Please set a provider, or check that ' . $centreon_open_tickets_path
. 'providers/' . $providerName . '/' . $providerName . 'Provider.class.php exists';
return;
}
// initate provider
require_once $centreon_open_tickets_path . 'providers/' . $providerName . '/' . $providerName
. 'Provider.class.php';
$className = $providerName . 'Provider';
$centreonProvider = new $className(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$getInformation['rule_id'],
null,
$getInformation['provider_id'],
$providerName
);
// check if methods exist
foreach ($getInformation['methods'] as $method) {
if (! method_exists($centreonProvider, $method)) {
$result['code'] = 1;
$result['msg'] = 'The provider method does not exist';
return;
}
}
try {
$data = [];
if (array_key_exists('provider_data', $getInformation)) {
$data = $getInformation['provider_data'];
}
foreach ($getInformation['methods'] as $method) {
$result[$method] = $centreonProvider->{$method}($data);
}
} catch (Exception $e) {
$result['code'] = 1;
$result['msg'] = $e->getMessage();
}
}
header('Content-type: text/plain');
echo json_encode($result);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/Otrs/OtrsProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/Otrs/OtrsProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class OtrsProvider extends AbstractProvider
{
use LoggerTrait;
public const OTRS_QUEUE_TYPE = 10;
public const OTRS_PRIORITY_TYPE = 11;
public const OTRS_STATE_TYPE = 12;
public const OTRS_TYPE_TYPE = 13;
public const OTRS_CUSTOMERUSER_TYPE = 14;
public const OTRS_OWNER_TYPE = 15;
public const OTRS_RESPONSIBLE_TYPE = 16;
public const ARG_QUEUE = 1;
public const ARG_PRIORITY = 2;
public const ARG_STATE = 3;
public const ARG_TYPE = 4;
public const ARG_CUSTOMERUSER = 5;
public const ARG_SUBJECT = 6;
public const ARG_BODY = 7;
public const ARG_FROM = 8;
public const ARG_CONTENTTYPE = 9;
public const ARG_OWNER = 17;
public const ARG_RESPONSIBLE = 18;
/** @var string */
protected $ws_error;
/** @var int */
protected $otrs_connected = 0;
/** @var null|string */
protected $otrs_session = null;
/** @var null|array */
protected $otrs_call_response;
protected $attach_files = 1;
protected $close_advanced = 1;
/** @var array<int, string> */
protected $internal_arg_name = [self::ARG_QUEUE => 'Queue', self::ARG_PRIORITY => 'Priority', self::ARG_STATE => 'State', self::ARG_TYPE => 'Type', self::ARG_CUSTOMERUSER => 'CustomerUser', self::ARG_SUBJECT => 'Subject', self::ARG_BODY => 'Body', self::ARG_FROM => 'From', self::ARG_CONTENTTYPE => 'ContentType', self::ARG_OWNER => 'Owner', self::ARG_RESPONSIBLE => 'Responsible'];
public function __destruct()
{
}
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
public function closeTicket(&$tickets): void
{
if ($this->doCloseTicket()) {
foreach ($tickets as $k => $v) {
if ($this->closeTicketOtrs($k) == 0) {
$tickets[$k]['status'] = 2;
} else {
$tickets[$k]['status'] = -1;
$tickets[$k]['msg_error'] = $this->ws_error;
}
}
} else {
parent::closeTicket($tickets);
}
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['path'] = '/otrs';
$this->default_data['rest_link'] = 'nph-genericinterface.pl/Webservice';
$this->default_data['webservice_name'] = 'centreon';
$this->default_data['https'] = 0;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_SUBJECT, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers/'
. 'Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_BODY, 'Value' => '{$body}'], ['Arg' => self::ARG_FROM, 'Value' => '{$user.email}'], ['Arg' => self::ARG_QUEUE, 'Value' => '{$select.otrs_queue.value}'], ['Arg' => self::ARG_PRIORITY, 'Value' => '{$select.otrs_priority.value}'], ['Arg' => self::ARG_STATE, 'Value' => '{$select.otrs_state.value}'], ['Arg' => self::ARG_TYPE, 'Value' => '{$select.otrs_type.value}'], ['Arg' => self::ARG_CUSTOMERUSER, 'Value' => '{$select.otrs_customeruser.value}'], ['Arg' => self::ARG_CONTENTTYPE, 'Value' => 'text/html; charset=utf8']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain(1);
$this->default_data['url'] = 'http://{$address}/index.pl?Action=AgentTicketZoom;TicketNumber={$ticket_id}';
$this->default_data['clones']['groupList'] = [['Id' => 'otrs_queue', 'Label' => _('Otrs queue'), 'Type' => self::OTRS_QUEUE_TYPE, 'Filter' => '', 'Mandatory' => '1'], ['Id' => 'otrs_priority', 'Label' => _('Otrs priority'), 'Type' => self::OTRS_PRIORITY_TYPE, 'Filter' => '', 'Mandatory' => '1'], ['Id' => 'otrs_state', 'Label' => _('Otrs state'), 'Type' => self::OTRS_STATE_TYPE, 'Filter' => '', 'Mandatory' => '1'], ['Id' => 'otrs_type', 'Label' => _('Otrs type'), 'Type' => self::OTRS_TYPE_TYPE, 'Filter' => '', 'Mandatory' => ''], ['Id' => 'otrs_customeruser', 'Label' => _('Otrs customer user'), 'Type' => self::OTRS_CUSTOMERUSER_TYPE, 'Filter' => '', 'Mandatory' => '1']];
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('rest_link', "Please set 'Rest Link' value");
$this->checkFormValue('webservice_name', "Please set 'Webservice Name' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/Otrs/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['otrs' => _('OTRS')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$path_html = '<input size="50" name="path" type="text" value="'
. $this->getFormValue('path') . '" />';
$rest_link_html = '<input size="50" name="rest_link" type="text" value="'
. $this->getFormValue('rest_link') . '" />';
$webservice_name_html = '<input size="50" name="webservice_name" type="text" value="'
. $this->getFormValue('webservice_name') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$https_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="https" name="https" value="yes" '
. ($this->getFormValue('https') === 'yes' ? 'checked' : '') . '/>'
. '<label class="empty-label" for="https"></label></div>';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = ['address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html], 'path' => ['label' => _('Path'), 'html' => $path_html], 'rest_link' => ['label' => _('Rest link') . $this->required_field, 'html' => $rest_link_html], 'webservice_name' => ['label' => _('Webservice name') . $this->required_field, 'html' => $webservice_name_html], 'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html], 'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html], 'https' => ['label' => _('Use https'), 'html' => $https_html], 'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html], 'mappingticket' => ['label' => _('Mapping ticket arguments')], 'mappingticketdynamicfield' => ['label' => _('Mapping ticket dynamic field')]];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_QUEUE . '">' . _('Queue') . '</options>'
. '<option value="' . self::ARG_PRIORITY . '">' . _('Priority') . '</options>'
. '<option value="' . self::ARG_STATE . '">' . _('State') . '</options>'
. '<option value="' . self::ARG_TYPE . '">' . _('Type') . '</options>'
. '<option value="' . self::ARG_CUSTOMERUSER . '">' . _('Customer user') . '</options>'
. '<option value="' . self::ARG_OWNER . '">' . _('Owner') . '</options>'
. '<option value="' . self::ARG_RESPONSIBLE . '">' . _('Responsible') . '</options>'
. '<option value="' . self::ARG_FROM . '">' . _('From') . '</options>'
. '<option value="' . self::ARG_SUBJECT . '">' . _('Subject') . '</options>'
. '<option value="' . self::ARG_BODY . '">' . _('Body') . '</options>'
. '<option value="' . self::ARG_CONTENTTYPE . '">' . _('Content Type') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
// mapping Ticket DynamicField
$mappingTicketDynamicFieldName_html = '<input id="mappingTicketDynamicFieldName_#index#" '
. 'name="mappingTicketDynamicFieldName[#index#]" size="20" type="text" />';
$mappingTicketDynamicFieldValue_html = '<input id="mappingTicketDynamicFieldValue_#index#" '
. 'name="mappingTicketDynamicFieldValue[#index#]" size="20" type="text" />';
$array_form['mappingTicketDynamicField'] = [['label' => _('Name'), 'html' => $mappingTicketDynamicFieldName_html], ['label' => _('Value'), 'html' => $mappingTicketDynamicFieldValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
$this->config['clones']['mappingTicketDynamicField'] = $this->getCloneValue('mappingTicketDynamicField');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['path'] = $this->submitted_config['path'];
$this->save_config['simple']['rest_link'] = $this->submitted_config['rest_link'];
$this->save_config['simple']['webservice_name'] = $this->submitted_config['webservice_name'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['https'] = (isset($this->submitted_config['https'])
&& $this->submitted_config['https'] == 'yes')
? $this->submitted_config['https'] : '';
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
$this->save_config['clones']['mappingTicketDynamicField'] = $this->getCloneSubmitted(
'mappingTicketDynamicField',
['Name', 'Value']
);
}
/**
* @return string
*/
protected function getGroupListOptions()
{
return '<option value="' . self::OTRS_QUEUE_TYPE . '">Otrs queue</options>'
. '<option value="' . self::OTRS_PRIORITY_TYPE . '">Otrs priority</options>'
. '<option value="' . self::OTRS_STATE_TYPE . '">Otrs state</options>'
. '<option value="' . self::OTRS_CUSTOMERUSER_TYPE . '">Otrs customer user</options>'
. '<option value="' . self::OTRS_TYPE_TYPE . '">Otrs type</options>'
. '<option value="' . self::OTRS_OWNER_TYPE . '">Otrs owner</options>'
. '<option value="' . self::OTRS_RESPONSIBLE_TYPE . '">Otrs responsible</options>';
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOtrsQueue($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listQueueOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('otrs_queue', $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOtrsPriority($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listPriorityOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('otrs_priority', $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOtrsState($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listStateOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('otrs_state', $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOtrsType($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listTypeOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('otrs_type', $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return int|void
*/
protected function assignOtrsCustomerUser($entry, &$groups_order, &$groups)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listCustomerUserOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession('otrs_customeruser', $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @param mixed $label_session
* @return int|void
*/
protected function assignOtrsUser($entry, &$groups_order, &$groups, $label_session)
{
// no filter $entry['Filter']. preg_match used
$code = $this->listUserOtrs();
$groups[$entry['Id']] = ['label' => _($entry['Label']) . (
isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''
), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
$groups_order[] = $entry['Id'];
if ($code == -1) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $this->ws_error;
return 0;
}
$result = [];
foreach ($this->otrs_call_response['response'] as $row) {
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$row['id']] = $this->to_utf8($row['name']);
continue;
}
if (preg_match('/' . $entry['Filter'] . '/', $row['name'])) {
$result[$row['id']] = $this->to_utf8($row['name']);
}
}
$this->saveSession($label_session, $this->otrs_call_response['response']);
$groups[$entry['Id']]['values'] = $result;
}
/**
* @param array $entry
* @param array $groups_order
* @param array $groups
* @return void
*/
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::OTRS_QUEUE_TYPE) {
$this->assignOtrsQueue($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::OTRS_PRIORITY_TYPE) {
$this->assignOtrsPriority($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::OTRS_STATE_TYPE) {
$this->assignOtrsState($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::OTRS_TYPE_TYPE) {
$this->assignOtrsType($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::OTRS_CUSTOMERUSER_TYPE) {
$this->assignOtrsCustomerUser($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::OTRS_OWNER_TYPE) {
$this->assignOtrsUser($entry, $groups_order, $groups, 'otrs_owner');
} elseif ($entry['Type'] == self::OTRS_RESPONSIBLE_TYPE) {
$this->assignOtrsUser($entry, $groups_order, $groups, 'otrs_responsible');
}
}
/**
* @param string $select_input_id
* @param string $selected_id
* @return array
*/
protected function assignSubmittedValuesSelectMore($select_input_id, $selected_id)
{
$session_name = null;
foreach ($this->rule_data['clones']['groupList'] as $value) {
if ($value['Id'] == $select_input_id) {
if ($value['Type'] == self::OTRS_QUEUE_TYPE) {
$session_name = 'otrs_queue';
} elseif ($value['Type'] == self::OTRS_PRIORITY_TYPE) {
$session_name = 'otrs_priority';
} elseif ($value['Type'] == self::OTRS_STATE_TYPE) {
$session_name = 'otrs_state';
} elseif ($value['Type'] == self::OTRS_TYPE_TYPE) {
$session_name = 'otrs_type';
} elseif ($value['Type'] == self::OTRS_CUSTOMERUSER_TYPE) {
$session_name = 'otrs_customeruser';
} elseif ($value['Type'] == self::OTRS_OWNER_TYPE) {
$session_name = 'otrs_owner';
} elseif ($value['Type'] == self::OTRS_RESPONSIBLE_TYPE) {
$session_name = 'otrs_responsible';
}
}
}
if (is_null($session_name) && $selected_id == -1) {
return [];
}
if ($selected_id == -1) {
return ['id' => null, 'value' => null];
}
$result = $this->getSession($session_name);
if (is_null($result)) {
return [];
}
foreach ($result as $value) {
if ($value['id'] == $selected_id) {
return $value;
}
}
return [];
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
$ticket_dynamic_fields = [];
if (isset($this->rule_data['clones']['mappingTicketDynamicField'])) {
foreach ($this->rule_data['clones']['mappingTicketDynamicField'] as $value) {
if ($value['Name'] == '' || $value['Value'] == '') {
continue;
}
$array_tmp = [];
$tpl->assign('string', $value['Name']);
$array_tmp = ['Name' => $tpl->fetch('eval.ihtml')];
$tpl->assign('string', $value['Value']);
$array_tmp['Value'] = $tpl->fetch('eval.ihtml');
$ticket_dynamic_fields[] = $array_tmp;
}
}
$code = $this->createTicketOtrs($ticket_arguments, $ticket_dynamic_fields);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->otrs_call_response['TicketNumber'], 'subject' => $ticket_arguments['Subject'], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments, 'dynamic_fields' => $ticket_dynamic_fields]
)]
);
return $result;
}
/**
* REST API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
/**
* @return int
*/
protected function listQueueOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('QueueGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function listPriorityOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('PriorityGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function listStateOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('StateGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function listTypeOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('TypeGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function listCustomerUserOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('CustomerUserGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function listUserOtrs()
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session];
if ($this->callRest('UserGet', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @param string $ticket_number
* @return int
*/
protected function closeTicketOtrs($ticket_number)
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session, 'TicketNumber' => $ticket_number, 'Ticket' => ['State' => 'closed successful']];
if ($this->callRest('TicketUpdate', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @param array $ticket_arguments
* @param array $ticket_dynamic_fields
* @return int
*/
protected function createTicketOtrs($ticket_arguments, $ticket_dynamic_fields)
{
if ($this->otrs_connected == 0) {
if ($this->loginOtrs() == -1) {
return -1;
}
}
$argument = ['SessionID' => $this->otrs_session, 'Ticket' => [
'Title' => $ticket_arguments['Subject'],
// 'QueueID' => xxx,
'Queue' => $ticket_arguments['Queue'],
// 'StateID' => xxx,
'State' => $ticket_arguments['State'],
// 'PriorityID' => xxx,
'Priority' => $ticket_arguments['Priority'],
// 'TypeID' => 123,
'Type' => $ticket_arguments['Type'],
// 'OwnerID' => 123,
'Owner' => $ticket_arguments['Owner'],
// 'ResponsibleID' => 123,
'Responsible' => $ticket_arguments['Responsible'],
'CustomerUser' => $ticket_arguments['CustomerUser'],
], 'Article' => [
'From' => $ticket_arguments['From'],
// Must be an email
'Subject' => $ticket_arguments['Subject'],
'Body' => $ticket_arguments['Body'],
'ContentType' => $ticket_arguments['ContentType'],
]];
$files = [];
$attach_files = $this->getUploadFiles();
foreach ($attach_files as $file) {
$base64_content = base64_encode(file_get_contents($file['filepath']));
$files[] = ['Content' => $base64_content, 'Filename' => $file['filename'], 'ContentType' => mime_content_type($file['filepath'])];
}
if ($files !== []) {
$argument['Attachment'] = $files;
}
if (count($ticket_dynamic_fields) > 0) {
$argument['DynamicField'] = $ticket_dynamic_fields;
}
if ($this->callRest('TicketCreate', $argument) == 1) {
return -1;
}
return 0;
}
/**
* @return int
*/
protected function loginOtrs()
{
if ($this->otrs_connected == 1) {
return 0;
}
if (! extension_loaded('curl')) {
$this->setWsError('cannot load curl extension');
return -1;
}
$argument = ['UserLogin' => $this->rule_data['username'], 'Password' => $this->rule_data['password']];
if ($this->callRest('SessionCreate', $argument) == 1) {
return -1;
}
$this->otrs_session = $this->otrs_call_response['SessionID'];
$this->otrs_connected = 1;
return 0;
}
/**
* @param string $function
* @param mixed $argument
* @return int
*/
protected function callRest($function, $argument)
{
$this->otrs_call_response = null;
$proto = 'http';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyVistaRest/EasyVistaRestProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyVistaRest/EasyVistaRestProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class EasyVistaRestProvider extends AbstractProvider
{
use LoggerTrait;
public const EZV_ASSET_TYPE = 16;
public const ARG_TITLE = 1;
public const ARG_URGENCY_ID = 2;
public const ARG_REQUESTOR_NAME = 3;
public const ARG_RECIPIENT_NAME = 4;
public const ARG_PHONE = 5;
public const ARG_ORIGIN = 6;
public const ARG_IMPACT_ID = 7;
public const ARG_DESCRIPTION = 8;
public const ARG_DEPARTMENT_CODE = 9;
public const ARG_CI_NAME = 10;
public const ARG_ASSET_NAME = 11;
public const ARG_LOCATION_CODE = 12;
public const ARG_CATALOG_GUID = 13;
public const ARG_CATALOG_CODE = 14;
public const ARG_CUSTOM_EZV = 15;
protected $close_advanced = 1;
protected $proxy_enabled = 1;
protected $internal_arg_name = [
self::ARG_TITLE => 'title',
self::ARG_URGENCY_ID => 'urgency',
self::ARG_REQUESTOR_NAME => 'requestor',
self::ARG_RECIPIENT_NAME => 'recipient',
self::ARG_PHONE => 'phone',
self::ARG_ORIGIN => 'origin',
self::ARG_IMPACT_ID => 'impact',
self::ARG_DESCRIPTION => 'description',
self::ARG_DEPARTMENT_CODE => 'department',
self::ARG_CI_NAME => 'CI',
self::ARG_ASSET_NAME => 'asset',
self::ARG_LOCATION_CODE => 'requester',
self::ARG_CATALOG_GUID => 'catalog_guid',
self::ARG_CATALOG_CODE => 'catalog_code',
];
/*
* checks if all mandatory fields have been filled
*
* @return {array} telling us if there is a missing parameter
*/
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
public static function test($info): void
{
// not implemented because there's no known url to test the api connection
}
/*
* check if the close option is enabled, if so, try to close every selected ticket
*
* @param {array} $tickets
*
* @return void
*/
public function closeTicket(&$tickets): void
{
if ($this->doCloseTicket()) {
foreach ($tickets as $k => $v) {
try {
$this->closeTicketEzv($k);
$tickets[$k]['status'] = 2;
} catch (Exception $e) {
$tickets[$k]['status'] = -1;
$tickets[$k]['msg_error'] = $e->getMessage();
}
}
} else {
parent::closeTicket($tickets);
}
}
// webservice methods
public function getHostgroups($centreon_path, $data)
{
$hostCount = count($data['host_list']);
$listIds = '';
$queryValues = [];
foreach ($data['host_list'] as $hostId) {
$listIds .= ':hId_' . $hostId . ', ';
$queryValues[':hId_' . $hostId] = (int) $hostId;
}
$listIds = rtrim($listIds, ', ');
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
$db_storage = new CentreonDBManager('centstorage');
$query = 'SELECT name FROM hostgroups WHERE hostgroup_id IN'
. ' (SELECT hostgroup_hg_id FROM centreon.hostgroup_relation WHERE host_host_id IN (' . $listIds . ')'
. ' GROUP BY hostgroup_hg_id HAVING count(hostgroup_hg_id) = :host_count)';
$dbQuery = $db_storage->prepare($query);
foreach ($queryValues as $bindName => $bindValue) {
$dbQuery->bindValue($bindName, $bindValue, PDO::PARAM_INT);
}
$dbQuery->bindValue(':host_count', $hostCount, PDO::PARAM_INT);
$dbQuery->execute();
$result = [];
while ($row = $dbQuery->fetch()) {
array_push($result, $row['name']);
}
return $result;
}
// Set default values for our rule form options
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['api_path'] = '/api/v1';
$this->default_data['protocol'] = 'https';
$this->default_data['account'] = '';
$this->default_data['token'] = '';
$this->default_data['use_token'] = 1;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [
[
'Arg' => self::ARG_TITLE,
'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}',
],
[
'Arg' => self::ARG_DESCRIPTION,
'Value' => '{$body}',
],
[
'Arg' => self::ARG_URGENCY_ID,
'Value' => '{$select.ezv_urgency.id}',
],
[
'Arg' => self::ARG_REQUESTOR_NAME,
'Value' => '{$select.ezv_requestor_name.id}',
],
[
'Arg' => self::ARG_RECIPIENT_NAME,
'Value' => '{$select.ezv_recipient_name.id}',
],
[
'Arg' => self::ARG_PHONE,
'Value' => '{$select.ezv_phone.id}',
],
[
'Arg' => self::ARG_ORIGIN,
'Value' => '{$select.ezv_origin.value}',
],
[
'Arg' => self::ARG_IMPACT_ID,
'Value' => '{$select.ezv_impact_id.id}',
],
[
'Arg' => self::ARG_DEPARTMENT_CODE,
'Value' => '{$select.ezv_department_code.value}',
],
[
'Arg' => self::ARG_CI_NAME,
'Value' => '{$select.ezv_ci_name.value}',
],
[
'Arg' => self::ARG_ASSET_NAME,
'Value' => '{$select.ezv_asset_name.value}',
],
[
'Arg' => self::ARG_LOCATION_CODE,
'Value' => '{$select.ezv_location_code.value}',
],
[
'Arg' => self::ARG_CATALOG_GUID,
'Value' => '{$select.ezv_catalog_guid.id}',
],
[
'Arg' => self::ARG_CATALOG_CODE,
'Value' => '{$select.ezv_catalog_code.id}',
],
];
}
/*
* Set default values for the widget popup when opening a ticket
*
* @return void
*/
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = 'tobedetermined';
$this->default_data['format_popup'] = '
<table class="table">
<tr>
<td class="FormHeader" colspan="2"><h3 style="color: #00bfb3;">{$title}</h3></td>
</tr>
<tr>
<td class="FormRowField" style="padding-left:15px;">{$custom_message.label}</td>
<td class="FormRowValue" style="padding-left:15px;">
<textarea id="custom_message" name="custom_message" cols="50" rows="6"></textarea>
</td>
</tr>
<tr>
<td class="FormRowField" style="padding-left:15px;">Use hostgroup name as CI</td>
<td class="FormRowField" style="padding-left:15px;"><input id="ci_type_selector" type="checkbox"></input></td>
</tr>
</tr>
{include file="file:$centreon_open_tickets_path/providers/Abstract/templates/groups.ihtml"}
{include file="file:$centreon_open_tickets_path/providers/EasyVistaRest/templates/handle_ci.ihtml"}
</table>';
// $this->default_data['clones']['groupList'] = [
// [
// 'Id' => 'ezv_asset_name',
// 'Label' => _('Assets'),
// 'Type' => self::EZV_ASSET_TYPE,
// 'Filter' => '',
// 'Mandatory' => ''
// ]
// ];
// $this->default_data['clones']['customList'] = [
// [
// 'Id' => 'ezv_origin',
// 'Value' => '1',
// 'Label' => 'Very Low',
// 'Default' => ''
// ]
// ];
}
/*
* Verify if every mandatory form field is filled with data
*
* @throw \Exception when a form field is not set
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', 'Please set "Address" value');
$this->checkFormValue('api_path', 'Please set "API path" value');
$this->checkFormValue('protocol', 'Please set "Protocol" value');
$this->checkFormValue('account', 'Please set "Account" value');
$this->checkFormValue('token', 'Please set "Token or Password" value');
$this->checkFormInteger('timeout', '"Timeout" must be an integer');
$this->checkFormInteger('use_token', '"Use token" must be an integer');
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
// Initiate your html configuration and let Smarty display it in the rule form
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/EasyVistaRest/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['EasyVistaRest' => _('Easyvista Rest Api')]);
$tpl->assign('webServiceUrl', './api/internal.php');
// we create the html that is going to be displayed
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$api_path_html = '<input size="50" name="api_path" type="text" value="'
. $this->getFormValue('api_path') . '" />';
$protocol_html = '<input size="50" name="protocol" type="text" value="'
. $this->getFormValue('protocol') . '" />';
$account_html = '<input size="50" name="account" type="text" value="'
. $this->getFormValue('account') . '" autocomplete="off" />';
$token_html = '<input size="50" name="token" type="password" value="'
. $this->getFormValue('token') . '" autocomplete="off" />';
$timeout_html = '<input size="50" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" :>';
$use_token_html = '<input size="50" name="use_token" type="text" value="'
. $this->getFormValue('use_token') . '" :>';
// this array is here to link a label with the html code that we've wrote above
$array_form = [
'address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html],
'api_path' => ['label' => _('API path') . $this->required_field, 'html' => $api_path_html],
'protocol' => ['label' => _('Protocol') . $this->required_field, 'html' => $protocol_html],
'account' => ['label' => _('Account') . $this->required_field, 'html' => $account_html],
'token' => ['label' => _('Bearer token or account password') . $this->required_field, 'html' => $token_html],
'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html],
'use_token' => ['label' => _('Use token'), 'html' => $use_token_html],
// we add a key to our array
'mappingTicketLabel' => ['label' => _('Mapping ticket arguments')],
];
// html
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" '
. 'name="mappingTicketValue[#index#]" size="20" type="text"';
// html code for a dropdown list where we will be able to select something from the following list
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" '
. 'name="mappingTicketArg[#index#]" type="select-one">'
. '<option value="' . self::ARG_TITLE . '">' . _('Title') . '</option>'
. '<option value="' . self::ARG_URGENCY_ID . '">' . _('Urgency') . '</option>'
. '<option value="' . self::ARG_REQUESTOR_NAME . '">' . _('Requester') . '</option>'
. '<option value="' . self::ARG_RECIPIENT_NAME . '">' . _('Recipient') . '</option>'
. '<option value="' . self::ARG_PHONE . '">' . _('Phone') . '</option>'
. '<option value="' . self::ARG_ORIGIN . '">' . _('Origin') . '</option>'
. '<option value="' . self::ARG_IMPACT_ID . '">' . _('Impact') . '</option>'
. '<option value="' . self::ARG_DESCRIPTION . '">' . _('Description') . '</option>'
. '<option value="' . self::ARG_DEPARTMENT_CODE . '">' . _('Department') . '</option>'
. '<option value="' . self::ARG_CI_NAME . '">' . _('CI') . '</option>'
. '<option value="' . self::ARG_ASSET_NAME . '">' . _('Asset') . '</option>'
. '<option value="' . self::ARG_LOCATION_CODE . '">' . _('Location') . '</option>'
. '<option value="' . self::ARG_CATALOG_GUID . '">' . _('Catalog GUID') . '</option>'
. '<option value="' . self::ARG_CATALOG_CODE . '">' . _('Catalog code') . '</option>'
. '<option value="' . self::ARG_CUSTOM_EZV . '">' . _('Custom Field') . '</option>'
. '</select>';
// we asociate the label with the html code but for the arguments that we've been working on lately
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
protected function getConfigContainer2Extra()
{
}
// Saves the rule form in the database
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['api_path'] = $this->submitted_config['api_path'];
$this->save_config['simple']['protocol'] = $this->submitted_config['protocol'];
$this->save_config['simple']['account'] = $this->submitted_config['account'];
$this->save_config['simple']['token'] = $this->submitted_config['token'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['simple']['use_token'] = $this->submitted_config['use_token'];
// saves the ticket arguments
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted('mappingTicket', ['Arg', 'Value']);
}
/*
* Adds new types to the list of types
*
* @return {string} $str html code that add an option to a select
*/
protected function getGroupListOptions()
{
return '<option value="' . self::EZV_ASSET_TYPE . '">Asset</option>';
}
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::EZV_ASSET_TYPE) {
$this->assignEzvAssets($entry, $groups_order, $groups);
}
}
protected function assignEzvAssets($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get entities
try {
$listAssets = $this->getCache($entry['Id']);
if (is_null($listAssets)) {
$listAssets = $this->getAssets($entry['Filter']);
$this->setCache($entry['Id'], $listAssets, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listAssets['records'] ?? [] as $asset) {
// HREF structure is the following: https://{your_server}/api/v1/{your_account}/assets/9478 we only keep id
preg_match('/.*\/([0-9]+)$/', $asset['HREF'], $match);
$result[$match[1]] = $this->to_utf8($asset['ASSET_TAG']);
}
$groups[$entry['Id']]['values'] = $result;
}
protected function getAssets($filter)
{
// add the api endpoint and method to our info array
$info['query_endpoint'] = '/assets?fields=asset_tag,HREF';
if (! empty($filter)) {
$info['query_endpoint'] .= '&' . $filter;
}
$info['method'] = 'GET';
// try to get assets from ezv
try {
// the variable is going to be used outside of this method.
$result = $this->curlQuery($info);
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return $result;
}
/*
* brings all parameters together in order to build the ticket arguments and save
* ticket data in the database
*
* @param {object} $db_storage centreon storage database informations
* @param {array} $contact centreon contact informations
* @param {array} $host_problems centreon host information
* @param {array} $service_problems centreon service information
* @param {array} $extraTicketArguments
*
* @return {array} $result will tell us if the submit ticket action resulted in a ticket being opened
*/
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems, $extraTicketArguments = [])
{
// initiate a result array
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($this->centreon_open_tickets_path, 'providers/Abstract/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
// assign submitted values from the widget to the template
$this->assignSubmittedValues($tpl);
$ticketArguments = $extraTicketArguments;
if (isset($this->rule_data['clones']['mappingTicket'])) {
// for each ticket argument in the rule form, we retrieve its value
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$resultString = $tpl->fetch('eval.ihtml');
if ($resultString == '') {
$resultstring = null;
}
// specific condition to handle ezv custom field "dynamically"
if ($this->internal_arg_name[$value['Arg']] == $this->internal_arg_name[self::ARG_CUSTOM_EZV]) {
$ticketArguments[$value['Value']] = $resultString;
} else {
$ticketArguments[$this->internal_arg_name[$value['Arg']]] = $resultString;
}
}
}
// we try to open the ticket
try {
$ticketId = $this->createTicket($ticketArguments);
} catch (Exception $e) {
$result['ticket_error_message'] = $e->getMessage();
return $result;
}
// we save ticket data in our database
$this->saveHistory($db_storage, $result, ['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $ticketId, 'subject' => $ticketArguments[$this->internal_arg_name[self::ARG_TITLE]], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode($ticketArguments)]);
return $result;
}
protected function curlQuery($info)
{
// check if php curl is installed
if (! extension_loaded('curl')) {
throw new Exception("couldn't find php curl", 10);
}
$curl = curl_init();
$apiAddress = $this->getFormValue('protocol') . '://' . $this->getFormValue('address')
. $this->getFormValue('api_path') . $info['query_endpoint'];
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
$info['headers'] = [
'content-type: application/json',
];
if ($this->getFormValue(('use_token') == 1)) {
array_push($info['headers'], 'Authorization: Bearer ' . $this->getFormValue('token'));
}
// initiate our curl options
curl_setopt($curl, CURLOPT_URL, $apiAddress);
curl_setopt($curl, CURLOPT_HTTPHEADER, $info['headers']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt($curl, CURLOPT_POST, $info['method']);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->getFormValue('timeout'));
$optionsToLog = [
'apiAddress' => $apiAddress,
'method' => $info['method'],
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($curl, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
if ($this->getFormValue('use_token') != 1) {
curl_setopt($curl, CURLOPT_USERPWD, $this->getFormValue('account') . ':' . $this->getFormValue('token'));
}
// add postData if needed
if (! empty($info['data'])) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($info['data']));
}
// change curl method with a custom one (PUT, DELETE) if needed
if (isset($info['custom_request'])) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $info['custom_request']);
$optionsToLog['custom_request'] = $info['custom_request'];
}
// if proxy is set, we add it to curl
if (
$this->getFormValue('proxy_address') != ''
&& $this->getFormValue('proxy_port') != ''
) {
curl_setopt(
$curl,
CURLOPT_PROXY,
$this->getFormValue('proxy_address') . ':' . $this->getFormValue('proxy_port')
);
// if proxy authentication configuration is set, we add it to curl
if (
$this->getFormValue('proxy_username') != ''
&& $this->getFormValue('proxy_password') != ''
) {
curl_setopt(
$curl,
CURLOPT_PROXYUSERPWD,
$this->getFormValue('proxy_username') . ':' . $this->getFormValue('proxy_password')
);
}
}
// log the curl options
$this->debug('Easyvista Rest API request options', [
'options' => $optionsToLog,
]);
// execute curl and get status information
$curlResult = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// 200 for get operations and 201 for post
if ($httpCode != 200 && $httpCode != 201) {
throw new Exception('An error happened with endpoint: ' . $apiAddress
. '. Easyvista response is: ' . $curlResult);
}
return json_decode($curlResult, true);
}
protected function createTicket($ticketArguments)
{
// $file = fopen("/var/log/php-fpm/ezv", "a") or die ("Unable to open file!");
// add the api endpoint and method to our info array
$info['query_endpoint'] = '/requests';
$info['method'] = 'POST';
$info['data'] = [
'requests' => [
[
'catalog_guid' => $ticketArguments[$this->internal_arg_name[self::ARG_CATALOG_GUID]],
'catalog_code' => $ticketArguments[$this->internal_arg_name[self::ARG_CATALOG_CODE]],
'title' => $ticketArguments[$this->internal_arg_name[self::ARG_TITLE]],
],
],
];
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_ASSET_NAME]])) {
$info['data']['requests'][0]['asset_name'] = $ticketArguments[$this->internal_arg_name[self::ARG_ASSET_NAME]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_URGENCY_ID]])) {
$info['data']['requests'][0]['urgency_id'] = $ticketArguments[$this->internal_arg_name[self::ARG_URGENCY_ID]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_REQUESTOR_NAME]])) {
$info['data']['requests'][0]['requester_name'] = $ticketArguments[$this->internal_arg_name[self::ARG_REQUESTOR_NAME]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_RECIPIENT_NAME]])) {
$info['data']['requests'][0]['recipient_name'] = $ticketArguments[$this->internal_arg_name[self::ARG_RECIPIENT_NAME]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_PHONE]])) {
$info['data']['requests'][0]['phone'] = $ticketArguments[$this->internal_arg_name[self::ARG_PHONE]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_ORIGIN]])) {
$info['data']['requests'][0]['origin'] = $ticketArguments[$this->internal_arg_name[self::ARG_ORIGIN]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_IMPACT_ID]])) {
$info['data']['requests'][0]['impact_id'] = $ticketArguments[$this->internal_arg_name[self::ARG_IMPACT_ID]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_DESCRIPTION]])) {
$info['data']['requests'][0]['description'] = $ticketArguments[$this->internal_arg_name[self::ARG_DESCRIPTION]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_DEPARTMENT_CODE]])) {
$info['data']['requests'][0]['department_code'] = $ticketArguments[$this->internal_arg_name[self::ARG_DEPARTMENT_CODE]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_CI_NAME]])) {
$info['data']['requests'][0]['ci_name'] = $ticketArguments[$this->internal_arg_name[self::ARG_CI_NAME]];
}
if (! empty($ticketArguments[$this->internal_arg_name[self::ARG_LOCATION_CODE]])) {
$info['data']['requests'][0]['location_code'] = $ticketArguments[$this->internal_arg_name[self::ARG_LOCATION_CODE]];
}
foreach ($ticketArguments as $id => $value) {
// $id is structure is "{$select.e_my_custom_field_name.value}" we keep "e_my_custom_field_name"
if (preg_match('/.*\.(e_.*)\.[id|value|placeholder].*/', $id, $match)) {
$info['data']['requests'][0][$match[1]] = $value;
}
}
// fwrite($file, print_r("\n ticketargs \n",true));
// fwrite($file, print_r($ticketArguments,true));
// fwrite($file, print_r("\n info \n",true));
// fwrite($file, print_r(json_encode($info['data']),true));
$result = $this->curlQuery($info);
preg_match('~' . $this->getFormValue('address') . $this->getFormValue('api_path') . $info['query_endpoint'] . '/(.*)$~', $result['HREF'], $match);
return $match[1];
// fclose($file);
// return 1234;
}
protected function closeTicketEzv($ticketId)
{
// add the api endpoint and method to our info array
$info['query_endpoint'] = '/requests/' . $ticketId;
$info['method'] = 0;
$info['custom_request'] = 'PUT';
$info['data'] = [
'closed' => [],
];
try {
$this->curlQuery($info);
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyVistaRest/ajax/call.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/EasyVistaRest/ajax/call.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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__ . '/../../../centreon-open-tickets.conf.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/providers/register.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/rule.php';
require_once $centreon_path . 'www/modules/centreon-open-tickets/class/centreonDBManager.class.php';
$centreon_open_tickets_path = $centreon_path . 'www/modules/centreon-open-tickets/';
require_once $centreon_open_tickets_path . 'providers/Abstract/AbstractProvider.class.php';
session_start();
$db = new CentreonDBManager();
$rule = new Centreon_OpenTickets_Rule($db);
if (isset($_SESSION['centreon'])) {
/** @var Centreon $centreon */
$centreon = $_SESSION['centreon'];
} else {
exit;
}
define('SMARTY_DIR', "{$centreon_path}/vendor/smarty/smarty/libs/");
require_once SMARTY_DIR . 'Smarty.class.php';
require_once $centreon_path . 'www/include/common/common-Func.php';
// check if there is data in POST
if (! isset($_POST['data'])) {
$result = ['code' => 1, 'msg' => "POST 'data' is required."];
} else {
$getInformation = isset($_POST['data']) ? json_decode($_POST['data'], true) : null;
$result = ['code' => 0, 'msg' => 'ok'];
// check if there is the provider id in the data
if (is_null($getInformation['provider_id'])) {
$result['code'] = 1;
$result['msg'] = 'Please set the provider_id';
return;
}
// check if there is a provider method that we have to call
if (is_null($getInformation['methods'])) {
$result['code'] = 1;
$result['msg'] = 'Please use a provider function';
return;
}
foreach ($register_providers as $name => $id) {
if ($id == $getInformation['provider_id']) {
$providerName = $name;
break;
}
}
// check if provider exists
if (is_null($providerName) || ! file_exists($centreon_open_tickets_path . 'providers/' . $providerName . '/'
. $providerName . 'Provider.class.php')) {
$result['code'] = 1;
$result['msg'] = 'Please set a provider, or check that ' . $centreon_open_tickets_path
. 'providers/' . $providerName . '/' . $providerName . 'Provider.class.php exists';
return;
}
// initate provider
require_once $centreon_open_tickets_path . 'providers/' . $providerName . '/' . $providerName
. 'Provider.class.php';
$className = $providerName . 'Provider';
$centreonProvider = new $className(
$rule,
$centreon_path,
$centreon_open_tickets_path,
$getInformation['rule_id'],
null,
$getInformation['provider_id'],
$providerName
);
// check if methods exist
foreach ($getInformation['methods'] as $method) {
if (! method_exists($centreonProvider, $method)) {
$result['code'] = 1;
$result['msg'] = 'The provider method does not exist';
return;
}
}
try {
$data = [];
if (array_key_exists('provider_data', $getInformation)) {
$data = $getInformation['provider_data'];
}
foreach ($getInformation['methods'] as $method) {
$result[$method] = $centreonProvider->{$method}($centreon_path, $data);
}
} catch (Exception $e) {
$result['code'] = 1;
$result['msg'] = $e->getMessage();
}
}
header('Content-type: text/plain');
echo json_encode($result);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/BmcFootprints11/BmcFootprints11Provider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/BmcFootprints11/BmcFootprints11Provider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class BmcFootprints11Provider extends AbstractProvider
{
use LoggerTrait;
public const ARG_TITLE = 1;
public const ARG_DESCRIPTION = 2;
public const ARG_STATUS = 3;
public const ARG_PROJECTID = 4;
public const ARG_PRIORITYNUMBER = 5;
public const ARG_ASSIGNEE = 6;
protected $internal_arg_name = [
self::ARG_TITLE => 'Title',
self::ARG_DESCRIPTION => 'Description',
self::ARG_STATUS => 'Status',
self::ARG_PROJECTID => 'ProjectID',
self::ARG_PRIORITYNUMBER => 'PriorityNumber',
self::ARG_ASSIGNEE => 'Assignee',
];
/** @var string */
protected $ws_error;
/** @var string */
protected $_ticket_number;
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/**
* Set default extra value
*/
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['wspath'] = '/MRcgi/MRWebServices.pl';
$this->default_data['action'] = '/MRWebServices';
$this->default_data['https'] = 0;
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [['Arg' => self::ARG_TITLE, 'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}'], ['Arg' => self::ARG_DESCRIPTION, 'Value' => '{$body}'], ['Arg' => self::ARG_STATUS, 'Value' => 'Open'], ['Arg' => self::ARG_PROJECTID, 'Value' => '1'], ['Arg' => self::ARG_ASSIGNEE, 'Value' => '{$user.alias}']];
}
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = 'http://{$address}/TicketNumber={$ticket_id}';
}
/**
* Check form
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', "Please set 'Address' value");
$this->checkFormValue('wspath', "Please set 'Webservice Path' value");
$this->checkFormValue('action', "Please set 'Action' value");
$this->checkFormValue('timeout', "Please set 'Timeout' value");
$this->checkFormValue('username', "Please set 'Username' value");
$this->checkFormValue('password', "Please set 'Password' value");
$this->checkFormValue('macro_ticket_id', "Please set 'Macro Ticket ID' value");
$this->checkFormInteger('timeout', "'Timeout' must be a number");
$this->checkFormInteger('confirm_autoclose', "'Confirm popup autoclose' must be a number");
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
/**
* Build the specifc config: from, to, subject, body, headers
*/
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/BmcFootprints11/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['bmc' => _('BMC Footprints 11')]);
// Form
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$wspath_html = '<input size="50" name="wspath" type="text" value="'
. $this->getFormValue('wspath') . '" />';
$action_html = '<input size="50" name="action" type="text" value="'
. $this->getFormValue('action') . '" />';
$username_html = '<input size="50" name="username" type="text" value="'
. $this->getFormValue('username') . '" />';
$password_html = '<input size="50" name="password" type="password" value="'
. $this->getFormValue('password') . '" autocomplete="off" />';
$https_html = '<div class="md-checkbox md-checkbox-inline">'
. '<input type="checkbox" id="https" name="https" value="yes" '
. ($this->getFormValue('https') === 'yes' ? 'checked' : '')
. '/><label class="empty-label" for="https"></label></div>';
$timeout_html = '<input size="2" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" />';
$array_form = [
'address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html],
'wspath' => ['label' => _('Webservice Path') . $this->required_field, 'html' => $wspath_html],
'action' => ['label' => _('Action') . $this->required_field, 'html' => $action_html],
'username' => ['label' => _('Username') . $this->required_field, 'html' => $username_html],
'password' => ['label' => _('Password') . $this->required_field, 'html' => $password_html],
'https' => ['label' => _('Use https'), 'html' => $https_html],
'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html],
'mappingticket' => ['label' => _('Mapping ticket arguments')],
'mappingticketprojectfield' => ['label' => _('Mapping ticket project field')],
];
// mapping Ticket clone
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" name="mappingTicketValue[#index#]" '
. 'size="20" type="text" />';
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" name="mappingTicketArg[#index#]" '
. 'type="select-one">'
. '<option value="' . self::ARG_TITLE . '">' . _('Title') . '</options>'
. '<option value="' . self::ARG_DESCRIPTION . '">' . _('Description') . '</options>'
. '<option value="' . self::ARG_STATUS . '">' . _('Status') . '</options>'
. '<option value="' . self::ARG_PROJECTID . '">' . _('Project ID') . '</options>'
. '<option value="' . self::ARG_PRIORITYNUMBER . '">' . _('Priority Number') . '</options>'
. '<option value="' . self::ARG_ASSIGNEE . '">' . _('Assignee') . '</options>'
. '</select>';
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
// mapping Ticket ProjectField
$mappingTicketProjectFieldName_html = '<input id="mappingTicketProjectFieldName_#index#" '
. 'name="mappingTicketProjectFieldName[#index#]" size="20" type="text" />';
$mappingTicketProjectFieldValue_html = '<input id="mappingTicketProjectFieldValue_#index#" '
. 'name="mappingTicketProjectFieldValue[#index#]" size="20" type="text" />';
$array_form['mappingTicketProjectField'] = [['label' => _('Name'), 'html' => $mappingTicketProjectFieldName_html], ['label' => _('Value'), 'html' => $mappingTicketProjectFieldValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
$this->config['clones']['mappingTicketProjectField'] = $this->getCloneValue('mappingTicketProjectField');
}
/**
* Build the specific advanced config: -
*/
protected function getConfigContainer2Extra()
{
}
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['wspath'] = $this->submitted_config['wspath'];
$this->save_config['simple']['action'] = $this->submitted_config['action'];
$this->save_config['simple']['username'] = $this->submitted_config['username'];
$this->save_config['simple']['password'] = $this->submitted_config['password'];
$this->save_config['simple']['https'] = (
isset($this->submitted_config['https']) && $this->submitted_config['https'] == 'yes'
) ? $this->submitted_config['https'] : '';
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted(
'mappingTicket',
['Arg', 'Value']
);
$this->save_config['clones']['mappingTicketProjectField'] = $this->getCloneSubmitted(
'mappingTicketProjectField',
['Name', 'Value']
);
}
protected function doSubmit($db_storage, $contact, $host_problems, $service_problems)
{
$result = ['ticket_id' => null, 'ticket_error_message' => null, 'ticket_is_ok' => 0, 'ticket_time' => time()];
$tpl = $this->initSmartyTemplate();
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('user', $contact);
$tpl->assign('host_selected', $host_problems);
$tpl->assign('service_selected', $service_problems);
$this->assignSubmittedValues($tpl);
$ticket_arguments = [];
if (isset($this->rule_data['clones']['mappingTicket'])) {
foreach ($this->rule_data['clones']['mappingTicket'] as $value) {
$tpl->assign('string', $value['Value']);
$result_str = $tpl->fetch('eval.ihtml');
if ($result_str == '') {
$result_str = null;
}
$ticket_arguments[$this->internal_arg_name[$value['Arg']]] = $result_str;
}
}
$ticket_project_fields = [];
if (isset($this->rule_data['clones']['mappingTicketProjectField'])) {
foreach ($this->rule_data['clones']['mappingTicketProjectField'] as $value) {
if ($value['Name'] == '' || $value['Value'] == '') {
continue;
}
$array_tmp = [];
$tpl->assign('string', $value['Name']);
$array_tmp = ['Name' => $tpl->fetch('eval.ihtml')];
$tpl->assign('string', $value['Value']);
$array_tmp['Value'] = $tpl->fetch('eval.ihtml');
$ticket_project_fields[] = $array_tmp;
}
}
$code = $this->createTicket($ticket_arguments, $ticket_project_fields);
if ($code == -1) {
$result['ticket_error_message'] = $this->ws_error;
return $result;
}
$this->saveHistory(
$db_storage,
$result,
['contact' => $contact, 'host_problems' => $host_problems, 'service_problems' => $service_problems, 'ticket_value' => $this->_ticket_number, 'subject' => $ticket_arguments['Subject'], 'data_type' => self::DATA_TYPE_JSON, 'data' => json_encode(
['arguments' => $ticket_arguments, 'project_fields' => $ticket_project_fields]
)]
);
return $result;
}
/**
* SOAP API
*
* @param string $error
* @return void
*/
protected function setWsError($error)
{
$this->ws_error = $error;
}
protected function createTicket($ticket_arguments, $ticket_project_fields)
{
$project_fields = '';
foreach ($ticket_project_fields as $entry) {
$type = 'string';
if (preg_match('/^[0-9]+$/', $entry['Value'])) {
$type = 'integer';
}
$project_fields .= '<' . $entry['Name'] . ' xsi:type="xsd:' . $type . '">'
. $entry['Value'] . '</' . $entry['Name'] . '>';
}
if ($project_fields != '') {
$project_fields = '<projfields>' . $project_fields . '</projfields>';
}
$proto = 'http';
if (isset($this->rule_data['https']) && $this->rule_data['https'] == 'yes') {
$proto = 'https';
}
$url = $proto . '://' . $this->rule_data['address'] . $this->rule_data['action'];
$data = '<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MRWebServices__createIssue
xmlns="' . $url . '">
<c-gensym3 xsi:type="xsd:string">' . $this->rule_data['username'] . '</c-gensym3>
<c-gensym5 xsi:type="xsd:string"><![CDATA[' . $this->rule_data['password'] . ']]></c-gensym5>
<c-gensym7 xsi:type="xsd:string"/>
<c-gensym9>
<assignees
soapenc:arrayType="xsd:string[1]" xsi:type="soapenc:Array">
<item xsi:type="xsd:string">'
. $ticket_arguments[$this->internal_arg_name[self::ARG_ASSIGNEE]] . '</item>
</assignees>
' . $project_fields
. (isset($ticket_arguments[$this->internal_arg_name[self::ARG_PRIORITYNUMBER]])
? '<priorityNumber xsi:type="xsd:int">'
. $ticket_arguments[$this->internal_arg_name[self::ARG_PRIORITYNUMBER]]
. '</priorityNumber>' : '') . '
<status xsi:type="xsd:string">'
. $ticket_arguments[$this->internal_arg_name[self::ARG_STATUS]] . '</status>
<projectID xsi:type="xsd:int">'
. $ticket_arguments[$this->internal_arg_name[self::ARG_PROJECTID]] . '</projectID>
<title xsi:type="xsd:string"><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_TITLE]] . ']]></title>
<description xsi:type="xsd:string"><![CDATA['
. $ticket_arguments[$this->internal_arg_name[self::ARG_DESCRIPTION]] . ']]></description>
</c-gensym9>
</MRWebServices__createIssue>
</soap:Body>
</soap:Envelope>
';
if ($this->callSOAP($data, $url) == 1) {
return -1;
}
return 0;
}
protected function callSOAP($data, $url)
{
$proto = 'http';
if (isset($this->rule_data['https']) && $this->rule_data['https'] == 'yes') {
$proto = 'https';
}
$endpoint = $proto . '://' . $this->rule_data['address'] . $this->rule_data['wspath'];
$ch = curl_init($endpoint);
if ($ch == false) {
$this->setWsError('cannot init curl object');
return 1;
}
// ssl peer verification
$peerVerify = ($this->rule_data['peer_verify'] ?? 'yes') === 'yes';
$verifyHost = $peerVerify ? 2 : 0;
$caCertPath = $this->rule_data['ca_cert_path'] ?? '';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->rule_data['timeout']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
['Content-Type: text/xml;charset=UTF-8', 'SOAPAction: ' . $url . '#MRWebServices__createIssue', 'Content-Length: ' . strlen($data)]
);
$optionsToLog = [
'apiAddress' => $endpoint,
'SOAPAction' => $url . '#MRWebServices__createIssue',
'peerVerify' => $peerVerify,
'verifyHost' => $verifyHost,
'caCertPath' => '',
];
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caCertPath);
$optionsToLog['caCertPath'] = $caCertPath;
}
// log the curl options
$this->debug('BMC Footprints API request options', [
'options' => $optionsToLog,
]);
$result = curl_exec($ch);
curl_close($ch);
if ($result == false) {
$this->setWsError(curl_error($ch));
return 1;
}
/*
* OK:
* <?xml version="1.0" encoding="UTF-8" ?>
* <SOAP-ENV:Envelope
* xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
* xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
* xmlns:xsd="http://www.w3.org/2001/XMLSchema"
* SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
* <SOAP-ENV:Body>
* <namesp1:MRWebServices__createIssueResponse
* xmlns:namesp1="http://10.33.48.225/MRWebServices">
* <return xsi:type="xsd:string">2399</return>
* </namesp1:MRWebServices__createIssueResponse>
* </SOAP-ENV:Body>
* </SOAP-ENV:Envelope>
*
* NOK:
* <?xml version="1.0" encoding="UTF-8"?>
* <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
* <SOAP-ENV:Body>
* <SOAP-ENV:Fault>
* <faultcode>SOAP-ENV:Server</faultcode>
* <faultstring>Une page d'erreur s'est affiche l'utilisateur des Services Web.
* Dtails: Utilisateur 'toto' n'existe pas dans FootPrints Service Core.
* Suivi de la pile: Suivi de la pile:
* file:/usr/local/footprintsservicecore/cgi/MRWebServices.pl, line:74, sub:SOAP::Transport::HTTP::CGI::handle
* file:/mnt/data/footprintsservicecore/footprints_perl/lib/site_perl/5.10.0/SOAP/Transport/HTTP.pm, line:369, sub:SOAP::Transport::HTTP::Server::handle
* file:/mnt/data/footprintsservicecore/footprints_perl/lib/site_perl/5.10.0/SOAP/Transport/HTTP.pm, line:286, sub:SOAP::Server::handle
* file:/mnt/data/footprintsservicecore/footprints_perl/lib/site_perl/5.10.0/SOAP/Lite.pm, line:2282, sub:(eval)
* file:/mnt/data/footprintsservicecore/footprints_perl/lib/site_perl/5.10.0/SOAP/Lite.pm, line:2310, sub:(eval)
* file:/mnt/data/footprintsservicecore/footprints_perl/lib/site_perl/5.10.0/SOAP/Lite.pm, line:2322, sub:MRWebServices::MRWebServices__createIssue
* file:/usr/local/footprintsservicecore//cgi/SUBS/MRWebServices/createIssue.pl, line:59, sub:MRWebServices::MRWebServices__checkWebServicesLogin
* file:/usr/local/footprintsservicecore//cgi/SUBS/MRWebServices/checkWebServicesLogin.pl, line:47, sub:FP::Errorpage
* file:/usr/local/footprintsservicecore//cgi/SUBS/Errorpage.pl, line:125, sub:MRWebServices::__ANON__
* file:(eval 1330), line:6, sub:FP::printStackTrace
* </faultstring>
* </SOAP-ENV:Fault>
* </SOAP-ENV:Body></SOAP-ENV:Envelope>
*/
if (! preg_match('/<return.*?>(.*?)<\/return>/msi', $result, $matches)) {
$this->setWsError($result);
return 1;
}
$this->_ticket_number = $matches[1];
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/providers/GlpiRestApi/GlpiRestApiProvider.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/providers/GlpiRestApi/GlpiRestApiProvider.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Domain\Log\LoggerTrait;
class GlpiRestApiProvider extends AbstractProvider
{
use LoggerTrait;
public const GLPI_ENTITY_TYPE = 14;
public const GLPI_GROUP_TYPE = 15;
public const GLPI_ITIL_CATEGORY_TYPE = 16;
public const GLPI_USER_TYPE = 17;
public const GLPI_SUPPLIER_TYPE = 18;
public const GLPI_REQUESTER_TYPE = 19;
public const ARG_CONTENT = 1;
public const ARG_ENTITY = 2;
public const ARG_URGENCY = 3;
public const ARG_IMPACT = 4;
public const ARG_ITIL_CATEGORY = 5;
public const ARG_USER = 6;
public const ARG_GROUP = 7;
public const ARG_TITLE = 8;
public const ARG_PRIORITY = 9;
public const ARG_SUPPLIER = 10;
public const ARG_GROUP_ROLE = 11;
public const ARG_USER_ROLE = 12;
public const ARG_REQUESTER = 13;
private const PAGE_SIZE = 20;
protected $close_advanced = 1;
protected $proxy_enabled = 1;
/** @var null|array */
protected $glpiCallResult;
protected $internal_arg_name = [
self::ARG_CONTENT => 'content',
self::ARG_ENTITY => 'entity',
self::ARG_URGENCY => 'urgency',
self::ARG_IMPACT => 'impact',
self::ARG_ITIL_CATEGORY => 'category',
self::ARG_USER => 'user',
self::ARG_GROUP => 'group',
self::ARG_TITLE => 'title',
self::ARG_PRIORITY => 'priority',
self::ARG_SUPPLIER => 'supplier',
self::ARG_GROUP_ROLE => 'group_role',
self::ARG_USER_ROLE => 'user_role',
self::ARG_REQUESTER => 'requester',
];
/*
* checks if all mandatory fields have been filled
*
* @return {array} telling us if there is a missing parameter
*/
public function validateFormatPopup()
{
$result = ['code' => 0, 'message' => 'ok'];
$this->validateFormatPopupLists($result);
return $result;
}
/*
* test if we can reach Glpi webservice with the given Configuration
*
* @param {array} $info required information to reach the glpi api
*
* @return {bool}
*
* throw \Exception if there are some missing parameters
* throw \Exception if the connection failed
*/
public static function test($info)
{
// this is called through our javascript code. Those parameters are already checked in JS code.
// but since this function is public, we check again because anyone could use this function
if (
! isset($info['address'])
|| ! isset($info['api_path'])
|| ! isset($info['user_token'])
|| ! isset($info['app_token'])
|| ! isset($info['protocol'])
) {
throw new Exception('missing arguments', 13);
}
// check if php curl is installed
if (! extension_loaded('curl')) {
throw new Exception("couldn't find php curl", 10);
}
$curl = curl_init();
$apiAddress = $info['protocol'] . '://' . $info['address'] . $info['api_path'] . '/initSession';
$info['method'] = 0;
// set headers
$info['headers'] = ['App-Token: ' . $info['app_token'], 'Authorization: user_token ' . $info['user_token'], 'Content-Type: application/json'];
// ssl peer verify
$peerVerify = (bool) ($info['peer_verify'] ?? true);
$caCertPath = $info['ca_cert_path'] ?? '';
// initiate our curl options
curl_setopt($curl, CURLOPT_URL, $apiAddress);
curl_setopt($curl, CURLOPT_HTTPHEADER, $info['headers']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $peerVerify);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $peerVerify ? 2 : 0);
curl_setopt($curl, CURLOPT_POST, $info['method']);
curl_setopt($curl, CURLOPT_TIMEOUT, $info['timeout']);
// Use custom CA only when verification is enabled
if ($peerVerify && is_string($caCertPath) && $caCertPath !== '') {
curl_setopt($curl, CURLOPT_CAINFO, $caCertPath);
}
// execute curl and get status information
$curlResult = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode > 301) {
throw new Exception('curl result: ' . $curlResult . '|| HTTP return code: ' . $httpCode, 11);
}
return true;
}
/*
* check if the close option is enabled, if so, try to close every selected ticket
*
* @param {array} $tickets
*
* @return void
*/
public function closeTicket(&$tickets): void
{
if ($this->doCloseTicket()) {
foreach ($tickets as $k => $v) {
try {
$this->closeTicketGlpi($k);
$tickets[$k]['status'] = 2;
} catch (Exception $e) {
$tickets[$k]['status'] = -1;
$tickets[$k]['msg_error'] = $e->getMessage();
}
}
} else {
parent::closeTicket($tickets);
}
}
// Set default values for our rule form options
protected function setDefaultValueExtra()
{
$this->default_data['address'] = '127.0.0.1';
$this->default_data['api_path'] = '/glpi/apirest.php';
$this->default_data['protocol'] = 'http';
$this->default_data['user_token'] = '';
$this->default_data['app_token'] = '';
$this->default_data['timeout'] = 60;
$this->default_data['clones']['mappingTicket'] = [
[
'Arg' => self::ARG_TITLE,
'Value' => 'Issue {include file="file:$centreon_open_tickets_path/providers'
. '/Abstract/templates/display_title.ihtml"}',
],
[
'Arg' => self::ARG_CONTENT,
'Value' => '{$body}',
],
[
'Arg' => self::ARG_ENTITY,
'Value' => '{$select.glpi_entity.id}',
],
[
'Arg' => self::ARG_ITIL_CATEGORY,
'Value' => '{$select.glpi_itil_category.id}',
],
[
'Arg' => self::ARG_REQUESTER,
'Value' => '{$select.glpi_requester.id}',
],
[
'Arg' => self::ARG_USER,
'Value' => '{$select.glpi_users.id}',
],
[
'Arg' => self::ARG_USER_ROLE,
'Value' => '{$select.user_role.value}',
],
[
'Arg' => self::ARG_GROUP,
'Value' => '{$select.glpi_group.id}',
],
[
'Arg' => self::ARG_GROUP_ROLE,
'Value' => '{$select.group_role.value}',
],
[
'Arg' => self::ARG_URGENCY,
'Value' => '{$select.urgency.value}',
],
[
'Arg' => self::ARG_IMPACT,
'Value' => '{$select.impact.value}',
],
[
'Arg' => self::ARG_PRIORITY,
'Value' => '{$select.priority.value}',
],
[
'Arg' => self::ARG_SUPPLIER,
'Value' => '{$select.glpi_supplier.id}',
],
];
}
/*
* Set default values for the widget popup when opening a ticket
*
* @return void
*/
protected function setDefaultValueMain($body_html = 0)
{
parent::setDefaultValueMain($body_html);
$this->default_data['url'] = '{$protocol}://{$address}/glpi/front/ticket.form.php?id={$ticket_id}';
$this->default_data['clones']['groupList'] = [
[
'Id' => 'glpi_entity',
'Label' => _('Entity'),
'Type' => self::GLPI_ENTITY_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'glpi_itil_category',
'Label' => _('Itil category'),
'Type' => self::GLPI_ITIL_CATEGORY_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'glpi_requester',
'Label' => _('Requester'),
'Type' => self::GLPI_REQUESTER_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'glpi_users',
'Label' => _('Glpi users'),
'Type' => self::GLPI_USER_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'user_role',
'Label' => _('user_role'),
'Type' => self::CUSTOM_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'glpi_group',
'Label' => _('Glpi group'),
'Type' => self::GLPI_GROUP_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'group_role',
'Label' => _('group_role'),
'Type' => self::CUSTOM_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'urgency',
'Label' => _('Urgency'),
'Type' => self::CUSTOM_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'impact',
'Label' => _('Impact'),
'Type' => self::CUSTOM_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'priority',
'Label' => _('Priority'),
'Type' => self::CUSTOM_TYPE,
'Filter' => '',
'Mandatory' => '',
],
[
'Id' => 'glpi_supplier',
'Label' => _('Glpi supplier'),
'Type' => self::GLPI_SUPPLIER_TYPE,
'Filter' => '',
'Mandatory' => '',
],
];
$this->default_data['clones']['customList'] = [
[
'Id' => 'urgency',
'Value' => '1',
'Label' => 'Very Low',
'Default' => '',
],
[
'Id' => 'urgency',
'Value' => '2',
'Label' => 'Low',
'Default' => '',
],
[
'Id' => 'urgency',
'Value' => '3',
'Label' => 'Medium',
'Default' => '',
],
[
'Id' => 'urgency',
'Value' => '4',
'Label' => 'High',
'Default' => '',
],
[
'Id' => 'urgency',
'Value' => '5',
'Label' => 'Very High',
'Default' => '',
],
[
'Id' => 'impact',
'Value' => '1',
'Label' => '',
'Default' => '',
],
[
'Id' => 'impact',
'Value' => '2',
'Label' => '',
'Default' => '',
],
[
'Id' => 'impact',
'Value' => '3',
'Label' => '',
'Default' => '',
],
[
'Id' => 'impact',
'Value' => '4',
'Label' => '',
'Default' => '',
],
[
'Id' => 'impact',
'Value' => '5',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '1',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '2',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '3',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '4',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '5',
'Label' => '',
'Default' => '',
],
[
'Id' => 'priority',
'Value' => '6',
'Label' => '',
'Default' => '',
],
[
'Id' => 'group_role',
'Value' => '3',
'Label' => 'Watcher',
'Default' => '',
],
[
'Id' => 'group_role',
'Value' => '2',
'Label' => 'Assigned',
'Default' => '',
],
[
'Id' => 'user_role',
'Value' => '3',
'Label' => 'Watcher',
'Default' => '',
],
[
'Id' => 'user_role',
'Value' => '2',
'Label' => 'Assigned',
'Default' => '',
],
];
}
/*
* Verify if every mandatory form field is filled with data
*
* @throw \Exception when a form field is not set
*/
protected function checkConfigForm()
{
$this->check_error_message = '';
$this->check_error_message_append = '';
$this->checkFormValue('address', 'Please set "Address" value');
$this->checkFormValue('api_path', 'Please set "API path" value');
$this->checkFormValue('protocol', 'Please set "Protocol" value');
$this->checkFormValue('user_token', 'Please set "User token" value');
$this->checkFormValue('app_token', 'Please set "APP token" value');
$this->checkFormInteger('timeout', '"Timeout" must be an integer');
$this->checkLists();
if ($this->check_error_message != '') {
throw new Exception($this->check_error_message);
}
}
// Initiate your html configuration and let Smarty display it in the rule form
protected function getConfigContainer1Extra()
{
$tpl = $this->initSmartyTemplate('providers/GlpiRestApi/templates');
$tpl->assign('centreon_open_tickets_path', $this->centreon_open_tickets_path);
$tpl->assign('img_brick', './modules/centreon-open-tickets/images/brick.png');
$tpl->assign('header', ['GlpiRestApi' => _('Glpi Rest Api')]);
$tpl->assign('webServiceUrl', './api/internal.php');
// we create the html that is going to be displayed
$address_html = '<input size="50" name="address" type="text" value="'
. $this->getFormValue('address') . '" />';
$api_path_html = '<input size="50" name="api_path" type="text" value="'
. $this->getFormValue('api_path') . '" />';
$protocol_html = '<input size="50" name="protocol" type="text" value="'
. $this->getFormValue('protocol') . '" />';
$user_token_html = '<input size="50" name="user_token" type="text" value="'
. $this->getFormValue('user_token') . '" autocomplete="off" />';
$app_token_html = '<input size="50" name="app_token" type="text" value="'
. $this->getFormValue('app_token') . '" autocomplete="off" />';
$timeout_html = '<input size="50" name="timeout" type="text" value="'
. $this->getFormValue('timeout') . '" :>';
// this array is here to link a label with the html code that we've wrote above
$array_form = [
'address' => ['label' => _('Address') . $this->required_field, 'html' => $address_html],
'api_path' => ['label' => _('API path') . $this->required_field, 'html' => $api_path_html],
'protocol' => ['label' => _('Protocol') . $this->required_field, 'html' => $protocol_html],
'user_token' => ['label' => _('User token') . $this->required_field, 'html' => $user_token_html],
'app_token' => ['label' => _('APP token') . $this->required_field, 'html' => $app_token_html],
'timeout' => ['label' => _('Timeout'), 'html' => $timeout_html],
// we add a key to our array
'mappingTicketLabel' => ['label' => _('Mapping ticket arguments')],
];
// html
$mappingTicketValue_html = '<input id="mappingTicketValue_#index#" '
. 'name="mappingTicketValue[#index#]" size="20" type="text"';
// html code for a dropdown list where we will be able to select something from the following list
$mappingTicketArg_html = '<select id="mappingTicketArg_#index#" '
. 'name="mappingTicketArg[#index#]" type="select-one">'
. '<option value="' . self::ARG_TITLE . '">' . _('Title') . '</option>'
. '<option value="' . self::ARG_CONTENT . '">' . _('Content') . '</option>'
. '<option value="' . self::ARG_ENTITY . '">' . _('Entity') . '</option>'
. '<option value="' . self::ARG_ITIL_CATEGORY . '">' . _('Category') . '</option>'
. '<option value="' . self::ARG_REQUESTER . '">' . _('Requester') . '</option>'
. '<option value="' . self::ARG_USER . '">' . _('User') . '</option>'
. '<option value="' . self::ARG_USER_ROLE . '">' . _('user_role') . '</option>'
. '<option value="' . self::ARG_GROUP . '">' . _('Group') . '</option>'
. '<option value="' . self::ARG_GROUP_ROLE . '">' . _('group_role') . '</option>'
. '<option value="' . self::ARG_URGENCY . '">' . _('Urgency') . '</option>'
. '<option value="' . self::ARG_IMPACT . '">' . _('Impact') . '</option>'
. '<option value="' . self::ARG_PRIORITY . '">' . _('Priority') . '</option>'
. '<option value="' . self::ARG_SUPPLIER . '">' . _('Supplier') . '</option>'
. '</select>';
// we asociate the label with the html code but for the arguments that we've been working on lately
$array_form['mappingTicket'] = [['label' => _('Argument'), 'html' => $mappingTicketArg_html], ['label' => _('Value'), 'html' => $mappingTicketValue_html]];
$tpl->assign('form', $array_form);
$this->config['container1_html'] .= $tpl->fetch('conf_container1extra.ihtml');
$this->config['clones']['mappingTicket'] = $this->getCloneValue('mappingTicket');
}
protected function getConfigContainer2Extra()
{
}
// Saves the rule form in the database
protected function saveConfigExtra()
{
$this->save_config['simple']['address'] = $this->submitted_config['address'];
$this->save_config['simple']['api_path'] = $this->submitted_config['api_path'];
$this->save_config['simple']['protocol'] = $this->submitted_config['protocol'];
$this->save_config['simple']['user_token'] = $this->submitted_config['user_token'];
$this->save_config['simple']['app_token'] = $this->submitted_config['app_token'];
$this->save_config['simple']['timeout'] = $this->submitted_config['timeout'];
// saves the ticket arguments
$this->save_config['clones']['mappingTicket'] = $this->getCloneSubmitted('mappingTicket', ['Arg', 'Value']);
}
/*
* Adds new types to the list of types
*
* @return {string} $str html code that add an option to a select
*/
protected function getGroupListOptions()
{
return '<option value="' . self::GLPI_ENTITY_TYPE . '">Entity</option>'
. '<option value="' . self::GLPI_REQUESTER_TYPE . '">Requester</option>'
. '<option value="' . self::GLPI_GROUP_TYPE . '">Group</option>'
. '<option value="' . self::GLPI_ITIL_CATEGORY_TYPE . '">ITIL category</option>'
. '<option value="' . self::GLPI_USER_TYPE . '">User</option>'
. '<option value="' . self::GLPI_SUPPLIER_TYPE . '">Supplier</option>';
}
/*
* configure variables with the data provided by the glpi api
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*/
protected function assignOthers($entry, &$groups_order, &$groups)
{
if ($entry['Type'] == self::GLPI_ENTITY_TYPE) {
$this->assignGlpiEntities($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_GROUP_TYPE) {
$this->assignGlpiGroups($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_ITIL_CATEGORY_TYPE) {
$this->assignItilCategories($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_USER_TYPE) {
$this->assignGlpiUsers($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_SUPPLIER_TYPE) {
$this->assignGlpiSuppliers($entry, $groups_order, $groups);
} elseif ($entry['Type'] == self::GLPI_REQUESTER_TYPE) {
$this->assignGlpiRequesters($entry, $groups_order, $groups);
}
}
/*
* handle gathered entities
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*
* throw \Exception if we can't get entities from glpi
*/
protected function assignGlpiEntities($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get entities
try {
$listEntities = $this->getCache($entry['Id']);
if (is_null($listEntities)) {
// if no entity found in cache, get them from glpi and put them in cache for 8 hours
$listEntities = $this->getEntities();
$this->setCache($entry['Id'], $listEntities, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listEntities['myentities'] ?? [] as $entity) {
// foreach entity found, if we don't have any filter configured,
// we just put the id and the name of the entity inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$entity['id']] = $this->to_utf8($entity['name']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the entity inside the result array
if (preg_match('/' . $entry['Filter'] . '/', $entity['name'])) {
$result[$entity['id']] = $this->to_utf8($entity['name']);
}
}
$groups[$entry['Id']]['values'] = $result;
}
/*
* handle gathered requesters
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*
* throw \Exception if we can't get requesters from glpi
*/
protected function assignGlpiRequesters($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get requesters
try {
$listRequesters = $this->getCache($entry['Id']);
if (is_null($listRequesters)) {
$listRequesters = $this->getUsers();
$this->setCache($entry['Id'], $listRequesters, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listRequesters ?? [] as $requester) {
// foreach requester found, if we don't have any filter configured,
// we just put the id and the name of the requester inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$requester['id']] = $this->to_utf8($requester['name']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the requester inside the result array
if (preg_match('/' . $entry['Filter'] . '/', $requester['name'])) {
$result[$requester['id']] = $this->to_utf8($requester['name']);
}
}
$groups[$entry['Id']]['values'] = $result;
}
/*
* handle gathered users
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*
* throw \Exception if we can't get users from glpi
*/
protected function assignGlpiUsers($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get users
try {
$listUsers = $this->getCache($entry['Id']);
if (is_null($listUsers)) {
$listUsers = $this->getUsers();
$this->setCache($entry['Id'], $listUsers, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listUsers ?? [] as $user) {
// foreach user found, if we don't have any filter configured,
// we just put the id and the name of the user inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$user['id']] = $this->to_utf8($user['name']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the user inside the result array
if (preg_match('/' . $entry['Filter'] . '/', $user['name'])) {
$result[$user['id']] = $this->to_utf8($user['name']);
}
}
$groups[$entry['Id']]['values'] = $result;
}
/*
* handle gathered groups
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*
* throw \Exception if we can't get groups from glpi
*/
protected function assignGlpiGroups($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get groups
try {
$listGroups = $this->getCache($entry['Id']);
if (is_null($listGroups)) {
$listGroups = $this->getGroups();
$this->setCache($entry['Id'], $listGroups, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
// using $glpiGroup to avoid confusion with $groups and $groups_order
foreach ($listGroups ?? [] as $glpiGroup) {
// foreach group found, if we don't have any filter configured,
// we just put the id and the name of the group inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$glpiGroup['id']] = $this->to_utf8($glpiGroup['completename']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the group inside the result array
if (preg_match('/' . $entry['Filter'] . '/', $glpiGroup['completename'])) {
$result[$glpiGroup['id']] = $this->to_utf8($glpiGroup['completename']);
}
}
$groups[$entry['Id']]['values'] = $result;
}
/*
* handle gathered suppliers
*
* @param {array} $entry ticket argument configuration information
* @param {array} $groups_order order of the ticket arguments
* @param {array} $groups store the data gathered from glpi
*
* @return void
*
* throw \Exception if we can't get suppliers from glpi
*/
protected function assignGlpiSuppliers($entry, &$groups_order, &$groups)
{
// add a label to our entry and activate sorting or not.
$groups[$entry['Id']] = ['label' => _($entry['Label'])
. (isset($entry['Mandatory']) && $entry['Mandatory'] == 1 ? $this->required_field : ''), 'sort' => (isset($entry['Sort']) && $entry['Sort'] == 1 ? 1 : 0)];
// adds our entry in the group order array
$groups_order[] = $entry['Id'];
// try to get suppliers
try {
$listSuppliers = $this->getCache($entry['Id']);
if (is_null($listSuppliers)) {
$listSuppliers = $this->getSuppliers();
$this->setCache($entry['Id'], $listSuppliers, 8 * 3600);
}
} catch (Exception $e) {
$groups[$entry['Id']]['code'] = -1;
$groups[$entry['Id']]['msg_error'] = $e->getMessage();
}
$result = [];
foreach ($listSuppliers ?? [] as $supplier) {
// foreach supplier found, if we don't have any filter configured,
// we just put the id and the name of the supplier inside the result array
if (! isset($entry['Filter']) || is_null($entry['Filter']) || $entry['Filter'] == '') {
$result[$supplier['id']] = $this->to_utf8($supplier['name']);
continue;
}
// if we do have have a filter, we make sure that the match the filter, if so, we put the name and the id
// of the supplier inside the result array
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/class/ticketLog.php | centreon-open-tickets/www/modules/centreon-open-tickets/class/ticketLog.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
class Centreon_OpenTickets_Log
{
protected $_db;
protected $_dbStorage;
/**
* Constructor
*
* @param CentreonDB $db
* @param CentreonDB $dbStorage
* @return void
*/
public function __construct($db, $dbStorage)
{
$this->_db = $db;
$this->_dbStorage = $dbStorage;
}
/*
* Params example:
* [host_filter] => Array
* (
* [0] => 105
* )
* [service_filter] => Array
* (
* [0] => 104-836
* [1] => 105-838
* )
*
* [subject] => test
* [StartDate] => 06/10/2016
* [StartTime] => 10:20
* [EndDate] => 06/06/2016
* [EndTime] =>
* [ticket_id] => XXXX
* [period] => 10800
*/
public function getLog($params, $centreon_bg, $pagination = 30, $current_page = 1, $all = false)
{
// Get time
$range_time = $this->getTime(
$params['StartDate'],
$params['StartTime'],
$params['EndDate'],
$params['EndTime'],
$params['period']
);
$query = 'SELECT SQL_CALC_FOUND_ROWS mot.ticket_value AS ticket_id, mot.timestamp, mot.user, '
. 'motl.hostname AS host_name, motl.service_description, motd.subject '
. 'FROM mod_open_tickets_link motl, mod_open_tickets_data motd, mod_open_tickets mot WHERE ';
if (! is_null($range_time['start'])) {
$query .= 'mot.timestamp >= ' . $range_time['start'] . ' AND ';
}
if (! is_null($range_time['end'])) {
$query .= 'mot.timestamp <= ' . $range_time['end'] . ' AND ';
}
if (! is_null($params['ticket_id']) && $params['ticket_id'] != '') {
$query .= "mot.ticket_value LIKE '%" . $this->_db->escape($params['ticket_id']) . "%' AND ";
}
if (! is_null($params['subject']) && $params['subject'] != '') {
$query .= "motd.subject LIKE '%" . $this->_db->escape($params['subject']) . "%' AND ";
}
$build_services_filter = '';
$build_services_filter_append = '';
if (isset($params['service_filter']) && is_array($params['service_filter'])) {
foreach ($params['service_filter'] as $val) {
$tmp = explode('-', $val);
$build_services_filter .= $build_services_filter_append . '(motl.host_id = ' . $tmp[0]
. ' AND motl.service_id = ' . $tmp[1] . ') ';
$build_services_filter_append = 'OR ';
}
}
if (isset($params['host_filter']) && count($params['host_filter']) > 0) {
if ($build_services_filter != '') {
$query .= '(motl.host_id IN (' . join(',', $params['host_filter']) . ') '
. 'OR (' . $build_services_filter . ')) AND ';
} else {
$query .= 'motl.host_id IN (' . join(',', $params['host_filter']) . ') AND ';
}
} elseif ($build_services_filter != '') {
$query .= '(' . $build_services_filter . ') AND ';
}
if (! $centreon_bg->is_admin) {
$query .= 'EXISTS(SELECT 1 FROM centreon_acl WHERE centreon_acl.group_id IN ('
. $centreon_bg->grouplistStr
. ') AND motl.host_id = centreon_acl.host_id '
. 'AND (motl.service_id IS NULL OR motl.service_id = centreon_acl.service_id)) AND ';
}
$query .= 'motl.ticket_id = motd.ticket_id AND motd.ticket_id = mot.ticket_id
ORDER BY `timestamp` DESC ';
// Pagination
if (is_null($current_page) || $current_page <= 0) {
$current_page = 1;
}
if (is_null($pagination) || $pagination <= 0) {
$pagination = 30;
}
if ($all == false) {
$query .= 'LIMIT ' . (($current_page - 1) * $pagination) . ', ' . $pagination;
}
$stmt = $this->_dbStorage->prepare($query);
$stmt->execute();
$result['tickets'] = $stmt->fetchAll();
$rows = $stmt->rowCount();
$result['rows'] = $rows;
$result['start'] = $range_time['start'];
$result['end'] = $range_time['end'];
return $result;
}
protected function getTime($start_date, $start_time, $end_date, $end_time, $period)
{
$start = null;
$end = null;
$auto_period = 1;
if (! is_null($start_date) && $start_date != '') {
$auto_period = 0;
if ($start_time == '') {
$start_time = '00:00';
}
preg_match("/^([0-9]*)\/([0-9]*)\/([0-9]*)/", $start_date, $matchesD);
preg_match('/^([0-9]*):([0-9]*)/', $start_time, $matchesT);
$start = mktime($matchesT[1], $matchesT[2], '0', $matchesD[1], $matchesD[2], $matchesD[3]);
}
if (! is_null($end_date) && $end_date != '') {
$auto_period = 0;
if ($end_time == '') {
$end_time = '00:00';
}
preg_match("/^([0-9]*)\/([0-9]*)\/([0-9]*)/", $end_date, $matchesD);
preg_match('/^([0-9]*):([0-9]*)/', $end_time, $matchesT);
$end = mktime($matchesT[1], $matchesT[2], '0', $matchesD[1], $matchesD[2], $matchesD[3]);
}
if ($auto_period == 1 && ! is_null($period) && $period > 0) {
$start = time() - ($period);
$end = time();
}
return ['start' => $start, 'end' => $end];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/class/centreonDBManager.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/class/centreonDBManager.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once $centreon_path . '/www/class/centreonDB.class.php';
class CentreonDBManager extends CentreonDB
{
#[ReturnTypeWillChange]
public function lastinsertId($name = null)
{
$dbResult = $this->query('SELECT LAST_INSERT_ID() AS last_id FROM ' . $name);
if (! ($row = $dbResult->fetch())) {
throw new Exception('Cannot get last id');
}
return $row['last_id'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/class/automatic.class.php | centreon-open-tickets/www/modules/centreon-open-tickets/class/automatic.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
class Automatic
{
/** @var Centreon */
protected $centreon;
/** @var CentreonDB */
protected $dbCentstorage;
/** @var CentreonDB */
protected $dbCentreon;
/** @var string */
protected $centreonPath;
/** @var string */
protected $openTicketPath;
/** @var Centreon_OpenTickets_Rule */
protected $rule;
/** @var string */
protected $uniqId;
/** @var array<string, int> */
protected $registerProviders;
/**
* Constructor
*
* @param Centreon_OpenTickets_Rule $rule
* @param string $centreonPath
* @param string $openTicketPath
* @param Centreon $centreon
* @param CentreonDB $dbCentstorage
* @param CentreonDB $dbCentreon
* @return void
*/
public function __construct($rule, $centreonPath, $openTicketPath, $centreon, $dbCentstorage, $dbCentreon)
{
global $register_providers;
require_once $openTicketPath . 'providers/register.php';
require_once $openTicketPath . 'providers/Abstract/AbstractProvider.class.php';
$this->registerProviders = $register_providers;
$this->rule = $rule;
$this->centreonPath = $centreonPath;
$this->openTicketPath = $openTicketPath;
$this->centreon = $centreon;
$this->dbCentstorage = $dbCentstorage;
$this->dbCentreon = $dbCentreon;
$this->uniqId = uniqid();
}
/**
* Open a service ticket
*
* @param mixed $params
* @return array
*/
public function openService($params)
{
$ruleInfo = $this->getRuleInfo($params['rule_name']);
$contact = $this->getContactInformation($params);
$service = $this->getServiceInformation($params);
$rv = $this->submitTicket($params, $ruleInfo, $contact, [], [$service]);
$this->doChainRules($rv['chainRuleList'], $params, $contact, [], [$service]);
$this->externalServiceCommands($rv['providerClass'], $rv['ticket_id'], $contact, $service);
return ['code' => 0, 'message' => 'Open ticket ' . $rv['ticket_id']];
}
/**
* Open a host ticket
*
* @param mixed $params
* @return array
*/
public function openHost($params)
{
$ruleInfo = $this->getRuleInfo($params['rule_name']);
$contact = $this->getContactInformation($params);
$host = $this->getHostInformation($params);
$rv = $this->submitTicket($params, $ruleInfo, $contact, [$host], []);
$this->doChainRules($rv['chainRuleList'], $params, $contact, [$host], []);
$this->externalHostCommands($rv['providerClass'], $rv['ticket_id'], $contact, $host);
return ['code' => 0, 'message' => 'Open ticket ' . $rv['ticket_id']];
}
/**
* Close a host ticket
*
* @param mixed $params
* @return array
*/
public function closeHost($params)
{
$ruleInfo = $this->getRuleInfo($params['rule_name']);
$host = $this->getHostInformation($params);
$providerClass = $this->getProviderClass($ruleInfo);
$macroName = $providerClass->getMacroTicketId();
$ticketId = $this->getHostTicket($params, $macroName);
$rv = ['code' => 0, 'message' => 'no ticket found for host: ' . $host['name']];
if ($ticketId) {
$closeTicketData = [
$ticketId => [],
];
try {
$providerClass->closeTicket($closeTicketData);
$this->changeMacroHost($macroName, $host);
$rv = ['code' => 0, 'message' => 'ticket ' . $ticketId . ' has been closed'];
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
}
return $rv;
}
/**
* Close a service ticket
*
* @param mixed $params
* @return array
*/
public function closeService($params)
{
$ruleInfo = $this->getRuleInfo($params['rule_name']);
$service = $this->getServiceInformation($params);
$providerClass = $this->getProviderClass($ruleInfo);
$macroName = $providerClass->getMacroTicketId();
$ticketId = $this->getServiceTicket($params, $macroName);
$rv = ['code' => 0, 'message' => 'no ticket found for service: '
. $service['host_name'] . ' ' . $service['description']];
if ($ticketId) {
$closeTicketData = [
$ticketId => [],
];
try {
$providerClass->closeTicket($closeTicketData);
$this->changeMacroService($macroName, $service);
$rv = ['code' => 0, 'message' => 'ticket ' . $ticketId . ' has been closed'];
} catch (Exception $e) {
$rv = ['code' => -1, 'message' => $e->getMessage()];
}
}
return $rv;
}
/**
* Get rule information
*
* @param string $name
* @return array
*/
protected function getRuleInfo($name)
{
$stmt = $this->dbCentreon->prepare(
"SELECT rule_id, alias, provider_id FROM mod_open_tickets_rule
WHERE alias = :alias AND activate = '1'"
);
$stmt->bindParam(':alias', $name, PDO::PARAM_STR);
$stmt->execute();
if (! ($ruleInfo = $stmt->fetch(PDO::FETCH_ASSOC))) {
throw new Exception('Wrong parameter rule_id');
}
return $ruleInfo;
}
/**
* Get contact information
*
* @param array $params
* @return array
*/
protected function getContactInformation($params)
{
$rv = ['alias' => '', 'email' => '', 'name' => ''];
$dbResult = $this->dbCentreon->query(
"SELECT
contact_name as `name`,
contact_alias as `alias`,
contact_email as email
FROM contact
WHERE contact_id = '" . $this->centreon->user->user_id . "' LIMIT 1"
);
if (($row = $dbResult->fetch())) {
$rv = $row;
}
if (isset($params['contact_name'])) {
$row['name'] = $params['contact_name'];
}
if (isset($params['contact_alias'])) {
$row['alias'] = $params['contact_alias'];
}
if (isset($params['contact_email'])) {
$row['email'] = $params['contact_email'];
}
return $rv;
}
/**
* Get service information
*
* @param mixed $params
* @throws Exception
* @return mixed
*/
protected function getServiceInformation($params)
{
$query = 'SELECT
services.*,
hosts.address,
hosts.state AS host_state,
hosts.host_id,
hosts.name AS host_name,
hosts.instance_id
FROM services, hosts
WHERE services.host_id = :host_id AND
services.service_id = :service_id AND
services.host_id = hosts.host_id';
if (! $this->centreon->user->admin) {
$query
.= ' AND EXISTS(
SELECT * FROM centreon_acl WHERE centreon_acl.group_id IN ('
. $this->centreon->user->groupListStr . ') AND '
. ' centreon_acl.host_id = :host_id AND centreon_acl.service_id = :service_id)';
}
$stmt = $this->dbCentstorage->prepare($query);
$stmt->bindParam(':host_id', $params['host_id'], PDO::PARAM_INT);
$stmt->bindParam(':service_id', $params['service_id'], PDO::PARAM_INT);
$stmt->execute();
if (! ($service = $stmt->fetch(PDO::FETCH_ASSOC))) {
throw new Exception('Wrong parameter host_id/service_id or acl');
}
$stmt = $this->dbCentstorage->prepare(
'SELECT host_id, service_id, COUNT(*) AS num_metrics
FROM index_data, metrics
WHERE index_data.host_id = :host_id AND
index_data.service_id = :service_id AND
index_data.id = metrics.index_id
GROUP BY host_id, service_id'
);
$stmt->bindParam(':host_id', $params['host_id'], PDO::PARAM_INT);
$stmt->bindParam(':service_id', $params['service_id'], PDO::PARAM_INT);
$stmt->execute();
$service['num_metrics'] = 0;
if (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$service['num_metrics'] = $row['num_metrics'];
}
$service['service_state'] = $service['state'];
$service['state_str'] = $params['service_state'];
$service['last_state_change_duration'] = CentreonDuration::toString(
time() - $service['last_state_change']
);
$service['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $service['last_hard_state_change']
);
if (isset($params['last_service_state_change'])) {
$service['last_state_change_duration'] = CentreonDuration::toString(
time() - $params['last_service_state_change']
);
$service['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $params['last_service_state_change']
);
}
if (isset($params['service_output'])) {
$service['output'] = $params['service_output'];
}
if (isset($params['service_description'])) {
$service['description'] = $params['service_description'];
}
if (isset($params['host_name'])) {
$service['host_name'] = $params['host_name'];
}
if (isset($params['host_alias'])) {
$service['host_alias'] = $params['host_alias'];
}
return $service;
}
/**
* Get host information
*
* @param mixed $params
* @throws Exception
* @return mixed
*/
protected function getHostInformation($params)
{
$query = 'SELECT * FROM hosts WHERE hosts.host_id = :host_id';
if (! $this->centreon->user->admin) {
$query
.= ' AND EXISTS(
SELECT * FROM centreon_acl WHERE centreon_acl.group_id IN ('
. $this->centreon->user->groupListStr . ') AND '
. ' centreon_acl.host_id = :host_id)';
}
$stmt = $this->dbCentstorage->prepare($query);
$stmt->bindParam(':host_id', $params['host_id'], PDO::PARAM_INT);
$stmt->execute();
if (! ($host = $stmt->fetch(PDO::FETCH_ASSOC))) {
throw new Exception('Wrong parameter host_id or acl');
}
$host['host_state'] = $host['state'];
$host['state_str'] = $params['host_state'];
$host['last_state_change_duration'] = CentreonDuration::toString(
time() - $host['last_state_change']
);
$host['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $host['last_hard_state_change']
);
if (isset($params['last_host_state_change'])) {
$host['last_state_change_duration'] = CentreonDuration::toString(
time() - $params['last_host_state_change']
);
$host['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $params['last_host_state_change']
);
}
if (isset($params['host_output'])) {
$host['output'] = $params['host_output'];
}
if (isset($params['host_name'])) {
$host['name'] = $params['host_name'];
}
if (isset($params['host_alias'])) {
$host['alias'] = $params['host_alias'];
}
return $host;
}
/**
* Get provider class
*
* @param array $ruleInfo
* @throws Exception
* @return object
*/
protected function getProviderClass($ruleInfo)
{
$providerName = null;
foreach ($this->registerProviders as $name => $id) {
if (isset($ruleInfo['provider_id']) && $id == $ruleInfo['provider_id']) {
$providerName = $name;
break;
}
}
if (is_null($providerName)) {
throw new Exception('Provider not exist');
}
$file = $this->openTicketPath . 'providers/' . $providerName . '/' . $providerName . 'Provider.class.php';
if (! file_exists($file)) {
throw new Exception('Provider not exist');
}
require_once $file;
$classname = $providerName . 'Provider';
$providerClass = new $classname(
$this->rule,
$this->centreonPath,
$this->openTicketPath,
$ruleInfo['rule_id'],
null,
$ruleInfo['provider_id'],
$providerName
);
$providerClass->setUniqId($this->uniqId);
return $providerClass;
}
/**
* Get form values
*
* @param mixed $params
* @param mixed $groups
* @return array
*/
protected function getForm($params, $groups)
{
$form = ['title' => 'automate'];
if (isset($params['extra_properties']) && is_array($params['extra_properties'])) {
foreach ($params['extra_properties'] as $key => $value) {
$form[$key] = $value;
}
}
foreach ($groups as $groupId => $groupEntry) {
if (! isset($params['select'][$groupId])) {
if (count($groupEntry['values']) == 1) {
foreach ($groupEntry['values'] as $key => $value) {
$form['select_' . $groupId] = $key . '___' . $value;
if (
isset($groupEntry['placeholder'], $groupEntry['placeholder'][$key])
) {
$form['select_' . $groupId] .= '___' . $groupEntry['placeholder'][$key];
}
}
}
continue;
}
foreach ($groupEntry['values'] as $key => $value) {
if (
$params['select'][$groupId] == $key
|| $params['select'][$groupId] == $value
|| (
isset($groupEntry['placeholder'], $groupEntry['placeholder'][$key])
&& $params['select'][$groupId] == $groupEntry['placeholder'][$key]
)
) {
$form['select_' . $groupId] = $key . '___' . $value;
if (
isset($groupEntry['placeholder'], $groupEntry['placeholder'][$key])
) {
$form['select_' . $groupId] .= '___' . $groupEntry['placeholder'][$key];
}
}
}
}
return $form;
}
/**
* Submit provider ticket
*
* @param mixed $params
* @param array $ruleInfo
* @param array $contact
* @param array $host
* @param array $service
* @return array
*/
protected function submitTicket($params, $ruleInfo, $contact, $host, $service)
{
$providerClass = $this->getProviderClass($ruleInfo);
// execute popup to get extra listing in cache
$rv = $providerClass->getFormatPopup(
[
'title' => 'auto',
'user' => [
'name' => $contact['name'],
'alias' => $contact['alias'],
'email' => $contact['email'],
],
],
true
);
$form = $this->getForm($params, $rv['groups']);
$providerClass->setForm($form);
$rv = $providerClass->automateValidateFormatPopupLists();
if ($rv['code'] == 1) {
throw new Exception('please select ' . implode(', ', $rv['lists']));
}
// validate form
$rv = $providerClass->submitTicket(
$this->dbCentstorage,
$contact,
$host,
$service
);
if ($rv['ticket_is_ok'] == 0) {
throw new Exception('open ticket error');
}
$rv['chainRuleList'] = $providerClass->getChainRuleList();
$rv['providerClass'] = $providerClass;
return $rv;
}
/**
* Do rule chaining
*
* @param array $chainRuleList
* @param mixed $params
* @param array $contact
* @param array $host
* @param array $service
* @return void
*/
protected function doChainRules($chainRuleList, $params, $contact, $host, $service)
{
$loopCheck = [];
while (($ruleId = array_shift($chainRuleList))) {
$ruleInfo = $this->rule->getAliasAndProviderId($ruleId);
if (count($ruleInfo) == 0) {
continue;
}
if (isset($loopCheck[$ruleInfo['provider_id']])) {
continue;
}
$loopCheck[$ruleInfo['provider_id']] = 1;
$rv = $this->submitTicket($params, $ruleInfo, $contact, $host, $service);
array_unshift($chainRuleList, $rv['chainRuleList']);
}
}
/**
* Acknowledge, set macro and force check for a service
*
* @param object $providerClass
* @param string $ticketId
* @param array $contact
* @param array $service
* @return void
*/
protected function externalServiceCommands($providerClass, $ticketId, $contact, $service)
{
require_once $this->centreonPath . 'www/class/centreonExternalCommand.class.php';
$externalCmd = new CentreonExternalCommand();
$methodExternalName = 'set_process_command';
if (method_exists($externalCmd, $methodExternalName) == false) {
$methodExternalName = 'setProcessCommand';
}
$command = 'CHANGE_CUSTOM_SVC_VAR;%s;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$service['host_name'],
$service['description'],
$providerClass->getMacroTicketId(),
$ticketId
),
$service['instance_id'],
]
);
if ($providerClass->doAck()) {
$sticky = ! empty($this->centreon->optGen['monitoring_ack_sticky']) ? 2 : 1;
$notify = ! empty($this->centreon->optGen['monitoring_ack_notify']) ? 1 : 0;
$persistent = ! empty($this->centreon->optGen['monitoring_ack_persistent']) ? 1 : 0;
$command = 'ACKNOWLEDGE_SVC_PROBLEM;%s;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$service['host_name'],
$service['description'],
$sticky,
$notify,
$persistent,
$contact['alias'],
'open ticket: ' . $ticketId
),
$service['instance_id'],
]
);
}
if ($providerClass->doesScheduleCheck()) {
$command = 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;%d';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$service['host_name'],
$service['description'],
time()
),
$service['instance_id'],
]
);
}
$externalCmd->write();
}
/**
* Acknowledge, set macro and force check for a host
*
* @param object $providerClass
* @param string $ticketId
* @param array $contact
* @param array $host
* @return void
*/
protected function externalHostCommands($providerClass, $ticketId, $contact, $host)
{
require_once $this->centreonPath . 'www/class/centreonExternalCommand.class.php';
$externalCmd = new CentreonExternalCommand();
$methodExternalName = 'set_process_command';
if (method_exists($externalCmd, $methodExternalName) == false) {
$methodExternalName = 'setProcessCommand';
}
$command = 'CHANGE_CUSTOM_HOST_VAR;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$host['name'],
$providerClass->getMacroTicketId(),
$ticketId
),
$host['instance_id'],
]
);
if ($providerClass->doAck()) {
$sticky = ! empty($this->centreon->optGen['monitoring_ack_sticky']) ? 2 : 1;
$notify = ! empty($this->centreon->optGen['monitoring_ack_notify']) ? 1 : 0;
$persistent = ! empty($this->centreon->optGen['monitoring_ack_persistent']) ? 1 : 0;
$command = 'ACKNOWLEDGE_HOST_PROBLEM;%s;%s;%s;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$host['name'],
$sticky,
$notify,
$persistent,
$contact['alias'],
'open ticket: ' . $ticketId
),
$host['instance_id'],
]
);
}
if ($providerClass->doesScheduleCheck()) {
$command = 'SCHEDULE_FORCED_HOST_CHECK;%s;%d';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$host['name'],
time()
),
$host['instance_id'],
]
);
}
$externalCmd->write();
}
/**
* @param mixed $params
* @param string $macroName
* @return ?int $ticketId
*/
protected function getHostTicket($params, $macroName)
{
$stmt = $this->dbCentstorage->prepare(
'SELECT SQL_CALC_FOUND_ROWS mot.ticket_value AS ticket_id
FROM hosts h
LEFT JOIN customvariables cv ON (h.host_id = cv.host_id
AND (cv.service_id IS NULL or cv.service_id = 0)
AND cv.name = :macro_name)
LEFT JOIN mod_open_tickets mot ON cv.value = mot.ticket_value
WHERE h.host_id = :host_id'
);
$stmt->bindParam(':macro_name', $macroName, PDO::PARAM_STR);
$stmt->bindParam(':host_id', $params['host_id'], PDO::PARAM_INT);
$stmt->execute();
if (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$ticketId = $row['ticket_id'];
}
return $ticketId ?? null;
}
/**
* @param mixed $params
* @param string $macroName
* @return ?int $ticketId
*/
protected function getServiceTicket($params, $macroName)
{
$stmt = $this->dbCentstorage->prepare(
'SELECT SQL_CALC_FOUND_ROWS mot.ticket_value AS ticket_id
FROM services s
LEFT JOIN customvariables cv ON ( cv.service_id = :service_id AND cv.name = :macro_name)
LEFT JOIN mod_open_tickets mot ON cv.value = mot.ticket_value
WHERE s.service_id = :service_id'
);
$stmt->bindParam(':service_id', $params['service_id'], PDO::PARAM_INT);
$stmt->bindParam(':macro_name', $macroName, PDO::PARAM_STR);
$stmt->execute();
if (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$ticketId = $row['ticket_id'];
}
return $ticketId ?? null;
}
/**
* Reset the ticket custom macro for host
*
* @param string $macroName
* @param array $host
* @return void
*/
protected function changeMacroHost($macroName, $host)
{
require_once $this->centreonPath . 'www/class/centreonExternalCommand.class.php';
$externalCmd = new CentreonExternalCommand();
$methodExternalName = 'set_process_command';
if (method_exists($externalCmd, $methodExternalName) == false) {
$methodExternalName = 'setProcessCommand';
}
$command = 'CHANGE_CUSTOM_HOST_VAR;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$host['name'],
$macroName,
''
),
$host['instance_id'],
]
);
$externalCmd->write();
}
/**
* Reset the ticket custom macro for service
*
* @param string $macroName
* @param array $service
* @return void
*/
protected function changeMacroService($macroName, $service)
{
require_once $this->centreonPath . 'www/class/centreonExternalCommand.class.php';
$externalCmd = new CentreonExternalCommand();
$methodExternalName = 'set_process_command';
if (method_exists($externalCmd, $methodExternalName) == false) {
$methodExternalName = 'setProcessCommand';
}
$command = 'CHANGE_CUSTOM_SVC_VAR;%s;%s;%s;%s';
call_user_func_array(
[$externalCmd, $methodExternalName],
[
sprintf(
$command,
$service['host_name'],
$service['description'],
$macroName,
''
),
$service['instance_id'],
]
);
$externalCmd->write();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/class/rule.php | centreon-open-tickets/www/modules/centreon-open-tickets/class/rule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
class Centreon_OpenTickets_Rule
{
/** @var CentreonDB */
protected $_db;
protected $_provider = null;
/**
* Constructor
*
* @param CentreonDB $db
* @return void
*/
public function __construct($db)
{
$this->_db = $db;
}
public function getAliasAndProviderId($rule_id)
{
$result = [];
if (is_null($rule_id)) {
return $result;
}
$dbResult = $this->_db->query(
"SELECT alias, provider_id FROM mod_open_tickets_rule WHERE rule_id = '" . $rule_id . "' LIMIT 1"
);
if (($row = $dbResult->fetch())) {
$result['alias'] = $row['alias'];
$result['provider_id'] = $row['provider_id'];
}
return $result;
}
public function getUrl($rule_id, $ticket_id, $data, $widget_id)
{
$infos = $this->getAliasAndProviderId($rule_id);
$this->loadProvider($rule_id, $infos['provider_id'], $widget_id);
return $this->_provider->getUrl($ticket_id, $data);
}
public function getMacroNames($rule_id, $widget_id)
{
$result = ['ticket_id' => null];
if (! $rule_id) {
return $result;
}
$infos = $this->getAliasAndProviderId($rule_id);
if ($infos) {
$this->loadProvider($rule_id, $infos['provider_id'], $widget_id);
$result['ticket_id'] = $this->_provider->getMacroTicketId();
}
return $result;
}
/**
* @param CentreonDB|null $dbStorage
* @param string $cmd
* @param string $selection
*
* @return array<string, array>
*/
public function loadSelection(?CentreonDB $dbStorage, string $cmd, string $selection): array
{
global $centreon_bg;
if (is_null($dbStorage)) {
$dbStorage = new CentreonDB('centstorage');
}
$selected = ['host_selected' => [], 'service_selected' => []];
if (empty($selection)) {
return $selected;
}
$selectedValues = explode(',', $selection);
// cmd 3 = open ticket on services
if ($cmd == 3) {
$selectedStr = '';
$selectedStr2 = '';
$selectedStrAppend = '';
$queryParams = [];
$graphQueryParams = [];
foreach ($selectedValues as $key => $value) {
[$hostId, $serviceId] = explode(';', $value);
$selectedStr
.= $selectedStrAppend
. 'services.host_id = :host_id_' . $key
. ' AND services.service_id = :service_id_' . $key;
$selectedStr2 .= $selectedStrAppend
. 'host_id = :host_id_' . $key
. ' AND service_id = :service_id_' . $key;
$queryParams['host_id_' . $key] = $hostId;
$queryParams['service_id_' . $key] = $serviceId;
$graphQueryParams['host_id_' . $key] = $hostId;
$graphQueryParams['service_id_' . $key] = $serviceId;
$selectedStrAppend = ' OR ';
}
$query = <<<SQL
SELECT
services.*,
hosts.address,
hosts.state AS host_state,
hosts.host_id,
hosts.name AS host_name,
hosts.instance_id
FROM services
INNER JOIN hosts
ON services.host_id = hosts.host_id
WHERE ({$selectedStr})
SQL;
if (! $centreon_bg->is_admin) {
$aclGroupIdsCondition = '';
foreach (explode(',', str_replace("'", '', $centreon_bg->grouplistStr)) as $aclId) {
if (empty($aclGroupIdsCondition)) {
$aclGroupIdsCondition .= ':acl_' . $aclId;
} else {
$aclGroupIdsCondition .= ', :acl_' . $aclId;
}
$queryParams[':acl_' . $aclId] = (int) $aclId;
}
$query .= <<<SQL
AND EXISTS (
SELECT * FROM centreon_acl
WHERE centreon_acl.group_id IN ({$aclGroupIdsCondition})
AND hosts.host_id = centreon_acl.host_id
AND services.service_id = centreon_acl.service_id
)
SQL;
}
$graphQuery = <<<SQL
SELECT
host_id,
service_id,
COUNT(*) AS num_metrics
FROM index_data
INNER JOIN metrics
ON index_data.id = metrics.index_id
WHERE ({$selectedStr2})
GROUP BY host_id, service_id
SQL;
try {
$hostServiceStatement = $dbStorage->prepareQuery($query);
$dbStorage->executePreparedQuery($hostServiceStatement, $queryParams);
$graphStatement = $dbStorage->prepareQuery($graphQuery);
$dbStorage->executePreparedQuery($graphStatement, $graphQueryParams);
$graphData = [];
while (($row = $dbStorage->fetch($graphStatement))) {
$graphData[$row['host_id'] . '.' . $row['service_id']] = $row['num_metrics'];
}
while (($row = $dbStorage->fetch($hostServiceStatement))) {
$row['service_state'] = $row['state'];
$row['state_str'] = $this->getServiceStateStr($row['state']);
$row['last_state_change_duration'] = CentreonDuration::toString(
time() - $row['last_state_change']
);
$row['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $row['last_hard_state_change']
);
$row['num_metrics'] = $graphData[$row['host_id'] . '.' . $row['service_id']] ?? 0;
$selected['service_selected'][] = $row;
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'rule:loadSelection Error while retrieving hosts and services',
['selection' => $selection],
$e
);
return $selected;
}
// cmd 4 = open a ticket on hosts
} elseif ($cmd == 4) {
$hostsSelectedStr = '';
$hostsSelectedStrAppend = '';
$queryParams = [];
foreach ($selectedValues as $key => $value) {
[$hostId] = explode(';', $value);
$hostsSelectedStr .= $hostsSelectedStrAppend . ':host_id_' . $key;
$queryParams['host_id_' . $key] = $hostId;
$hostsSelectedStrAppend = ', ';
}
$query = <<<SQL
SELECT *
FROM hosts
WHERE host_id IN ({$hostsSelectedStr})
SQL;
if (! $centreon_bg->is_admin) {
$aclGroupIdsCondition = '';
foreach (explode(',', str_replace("'", '', $centreon_bg->grouplistStr)) as $aclId) {
if (empty($aclGroupIdsCondition)) {
$aclGroupIdsCondition .= ':acl_' . $aclId;
} else {
$aclGroupIdsCondition .= ', :acl_' . $aclId;
}
$queryParams[':acl_' . $aclId] = (int) $aclId;
}
$query .= <<<SQL
AND EXISTS (
SELECT * FROM centreon_acl
WHERE centreon_acl.group_id IN ({$aclGroupIdsCondition})
AND hosts.host_id = centreon_acl.host_id
)
SQL;
}
try {
$hostStatement = $dbStorage->prepareQuery($query);
$dbStorage->executePreparedQuery($hostStatement, $queryParams);
while (($row = $dbStorage->fetch($hostStatement))) {
$row['host_state'] = $row['state'];
$row['state_str'] = $this->getHostStateStr($row['state']);
$row['last_state_change_duration'] = CentreonDuration::toString(
time() - $row['last_state_change']
);
$row['last_hard_state_change_duration'] = CentreonDuration::toString(
time() - $row['last_hard_state_change']
);
$selected['host_selected'][] = $row;
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'rule:loadSelection Error while retrieving hosts and services',
['selection' => $selection],
$e
);
return $selected;
}
}
return $selected;
}
public function getFormatPopupProvider($rule_id, $args, $widget_id, $uniq_id, $cmd, $selection)
{
$infos = $this->getAliasAndProviderId($rule_id);
$this->loadProvider($rule_id, $infos['provider_id'], $widget_id, $uniq_id);
$selected = $this->loadSelection(null, (string) $cmd, (string) $selection);
$args['host_selected'] = $selected['host_selected'];
$args['service_selected'] = $selected['service_selected'];
return $this->_provider->getFormatPopup($args);
}
public function save($rule_id, $datas): void
{
$isTransactionActive = $this->_db->isTransactionActive();
$ruleId = (int) $rule_id;
try {
if (! $isTransactionActive) {
$this->_db->startTransaction();
}
$ruleExists = (bool) $this->_db->fetchOne(
query: <<<'SQL'
SELECT 1 FROM mod_open_tickets_rule WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
// Rule does not exist
if (! $ruleExists) {
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_rule (`alias`, `provider_id`, `provider_name`, `activate`)
VALUES (:ruleAlias, :providerId, :providerName, '1')
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('ruleAlias', $datas['rule_alias']),
QueryParameter::int('providerId', $datas['provider_id']),
QueryParameter::string('providerName', $datas['provider_name']),
])
);
$ruleId = $this->_db->lastInsertId();
} else {
$this->_db->update(
query: <<<'SQL'
UPDATE mod_open_tickets_rule
SET
`alias` = :ruleAlias,
`provider_id` = :providerId,
`provider_name` = :providerName
WHERE
rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('ruleAlias', $datas['rule_alias']),
QueryParameter::int('providerId', $datas['provider_id']),
QueryParameter::string('providerName', $datas['provider_name']),
QueryParameter::int('ruleId', $ruleId),
])
);
$this->_db->delete(
query: <<<'SQL'
DELETE FROM mod_open_tickets_form_clone WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
$this->_db->delete(
query: <<<'SQL'
DELETE FROM mod_open_tickets_form_value WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
}
foreach ($datas['simple'] as $uniq_id => $value) {
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_form_value (`uniq_id`, `value`, `rule_id`) VALUES (:uniqId, :value, :ruleId)
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('uniqId', $uniq_id),
QueryParameter::string('value', $value),
QueryParameter::int('ruleId', $ruleId),
])
);
}
foreach ($datas['clones'] as $uniq_id => $orders) {
foreach ($orders as $order => $values) {
foreach ($values as $key => $value) {
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_form_clone (`uniq_id`, `label`, `value`, `rule_id`, `order`)
VALUES (:uniqId, :label, :value, :ruleId, :order)
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('uniqId', $uniq_id),
QueryParameter::string('label', $key),
QueryParameter::string('value', $value),
QueryParameter::int('ruleId', $ruleId),
QueryParameter::int('order', $order),
])
);
}
}
}
if (! $isTransactionActive) {
$this->_db->commitTransaction();
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'An error occured while saving - updating open ticket rule',
[
'rule_id' => $ruleId,
]
);
if (! $isTransactionActive) {
try {
$this->_db->rollBackTransaction();
} catch (ConnectionException $rollbackException) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
"Rollback failed for open ticket rule save - update: {$rollbackException->getMessage()}",
[
'rule_id' => $ruleId,
]
);
throw new RepositoryException(
"Rollback failed for open ticket rule save - update: {$rollbackException->getMessage()}",
['rule_id' => $ruleId],
$rollbackException
);
}
}
throw new RepositoryException(
"Open Ticket rule save - update failed : {$exception->getMessage()}",
['rule_id' => $ruleId],
$exception
);
}
}
/**
* @return array<int, string>
*/
public function getRuleList()
{
try {
return $this->_db->fetchAllKeyValue(
query: <<<'SQL'
SELECT rule_id, alias FROM mod_open_tickets_rule ORDER BY alias
SQL
);
/**
* @var array<int, string>
*/
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
"An error occured while retrieving open ticket rules: {$exception->getMessage()}",
);
throw new RepositoryException(
message: "An error occured while retrieving open ticket rules: {$exception->getMessage()}",
previous: $exception->getPrevious()
);
}
}
public function get($ruleId)
{
$rule = [];
if (empty($ruleId)) {
return $rule;
}
try {
$queryParameters = QueryParameters::create([QueryParameter::int('ruleId', (int) $ruleId)]);
$rule = $this->_db->fetchAssociative(
query: <<<'SQL'
SELECT alias, provider_id FROM mod_open_tickets_rule WHERE rule_id = :ruleId
SQL,
queryParameters: $queryParameters
);
if (! $rule) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Could not get the rule as it does not exist',
customContext: ['rule_id' => $ruleId]
);
throw new RepositoryException('Could not get the rule as it does not exist');
}
$rule['clones'] = [];
$clonesQuery = <<<'SQL'
SELECT * FROM mod_open_tickets_form_clone WHERE rule_id = :ruleId ORDER BY uniq_id, `order` ASC
SQL;
foreach ($this->_db->iterateAssociative(query: $clonesQuery, queryParameters: $queryParameters) as $record) {
if (! isset($rule['clones'][$record['uniq_id']])) {
$rule['clones'][$record['uniq_id']] = [];
}
if (! isset($rule['clones'][$record['uniq_id']][$record['order']])) {
$rule['clones'][$record['uniq_id']][$record['order']] = [];
}
$rule['clones'][$record['uniq_id']][$record['order']][$record['label']] = $record['value'];
}
$formValueQuery = <<<'SQL'
SELECT * FROM mod_open_tickets_form_value WHERE rule_id = :ruleId
SQL;
foreach ($this->_db->iterateAssociative(query: $formValueQuery, queryParameters: $queryParameters) as $record) {
$rule[$record['uniq_id']] = $record['value'];
}
return $rule;
} catch (ValueObjectException|CollectionException|ConnectionException|RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
"An error occured while retrieving open ticket rule: {$exception->getMessage()}",
['rule_id' => $ruleId]
);
throw new RepositoryException(
message: "An error occured while retrieving open ticket rule: {$exception->getMessage()}",
previous: $exception->getPrevious()
);
}
}
/**
* Enable rules
*
* @param array $selectedRules
*/
public function enable($selectedRules): void
{
$this->_setActivate($selectedRules, 1);
}
/**
* Disable rules
*
* @param array $selectedRules
*/
public function disable($selectedRules): void
{
$this->_setActivate($selectedRules, 0);
}
/**
* Duplicate rules
*
* @param array $select
* @param array $duplicateNb
* @return void
*/
public function duplicate($select = [], $duplicateNb = []): void
{
// Do not attempt to do something if nothing has been selected.
if ($select === []) {
return;
}
$isTransactionActive = $this->_db->isTransactionActive();
$ruleIds = array_keys($select);
try {
if (! $isTransactionActive) {
$this->_db->startTransaction();
}
foreach ($ruleIds as $ruleId) {
$rule = $this->_db->fetchAssociative(
query: <<<'SQL'
SELECT
rule_id,
alias,
provider_id,
provider_name,
activate
FROM mod_open_tickets_rule
WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
if (! $rule) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Could not duplicate rule as it does not exist',
customContext: ['rule_id' => $ruleId]
);
throw new RepositoryException(
sprintf('Could not duplicate rule identified by ID %s as it does not exist', $ruleId),
);
}
$duplicationIndex = 1;
if (isset($duplicateNb[$ruleId]) && $duplicateNb[$ruleId] > 0) {
for ($duplicationNumber = 1; $duplicationNumber <= $duplicateNb[$ruleId]; $duplicationNumber++) {
$newName = sprintf('%s_%d', $rule['alias'], $duplicationNumber);
// Check that alias is not already in use
if ($this->isAliasAlreadyUsed($newName)) {
$duplicationIndex++;
continue;
}
// insert duplicated rule in database
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_rule (`alias`, `provider_id`, `provider_name`, `activate`)
VALUES (:ruleAlias, :providerId, :providerName, :activated)
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('ruleAlias', $newName),
QueryParameter::int('providerId', $rule['provider_id']),
QueryParameter::string('providerName', $rule['provider_name']),
QueryParameter::string('activated', $rule['activate']),
])
);
$duplicatedRuleId = $this->_db->lastInsertId('mod_open_tickets_rule');
// Get form values from initial rule
$ruleFormValues = $this->_db->fetchAllAssociative(
query: <<<'SQL'
SELECT * FROM mod_open_tickets_form_value WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
foreach ($ruleFormValues as $ruleFormValue) {
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_form_value (`uniq_id`, `value`, `rule_id`) VALUES (:uniqId, :value, :ruleId)
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('uniqId', $ruleFormValue['uniq_id']),
QueryParameter::string('value', $ruleFormValue['value']),
QueryParameter::int('ruleId', $duplicatedRuleId),
])
);
}
$ruleCloneValues = $this->_db->fetchAllAssociative(
query: <<<'SQL'
SELECT * FROM mod_open_tickets_form_clone WHERE rule_id = :ruleId
SQL,
queryParameters: QueryParameters::create([QueryParameter::int('ruleId', $ruleId)])
);
foreach ($ruleCloneValues as $ruleCloneValue) {
$this->_db->insert(
query: <<<'SQL'
INSERT INTO mod_open_tickets_form_clone (`uniq_id`, `label`, `value`, `rule_id`, `order`)
VALUES (:uniqId, :label, :value, :ruleId, :order)
SQL,
queryParameters: QueryParameters::create([
QueryParameter::string('uniqId', $ruleCloneValue['uniq_id']),
QueryParameter::string('label', $ruleCloneValue['label']),
QueryParameter::string('value', $ruleCloneValue['value']),
QueryParameter::int('ruleId', $duplicatedRuleId),
QueryParameter::int('order', $ruleCloneValue['order']),
])
);
}
}
}
}
if (! $isTransactionActive) {
$this->_db->commitTransaction();
}
} catch (ValueObjectException|CollectionException|ConnectionException|RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
"An error occured while duplicating open ticket rule(s): {$exception->getMessage()}",
['rule_ids' => $ruleIds]
);
if (! $isTransactionActive) {
try {
$this->_db->rollBackTransaction();
} catch (ConnectionException $rollbackException) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
"Rollback failed for open ticket rule duplication: {$rollbackException->getMessage()}",
['rule_ids' => $ruleIds]
);
throw new RepositoryException(
"Rollback failed for open ticket rule duplication: {$rollbackException->getMessage()}",
['rule_ids' => $ruleIds],
$rollbackException
);
}
}
throw new RepositoryException(
"Open Ticket rule duplication failed : {$exception->getMessage()}",
['rule_ids' => $ruleIds],
$exception
);
}
}
/**
* Delete rules
*
* @param array $select
*/
public function delete($select): void
{
$selectedRules = array_keys($select);
if ($selectedRules === []) {
return;
}
try {
$queryParameters = [];
$bindParams = [];
foreach ($selectedRules as $index => $ruleId) {
$queryParameters[] = QueryParameter::int('ruleId' . $index, $ruleId);
$bindParams[] = ':ruleId' . $index;
}
$bindQuery = implode(', ', $bindParams);
$this->_db->delete(
query: <<<SQL
DELETE FROM mod_open_tickets_rule WHERE rule_id IN ({$bindQuery})
SQL,
queryParameters: QueryParameters::create($queryParameters)
);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
"An error occured while deleting open ticket rule(s): {$exception->getMessage()}",
['rule_ids' => $selectedRules]
);
throw new RepositoryException(
"An error occured while deleting open ticket rule(s): {$exception->getMessage()}",
['rule_ids' => $selectedRules],
$exception
);
}
}
public function getHostgroup($filter)
{
$result = [];
$where = '';
if (! is_null($filter) && $filter != '') {
$where = " hg_name LIKE '" . $this->_db->escape($filter) . "' AND ";
}
$dbResult = $this->_db->query(
'SELECT hg_id, hg_name FROM hostgroup WHERE ' . $where . " hg_activate = '1' ORDER BY hg_name ASC"
);
while (($row = $dbResult->fetch())) {
$result[$row['hg_id']] = $row['hg_name'];
}
return $result;
}
public function getContactgroup($filter)
{
$result = [];
$where = '';
if (! is_null($filter) && $filter != '') {
$where = " cg_name LIKE '" . $this->_db->escape($filter) . "' AND ";
}
$dbResult = $this->_db->query(
'SELECT cg_id, cg_name FROM contactgroup WHERE ' . $where . " cg_activate = '1' ORDER BY cg_name ASC"
);
while (($row = $dbResult->fetch())) {
$result[$row['cg_id']] = $row['cg_name'];
}
return $result;
}
public function getServicegroup($filter)
{
$result = [];
$where = '';
if (! is_null($filter) && $filter != '') {
$where = " sg_name LIKE '" . $this->_db->escape($filter) . "' AND ";
}
$dbResult = $this->_db->query(
'SELECT sg_id, sg_name FROM servicegroup WHERE ' . $where . " sg_activate = '1' ORDER BY sg_name ASC"
);
while (($row = $dbResult->fetch())) {
$result[$row['sg_id']] = $row['sg_name'];
}
return $result;
}
public function getHostcategory($filter)
{
$result = [];
$where = '';
if (! is_null($filter) && $filter != '') {
$where = " hc_name LIKE '" . $this->_db->escape($filter) . "' AND ";
}
$dbResult = $this->_db->query(
'SELECT hc_id, hc_name
FROM hostcategories
WHERE ' . $where . " hc_activate = '1'
ORDER BY hc_name ASC"
);
while (($row = $dbResult->fetch())) {
$result[$row['hc_id']] = $row['hc_name'];
}
return $result;
}
public function getHostseverity($filter)
{
$result = [];
$where = '';
if (! is_null($filter) && $filter != '') {
$where = " hc_name LIKE '" . $this->_db->escape($filter) . "' AND ";
}
$dbResult = $this->_db->query(
'SELECT hc_id, hc_name
FROM hostcategories
WHERE ' . $where . " level IS NOT NULL
AND hc_activate = '1'
ORDER BY level ASC"
);
while (($row = $dbResult->fetch())) {
$result[$row['hc_id']] = $row['hc_name'];
}
return $result;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/class/request.php | centreon-open-tickets/www/modules/centreon-open-tickets/class/request.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
class CentreonOpenTicketsRequest
{
/** @var array */
protected $postVar = [];
/** @var array */
protected $getVar = [];
/**
* constructor
*
* @return void
*/
public function __construct()
{
foreach ($_POST as $key => $value) {
$this->postVar[$key] = $value;
}
foreach ($_GET as $key => $value) {
$this->getVar[$key] = $value;
}
}
/**
* Return value of requested object
*
* @param string $index
* @return mixed
*/
public function getParam($index)
{
return $this->getVar[$index] ?? $this->postVar[$index] ?? null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/php/uninstall.php | centreon-open-tickets/www/modules/centreon-open-tickets/php/uninstall.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 __DIR__ . '/clear_cache.php';
| 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.