<?php

/*
 * Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For more information : contact@centreon.com
 *
 */

if (! isset($centreon)) {
    exit();
}

function sanitizeShellString($string)
{
    $string = str_replace('\'', ' ', trim(urldecode($string)));
    $string = str_replace('`', ' ', $string);

    return str_replace('$(', '(', $string);
}

/**
 * Ack hosts massively
 * @param $key
 * @return string
 */
function massiveHostAck($key)
{
    global $pearDB, $is_admin, $centreon;
    static $processedHosts = [];

    $actions = $centreon->user->access->checkAction('host_acknowledgement');

    $key = urldecode($key);
    $tmp = preg_split("/\;/", $key);
    $hostName = $tmp[0];
    if (isset($processedHosts[$hostName])) {
        return null;
    }
    $processedHosts[$hostName] = true;

    $persistent = isset($_POST['persistent']) && $_POST['persistent'] == 'true' ? '1' : '0';
    $notify = isset($_POST['notify']) && $_POST['notify'] == 'true' ? '1' : '0';
    $sticky = isset($_POST['sticky']) && $_POST['sticky'] == 'true' ? '2' : '1';
    $force_check = isset($_POST['force_check']) && $_POST['force_check'] == 'true' ? '1' : '0';

    $_POST['comment'] = sanitizeShellString($_POST['comment']);

    $extCmdObj = new CentreonExternalCommand($centreon);

    if ($actions == true || $is_admin) {
        $extCmdObj->acknowledgeHost(
            $hostName,
            $sticky,
            $notify,
            $persistent,
            $_POST['author'],
            $_POST['comment']
        );

        if ($force_check == 1) {
            $extCmdObj->scheduleForcedCheckHost(
                $hostName
            );
        }
    }

    $actions = $centreon->user->access->checkAction('service_acknowledgement');
    if (
        ($actions == true || $is_admin)
        && isset($_POST['ackhostservice'])
        && $_POST['ackhostservice'] == 'true'
    ) {
        $statement = $pearDB->prepare('SELECT host_id FROM `host` WHERE host_name = :hostName LIMIT 1');
        $statement->bindValue(':hostName', $hostName, PDO::PARAM_STR);
        $statement->execute();
        $row = $statement->fetchRow();
        $svc_tab = getMyHostServices($row['host_id']);
        if (count($svc_tab)) {
            foreach ($svc_tab as $key2 => $value) {
                $extCmdObj->acknowledgeService(
                    $hostName,
                    $value,
                    $sticky,
                    $notify,
                    $persistent,
                    $_POST['author'],
                    $_POST['comment']
                );
                if (
                    $force_check == 1
                    && $centreon->user->access->checkAction('service_schedule_forced_check') == true
                ) {
                    $extCmdObj->scheduleForcedCheckService(
                        $hostName,
                        $value
                    );
                }
            }
        }
    }

    // Set param in memory
    set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $sticky);
    set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $notify);
    set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $persistent);
    set_user_param($centreon->user->user_id, $pearDB, 'force_check', $force_check);

    return _('Your command has been sent');
}

/**
 * Ack services massively
 * @param $key
 * @throws Exception
 * @return null|string
 */
function massiveServiceAck($key)
{
    global $pearDB, $is_admin, $centreon;

    $actions = $centreon->user->access->checkAction('service_acknowledgement');

    $key = urldecode($key);

    $tmp = preg_split("/\;/", $key);

    if (! isset($tmp[0])) {
        throw new Exception('No host found');
    }
    $hostName = $tmp[0];

    if (! isset($tmp[1])) {
        throw new Exception('No service found');
    }
    $serviceDescription = $tmp[1];

    $persistent = isset($_POST['persistent']) && $_POST['persistent'] == 'true' ? '1' : '0';
    $notify = isset($_POST['notify']) && $_POST['notify'] == 'true' ? '1' : '0';
    $sticky = isset($_POST['sticky']) && $_POST['sticky'] == 'true' ? '2' : '1';
    $force_check = isset($_POST['force_check']) && $_POST['force_check'] == 'true' ? '1' : '0';

    if ($actions == true || $is_admin) {
        $_POST['comment'] = sanitizeShellString($_POST['comment']);

        $extCmdObj = new CentreonExternalCommand($centreon);
        $extCmdObj->acknowledgeService(
            $hostName,
            $serviceDescription,
            $sticky,
            $notify,
            $persistent,
            $_POST['author'],
            $_POST['comment']
        );

        if ($force_check == 1 && $centreon->user->access->checkAction('service_schedule_forced_check') == true) {
            $extCmdObj->scheduleForcedCheckService(
                $hostName,
                $serviceDescription
            );
        }
        set_user_param($centreon->user->user_id, $pearDB, 'ack_sticky', $sticky);
        set_user_param($centreon->user->user_id, $pearDB, 'ack_notify', $notify);
        set_user_param($centreon->user->user_id, $pearDB, 'ack_persistent', $persistent);
        set_user_param($centreon->user->user_id, $pearDB, 'force_check', $force_check);

        return _('Your command has been sent');
    }

    return null;
}

