<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @filesource
 */
namespace seekquarry\yioop\views;

use seekquarry\yioop as B;
use seekquarry\yioop\configs as C;

/**
 * This view is used to display information about
 * the on/off state of the queue_servers and fetchers managed by
 * this instance of Yioop.
 *
 * @author Chris Pollett
 */
class MachinestatusView extends View
{
    /**
     * Instantiates a view for drawing the current status of media updater,
     * queue server, and fetchers in the  Yioop system
     * @param object $controller_object that is using this view
     */
    public function __construct($controller_object = null)
    {
        if (!empty($_REQUEST['noscript'])) {
            $this->layout = "web"; /*
                want whole rather than partial page if no Javascript
                calling context
                */
        }
        parent::__construct($controller_object);
    }
    /**
     * Draws the ManagestatusView to the output buffer
     *
     * @param array $data  contains on/off status info for each of the machines
     *     managed by this Yioop instance.
     */
    public function renderView($data)
    {
        $admin_url = htmlentities(B\controllerUrl('admin', true));
        $csrf_token = C\p('CSRF_TOKEN') . "=". $data[C\p('CSRF_TOKEN')];
        $base_url = "{$admin_url}a=manageMachines&amp;$csrf_token&amp;arg=";
        $log_url = $base_url ."log&amp;name=NAME_SERVER&type=MediaUpdater".
            "&id=0";
        $on_media_updater = $base_url . "update&amp;action=start&amp;".
            "name=NAME_SERVER&amp;type=MediaUpdater&amp;id=0";
        $off_media_updater = $base_url ."update&amp;action=stop&amp;".
            "name=NAME_SERVER&amp;type=MediaUpdater&amp;id=0";
        $name_server_update = $data['MEDIA_MODE']=='name_server';
        $update_mode_url = $base_url . "updatemode";
        $caution = !isset($data['MACHINES']['NAME_SERVER']["MediaUpdater"])
            || $data['MACHINES']['NAME_SERVER']["MediaUpdater"] == 0;
        $target = (empty($_REQUEST['noscript'])) ? "" : " target='_parent' ";
        $icon_helper = $this->helper('iconlink');
        ?>
        <h1 class="slim home-groups-container"><?=
        tl('machinestatus_view_machine_statuses')?></h1>
        <?php
        $name_server_services_help = (empty($_GET['noscript'])) ?
            $this->helper("helpbutton")->render(
            "Name Server Services", $data[C\p('CSRF_TOKEN')], true) : "";
        $mail_mode = $data['MAIL_MODE'] ?? "disabled";
        $show_mail_row = in_array($mail_mode, ['mailsite', 'both']);
        ?>
        <h2><?= tl('machinestatus_view_name_server_services') .
            "&nbsp;" . $name_server_services_help ?></h2>
        <table class="machine-services-table">
        <thead><tr>
            <th class="machine-services-name"><?=
                tl('machinestatus_view_service') ?></th>
            <th class="machine-services-log"><?=
                tl('machinestatus_view_log') ?></th>
            <th class="machine-services-toggle"><?=
                tl('machinestatus_view_status') ?></th>
        </tr></thead>
        <tbody>
            <tr>
                <td class="machine-services-name"><?=
                    tl('machinestatus_view_media_updater') ?><?php
                    $icon_helper->renderLink(
                        $base_url . 'mediajobs',
                        "media_jobs", "", false,
                        "icon-inline"); ?><?php
                    $icon_helper->renderLink(
                        $admin_url . "a=searchSources&amp;" .
                        $csrf_token,
                        "media_sources", "", false,
                        "icon-inline"); ?>
                </td>
                <td class="machine-services-log">
                    <a <?=$target?> href="<?= $log_url ?>"><?=
                    tl('machinestatus_view_log') ?></a>
                </td>
                <td class="machine-services-toggle"><?php
                    $this->helper("toggle")->render(
                    ($data['MACHINES']['NAME_SERVER']
                        ["MEDIA_UPDATER_TURNED_ON"] == 1),
                    $on_media_updater,
                    $off_media_updater, $caution); ?>
                </td>
            </tr>
            <?php
            if ($show_mail_row) {
                $mail_log_url = $base_url . "log&amp;" .
                    "name=NAME_SERVER&type=MailServer&id=0";
                $on_mail_server = $base_url .
                    "update&amp;action=start&amp;" .
                    "name=NAME_SERVER&amp;type=MailServer&amp;id=0";
                $off_mail_server = $base_url .
                    "update&amp;action=stop&amp;" .
                    "name=NAME_SERVER&amp;type=MailServer&amp;id=0";
                $mail_caution = !isset(
                    $data['MACHINES']['NAME_SERVER']["MailServer"])
                    || $data['MACHINES']['NAME_SERVER']
                    ["MailServer"] == 0;
                ?>
                <tr>
                    <td class="machine-services-name"><?=
                        tl('machinestatus_view_mail_server') ?><?php
                        $icon_helper->renderLink(
                            htmlentities(B\controllerUrl(
                            "user_mail", true)) . $csrf_token,
                            "mail", "", false,
                            "icon-inline"); ?>
                    </td>
                    <td class="machine-services-log">
                        <a <?=$target?> href="<?=
                        $mail_log_url ?>"><?=
                        tl('machinestatus_view_log') ?></a>
                    </td>
                    <td class="machine-services-toggle"><?php
                        $this->helper("toggle")->render(
                        ($data['MACHINES']['NAME_SERVER']
                            ["MAIL_SERVER_TURNED_ON"] == 1),
                        $on_mail_server,
                        $off_mail_server, $mail_caution); ?>
                    </td>
                </tr>
                <?php
            }
            ?>
        </tbody>
        </table>
        <?php
        $machine_info_help = (empty($_GET['noscript'])) ?
            $this->helper("helpbutton")->render(
            "Machine Information", $data[C\p('CSRF_TOKEN')], true) : "";
        $manage_machines_help = (empty($_GET['noscript'])) ?
            $this->helper("helpbutton")->render(
            "Manage Machines", $data[C\p('CSRF_TOKEN')], true) : "";
        if (count($data['MACHINES']) >= 1) {
            $data['TABLE_TITLE'] = tl('machinestatus_view_machines');
            $data['TABLE_TITLE_HELP'] = $machine_info_help;
            $data['ACTIVITY'] = 'manageMachines';
            $data['VIEW'] = $this;
            $data['TOGGLE_ID'] = 'add-machine-form';
            $data['FORM_TYPE'] = null;
            $data['NO_SEARCH'] = true;
            $data['NO_FLOAT_TABLE'] = false;
            ?><div class="paging-clearfix"><?php
            $this->helper("pagingtable")->render($data);
            ?></div><?php
        } ?>
        <div id='add-machine-form' class='box'>
        <h2><?= tl('machinestatus_view_add_machine') . "&nbsp;" .
            $manage_machines_help ?></h2>
        <form <?=$target ?> id="name-form" method="post">
        <input type="hidden" name="c" value="admin" >
        <input type="hidden" name="<?= C\p('CSRF_TOKEN') ?>" value="<?=
            $data[C\p('CSRF_TOKEN')] ?>" >
        <input type="hidden" name="a" value="manageMachines" >
        <input type="hidden" name="arg" value="addmachine" >
        <table class="name-table">
        <tr><th><label for="machine-name"><?=
            tl('machinestatus_view_machine_name') ?></label></th>
            <td><input type="text" id="machine-name" name="name"
                maxlength="<?= C\NAME_LEN ?>" class="wide-field" ></td>
        </tr>
        <tr><th><label for="machine-url"><?=
            tl('machinestatus_view_machineurl')?></label></th>
            <td><input type="url" id="machine-url" name="url"
                maxlength="<?=C\MAX_URL_LEN ?>" class="wide-field" ></td></tr>
        <tr><th><label for="channel-type"><?=
            tl('machinestatus_view_machine_channel_type')?></label></th>
            <td><?= $this->helper("options")->render("channel-type",
            "channel", $data['CHANNELS'], $data['CHANNEL'],
            "toggleReplica()");
            ?></td></tr>
         <tr id="m1"><th><label for="parent-machine-name"><?=
            tl('machinestatus_view_parent_name')?></label></th>
            <td><?= $this->helper("options")->render(
                "parent-machine-name", "parent",
                $data['PARENT_MACHINES'], $data['PARENT']); ?></td></tr>
        <tr id="m2"><th><label for="fetcher-number"><?=
            tl('machinestatus_view_num_fetchers')?></label></th><td>
            <?php $this->helper("options")->render("fetcher-number",
            "num_fetchers", $data['FETCHER_NUMBERS'],$data['FETCHER_NUMBER']);
            ?></td></tr>
        <tr><th></th><td><button class="button-box" type="submit"><?=
            tl('machinestatus_view_save') ?></button></td>
        </tr>
        </table>
        </form>
        </div>
        <?php
        foreach ($data['MACHINES'] as $k => $m) {
            if (!is_numeric($k)) {
                continue;
            }
            $on_queue_server = $base_url . "update&amp;name={$m['NAME']}".
                "&amp;channel={$m['CHANNEL']}&amp;type=QueueServer".
                "&amp;action=start";
            $off_queue_server = $base_url . "update&amp;name={$m['NAME']}".
                "&amp;channel={$m['CHANNEL']}&amp;type=QueueServer".
                "&amp;action=stop";
            $on_mirror = $base_url . "update&amp;name={$m['NAME']}".
                "&amp;type=Mirror&amp;action=start";
            $off_mirror = $base_url . "update&amp;name={$m['NAME']}".
                "&amp;type=Mirror&amp;action=stop";
            $on_media_updater = $base_url . "update&amp;action=start&amp;".
                "name={$m['NAME']}&amp;type=MediaUpdater&amp;id=0";
            $off_media_updater = $base_url ."update&amp;action=stop&amp;".
                "name={$m['NAME']}&amp;type=MediaUpdater&amp;id=0";
            $detail_label = empty($m['CHANNEL']) ?
                tl('machinestatus_view_channel', $m['CHANNEL']) :
                tl('machinestatus_view_parent', $m['PARENT']);
            ?>
            <div class="box machine-box">
            <details class="machine-details">
                <summary class="machine-summary"><?php
                    e($m['NAME']);
                    $icon_helper->renderLink(
                        $base_url . "deletemachine&amp;name={$m['NAME']}",
                        "delete", "", false,
                        "icon-inline"); ?>
                </summary>
                <div class="machine-details-body">
                    <span class="machine-detail-tag"><?=
                        $detail_label ?></span>
                    <span class="machine-detail-tag"><?=
                        e($m['URL']) ?></span>
                </div>
            </details>
            <?php
            if (!empty($m['STATUSES']) &&
                $m['STATUSES'] == 'NOT_CONFIGURED_ERROR') {
                ?>
                <p class="red"><?=
                    tl('machinestatus_view_not_configured') ?></p>
                </div><?php
                continue;
            }
            ?>
            <table class="machine-services-table"><tbody>
            <?php
            if (!empty($m['PARENT'])) {
                $log_url = $base_url . "log&name={$m['NAME']}".
                    "&type=Mirror&id=0";
                $caution = isset($m['STATUSES']['Mirror']) && (
                    !isset($m['STATUSES']['Mirror'][-1]) ||
                    !$m['STATUSES']['Mirror'][-1]);
                ?>
                <tr>
                    <td class="machine-services-name"><?=
                        tl('machinestatus_view_mirror', $m['PARENT'])
                        ?></td>
                    <td class="machine-services-log">
                        <a <?=$target?> href="<?php
                        e($log_url); ?>"><?=
                        tl('machinestatus_view_log') ?></a>
                    </td>
                    <td class="machine-services-toggle"><?php
                        $this->helper("toggle")->render(
                            isset($m['STATUSES']['Mirror']),
                            $on_mirror, $off_mirror, $caution); ?>
                    </td>
                </tr>
                </tbody></table></div><?php
                continue;
            }
            if (isset($m['CHANNEL']) && intval($m['CHANNEL']) >= 0) {
                $qs_log_url = $base_url . "log&name={$m['NAME']}".
                    "&channel={$m['CHANNEL']}&type=QueueServer&id=0";
                $caution =
                    isset($m['STATUSES']["QueueServer"][$m['CHANNEL']]) &&
                    !$m['STATUSES']["QueueServer"][$m['CHANNEL']];
                ?>
                <tr>
                    <td class="machine-services-name"><?=
                        tl('machinestatus_view_queue_server') ?></td>
                    <td class="machine-services-log">
                        <a <?=$target?> href="<?= $qs_log_url ?>"><?=
                        tl('machinestatus_view_log') ?></a>
                    </td>
                    <td class="machine-services-toggle"><?php
                        $this->helper("toggle")->render(
                            isset($m['STATUSES']["QueueServer"]
                                [$m['CHANNEL']]),
                            $on_queue_server, $off_queue_server,
                            $caution); ?>
                    </td>
                </tr>
                <?php
            } else {
                ?>
                <tr>
                    <td class="machine-services-name"><?=
                        tl('machinestatus_view_queue_server') ?></td>
                    <td class="machine-services-log">&nbsp;</td>
                    <td class="machine-services-toggle">
                        <span class="dim"><?= tl(
                        'machinestatus_view_no_queue_server')
                        ?></span>
                    </td>
                </tr>
                <?php
            }
            if (!$name_server_update) {
                $mu_log_url = $base_url . "log&name={$m['NAME']}".
                    "&channel={$m['CHANNEL']}&type=MediaUpdater&id=0";
                $caution = isset($m['STATUSES']["MediaUpdater"]) && (
                    !isset($m['STATUSES']["MediaUpdater"][-1]) ||
                    !$m['STATUSES']["MediaUpdater"][-1]);
                ?>
                <tr>
                    <td class="machine-services-name"><?=
                        tl('machinestatus_view_media_updater') ?></td>
                    <td class="machine-services-log">
                        <a <?=$target?> href="<?= $mu_log_url ?>"><?=
                        tl('machinestatus_view_log') ?></a>
                    </td>
                    <td class="machine-services-toggle"><?php
                        $this->helper("toggle")->render(
                            isset($m['STATUSES']["MediaUpdater"]),
                            $on_media_updater, $off_media_updater,
                            $caution); ?>
                    </td>
                </tr>
                <?php
            }
            if (empty($m['NUM_FETCHERS'])) {
                ?>
                <tr>
                    <td class="machine-services-name" colspan="3">
                        <span class="dim"><?= tl(
                        'machinestatus_view_no_fetchers') ?></span>
                    </td>
                </tr>
                <?php
            } else {
                for ($i = 0; $i < $m['NUM_FETCHERS']; $i++) {
                    $on_fetcher = $base_url . "update&amp;name={$m['NAME']}".
                        "&amp;action=start&amp;type=Fetcher&amp;id=$i".
                        "&amp;channel={$m['CHANNEL']}";
                    $off_fetcher = $base_url . "update&amp;name={$m['NAME']}".
                        "&amp;action=stop&amp;type=Fetcher&amp;id=$i".
                        "&amp;channel={$m['CHANNEL']}";
                    $fetcher_log_url = $base_url .
                        "log&amp;name={$m['NAME']}&amp;type=Fetcher&id=$i".
                        "&amp;channel={$m['CHANNEL']}";
                    $toggle_state = false;
                    $caution = false;
                    if (isset($m['STATUSES']["Fetcher"][$i])) {
                        $toggle_state = true;
                        $caution = ($m['STATUSES']["Fetcher"][$i] == 0);
                    }
                    $fetcher_label = sprintf("%s #%02d",
                        tl('machinestatus_view_fetchers'), $i);
                    ?>
                    <tr>
                        <td class="machine-services-name"><?=
                            $fetcher_label ?></td>
                        <td class="machine-services-log">
                            <a <?=$target?> href="<?=
                            $fetcher_log_url ?>"><?=
                            tl('machinestatus_view_log') ?></a>
                        </td>
                        <td class="machine-services-toggle"><?php
                            $this->helper("toggle")->render(
                                $toggle_state, $on_fetcher,
                                $off_fetcher, $caution); ?>
                        </td>
                    </tr>
                    <?php
                }
            }
            ?>
            </tbody></table>
            </div>
            <?php
        }
    }
}
