Menu="Notifications:3"
Title="Notification Agents"
Tag="rss-square"
---
<?php
/* Copyright 2005-2023, Lime Technology
 * Copyright 2012-2023, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<script>
var scripts = new Object();
var enabledAgents = new Object();
var disabledAgents = new Object();
var openPage = true;

<?$width = [166,300]?>
<?if ($tabbed):?>
$('#tab3').bind({click:function(){initDropdown();}});
$(function(){if ($('#tab3').is(':checked')) initDropdown();});
<?else:?>
$(function(){initDropdown();});
<?endif;?>

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined' ? args[number] : match;
    });
  };
}
function addSlashes(text) {
  return text.replace(/\"/g, "\\\"");
}
function prepareService(el, name) {
  var script = scripts[name];
  var vars = "";
  var form = $(el).parents('form:first');
  form.find('.variable').each(function() {
    vars += $(this).attr('name')+'="'+addSlashes($(this).val())+"\"\n";
  });
  $('[name="'+name+'"] [id^="slot_"]').each(function() {
    var include = '';
    $(this).find('option').each(function() {
      if ($(this).is(':selected')) {
        if (include.length) include += '\\n';
        include += $(this).val();
        $(this).removeAttr('selected');
      }
    });
    vars += $(this).attr('name')+'="'+include+"\"\n";
  });
  var cmd = (form.find('select[name="Enabled"]').val()=='yes' ? 'enable' : 'disable');
  form.find('input[name="#arg\\[1\\]"]').val(cmd);
  form.find('input[name="#arg\\[2\\]"]').val(name+'.sh');
  form.find('input[name="text"]').val(script.format(vars,'\n'));
}
function execCmd(cmd, name) {
  var form = $('#formExec');
  form.find('input[name="#arg\\[1\\]"]').val(cmd);
  if (name) form.find('input[name="#arg\\[2\\]"]').val(name+'.sh');
  form.submit();
}
function testService(name) {
  var form = $('#formExec');
  form.find('input[name="#arg\\[1\\]"]').val('test');
  form.find('input[name="#arg\\[2\\]"]').val(name+'.sh');
  form.append('<input type="hidden" name="#env[]" value="EVENT='+name+' test.">');
  form.append('<input type="hidden" name="#env[]" value="SUBJECT='+name+' test.">');
  form.append('<input type="hidden" name="#env[]" value="DESCRIPTION='+name+' test.">');
  form.append('<input type="hidden" name="#env[]" value="IMPORTANCE=normal">');
  // host is normally added to link by the notify script. add it here since calling the agent directly.
  form.append('<input type="hidden" name="#env[]" value="LINK='+window.location.origin+'/Settings/Notifications">');
  form.submit();
}
function initDropdown() {
  if (openPage) {$("[id^='slot_']").dropdownchecklist({width:<?=$width[1]?>,explicitClose:'..._(close)_'}); openPage = false;}
}
</script>
<form method="POST" id="formExec" action="/update.php" target="progressFrame">
<input type="hidden" name="#command" value="/webGui/scripts/agent">
<input type="hidden" name="#arg[1]" value="">
<input type="hidden" name="#arg[2]" value="">

</form>

<?php
$fields = ['Event','Subject','Timestamp','Description','Importance','Content','Link'];
$xml_files = glob("/usr/local/emhttp/plugins/dynamix/agents/*.xml");
$i = 1;
foreach ($xml_files as $xml_file) {
    $xml = @simplexml_load_file($xml_file);
    if (! $xml) {
        continue;
    }

    if (isset($xml->Language)) {
        $guiLanguage = ($locale == "") ? "en_US" : $locale;
        $acceptedLanguages = explode(" ", $xml->Language);
        if (! in_array($guiLanguage, $acceptedLanguages)) {
            continue;
        }
    }
    $name = str_replace(' ', '_', $xml->Name);
    $titleId = 'agent-' . strtolower($name);
    $enabledAgent = agent_fullname("$name.sh", "enabled");
    $disabledAgent = agent_fullname("$name.sh", "disabled");
    if (is_file($disabledAgent)) {
        $file = $disabledAgent;
        if (is_file($enabledAgent)) {
            unlink($enabledAgent);
        }
    } else {
        $file = $enabledAgent;
    }
    $values = [];
    $script = "";
    if (is_file($file)) {
        preg_match("/[#]{6,100}([^#]*?)[#]{6,100}/si", file_get_contents($file), $match);
        if (isset($match[1])) {
            foreach (explode(PHP_EOL, $match[1]) as $line) {
                if (strpos($line, "=")) {
                    [$k, $v] = my_explode("=", str_replace("\"", "", $line), 2);
                    $values[$k] = $v;
                }
            }
        }
    }
    foreach (explode(PHP_EOL, (string) $xml->Script) as $line) {
        if (trim($line)) {
            $script .= trim($line)."{1}";
        }
    }

    $displayName = str_replace('_', ' ', $name);
    $iconPath = "/plugins/dynamix/icons/" . strtolower(str_replace('_', '', $name)) . ".png";
    $isEnabled = is_file($enabledAgent);
    $statusClass = $isEnabled ? 'green' : 'red';
    $statusText = $isEnabled ? _("Enabled") : _("Disabled");
    ?>

<div id="<?= $titleId ?>" class="title">
    <span class="left">
        <img src="<?= $iconPath ?>" class="icon" style="height:16px;width:16px;">
        <?= $displayName ?>
    </span>
    <span class="right status">
        <span class="<?= $statusClass ?>"><?= $statusText ?></span>
    </span>
</div>

<form method="POST" name="<?= $name ?>" action="/update.php" target="progressFrame">
    <input type="hidden" name="#include" value="/webGui/include/update.file.php">
    <input type="hidden" name="#file" value="<?= $file ?>">
    <input type="hidden" name="#command" value="/webGui/scripts/agent">
    <input type="hidden" name="#arg[1]" value="">
    <input type="hidden" name="#arg[2]" value="">
    <input type="hidden" name="text" value="">

    <dl>
        <dt><?= _("Agent function") ?>:</dt>
        <dd>
            <select name="Enabled">
                <?= mk_option(is_file($disabledAgent), 'no', _('Disabled')) ?>
                <?= mk_option(is_file($enabledAgent), 'yes', _('Enabled')) ?>
            </select>
        </dd>
    </dl>

    <script>
        scripts["<?= $name ?>"] = <?= json_encode($script) ?>;
        enabledAgents["<?= $name ?>"] = "<?= $enabledAgent ?>";
        disabledAgents["<?= $name ?>"] = "<?= $disabledAgent ?>";
    </script>

    <?php foreach ($xml->Variables->children() as $v):
        $vName = preg_replace('#\[([^\]]*)\]#', '<$1>', (string) $v);
        $vDesc = ucfirst(strtolower(preg_replace('#\[([^\]]*)\]#', '<$1>', $v->attributes()->Desc)));
        $vDefault = preg_replace('#\[([^\]]*)\]#', '<$1>', $v->attributes()->Default);
        $vHelp = preg_replace('#\[([^\]]*)\]#', '<$1>', $v->attributes()->Help);
        $currentValue = isset($values[$vName]) ? $values[$vName] : $vDefault;
        $isTitleOrMessage = preg_match('/title|message/', $vDesc);
        ?>
        <dl>
            <dt><?= $vDesc ?>:</dt>
            <dd>
                <?php if ($isTitleOrMessage):
                    $value = str_replace('\n', ',', $currentValue);
                    ?>
                    <select id="slot_<?= $i++ ?>" name="<?= $vName ?>" multiple style="display:none">
                        <?php foreach ($fields as $field): ?>
                            <?= mk_option_check($value, '$'.strtoupper($field), _($field)) ?>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="text" name="<?= $vName ?>" class="variable" required value="<?= $currentValue ?>">
                <?php endif; ?>
            </dd>
        </dl>

        <?php if ($vHelp): ?>
            <blockquote class="inline_help"><?= $vHelp ?></blockquote>
        <?php endif; ?>
    <?php endforeach; ?>

    <dl>
        <dt>&nbsp;</dt>
        <dd>
            <div class="buttons-spaced">
              <input type="submit" value="<?= _("Apply") ?>" onclick="prepareService(this, '<?= $name ?>')" disabled>
              <input type="button" value="<?= _("Done") ?>" onclick="done()">

              <?php if (is_file($file)): ?>
                  <input type="button" value="<?= _("Delete") ?>" onclick="execCmd('delete','<?= $name ?>')">
                  <input type="button" value="<?= _("Test") ?>" onclick="testService('<?= $name ?>')"<?= $file == $enabledAgent ? '>' : ' disabled>' ?>
              <?php endif; ?>
            </div>
        </dd>
    </dl>
</form>

<?php
}
?>