/**
 * Sets host downtime massively
 * @param $key
 * @throws Exception
 * @return null
 */
function massiveHostDowntime($key)
{
    global $is_admin, $centreon;
    static $processedHosts = [];

    $actions = $centreon->user->access->checkAction('host_schedule_downtime');

    if ($actions == true || $is_admin) {
        $key = urldecode($key);

        $tmp = preg_split("/\;/", $key);
        if (! isset($tmp[0])) {
            throw new Exception('No host found');
        }

        $host_name = $tmp[0];
        if (isset($processedHosts[$host_name])) {
            return null;
        }
        $processedHosts[$host_name] = true;

        $start = isset($_POST['start']) && $_POST['start'] ? $_POST['start'] : time();
        $end = isset($_POST['end']) && $_POST['end'] ? $_POST['end'] : time();
        $comment = isset($_POST['comment']) && $_POST['comment'] ? sanitizeShellString($_POST['comment']) : '';
        $fixed = isset($_POST['fixed']) && $_POST['fixed'] == 'true' ? $fixed = 1 : $fixed = 0;
        $duration = isset($_POST['duration']) && $_POST['duration'] && is_numeric($_POST['duration'])
            ? $duration = $_POST['duration']
            : $duration = 0;
        $duration_scale = isset($_POST['duration_scale']) && $_POST['duration_scale']
            ? $duration_scale = $_POST['duration_scale']
            : $duration_scale = 's';
        $hostTime = isset($_POST['host_or_centreon_time']) && $_POST['host_or_centreon_time'] == 'true' ? '1' : '0';

        if ($duration > 0) {
            switch ($duration_scale) {
                default:
                case 's':
                    $duration = $duration;
                    break;
                case 'm':
                    $duration = $duration * 60;
                    break;
                case 'h':
                    $duration = $duration * 60 * 60;
                    break;
                case 'd':
                    $duration = $duration * 60 * 60 * 24;
                    break;
            }
        }

        $host = getMyHostID($host_name);

        $with_services = false;
        if (
            ($centreon->user->access->checkAction('service_schedule_downtime') == true)
            && isset($_POST['downtimehostservice'])
            && $_POST['downtimehostservice'] == 'true'
        ) {
            $with_services = true;
        }

        $extCmdObj = new CentreonExternalCommand($centreon);
        $extCmdObj->addHostDowntime($host, $comment, $start, $end, $fixed, $duration, $with_services, $hostTime);
    }

    return null;
}

// Sets service downtime massively
function massiveServiceDowntime($key)
{
    global $is_admin, $centreon;

    $actions = $centreon->user->access->checkAction('service_schedule_downtime');

    if ($actions == true || $is_admin) {
        $key = urldecode($key);
        $tmp = preg_split("/\;/", $key);

        if (! isset($tmp[0])) {
            throw new Exception('No host found');
        }
        $host_name = $tmp[0];

        if (! isset($tmp[1])) {
            throw new Exception('No service found');
        }
        $svc_description = $tmp[1];

        $start = isset($_POST['start']) && $_POST['start'] ? $_POST['start'] : time();
        $end = isset($_POST['end']) && $_POST['end'] ? $_POST['end'] : time();
        $comment = isset($_POST['comment']) && $_POST['comment'] ? sanitizeShellString($_POST['comment']) : '';
        $fixed = isset($_POST['fixed']) && $_POST['fixed'] == 'true' ? 1 : 0;
        $duration = isset($_POST['duration']) && $_POST['duration'] && is_numeric($_POST['duration'])
            ? $_POST['duration'] : 0;
        $duration_scale = isset($_POST['duration_scale']) && $_POST['duration_scale'] ? $_POST['duration_scale'] : 's';
        $hostTime = isset($_POST['host_or_centreon_time']) && $_POST['host_or_centreon_time'] == 'true' ? '1' : '0';

        if ($duration > 0) {
            switch ($duration_scale) {
                default:
                case 's':
                    $duration = $duration;
                    break;
                case 'm':
                    $duration = $duration * 60;
                    break;
                case 'h':
                    $duration = $duration * 60 * 60;
                    break;
                case 'd':
                    $duration = $duration * 60 * 60 * 24;
                    break;
            }
        }

        $host = getMyHostID($host_name);
        $service = getMyServiceID($svc_description, $host);

        $extCmdObj = new CentreonExternalCommand($centreon);
        $extCmdObj->addSvcDowntime($host, $service, $comment, $start, $end, $fixed, $duration, $hostTime);
    }

    return null;
}
