<?php


// in fcgi environments the rewrite rule in mailbeez_image_engine
// like
// RewriteRule ^([^.]+\.(jpg|png|gif))$ /mailhive.php/api/public/v1.0/editor/imgengine/?id=$1&type=$2&c=$0 [' . $parameters . ']
//
// gives "no input file specified"
//
// with changing to mailhive.php?/api...
// the rewrite rule works, but the PATH_INFO is not longer set
// so fix this and restore the correct $_SERVER variables
define('MAILHIVE_START_TIME', microtime(true));
define('MAILHIVE_START_MEMORY', memory_get_usage());

if (stristr($_SERVER['SERVER_SOFTWARE'], 'nginx') && (!isset($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '')) {
    // on NGINX there is no PATH_INFO or QUERY_STRING for urls like mailhive.php/api
    $requestUriString = $_SERVER['REQUEST_URI'];
    if (stristr($requestUriString, '?')) {
        list($requestUriString,) = explode('?', $requestUriString);
    }

    $pathInfo = str_replace($_SERVER['SCRIPT_NAME'], '', $requestUriString);

    $pathInfo = preg_replace('/^\/m/', '', $pathInfo);

    $_SERVER['PATH_INFO'] = $pathInfo; // /a=b

    if (stristr($pathInfo, '?')) {
        list($d, $queryString) = explode('?', $pathInfo);
        $_SERVER['QUERY_STRING'] = $queryString;
    }
}
// does not work reliable (?)
if (!isset($_SERVER['PATH_INFO']) && isset($_SERVER['ORIG_PATH_INFO'])) {
    // works for danijel
    $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
}


if (!isset($_SERVER['PATH_INFO']) && isset($_SERVER['QUERY_STRING'])) {
    if (stristr($_SERVER['QUERY_STRING'], '?')) {
        list($path, $query) = explode('?', $_SERVER['QUERY_STRING']);
        $_SERVER['PATH_INFO'] = $path;
        $_SERVER['QUERY_STRING'] = $query;
        parse_str($query, $get_array);
        $_GET = array_merge($_GET, $get_array);
    } else {
        $_SERVER['PATH_INFO'] = $_SERVER['QUERY_STRING'];
    }
} elseif (!isset($_SERVER['PATH_INFO'])) {
    // works on estugo
    $_SERVER['PATH_INFO'] = $_SERVER['QUERY_STRING'];
}


// set MH_ROOT_PATH
if (!defined('MH_ROOT_PATH')) {
    // default location
    $_MH_ROOT_PATH = 'mailhive/';
    $_mh_search_paths = array('mailhive/', 'ext/mailhive/', 'includes/external/mailhive/');

    foreach ($_mh_search_paths as $_MH_ROOT_PATH_TRY) {
        if (file_exists($_MH_ROOT_PATH_TRY . 'cloudbeez/cloudloader_core.php')) {
            $_MH_ROOT_PATH = $_MH_ROOT_PATH_TRY;
            break;
        }
    }

    define('MH_ROOT_PATH', $_MH_ROOT_PATH);
}


function mh_sanitize_url($array)
{
    $array = str_ireplace(array('select', 'count(', 'from', 'concat', 'schema', 'where', 'table', 'limit', 'script', 'onload', '<svg'), '', $array);
    return $array;
}


$_GET = mh_sanitize_url($_GET);


// sitezen direct api

if (isset($_SERVER['HTTP_X_SITEZEN_TOKEN'])) {
    $sitezen_api_file = MH_ROOT_PATH . 'configbeez/config_sitezen/includes/inc_sitezen_bootstrap.php';
    if (file_exists($sitezen_api_file)) {
        include($sitezen_api_file);
        exit();
    }
    header('X-SiteZen-Status: 403');
    header((isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0') . ' 401 Unauthorized');
    exit();
}



// sitebeez direct api
if (isset($_GET['sitebeez'])) {
    $sitebeez_api_file = MH_ROOT_PATH . 'configbeez/config_sitebeez/includes/inc_sitebeez_widgets.php';
    if (file_exists($sitebeez_api_file)) {
        include($sitebeez_api_file);
    } else {
        header((isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0') . ' 400 Bad Request');
    }
    exit();
}

// message event API call
// GET ?mi - open
// GET ?mid - click/order


if (!isset($_GET['ma'])
    // todo
    // find solution to track with api call e.g. api/public/v1.0/newsletter/confirm/...?mid=123
    && !(stristr($_SERVER['PATH_INFO'], 'api/public') || stristr($_SERVER['PATH_INFO'], 'api/private') || stristr($_SERVER['PATH_INFO'], 'api/internal'))
) {
// ignore mid parameter if action is called
    if ((isset($_GET['mid'])) ||
        isset($_GET['mi']) && (!isset($_GET['n2go_rid']) ||
            (isset($_GET['n2go_rid']) && ($_GET['n2go_rid'] != '{{recipient.id}}') && $_GET['n2go_rid'] != ''))
    ) {

        $dirTmp = getcwd();
        $dirTmp = $_SERVER['DOCUMENT_ROOT'] . '/' . $dirTmp;
        $store_basedir = '';
        if (strlen(substr($dirTmp, strlen($_SERVER['DOCUMENT_ROOT']) + 1)) > 0) {
            $store_basedir = substr($dirTmp, strlen($_SERVER['DOCUMENT_ROOT']) + 1) . "/";
        }
        require_once($store_basedir . MH_ROOT_PATH . 'common/classes/clicktracker.php');

        // API event processed
        if (mb_clicktracker::record_event($store_basedir)) {
            // output of image or json
            // stop processing

            exit();
        }

    }
}


// disable Gzip compression
define('GZIP_COMPRESSION', 'false');
define('GZIP_LEVEL', '0');

$mh_module_request = false;
if (isset($_GET["module"])) {
    $mh_module_request = $_GET["module"];
}

// zencart 1.5.8 filters some query parameters, e.g. 'id' used by image engine in
// includes/init_includes/init_sanitize.php


if (isset($_REQUEST['id'])) {
    $_REQUEST['img_id'] = $_REQUEST['id'];
}

// some modifications will look for q parameter in the url and do some fancy stuff...

if (isset($_GET['q'])) {
    $_GET['q_sub'] = $_GET['q'];
    unset($_GET['q']);
}

if (!isset($_SESSION['languages_id'])) {
    // "message": "Undefined array key \"languages_id\"",
    //"file": "/inc/get_href_link.inc.php",
    $_SESSION['languages_id'] = -1;
}

require_once('includes/application_top.php');


if (isset($_GET['q_sub'])) {
    $_GET['q'] = $_GET['q_sub'];
    unset($_GET['q_sub']);
}


// the get parameter can contain / which might get filtered
// restore original request
if ($mh_module_request) {
    $_REQUEST["module"] = $mh_module_request;
    $_GET["module"] = $_REQUEST["module"];
}


// Error reporting
//define('STRICT_ERROR_REPORTING', true); // zencart

// todo: make configurable
//error_reporting(E_ALL & ~E_NOTICE);
//error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_STRICT);
//ini_set('display_errors', 0);
ini_set('display_errors', 1);

if (!defined('MH_DIR_FS_CATALOG')) {
    if (substr(constant('DIR_FS_CATALOG'), -1) != '/') {
        define('MH_DIR_FS_CATALOG', DIR_FS_CATALOG . '/');
    } else {
        define('MH_DIR_FS_CATALOG', DIR_FS_CATALOG);
    }
}


require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/compatibility.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailhive.php');
$request_profiler->restart('mailhive_1');


if (mh_get('job')) {

    switch (mh_get('job')) {
        case 'analytics':
            require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/clicktracker.php');
            $tracker = new mb_clicktracker();
            // API event processed
            $silent = false;
            $log = array();
            $log['open'] = $tracker->import_open_log_file($silent);
            $log['click'] = $tracker->import_click_log_file($silent);
            $log['order'] = $tracker->import_order_log_file($silent);
            $log['coupon'] = $tracker->consolidate_coupon_data($silent);
            mb_clicktracker::outputSuccess('json', $silent, $log);
            exit();
            break;
    }
}


function mh_restoreLng()
{
    if (isset($_SESSION['languages_id_backup'])) {
        $_SESSION['languages_id'] = $_SESSION['languages_id_backup'];
        unset($_SESSION['languages_id_backup']);
    }
}


if (mh_get('memtest')) {


    function loadmem($howmuchmeg)
    {
        $a = str_repeat("0", $howmuchmeg * 1024 * 1024); // alocating 10 chars times million chars
        return $a;
    }


    $memory_limit = ini_get('memory_limit');
    echo "configured Memory Limit: $memory_limit <hr>";
    echo "Current Memory Usage: " . number_format(memory_get_usage() / 1024 / 1024, 2) . "M <hr>";
    echo "testing real memory limit by adding up to 1024M...<br><br>";
    for ($i = 1; $i < 1024; $i++) {
        //echo "used memory is " . memory_get_usage() . "<br/>";
        $a = loadmem($i);
        //echo "used memory after allocating ".$i."m is " . memory_get_usage() . "<br/>"; // 57960
        //echo "used memory after unsetting allocated memory is " . memory_get_usage() . "<br/>"; // 36744
        echo "Allocating additional " . $i . "M (" . memory_get_usage() . ") memory - OK" . "<br />";
        unset($a);
    }

    mh_restoreLng();
    exit();
}


if (isset($_POST['cldbz'])) {
    // cloudbeez api call

    require_once(MH_DIR_CONFIG . 'config_cloudbeez/classes/api_cloudbeez_provider.php');
    $api = new cloudBeezApiProvider();
    $api->run();
    mh_restoreLng();
    mh_exit();
}


if (stristr($_SERVER['PATH_INFO'], 'api/public') || stristr($_SERVER['PATH_INFO'], 'api/private') || stristr($_SERVER['PATH_INFO'], 'api/internal')) {
    // api call
    require_once(MH_DIR_CONFIG . 'config_api/api.php');
    $api = new mailbeezApi;
    $api->processApi();
    mh_restoreLng();
    mh_exit();
}

$request_profiler->restart('top_load_application_top');

// todo
// language constants
define('TEXT_EMAIL_ALREADY_SEND', 'was already sent: ');
define('TEXT_EMAIL_SEND', 'successfully sent: ');
define('TEXT_EMAIL_SEND_FAILED', 'FAILED - email was not sent due to an error - check email_failed.log: ');
define('TEXT_EMAIL_SEND_FAILED_MSG', 'FAILED - email was not sent due to an error: ');
define('TEXT_EMAIL_BLOCKED', 'blocked by customer: ');
define('TEXT_EMAIL_FILTER_BLOCKED', 'blocked by filter: ');
define('TEXT_EMAIL_VALID_BLOCKED', 'blocked by validation: ');
define('TEXT_EMAIL_FILTER_STOP', 'stopped by filter: ');
define('TEXT_EMAIL_BOUNCE_BLOCKED', 'blocked by bounce handler: ');
define('TEXT_EMAIL_SUBSCRIPTION_BLOCKED', 'blocked by subscription check: ');
$cfg_gender_array = array('f' => 'Female', 'm' => 'Male', 'unknown' => 'unknown');


if (!mh_cfg('MAILBEEZ_VERSION')) {
    include(mh_cfg('MH_DIR_FS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'install/install.php');
    mh_restoreLng();
    exit();
}

if (mh_cfg('MAILBEEZ_MAILHIVE_PROCESS_CONTROL_MEMORY_LIMIT')) {
    ini_set('memory_limit', mh_cfg('MAILBEEZ_MAILHIVE_PROCESS_CONTROL_MEMORY_LIMIT'));
}

if (!ini_get('safe_mode')) {
    if (mh_cfg('MAILBEEZ_MAILHIVE_PROCESS_CONTROL_TIME_LIMIT')) {
        // eventually disabled
        @set_time_limit((int)mh_cfg('MAILBEEZ_MAILHIVE_PROCESS_CONTROL_TIME_LIMIT'));
    }
}

if (mh_cfg('MAILBEEZ_MAILHIVE_PROCESS_CONTROL_INGORE_USER_ABORT') == 'True') {
    ignore_user_abort(true);
}

$module = '';

if (mh_get('module')) {
    $_GET['module'] = mh_urlencode(mh_get('module')); // handling of submodule urls with "/"
    $module = mh_get('module');
}
//error_reporting(-1);


$request_profiler->restart('mailhive_3');
$mailHive = new mailHive($module, isset($_GET['mi']));
$request_profiler->restart('mailhive_4');


$mailhive_token = mh_cfg('MAILBEEZ_MAILHIVE_TOKEN');

if (mh_cfg('MAILBEEZ_CONFIG_SIMULATION_ENABLE_AUTOMATION') == 'True' || mh_cfg('MAILBEEZ_MAILHIVE_MODE') == 'production') {

// for cron simple plugin:
    if (mh_get('cron_simple')) {
        $inc_cron_path = MH_DIR_CONFIG . 'config_cron_simple/includes/cron_simple_run.php';
        if (file_exists($inc_cron_path)) {
            require_once($inc_cron_path);
        }
        mh_restoreLng();
        mh_exit();
    }


// for cron advanced plugin:
    if (mh_get('cron_advanced')) {
        $inc_cron_path = MH_DIR_CONFIG . 'config_cron_advanced/includes/cron_advanced_run.php';
        if (file_exists($inc_cron_path)) {
            require_once($inc_cron_path);
        }
        mh_restoreLng();
        mh_exit();
    }
}


// call external module action e.g. block
if (mh_get('ma')) {
    $module_action = mh_get('ma');
    $module = mh_get('m', false);
    $module_params = mh_get('mp', false);
    $result = $mailHive->moduleAction($module, 'external_' . $module_action, $module_params);
}

$mpaction = '';

if (mh_get($mailhive_token)) {
    $mpaction = mh_get($mailhive_token);
} elseif (mh_post($mailhive_token)) {
    $mpaction = mh_post($mailhive_token);
}


$silent_mode = mh_get('silent') ? true : false;

$output_plain = false;

$title_type = 'default';
$showMailBeezTitle = false;

if ($mpaction == 'view') {
    if (mh_get('module', '') != '') {
        $output_plain = true;
    } else {
        $title_type = 'choose_module';
    }
}

if ($mpaction == 'listLangView' || $mpaction == 'listLangTest') {
    $title_type = 'choose_lang';
}

if ($mpaction == 'listGndView' || $mpaction == 'listGndTest') {
    $title_type = 'choose_gender';
}

if ($mpaction == 'test') {
    if (!mh_get('module')) {
        $title_type = 'choose_module';
    }
}

if (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') {
    if (!mh_get('lng_id', false)) {
        if ($mpaction == 'test') {
            mh_redirect(mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'listLangTest&' . mh_get_all_get_params(array(mh_cfg('MAILBEEZ_MAILHIVE_TOKEN'))));
        } elseif ($mpaction == 'view') {
            mh_redirect(mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'listLangView&' . mh_get_all_get_params(array(mh_cfg('MAILBEEZ_MAILHIVE_TOKEN'))));
        }
    }
}
if (mh_cfg('MAILBEEZ_FILTER_ADD_GENDER_STATUS') == 'True') {
    if (!mh_get('gnd')) {
        if ($mpaction == 'test' || $mpaction == 'test') {
            mh_redirect(mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'listGndTest&' . mh_get_all_get_params(array(mh_cfg('MAILBEEZ_MAILHIVE_TOKEN'))));
        } elseif ($mpaction == 'view') {
            mh_redirect(mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'listGndView&' . mh_get_all_get_params(array(mh_cfg('MAILBEEZ_MAILHIVE_TOKEN'))));
        }

    }
}

if ($silent_mode == true) {
    ob_start();
    ob_start(); // ob_flush is called in process- method
}

if ($output_plain == false) {

    // todo
    // load using smarty
    // {include file="main_common_js.tpl"}
    // {include file="main_common_ceebox.tpl"}

    ?>
    <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html <?php echo mh_cfg('HTML_PARAMS'); ?>>
    <head>
        <base href="<?php echo MH_CATALOG_SERVER; ?>">

        <meta http-equiv="Content-Type"
              content="text/html; charset=<?php echo ($mpaction == 'view') ? mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET') : mh_cfg('CHARSET'); ?>">
        <meta name="robots" content="noindex">

        <title>MAILHIVE MEMORY <?php echo ini_get('memory_limit'); ?></title>
        <link rel="stylesheet" type="text/css" media="print, projection, screen"
              href="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/common.css?ver=<?php echo mh_cfg('MAILBEEZ_VERSION'); ?>">

        <?php
        switch ($mpaction) {
            case 'sendTest':
            case 'run':
                break;
            default:
                $smarty = new mh_Smarty;
                $smarty->setTemplateDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/templates/');
                $smarty->assign(array('MH_CATALOG_URL' => MH_CATALOG_SERVER . MH_DIR_WS_CATALOG,
                    'MH_ROOT_PATH' => MH_ROOT_PATH,
                    'MAILBEEZ_VERSION' => mh_cfg('MAILBEEZ_VERSION'),
                    'MAILBEEZ_MAILHIVE_POPUP_MODE' => mh_cfg('MAILBEEZ_MAILHIVE_POPUP_MODE'),
                    'MAILBEEZ_CIS_URL' => mh_cfg('MH_CIS_URL'),
                ));
                $main_js = $smarty->fetch('main_common_js.tpl');
                $main_ceebox = $smarty->fetch('main_common_ceebox.tpl');

                ?>
                <script language="javascript"
                        src="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/jquery-1.11.3.min.js?ver=<?php echo mh_cfg('MAILBEEZ_VERSION'); ?>"></script>
                <script src="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/jquery-migrate-1.4.1.js"></script>

            <?php
            echo $main_js;
            echo $main_ceebox;
            ?>

                <link rel="stylesheet" type="text/css" media="print, projection, screen"
                      href="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/vendor/bootstrap/css/bootstrap.min.css?ver=<?php echo mh_cfg('MAILBEEZ_VERSION'); ?>">
                <link rel="stylesheet" type="text/css" media="print, projection, screen"
                      href="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/css/font-awesome/css/font-awesome.min.css?ver=<?php echo mh_cfg('MAILBEEZ_VERSION'); ?>">


                <script language="javascript"
                        src="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/jquery-migrate-1.2.1.min.js"></script>
                <script language="javascript"
                        src="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/ceebox/js/jquery.ceebox.min.js?ver=<?php echo mh_cfg('MAILBEEZ_VERSION'); ?>"></script>

                <link rel="stylesheet" type="text/css"
                      href="<?php echo mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH'); ?>common/js/ceebox/css/ceebox_mh.css"/>

                <?php
                break;
        }
        ?>


    </head>
    <body style="padding: 10px;">
    <a name="top"></a>
    <script type="text/javascript">
        function scrolldown() {
            var a = document.anchors.length;
            var b = document.anchors[a - 1];
            var y = b.offsetTop;
            window.scrollTo(0, y + 120);
        }
    </script>
<?php switch ($title_type) {
case 'choose_module':
?>
    <h3 style="text-align: center">
        <?php echo mh_lng('MAILBEEZ_MAILHIVE_CHOOSE_MODULE_TITLE', 'Choose Module'); ?><br><br>
    </h3>
    <?php
    break;
case 'choose_lang':
    ?>
    <h3 style="text-align: center">
        <?php echo mh_lng('MAILBEEZ_MAILHIVE_CHOOSE_LANG_TITLE', 'Choose Language'); ?><br><br>
    </h3>
    <?php
    break;
case 'choose_gender':
    ?>

    <h3 style="text-align: center">
        <?php echo mh_lng('MAILBEEZ_MAILHIVE_CHOOSE_GENDER_TITLE', 'Choose Gender'); ?><br><br>
    </h3>
<?php
break;
default:
    ?>

<?php
} ?>
<?php if ($showMailBeezTitle) { ?>
    <div class="pageHeading">MailBeez - Mode: <?php echo mh_cfg('MAILBEEZ_MAILHIVE_MODE') ?></div>
    <?php //echo (defined('PROJECT_VERSION')) ? mh_cfg('PROJECT_VERSION') : '';?>

<hr size="1" noshade>
<?php } ?>

    <?php

}

if (mh_cfg('MAILBEEZ_MAILHIVE_STATUS') == 'False') {
    ?>
    MailHive inactive - please activate MailHive and MailBeez in Basic Configuration
    <?php

} else {

    if ($mpaction == 'test') {
        if (mh_get('module', '') != '') {
            ?>
            <div style="text-align: center; ">
                <div __class="panel panel-default">
                    <div __class="panel-heading">
                        <h3 __class="panel-title">
                            <?php echo mh_lng('MAILBEEZ_MAILHIVE_SEND_TEST_TITLE', 'Send Test-Mail') ?>
                        </h3>
                    </div>
                    <div __class="panel-body">
                        <div style="padding: 20px; width: 70%; margin: auto auto 30px;">
                            <?php echo mh_lng('MAILBEEZ_MAILHIVE_SEND_TEST_TEXT', 'Quickly send a test email to an email address of your choice. The system will fill in Test-Data for e.g. the Name of the recipient.'); ?>
                        </div>
                        <?php echo mh_draw_form('test', mh_href_link_mailhive(mh_get_all_get_params(array('module', $mailhive_token)), 'NONSSL'), 'post', '') .
                            mh_draw_hidden_field($mailhive_token, 'sendTest') .
                            mh_draw_hidden_field('module', mh_get('module')); ?>

                        <div class="form-inline">

                            <div class="form-group"
                                 style="display: inline-block; margin-bottom: 0px; vertical-align: middle;">
                                <label class="sr-only" for="email">Email</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" size="30" name="email" id="email"
                                           value="<?php echo mh_cfg('MAILBEEZ_MAILHIVE_EMAIL_COPY'); ?>">
                                </div>
                            </div>
                            <button type="submit"
                                    class="btn btn-primary">
                                <i class="fa fa-paper-plane" style="padding-right: 5px"></i>

                                <?php echo mh_lng('MAILBEEZ_MAILHIVE_SEND_TEST_BUTTON', 'Send Test-Mail') ?></button>
                        </div>

                        <!--                    </div>-->
                        <!--                     --><?php //echo mh_draw_input_field('email', mh_cfg('MAILBEEZ_MAILHIVE_EMAIL_COPY')) ?>
                        <!--                    <input  class="btn btn-primary" type="Submit" value="-->
                        <?php //echo mh_lng('MAILBEEZ_MAILHIVE_SEND_TEST_BUTTON', 'Send Test-Mail') ?><!--">-->
                        </form>
                        <br>
                        <br>
                        <?php if (mh_cfg('MAILBEEZ_MAILHIVE_COPY') == 'True') { ?>
                            <div style="padding: 10px;">
                                <?php echo mh_lng('MAILBEEZ_MAILHIVE_EMAIL_COPY_TEXT', 'Send Copy to') ?>:
                                <?php echo mh_cfg('MAILBEEZ_MAILHIVE_EMAIL_COPY') ?>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
            <?php

        } else {
            if (!is_array($mailHive->modules)) {
                ?>
                No Modules installed
                <?php

            } else {
                reset($mailHive->modules);
                foreach ($mailHive->modules as $idx => $mailbee_obj) {
                    $obj_code = substr($mailbee_obj, 0, strrpos($mailbee_obj, '.'));
                    $mailbeez_obj = $GLOBALS[$obj_code];
                    if (!$mailbeez_obj->do_process) continue;
                    if (!$mailbeez_obj->allow_preview) continue;
                    if ($mailbeez_obj->hidden) continue;
//                    print_r($mailbeez_obj);
                    ?>

                    <div style="text-align: center">
                        <a class="btn btn-default btn-primary_ btn-block "
                           style="margin-bottom: 10px; min-width: 50%; text-align: left; "
                           role="button"
                           href="<?php echo MAILBEEZ_MAILHIVE_URL . 'test&module=' . urlencode($mailbeez_obj->get_module_id()) . '&' . mh_get_all_get_params(array($mailhive_token)); ?>"
                        >
                            <div style="display: inline-block;  vertical-align: middle; padding-right: 10px; ">
                            </div>
                            <div class="mh_text-overflow" style=" vertical-align: middle;">
                                <?php echo $mailbeez_obj->title; ?>
                            </div>
                        </a>
                    </div>

                    <?php

                }
            }
        }
    } elseif ($mpaction == 'sendTest') {
        $mailHive->sendTest(mh_post('email'), mh_post('module'), mh_get('maintemplate_id'));
    } elseif ($mpaction == 'listAudience') {
        $module = mh_get('module', '');

        $result = $mailHive->listAudience($module);
    } elseif ($mpaction == 'listLangView' || $mpaction == 'listLangTest') {
        //include

        $lng_action = ($mpaction == 'listLangView') ? 'view' : 'test';
        $lng_action_url = MAILBEEZ_MAILHIVE_URL . $lng_action . '&' . mh_get_all_get_params(array($mailhive_token));

        include(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/inc_lng_select.php');
    } elseif ($mpaction == 'listGndView' || $mpaction == 'listGndTest') {
        $gnd_action = ($mpaction == 'listGndView') ? 'view' : 'test';

        foreach ($cfg_gender_array as $cfg_gnd_item => $cfg_gnd_item_text) {
            ?>
            <div class="mh_choose">
                <div class="mh_choose_item"><a
                            href="<?php echo MAILBEEZ_MAILHIVE_URL . $gnd_action . '&gnd=' . $cfg_gnd_item . '&' . mh_get_all_get_params(array($mailhive_token)); ?>">
                        <?php echo mh_image(mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'filterbeez/filter_add_gender/' . $cfg_gnd_item . '_b.png', $cfg_gnd_item, '24', '24', 'align="absmiddle" width="24" height="24"') . ' ';
                        echo $cfg_gnd_item_text;
                        ?></a>
                </div>
            </div>
            <?php

        }
    } elseif ($mpaction == 'view') {
        if (mh_get('module', '') != '') {
            $out = $mailHive->viewMail(mh_get('module'), mh_get('format'), mh_get('mh_theme'), mh_get('mh_template'), mh_get('maintemplate_id'));
            if (mh_get('format') == 'txt') {
                echo '<pre>';
            }
            echo $out[urldecode(mh_get('module'))] ?? '';
        } else {
            if (!is_array($mailHive->modules)) {
                ?>
                No Modules installed
                <?php

            } else {
                reset($mailHive->modules);
                foreach ($mailHive->modules as $idx => $mailbee_obj) {
                    $obj_code = substr($mailbee_obj, 0, strrpos($mailbee_obj, '.'));
                    $mailbeez_obj = $GLOBALS[$obj_code];
                    if (!$mailbeez_obj->do_process) continue;
                    if (!$mailbeez_obj->allow_preview) continue;
                    if ($mailbeez_obj->hidden) continue;

                    ?>
                    <div style="text-align: center">
                        <a class="btn btn-default btn-primary_ btn-block "
                           style="margin-bottom: 10px; min-width: 50%; text-align: left; "
                           role="button"
                           href="<?php echo MAILBEEZ_MAILHIVE_URL . 'view&module=' . urlencode($mailbeez_obj->get_module_id()) . '&' . mh_get_all_get_params(array('module', $mailhive_token)); ?>"
                        >
                            <div style="display: inline-block;  vertical-align: middle; padding-right: 10px; ">
                            </div>
                            <div class="mh_text-overflow" style="vertical-align: middle;">
                                <?php echo $mailbeez_obj->title; ?>
                            </div>
                        </a>
                    </div>

                    <?php

                }
            }
        }
    } elseif ($mpaction == 'run') {
        if (mh_cfg('MAILBEEZ_CONFIG_SIMULATION_ENABLE_AUTOMATION') == 'True' ||
            (mh_cfg('MAILBEEZ_MAILHIVE_MODE') == 'production' || mh_get('runconfirm') == 'true')) {
            mh_session_write_close();
            $module = mh_get('module', '');

            $result = $mailHive->run($module);
        } else {
            echo "<h3>sending process disabled in simulation mode</h3>";
        }

    } elseif ($mpaction == 'runconfirm') {
        ?>
        <div style="text-align: center; ">

            <div __class="panel panel-default">
                <div __class="panel-heading">
                    <h3 __class="panel-title">
                        <?php echo mh_lng('MAILBEEZ_MAILHIVE_RUN_NOW_TITLE', 'RUN NOW') ?>
                    </h3>
                </div>
                <div __class="panel-body">
                    <div style="padding: 20px; width: 70%; margin: auto auto 30px;">
                        <?php echo mh_lng('MAILBEEZ_MAILHIVE_RUN_NOW_TEXT', 'With click on "Run Now" the MailBeez module will be run. This can differ depending on the MailBeez mode. In "production" mode the MailBeez module will be run immediately, while in "test" mode the MailBeez module will be run after clicking on "Run Now".'); ?>
                    </div>
                    <button class="btn btn-primary"
                            onclick="window.location.href='<?php echo MAILBEEZ_MAILHIVE_URL . 'run&runconfirm=true&module=' . mh_get('module'); ?>'">
                        <!--                    onclick="window.location.href='-->
                        <?php //echo mh_href_link_mailhive($mailhive_token . '=run&module=' . mh_get('module'), MH_REQUEST_TYPE) ?><!--'">-->
                        <i class="fa fa-play" style="padding-right: 5px"></i>
                        <?php echo mh_lng('MAILBEEZ_MAILHIVE_RUN_NOW_BUTTON', 'RUN NOW') ?>
                    </button>
                    <br>
                    <br>
                    <br>
                    <br>
                    <div>
                        Mode:
                        <?php if (mh_cfg('MAILBEEZ_MAILHIVE_MODE') == 'production') { ?>
                            <div class="label label-success"><?php echo mh_cfg('MAILBEEZ_MAILHIVE_MODE') ?></div>
                        <?php } else { ?>
                            <div class="label label-warning"><?php echo mh_cfg('MAILBEEZ_MAILHIVE_MODE') ?></div>
                        <?php } ?>
                    </div>


                    <?php if (mh_cfg('MAILBEEZ_MAILHIVE_COPY') == 'True') { ?>
                        <div style="padding: 10px;">
                            <?php echo mh_lng('MAILBEEZ_MAILHIVE_EMAIL_COPY_TEXT', 'Send Copy to') ?>:
                            <?php echo mh_cfg('MAILBEEZ_MAILHIVE_EMAIL_COPY') ?>
                        </div>
                    <?php } ?>

                    <?php if (!mh_saas()) { ?>
                        <div style=" margin-top: 30px;" class="alert alert-info"
                             role="alert"><?php echo mh_lng('MAILBEEZ_MAILHIVE_AUTOMATION_HINT', 'Please configure MailBeez to run automatically') ?></div>
                    <?php } ?>

                </div>
            </div>

        </div>
        <?php

    } elseif ($mpaction == '') {
        //
    }
    ?>
    <?php
    if ($output_plain == false) {
        ?>
        <?php echo str_repeat(" ", 4096); ?>
        </body>
        </html>
        <?php

    }
}

//require(DIR_WS_INCLUDES . 'application_bottom.php');
mh_session_write_close();


if ($silent_mode == true) {
    $output = ob_get_contents();
    ob_end_clean();
    ?>
    done.
    </body>
    </html>
    <?php
}

$sitezen_module_file = MH_ROOT_PATH . 'configbeez/config_sitezen.php';
if (file_exists($sitezen_module_file)) {
    // keep db credentials up to date in case of changes
    include_once($sitezen_module_file);
    config_sitezen::generateEnvFile();
}

if (isset($request_profiler)) {
    $request_profiler->stop('bottom_end');
}

if (defined('DISPLAY_REQUEST_PROFILER') && DISPLAY_REQUEST_PROFILER == 'true') {
    if (isset($request_profiler)) {
        $request_profiler->output();
    }
}
mh_restoreLng();