<?php

/*
  MailBeez Automatic Trigger Email Campaigns
  http://www.mailbeez.com

  Copyright (c) 2010 - 2012 MailBeez

  inspired and in parts based on
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License

 */

///////////////////////////////////////////////////////////////////////////////
///                                                                          //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////


// pre-define some constants if not set
//mh_define('MAILBEEZ_MAILHIVE_POPUP_MODE', null);
//mh_define('MAILBEEZ_MAILHIVE_STATUS', null);
//mh_define('MAILBEEZ_VERSION', null);
//mh_define('DISPLAY_REQUEST_PROFILER', null);


function mh_define($const, $value)
{
    if (!defined($const))
        define($const, $value);
}


if (!defined('MH_REQUEST_TYPE')) {
    // set the type of request (secure or not)

    $mh_request_type = (((isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1'))) ||
        (isset($_SERVER['HTTP_X_FORWARDED_BY']) && strpos(strtoupper($_SERVER['HTTP_X_FORWARDED_BY']), 'SSL') !== false) ||
        (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && (strpos(strtoupper($_SERVER['HTTP_X_FORWARDED_HOST']), 'SSL') !== false || strpos(strtoupper($_SERVER['HTTP_X_FORWARDED_HOST']), str_replace('https://', '', HTTPS_SERVER)) !== false)) ||
        (isset($_SERVER['SCRIPT_URI']) && strtolower(substr($_SERVER['SCRIPT_URI'], 0, 6)) == 'https:') ||
        (isset($_SERVER['HTTP_REFERER']) && strtolower(substr($_SERVER['HTTP_REFERER'], 0, 6)) == 'https:') ||
        (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && ($_SERVER['HTTP_X_FORWARDED_SSL'] == '1' || strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on')) ||
        (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'ssl' || strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) ||
        (isset($_SERVER['HTTP_SSLSESSIONID']) && $_SERVER['HTTP_SSLSESSIONID'] != '') ||
        (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443')) ? 'SSL' : 'NONSSL';


    mh_define('MH_REQUEST_TYPE', $mh_request_type);
}


// define security token field for admin forms
$MH_POST_TOKEN = '';
// modified-shop
if (mh_session('CSRFName')) {
    $MH_POST_TOKEN = '<input type="hidden" name="' . mh_session('CSRFName') . '" value="' . mh_session('CSRFToken') . '" />';
}

// zencart
if (mh_session('securityToken')) {
    $MH_POST_TOKEN = '<input type="hidden" name="securityToken" value="' . mh_session('securityToken') . '" />';
}

mh_define('MH_POST_TOKEN', $MH_POST_TOKEN);

function mh_arr_val($array, $key, $fallback_value = null)
{
    return is_array($array) && isset($array[$key]) && ($array[$key] != false) ? $array[$key] : $fallback_value;
}


function mh_cfg($c, $fallback_value = null)
{
    if ($c == null) {
        return $fallback_value;
    }

    $cacheKey = 'C_' . $c;
    // invalid constant name
    if (stristr($c, ' ')) {
        return $fallback_value;
    }

    // 1) Request-local override wins
    if (isset($GLOBALS['__MH_CFG_OVERRIDES']) && is_array($GLOBALS['__MH_CFG_OVERRIDES']) && array_key_exists($c, $GLOBALS['__MH_CFG_OVERRIDES'])) {
        return $GLOBALS['__MH_CFG_OVERRIDES'][$c];
    }

    // 2) Shadow cache constant (allows refresh without touching $c)
    if (defined($cacheKey)) {
        return constant($cacheKey);
    }

    // 3) Initial bootstrap constant (if defined and not empty)
    if (defined($c) && constant($c) !== '') {
        // constant is defined, and not empty but can be false
        return constant($c);
    }

    // 4) GX: re-read single key and cache
    if (defined('MH_PLATFORM_GAMBIO_GX_CONFIGURATION') && MH_PLATFORM_GAMBIO_GX_CONFIGURATION) {
        $result = mh_read_config_item($c);
        if (is_array($result) && isset($result['result']) && $result['result'] == true) {
            if (!defined($cacheKey)) {
                define($cacheKey, $result['value']);
            }
            return $result['value'];
        }
    }

    // 5) If the constant exists but is empty, return it; else fallback
    if (defined($c)) {
        return constant($c);
    }

    // return fallback
    return $fallback_value;
}

/**
 * Set a request-local override so mh_cfg($key) returns $value for the remainder of the request.
 * Also defines C_$key (cache constant) if it does not exist yet.
 */
function mh_cfg_override_set($key, $value): void
{
    if (!isset($GLOBALS['__MH_CFG_OVERRIDES']) || !is_array($GLOBALS['__MH_CFG_OVERRIDES'])) {
        $GLOBALS['__MH_CFG_OVERRIDES'] = [];
    }
    $GLOBALS['__MH_CFG_OVERRIDES'][(string)$key] = $value;
    $cacheKey = 'C_' . (string)$key;
    if (!defined($cacheKey)) {
        // Constants cannot be changed; define only if absent
        @define($cacheKey, $value);
    }
}

/**
 * Clear a single override or all overrides if $key is null.
 */
function mh_cfg_override_clear($key = null): void
{
    if (!isset($GLOBALS['__MH_CFG_OVERRIDES']) || !is_array($GLOBALS['__MH_CFG_OVERRIDES'])) {
        $GLOBALS['__MH_CFG_OVERRIDES'] = [];
    }
    if ($key === null) {
        $GLOBALS['__MH_CFG_OVERRIDES'] = [];
    } else {
        unset($GLOBALS['__MH_CFG_OVERRIDES'][(string)$key]);
    }
}

/**
 * Re-read a single key from the storage layer and set it as an override.
 * Returns the fresh value when available; otherwise falls back to mh_cfg($key).
 */
function mh_cfg_refresh(string $key)
{
    $result = mh_read_config_item($key);
    if (is_array($result) && !empty($result['result'])) {
        mh_cfg_override_set($key, $result['value']);
        return $result['value'];
    }
    return mh_cfg($key);
}

/**
 * Refresh multiple keys by re-reading them from storage.
 */
function mh_cfg_refresh_many(array $keys): void
{
    foreach ($keys as $k) {
        mh_cfg_refresh((string)$k);
    }
}

function mh_lng($c, $fallback_value = null)
{

//    if ($fallback_value == null) {
//        $fallback_value = $c;
//    }
    return mh_cfg($c, $fallback_value);
}

function mh_fn($f, $fallback_value = null)
{
    return mh_cfg($f, $fallback_value);
}

function mh_get($name, $fallback = null, $type = 'string')
{
    if ($name === null || !isset($_GET[$name])) {
        return $fallback;
    }
    $value = $_GET[$name];
    if (is_string($value)) {
        $value = trim($value);
    }

    try {
        $value = mh_clean_input($value, $fallback, $type);
    } catch (Exception $e) {
        if ($type === 'int' && ($value === '' || $value === null)) {
            return $fallback !== null ? (int)$fallback : 0;
        }
        return $fallback;
    }

    return $value;
}

function mh_clean_input($value, $fallback = null, $type = 'string')
{
    if ($value === null) {
        $value = '';
    }

    if ($type == 'email_string') {
        $type = stristr($value, '@') ? 'email' : 'string';
    }

    if ($type == 'hex_string') {
        $type = stristr($value, '-') ? 'string' : 'hex';
    }
    // Define validation rules based on type
    $patterns = [
        'hex' => '/^[a-f0-9]{3,32}$/', // 12-character hexadecimal (set to 3..32 chars)
        'int' => '/^\d+$/', // Only digits
//        'string' => '/^[ =,._\/&\-*%\p{L}\p{N}]*$/u', // supports Unicode letters incl. ����
        'string' => '/^[ =,.:;?!_~@+&%#\[\]\(\)\"\'\\\\\/\-*\p{L}\p{N}]*$/u',
        'uuid' => '/^[a-f0-9\-]{36}$/',
        'email' => '/^[\p{L}\p{N}_\.\-]+@([\p{L}\p{N}\-]+\.)*[\p{L}\p{N}\-]*$/u',
        'slug' => '/^[a-z0-9-]+$/',
        'key'   => '/^[a-z0-9_\-]*$/',
    ];

    // Validate input against defined pattern
    if (isset($patterns[$type])) {
        if ($type === 'int' && ($value === '' || $value === null)) {
            return $value;
        }
        if (!preg_match($patterns[$type], $value)) {
            throw new Exception('Invalid value for type ' . $type . ': ' . $value);
        }
    }
    return $value;
}


function mh_session($name, $fallback = null)
{
    if ($name === null) {
        return $fallback;
    }
    if (is_string($name) && stristr($name, '->')) {
        $params = explode('->', $name);
        if ($postArray = mh_session($params[0])) {
            if (isset($postArray[$params[1]])) {
                return $postArray[$params[1]];
            }
        }
        return $fallback;
    }

    return isset($_SESSION[$name]) ? $_SESSION[$name] : $fallback;
}

function mh_server(string $name, $fallback = null)
{
    return $_SERVER[$name] ?? $fallback;
}

function mh_post($name, $fallback = null)
{
    if ($name === null) {
        return $fallback;
    }
    if (is_string($name) && stristr($name, '->')) {
        $params = explode('->', $name);
        if ($postArray = mh_post($params[0])) {
            if (isset($postArray[$params[1]])) {
                return $postArray[$params[1]];
            }
        }
        return $fallback;
    }

    return isset($_POST[$name]) ? $_POST[$name] : $fallback;
}

function mh_request($name, $fallback = null)
{
    return isset($_REQUEST[$name]) ? $_REQUEST[$name] : $fallback;
}


if (!function_exists('dd')) {

    function dd($d = null)
    {
        var_dump($d);
        exit();
    }
}

if (!function_exists('ddd')) {

    function ddd($d = null)
    {
        print_r($d);
        exit();
    }
}


// test
function __mh_log_query()
{
    return false;
}


mh_define('DIR_WS_IMAGES', 'images/');
mh_define('DIR_WS_ORIGINAL_IMAGES', DIR_WS_IMAGES . 'product_images/original_images/');
mh_define('DIR_WS_THUMBNAIL_IMAGES', DIR_WS_IMAGES . 'product_images/thumbnail_images/');
mh_define('DIR_WS_INFO_IMAGES', DIR_WS_IMAGES . 'product_images/info_images/');
mh_define('DIR_WS_POPUP_IMAGES', DIR_WS_IMAGES . 'product_images/popup_images/');
mh_define('DIR_WS_ICONS', DIR_WS_IMAGES . 'icons/');
//mh_define('DIR_WS_INCLUDES',DIR_FS_DOCUMENT_ROOT. 'includes/');
mh_define('DIR_WS_INCLUDES', 'includes/');
mh_define('DIR_WS_FUNCTIONS', DIR_WS_INCLUDES . 'functions/');
mh_define('DIR_WS_CLASSES', DIR_WS_INCLUDES . 'classes/');
mh_define('DIR_WS_MODULES', DIR_WS_INCLUDES . 'modules/');
mh_define('DIR_WS_LANGUAGES', DIR_WS_INCLUDES . 'languages/');

mh_define('MH_ROOT_PATH', 'mailhive/');
mh_define('ENABLE_SSL', false);
mh_define('FILENAME_PRODUCT_INFO', 'product_info.php'); // modified 2 compatibility
mh_define('FILENAME_PRODUCT_REVIEWS_WRITE', 'product_reviews_write.php'); // modified 2 compatibility
mh_define('FILENAME_MODULES', 'modules.php');

// osc CE Phoenix compatibility
mh_define('FILENAME_ACCOUNT_HISTORY_INFO', 'account_history_info.php');
mh_define('FILENAME_CHECKOUT_CONFIRMATION', 'checkout_confirmation.php');
mh_define('FILENAME_CHECKOUT_PAYMENT', 'checkout_payment.php');
mh_define('FILENAME_CHECKOUT_PROCESS', 'checkout_process.php');
mh_define('FILENAME_CHECKOUT_SHIPPING', 'checkout_shipping.php');
mh_define('FILENAME_CHECKOUT_SHIPPING_ADDRESS', 'checkout_shipping_address.php');
mh_define('FILENAME_CHECKOUT_SUCCESS', 'checkout_success.php');
mh_define('FILENAME_CREATE_ACCOUNT', 'create_account.php');
mh_define('FILENAME_DEFAULT', 'index.php');
mh_define('FILENAME_LOGIN', 'login.php');
mh_define('FILENAME_ORDERS', 'orders.php');
mh_define('FILENAME_PRODUCT_INFO', 'product_info.php');
mh_define('FILENAME_SHOPPING_CART', 'shopping_cart.php');


if (defined('DIR_WS_HTTP_CATALOG')) {
    // oscmax, cre
    mh_define('MH_DIR_WS_CATALOG', DIR_WS_HTTP_CATALOG);
}


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

if (substr(DIR_WS_CATALOG, -1) != '/') {
    mh_define('MH_DIR_WS_CATALOG', DIR_WS_CATALOG . '/');
} else {
    mh_define('MH_DIR_WS_CATALOG', DIR_WS_CATALOG);
}

if (isset($_GET['PROFILER'])) {
    define('DISPLAY_REQUEST_PROFILER', 'true');
}

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/request_profiler.php');

global $request_profiler;
$request_profiler = new request_profiler;
$request_profiler->start();

$request_profiler->restart('top_load_start');

// check if called in admin or storefront context

if (defined('DIR_WS_ADMIN')) {
    if (preg_match('#' . DIR_WS_ADMIN . '#', $_SERVER['PHP_SELF'])
        ||
        preg_match('#wp-admin#', $_SERVER['PHP_SELF'])
        // wp online store

    ) {
        mh_define('MH_CONTEXT', 'ADMIN');
    } else {
        mh_define('MH_CONTEXT', 'STORE');
    }
} else {
    mh_define('MH_CONTEXT', 'STORE');
}

if (mh_cfg('MH_CONTEXT') == 'ADMIN') {
    mh_define('_VALID_XTC', true);
}


// include local configuration if available
$local_conf_dir = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/local/';
if ($dir = @dir($local_conf_dir)) {
    while ($local_conf_file = $dir->read()) {
        if (!is_dir($local_conf_dir . $local_conf_file)) {
            if (preg_match('/\.php$/', $local_conf_file) > 0) {
                require_once($local_conf_dir . $local_conf_file);
            }
        }
    }
    $dir->close();
}

mh_define('FILENAME_MAILBEEZ_BLOCKGUI', MH_ROOT_PATH . 'gui/mailhive_block_gui.php'); // can be overwritten by local config file
mh_define('FILENAME_MAILBEEZ_UNBLOCKGUI', MH_ROOT_PATH . 'gui/mailhive_unblock_gui.php'); // can be overwritten by local config file
mh_define('FILENAME_MAILBEEZ_BLOCK_ALL_GUI', MH_ROOT_PATH . 'gui/mailhive_block_all_gui.php'); // can be overwritten by local config file
mh_define('FILENAME_MAILBEEZ_UNBLOCK_ALL_GUI', MH_ROOT_PATH . 'gui/mailhive_unblock_all_gui.php'); // can be overwritten by local config file

mh_define('MH_AUTOINSTALL', false);
mh_define('MH_SHOWMORELINK', true);

mh_define('MH_ADMIN_DIR_WS_PRE', '');
mh_define('MH_ADMIN_DIR_WS_IMAGES', MH_ADMIN_DIR_WS_PRE . MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'common/images/');

mh_define('DB_PREFIX', ''); //  zencart

mh_define('TABLE_MAILBEEZ_TRACKING', DB_PREFIX . 'mailbeez_tracking');
mh_define('TABLE_MAILBEEZ_BLOCK', DB_PREFIX . 'mailbeez_block');
mh_define('TABLE_MAILBEEZ_PROCESS', DB_PREFIX . 'mailbeez_process');
mh_define('TABLE_MAILBEEZ_BOUNCE', DB_PREFIX . 'mailbeez_bounces');
mh_define('TABLE_MAILBEEZ_BOUNCE_MSG_LOG', DB_PREFIX . 'mailbeez_bounces_msg_log');
mh_define('TABLE_MAILBEEZ_OPENS_LOG', DB_PREFIX . 'mailbeez_opens_log');
mh_define('TABLE_MAILBEEZ_TRACKING_CLICKS', DB_PREFIX . 'mailbeez_tracking_clicks');
mh_define('TABLE_MAILBEEZ_TRACKING_ORDERS', DB_PREFIX . 'mailbeez_tracking_orders');
mh_define('TABLE_MAILBEEZ_LOCK', DB_PREFIX . 'mailbeez_lock');
mh_define('TABLE_MAILBEEZ_ESP_EVENTS', DB_PREFIX . 'mailbeez_esp_events');
mh_define('TABLE_MAILBEEZ_ESP_MESSAGE_STATE', DB_PREFIX . 'mailbeez_esp_message_state');
mh_define('TABLE_MAILBEEZ_ESP_MESSAGE_MAP', DB_PREFIX . 'mailbeez_esp_message_map');


mh_define('FILENAME_MAILBEEZ', 'mailbeez.php');
mh_define('FILENAME_HIVE', 'mailhive.php');

mh_define('MAILBEEZ_CHECK_CACHE', false);
//mh_define('MH_RESPONSIVE', mh_cfg('MH_RESPONSIVE', 'False'));
//mh_define('MAILBEEZ_BOUNCEHIVE_STATUS', mh_cfg('MAILBEEZ_BOUNCEHIVE_STATUS', 'False'));


mh_define('MH_DIR_TEMPLATES_C', 'common/templates_c/');
mh_define('MH_DIR_CACHE', 'common/templates_c/');
mh_define('MH_DIR_LOGS', 'common/templates_c/');
mh_define('MH_DIR_WORK', 'common/templates_c/');


mh_define('MH_DIR_FS_TEMPLATES_C', MH_DIR_FS_CATALOG . MH_ROOT_PATH . MH_DIR_TEMPLATES_C);
mh_define('MH_DIR_FS_CACHE', MH_DIR_FS_CATALOG . MH_ROOT_PATH . MH_DIR_CACHE);
mh_define('MH_DIR_FS_LOGS', MH_DIR_FS_CATALOG . MH_ROOT_PATH . MH_DIR_LOGS);
mh_define('MH_DIR_FS_WORK', MH_DIR_FS_CATALOG . MH_ROOT_PATH . MH_DIR_WORK);
mh_define('MH_DIR_FS_UPLOAD', MH_DIR_FS_CATALOG);


$module_directory_ws = MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'mailbeez/';
$config_module_directory_ws = MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'configbeez/';
$filter_module_directory_ws = MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'filterbeez/';
$report_module_directory_ws = MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'reportbeez/';
$dashboard_module_directory_ws = MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/';


mh_define('MH_DIR_BEEZUI', 'app/');
mh_define('MH_DIR_APP', MH_DIR_FS_CATALOG . MH_ROOT_PATH . MH_DIR_BEEZUI);
mh_define('MH_DIR_MODULE', MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/');
mh_define('MH_DIR_CONFIG', MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'configbeez/');
mh_define('MH_DIR_FILTER', MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'filterbeez/');
mh_define('MH_DIR_REPORT', MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'reportbeez/');
mh_define('MH_DIR_DASHBOARD', MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'dashboardbeez/');

mh_define('MH_MODULE_DIRECTORY', MH_DIR_MODULE);
mh_define('MH_MODULE_DIRECTORY_WS', $module_directory_ws);
mh_define('MH_CONFIG_MODULE_DIRECTORY', MH_DIR_CONFIG);
mh_define('MH_CONFIG_MODULE_DIRECTORY_WS', $config_module_directory_ws);
mh_define('MH_FILTER_MODULE_DIRECTORY', MH_DIR_FILTER);
mh_define('MH_FILTER_MODULE_DIRECTORY_WS', $filter_module_directory_ws);
mh_define('MH_REPORT_MODULE_DIRECTORY', MH_DIR_REPORT);
mh_define('MH_REPORT_MODULE_DIRECTORY_WS', $report_module_directory_ws);
mh_define('MH_DASHBOARD_MODULE_DIRECTORY', MH_DIR_DASHBOARD);
mh_define('MH_DASHBOARD_MODULE_DIRECTORY_WS', $dashboard_module_directory_ws);


// backward compatibility
$module_directory = MH_DIR_MODULE;
$config_module_directory = MH_DIR_CONFIG;
$filter_module_directory = MH_DIR_FILTER;
$report_module_directory = MH_DIR_REPORT;
$dashboard_module_directory = MH_DIR_DASHBOARD;

// deprec
// keep for compatibility
$module_key = 'MAILBEEZ_INSTALLED';
$module_version_key = 'MAILBEEZ_INSTALLED_VERSIONS';
$config_module_key = 'MAILBEEZ_CONFIG_INSTALLED';
$config_module_version_key = 'MAILBEEZ_CONFIG_INSTALLED_VERSIONS';
$filter_module_key = 'MAILBEEZ_FILTER_INSTALLED';
$filter_module_version_key = 'MAILBEEZ_FILTER_INSTALLED_VERSIONS';
$report_module_key = 'MAILBEEZ_REPORT_INSTALLED';
$report_module_version_key = 'MAILBEEZ_REPORT_INSTALLED_VERSIONS';
$dashboard_module_key = 'MAILBEEZ_DASHBOARD_INSTALLED';
$dashboard_module_version_key = 'MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS';

// use these constants
mh_define('MH_DASHBOARD_MODULE_VERSION_KEY', $dashboard_module_version_key);
mh_define('MH_DASHBOARD_MODULE_KEY', $dashboard_module_key);
mh_define('MH_REPORT_MODULE_VERSION_KEY', $report_module_version_key);
mh_define('MH_REPORT_MODULE_KEY', $report_module_key);
mh_define('MH_FILTER_MODULE_VERSION_KEY', $filter_module_version_key);
mh_define('MH_FILTER_MODULE_KEY', $filter_module_key);
mh_define('MH_CONFIG_MODULE_VERSION_KEY', $config_module_version_key);
mh_define('MH_CONFIG_MODULE_KEY', $config_module_key);
mh_define('MH_MODULE_VERSION_KEY', $module_version_key);
mh_define('MH_MODULE_KEY', $module_key);


// zencart, xtcommerce
mh_define('DIR_WS_HTTP_CATALOG', MH_DIR_WS_CATALOG);
mh_define('DIR_WS_HTTPS_CATALOG', MH_DIR_WS_CATALOG);

// fall back in case not defined
mh_define('HTTPS_SERVER', str_replace('http:', 'https:', HTTP_SERVER));


mh_define('HTTP_CATALOG_SERVER', HTTP_SERVER);
mh_define('HTTPS_CATALOG_SERVER', HTTPS_SERVER);
mh_define('PROJECT_VERSION', ''); // if not available

mh_define('MH_CATALOG_SERVER', (MH_REQUEST_TYPE == 'SSL') ? HTTPS_CATALOG_SERVER : HTTP_CATALOG_SERVER);


/*
if (defined('ENABLE_SSL_ADMIN')) {
    // by default zencart
    mh_define('MH_CATALOG_SERVER', (ENABLE_SSL_ADMIN == 'true') ? HTTPS_CATALOG_SERVER : HTTP_CATALOG_SERVER);
} elseif (mh_get_conf('MH_CONTEXT') == 'ADMIN') {
    mh_define('MH_CATALOG_SERVER', (ENABLE_SSL == 'true') ? HTTPS_CATALOG_SERVER : HTTP_CATALOG_SERVER);
} else {
    mh_define('MH_CATALOG_SERVER', ($_SERVER["HTTPS"] == "on") ? HTTPS_CATALOG_SERVER : HTTP_CATALOG_SERVER);
//    mh_define('MH_CATALOG_SERVER', HTTP_CATALOG_SERVER);
}
*/

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/platform_observer.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_configuration_wrapper.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/modules_registry.php');

//$request_profiler->restart('top_load_start_1');


mh_define('MH_SPLITPAGE_NUM', mh_cfg('MAILBEEZ_ANALYTICS_SPLITPAGE_NUM'));
mh_define('MH_PAGE_NAME', 'page');

mh_define('MH_ID', MH_PLATFORM);
mh_define('MH_LINKID_1', '?a=' . MH_ID);
mh_define('MH_LINKID_2', '&a=' . MH_ID);

mh_define('MAILBEEZ_MAILHIVE_URL', MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . FILENAME_HIVE . '?' . mh_cfg('MAILBEEZ_MAILHIVE_TOKEN') . '=');
mh_define('MAILBEEZ_MAILHIVE_URL_DIRECT', MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . FILENAME_HIVE);
// adjustments need to be done in mailbeez_check.php / versioncheck.php as well


mh_define('MAILBEEZ_TRACKER_OPEN_PARAM', '?mi=');
mh_define('MAILBEEZ_TRACKER_MID_PARAM', 'mid');
mh_define('MAILBEEZ_MESSAGE_ID_TOKEN', '%message-id%');
mh_define('MAILBEEZ_TRACKER_REWRITE_MODE', 'shop');
mh_define('MAILBEEZ_TRACKER_URL', MAILBEEZ_MAILHIVE_URL_DIRECT . MAILBEEZ_TRACKER_OPEN_PARAM . MAILBEEZ_MESSAGE_ID_TOKEN);


mh_define('MAILBEEZ_API_ENTRYPOINT', str_replace('https://', '', str_replace('http://', '', MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . FILENAME_HIVE . '/api/')));
mh_define('MAILBEEZ_API_SSL', (MH_REQUEST_TYPE == 'SSL'));
mh_define('MAILBEEZ_API_PORT', 443);


//mh_define('MAILBEEZ_VERSION_CHECK_SERVER', 'http://127.0.0.1/wordpress_mailbeez');
//mh_define('MAILBEEZ_VERSION_CHECK_SERVER', 'http://grav-local.de');


//mh_define('MAILBEEZ_VERSION_CHECK_SERVER', 'http://cloudbeez');
mh_define('MAILBEEZ_VERSION_CHECK_SERVER', 'https://apps.mailbeez.com');

// set based on configuration (email engine PHPMailer...)
mh_define('MH_BOUNCEHANDLING_ENABLED', ('mlbz_ubvx' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) || ('mlbz_hysndr' == mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE')) ||  ((mh_cfg('MAILBEEZ_BOUNCEHIVE_STATUS') && mh_cfg('MAILBEEZ_BOUNCEHIVE_STATUS') == 'True' && preg_match('/PHPMailer/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))) || preg_match('/Newsletter2Go/', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE'))));
mh_define('MH_OPENTRACKER_ENABLED', mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'True');
mh_define('MH_CLICKTRACKER_ENABLED', mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'True');
mh_define('MH_ORDERTRACKER_ENABLED', mh_cfg('MAILBEEZ_ANALYTICS_STATUS') == 'True');

// Gambio
if (!defined('DIR_WS_THUMBNAIL_IMAGES') && defined('DIR_WS_CATALOG_THUMBNAIL_IMAGES')) {
    define('DIR_WS_THUMBNAIL_IMAGES', DIR_WS_CATALOG_THUMBNAIL_IMAGES);
}

if (isset($user_language) && $_SESSION['language'] == '') {
    $_SESSION['language'] = $language;
}


switch ($_SESSION['language']) {
    case "german":
        $lng_param = 'de';
        break;
    default:
        $lng_param = 'en';
}

mh_define('MAILBEEZ_VERSION_CHECK_URL', MAILBEEZ_VERSION_CHECK_SERVER . '/api/public/v1/version/' . $lng_param . '/' . 'a=' . MH_ID . '|'
    /*.
    . '|m=' . (defined('MAILBEEZ_INSTALLED_VERSIONS') ? MAILBEEZ_INSTALLED_VERSIONS : '')
    . '|c=' . (defined('MAILBEEZ_CONFIG_INSTALLED_VERSIONS') ? MAILBEEZ_CONFIG_INSTALLED_VERSIONS : '')
    . '|f=' . (defined('MAILBEEZ_FILTER_INSTALLED_VERSIONS') ? MAILBEEZ_FILTER_INSTALLED_VERSIONS : '')
    . '|r=' . (defined('MAILBEEZ_REPORT_INSTALLED_VERSIONS') ? MAILBEEZ_REPORT_INSTALLED_VERSIONS : '')
    . '|d=' . (defined('MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS') ? MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS : '')
    */

    . '/' . urlencode(MH_PLATFORM . '|' . PROJECT_VERSION));


// legacy version check
/*
mh_define('MAILBEEZ_VERSION_CHECK_URL', MAILBEEZ_VERSION_CHECK_SERVER . '/downloads/version_check_v2/?v=' . MAILBEEZ_VERSION . '&m=' . (defined('MAILBEEZ_INSTALLED_VERSIONS')
        ? MAILBEEZ_INSTALLED_VERSIONS : '') . '&c=' . (defined('MAILBEEZ_CONFIG_INSTALLED_VERSIONS')
        ? MAILBEEZ_CONFIG_INSTALLED_VERSIONS : '') . '&f=' . (defined('MAILBEEZ_FILTER_INSTALLED_VERSIONS')
        ? MAILBEEZ_FILTER_INSTALLED_VERSIONS : '') . '&r=' . (defined('MAILBEEZ_REPORT_INSTALLED_VERSIONS')
        ? MAILBEEZ_REPORT_INSTALLED_VERSIONS : '') . '&d=' . (defined('MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS')
        ? MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS
        : '') . mh_get_conf('MH_LINKID_2') . '&lang=' . $lng_param . '&p=' . urlencode(MH_PLATFORM . ' - ' . PROJECT_VERSION));
*/

mh_define('MAILBEEZ_CONTACT_EMAIL', 'helpdesk@mailbeez.com');

if (isset($PHP_SELF) && $PHP_SELF != '') {
    // oscommerce, zencart
    $file_extension = substr($PHP_SELF, strrpos($PHP_SELF, '.'));
} else {
    // xtc
    $file_extension = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '.'));
}

// override
$file_extension = '.php';

$file_extension = ($file_extension == '') ? '.php' : $file_extension;

mh_define('MH_FILE_EXTENSION', $file_extension);


$GLOBALS["file_extension"] = MH_FILE_EXTENSION;


if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/pro.php')) {
    try {
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/pro.php');
    } catch (Exception $e) {
        echo "Error loading pro.php";
    }
}
//$request_profiler->restart('top_load_start_2');


require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/admin_application_plugins/colorcodes.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/advanced_simulations.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/class_loader.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/admin_rights.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/email_engine.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/event_log.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/helper.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/price.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_smarty_wrapper.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/template_engine.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/update.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/versioncheck.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/systemcheck.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/logger.php');

//$request_profiler->restart('top_load_start_3');


if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/cloudbeez.php')) {
    include_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/cloudbeez.php');
}

if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/classes/mailbeez_pro.php')) {
    include_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'pro/classes/mailbeez_pro.php');
}


// support for json on servers w/o json extension
if (!function_exists('json_encode')) {
    require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/json_fallback.php');
}

if (!class_exists('ForceUTF8_Encoding')) {
    require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/ForceUTF8/Encoding.php');
}


// load common language resources
if (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/languages/' . $_SESSION['language'] . MH_FILE_EXTENSION)) {
    include_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/languages/' . $_SESSION['language'] . MH_FILE_EXTENSION);
} elseif (file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/languages/english' . MH_FILE_EXTENSION)) {
    include_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/languages/english' . MH_FILE_EXTENSION);
}

// include the list of functions plugins
$function_plugins_dir = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/function_plugins/';
if ($dir = @dir($function_plugins_dir)) {
    while ($function_plugins_file = $dir->read()) {
        if (!is_dir($function_plugins_dir . $function_plugins_file)) {
            if (preg_match('/\.php$/', $function_plugins_file) > 0) {
                require_once($function_plugins_dir . $function_plugins_file);
            }
        }
    }
    $dir->close();
}

function mh_reset_config_cache()
{
    global $messageStack;
    $config_cache_detected = false;
    if (function_exists('tep_reset_config_cache_block')) {
        tep_reset_config_cache_block('includes/config-cache.php');
        $config_cache_detected = true;
    }

    if (function_exists('updateConfiguration')) {
        updateConfiguration();
        $config_cache_detected = true;
    }

    if (file_exists('includes/configuration_cache.php')) {
        global $osC_Cache, $config_cache_file;
        if (!function_exists('count_products_in_category')) {
            require_once('includes/configuration_cache.php');
        }
        $config_cache_detected = true;
    }


    // Configuration cache for osCommerce 2.3.3
    if (file_exists(DIR_WS_FUNCTIONS . 'configuration_cache_write.php')) {
        include_once(DIR_WS_FUNCTIONS . 'configuration_cache_write.php');
        if (!write_configuration_cache_file()) {
            $messageStack->add_session(mh_lng('ERROR_CONFIG_CACHE_WRITE'));
        }
        $config_cache_detected = true;
    }

    if (file_exists(MH_DIR_FS_CATALOG . 'includes/classes/skaady_memcache.php')) {
        require_once(MH_DIR_FS_CATALOG . 'includes/classes/skaady_memcache.php');
        skaady_memcache::getInstance()->flush();
        $config_cache_detected;
    }

    return $config_cache_detected;
}


function mh_db_fetch_array()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_db_fetch_array', makeValuesReferenced($args));
            break;
        case 'zencart':
        case 'mercari':
            return call_user_func_array('tep_db_fetch_array', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            $args[0] = &$args[0];
            return call_user_func_array('xtc_db_fetch_array', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_db_free_result($db_query)
{
    if ($db_query === null || !is_object($db_query)) {
        return false;
    }

    // handle strange Warning
    //// WARNING(2): "mysqli_free_result(): Couldn't fetch mysqli_result"
    set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { /* ignore errors */
//        echo "ERROR mh_db_free_result $errno $errstr";
    }, E_WARNING);
    $result = ((mysqli_free_result($db_query) || (is_object($db_query) && (get_class($db_query) == "mysqli_result"))) ? true : false);
    restore_error_handler();

    return $result;
}

function mh_db_stripSqlComment($string = '')
{
    $RXSQLComments = '@(--[^\r\n]*)|(\#[^\r\n]*)|(/\*[\w\W]*?(?=\*/)\*/)@ms';
    return (($string == '') ? '' : preg_replace($RXSQLComments, '', $string));
}


function mh_db_query()
{
    $query_start_time = microtime(true);
    if (defined('DISPLAY_REQUEST_PROFILER') && (DISPLAY_REQUEST_PROFILER == 'true')) {
        $GLOBALS['START_TIME_DB_QUERY'][] = $query_start_time;
    }
    $args = func_get_args();

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            $result = call_user_func_array('tep_db_query', makeValuesReferenced($args));
            break;
        case 'zencart':
        case 'mercari':
            $result = call_user_func_array('tep_db_query', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            $result = call_user_func_array('xtc_db_query', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
    $query_end_time = microtime(true);
    if (defined('DISPLAY_REQUEST_PROFILER') && (DISPLAY_REQUEST_PROFILER == 'true')) {
        $GLOBALS['END_TIME_DB_QUERY'][] = $query_end_time;
    }

    $query_time = $query_end_time - $query_start_time;

    if (function_exists('mh_log_query')) {
        mh_log_query($query_time, $args[0]);
    }

    return $result;
}

function mh_db_perform()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_db_perform', makeValuesReferenced($args));
            break;
        case 'zencart':
        case 'mercari':
            return call_user_func_array('tep_db_perform', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_db_perform', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_db_num_rows()
{
    $args = func_get_args();
    if (empty($args) || $args[0] === null || !is_object($args[0])) {
        return 0;
    }

    // handle strange Warning
    //// WARNING(2): "mysqli_free_result(): Couldn't fetch mysqli_result"
    set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { /* ignore errors */
//        echo "ERROR mh_db_num_rows $errno $errstr";
    }, E_WARNING);

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            $result = call_user_func_array('tep_db_num_rows', makeValuesReferenced($args));
            break;
        case 'zencart':
        case 'mercari':
            $result = call_user_func_array('tep_db_num_rows', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            $result = call_user_func_array('xtc_db_num_rows', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
    restore_error_handler();

    return $result;
}

function mh_db_insert_id()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_db_insert_id', makeValuesReferenced($args));
            break;
        case 'zencart':
        case 'mercari':
            return call_user_func_array('tep_db_insert_id', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_db_insert_id', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_db_prepare_input()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
        case 'mercari':
            if (defined('MH_PLATFORM_OSC_WPOS')) {
                $args[0] = stripslashes($args[0]);
            }

            return call_user_func_array('tep_db_prepare_input', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_db_prepare_input', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_db_prepare_input', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_db_input()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
        case 'mercari':
            return call_user_func_array('tep_db_input', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_db_input', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_db_input', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_db_close()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_db_close', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('tep_db_close', makeValuesReferenced($args));
            break;
        case 'mercari':
        case 'xtc':
            break;
        case 'gambio':
            return call_user_func_array('xtc_db_close', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }

}


function mh_output_string()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_output_string', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_output_string', makeValuesReferenced($args));
            break;
        case 'mercari':
            $args[1] = array('"' => '&quot;');
            return call_user_func_array('parse_input_field_data', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            $args[1] = array('"' => '&quot;');
            return call_user_func_array('xtc_parse_input_field_data', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}


function mh_get_languages_directory($code)
{
    $cache = new mailbeez_cache;
    $cache->set_cache_id('lngDirectory-' . $code);

    if ($data = $cache->read_cache('session')) {
        return $data['value'];
    }

    $language_query = mh_db_query("SELECT languages_id, directory, name FROM " . TABLE_LANGUAGES . " WHERE code = '" . mh_db_input($code) . "'");
    if (mh_db_num_rows($language_query)) {
        $language = mh_db_fetch_array($language_query);
        $languages_id = $language['languages_id'];
        $result = array("directory" => $language['directory'],
            "name" => $language['name'],
            "languages_id" => (int)$languages_id);
    } else {

        if (stristr($code, '-')) {
            list($code_short, $region) = explode('-', $code);
            $result = mh_get_languages_directory($code_short);
        } else {
            $result = false;
        }
    }

    return $cache->set_cache($result, 'session');


}

function mh_get_languages()
{
    $cache = new mailbeez_cache;
    $cache->set_cache_id('lngCodes');

    if ($data = $cache->read_cache('session')) {
        return $data['value'];
    }

    $languages_query = mh_db_query("SELECT languages_id, name, code, image, directory FROM " . TABLE_LANGUAGES . " ORDER BY sort_order");

    while ($languages = mh_db_fetch_array($languages_query)) {
        $languages_array[] = array('id' => $languages['languages_id'],
            'name' => $languages['name'],
            'code' => $languages['code'],
            'image' => $languages['image'],
            'directory' => $languages['directory']);
    }
    return $cache->set_cache($languages_array, 'session');
}

function mh_get_language_code($lngId)
{
    $languagesArray = mh_get_languages();
    foreach ($languagesArray as $l) {
        if ($l['id'] == $lngId) {
            return $l['code'];
        }
    }
    return null;
}


function mh_get_customers_language_id()
{
    $args = func_get_args();
    if (function_exists('mh_lng_get_id')) {
        ob_start();
        if (is_array($args) && isset($args[0])) {
            $language_id = mh_lng_get_id($args[0]);
        } else {
            $language_id = mh_lng_get_id(null);
        }
        ob_end_clean();
        return $language_id;
    } else {
        return $_SESSION['languages_id'];
    }
}

if (!function_exists('mh_href_link')) {
    function mh_href_link()
    {
        $args = func_get_args();
        foreach ($args as &$arg) {
            if ($arg === null) {
                $arg = '';
            }
        }

        if (!isset($args[1])) {
            $args[1] = '';
        } else {
            // clean up path as some servers block urls with ../
            if (mh_cfg('MH_CONTEXT') == 'ADMIN') {
                $args[1] = str_replace('../common/', '', $args[1]);
                $args[1] = str_replace('../configbeez/', '', $args[1]);
                $args[1] = str_replace('../mailbeez/', '', $args[1]);
                $args[1] = str_replace('../reportbeez/', '', $args[1]);
                $args[1] = str_replace('../dashboardbeez/', '', $args[1]);
                $args[1] = str_replace('../filterbeez/', '', $args[1]);
            }
        }
        $args[2] = MH_REQUEST_TYPE;

        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
                // support for popups on WPOLS
                if (defined('MH_PLATFORM_OSC_WPOS')) {
                    if (stristr($args[1], 'popup=true')) {
                        $args[1] .= '&noheader=1';
                    }
                }
                if (mh_cfg('MH_CONTEXT') == 'STORE') {
                    $args[3] = false; // no session id
                }
                return call_user_func_array('tep_href_link', makeValuesReferenced($args));
                break;
            case 'mercari':
                // no longer supported
                return call_user_func_array('href_link', makeValuesReferenced($args));
                break;
            case 'zencart':
                $args[3] = false; // no session id
                $args[4] = true;
                $args[5] = true; // set static link

                $url = call_user_func_array('zen_href_link', makeValuesReferenced($args));

                // zencart 1.5.7 fix
                $url = str_replace('&amp;', '&', $url);
                $url = str_replace('index.php?cmd=mailbeez&', 'mailbeez.php?', $url);
                $url = str_replace('index.php?cmd=mailbeez?', 'mailbeez.php?', $url);
                $url = str_replace('index.php?cmd=mailbeez', 'mailbeez.php', $url);
                $url = str_replace('mailbeez.php&', 'mailbeez.php?', $url);

                return $url;
                break;
            case 'xtc':
            case 'gambio':
                if (mh_cfg('MH_CONTEXT') == 'STORE') {
                    $args[3] = false; // no session id
                }
                return call_user_func_array('xtc_href_link', makeValuesReferenced($args));
                break;
            default:
                return 'platform not supported';
        }
    }
}

function mh_catalog_href_link()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'zencart':
            if (function_exists('zen_catalog_href_link')) {
                // ADMIN
                return call_user_func_array('zen_catalog_href_link', makeValuesReferenced($args));
            } else {
                // STORE
                return call_user_func_array('mh_href_link', makeValuesReferenced($args));
            }
            break;
        default:
            return call_user_func_array('mh_href_link', makeValuesReferenced($args));
    }
}


function mh_href_link_mailhive($param_string = '')
{
    // form urls in mailhive.php

    // todo
    // refactoring

    switch (MH_PLATFORM) {
        case 'xtc':
        case 'gambio':
            $link_out = mh_href_link(FILENAME_HIVE, $param_string, MH_REQUEST_TYPE, false, false);
            break;
        default:
            $get_param = '';

            if (defined('MH_PLATFORM_OSC_WPOS') && mh_cfg('MH_CONTEXT') == 'STORE') {
                // wp online store
                if (substr($param_string, 0, 1) != '?') {
                    $get_param = '?';
                }
                return MAILBEEZ_MAILHIVE_URL_DIRECT . $get_param . tep_output_string($param_string);
            } else {
                return mh_href_email_link(FILENAME_HIVE, $get_param . $param_string, true);
            }
    }


    return $link_out;


}

function mh_href_link_plain($link, $param_string = '')
{
    // just an alias to keep things clean
    return mh_href_email_link($link, $param_string, true);
}

function mh_href_email_link($link, $param_string = '', $static = false)
{

    // output links
    switch (MH_PLATFORM) {
        case 'zencart':
            $link_out = zen_href_link($link, $param_string, MH_REQUEST_TYPE, false, true, $static);
            // fix issues with SEO plugins
            $link_out = str_replace('.php.html', '.php', $link_out);
            break;
        case 'xtc':
        case 'gambio':
            $link_out = mh_href_link($link, $param_string, MH_REQUEST_TYPE, false, false);
            break;
        default:
            $link_out = mh_href_link($link, $param_string, MH_REQUEST_TYPE, false);
            break;
    }


    return $link_out;
}

if (!function_exists('mh_href_email_product_link')) {
    function mh_href_email_product_link($productsArray, $lng_id = null)
    {
        // set language code in session to suppor gambio language urls
        // restore original language_code

        if ($lng_id) {
            $_SESSION['language_code_backup'] = mh_session('language_code');
            $_SESSION['language_code'] = mh_get_language_code($lng_id);
        }
        $url = mh_href_email_link(mh_fn('FILENAME_PRODUCT_INFO'), 'products_id=' . $productsArray['products_id']);
        if ($lng_id) {
            $_SESSION['language_code'] = mh_session('language_code_backup');
        }
        return $url;

    }
}

/** todo bug
 * zencart /mailhive.php?cron_simple=1
 *
 * PHP Warning: Undefined array key "language_code" in /kunden/102758_45894/web/mailhive/common/functions/compatibility.php on line 1063.
 * from ezt.php
 * if (!isset($_SESSION['language_code'])) {
 * if (!isset($lng) || (isset($lng) && !is_object($lng))) {
 * if (!class_exists('language')) {
 * include(DIR_WS_CLASSES . 'language.php');
 * }
 * $lng = new language;
 * }
 *
 * reset($lng->catalog_languages);
 * foreach ($lng->catalog_languages as $code => $value) {
 * if ($value['id'] == $_SESSION['languages_id']) {
 * $_SESSION['language_code'] = $value['code'];
 * break;
 * }
 * }
 *
 * }
 *
 *
 */


if (!function_exists('mh_filter_product_data')) {
    function mh_filter_product_data($productsArray, $lng_id = null)
    {
        return $productsArray;
    }
}


function mh_urlencode($url)
{
    // replace / with --
    //return urlencode($url);
    return $url;
}

function mh_urldecode($url)
{
    // replace -- with /
    //return urldecode($url);
    return $url;
}

function mh_draw_form()
{
    $args = func_get_args();
    if (mh_cfg('MH_CONTEXT') == 'ADMIN') {
        $args[2] = str_replace('../common/', '', $args[2]);
        $args[2] = str_replace('../configbeez/', '', $args[2]);
        $args[2] = str_replace('../mailbeez/', '', $args[2]);
        $args[2] = str_replace('../reportbeez/', '', $args[2]);
        $args[2] = str_replace('../dashboardbeez/', '', $args[2]);
        $args[2] = str_replace('../filterbeez/', '', $args[2]);
    }

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_form', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('draw_form', makeValuesReferenced($args));
            break;
        case 'zencart':
            // work around zencart 1.5.7
            $args[1] = str_replace('.php', '$php', $args[1]);
            $html = call_user_func_array('zen_draw_form', makeValuesReferenced($args));
            $html = str_replace('$php', '.php', $html);
            $html = str_replace('index.php?cmd=mailbeez.php?', 'mailbeez.php?', $html);
            $html = str_replace('index.php?cmd=mailbeez?', 'mailbeez.php?', $html);
            $html = str_replace('index.php?cmd=mailbeez', 'mailbeez.php', $html);
            $html = str_replace('mailbeez.php&amp;', 'mailbeez.php?', $html);
            $html = str_replace('mailbeez.php&', 'mailbeez.php?', $html);
            return $html;
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_form', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_draw_hidden_field()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_hidden_field', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('draw_hidden_field', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_draw_hidden_field', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_hidden_field', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_draw_input_field()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_input_field', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('draw_input_field', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_draw_input_field', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_input_field', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}


function mh_draw_textarea_field()
{
    $args = func_get_args();
    foreach ($args as &$arg) {
        if ($arg === null) {
            $arg = '';
        }
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
            if (MH_PLATFORM_OSCMAX_25) {
                return tep_draw_textarea_field($args[0], $args[2], $args[3], $args[4], $args[5], $args[6]);
                break;
            }
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_textarea_field', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('draw_textarea_field', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_draw_textarea_field', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_textarea_field', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

if (!function_exists('mh_image_submit')) {
    function mh_image_submit()
    {
        $args = func_get_args();
        foreach ($args as &$arg) {
            if ($arg === null) {
                $arg = '';
            }
        }
        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
                return call_user_func_array('tep_image_submit', makeValuesReferenced($args));
                break;
            case 'mercari':
                $button_text = 'Submit';
                if ($args[0] == 'button_update.gif')
                    $button_text = mh_lng('BUTTON_UPDATE');
                return '<input type="submit" class="button" onClick="this.blur();" value="' . $button_text . '"/>';
                break;
            /*

            if (!function_exists('image_submit')) {
                require_once(DIR_FS_INC . 'inc.image_submit.php');
            }
            return call_user_func_array('image_submit', makeValuesReferenced($args));
            break;
            */
            case 'zencart':
                return call_user_func_array('zen_image_submit', makeValuesReferenced($args));
                break;
            case 'xtc':
            case 'gambio':
                $button_text = 'Submit';
                if ($args[0] == 'button_update.gif') {
                    $button_text = mh_lng('BUTTON_UPDATE');
                }
                if (isset($args[1])) {
                    $button_text = $args[1];
                }

                return '<input type="submit" class="btn" onClick="this.blur();" value="' . $button_text . '"/>';
                break;
            default:
                return 'platform not supported';
        }
    }
}

if (!function_exists('mh_image_button')) {
    function mh_image_button()
    {
        $args = func_get_args();
        foreach ($args as &$arg) {
            if ($arg === null) {
                $arg = '';
            }
        }
        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
                return call_user_func_array('tep_image_button', makeValuesReferenced($args));
                break;
            case 'mercari':
                if (!function_exists('image_button')) {
                    require_once(DIR_FS_INC . 'inc.image_button.php');
                }
                return call_user_func_array('image_button', makeValuesReferenced($args));
                break;
            case 'zencart':
                return call_user_func_array('zen_image_button', makeValuesReferenced($args));
                break;
            case 'xtc':
            case 'gambio':
                if ($args[0] == 'button_module_install.gif')
                    return mh_lng('BUTTON_MODULE_INSTALL');
                if ($args[0] == 'button_module_remove.gif')
                    return mh_lng('BUTTON_MODULE_REMOVE');
                if ($args[0] == 'button_edit.gif')
                    return mh_lng('MH_BUTTON_EDIT', mh_lng('BUTTON_EDIT'));
                if ($args[0] == 'button_cancel.gif')
                    return mh_lng('MH_BUTTON_CANCEL', mh_lng('BUTTON_CANCEL'));

                break;
            default:
                return 'platform not supported';
        }
    }
}


function mh_review_button()
{
    //     global $language; // temporarily set to user language, set back before return
    // find the review-button
    switch (MH_PLATFORM) {
        case 'zencart':
            $review_button = zen_image_button(mh_cfg('BUTTON_IMAGE_WRITE_REVIEW'), mh_lng('BUTTON_WRITE_REVIEW_ALT'), 'border="0"');
            break;
        case 'creloaded':
            $review_button = tep_template_image_button('button_reviews.gif', mh_lng('IMAGE_BUTTON_REVIEWS'), 'align="middle" border="0"');
            break;
        default:
            $review_button = mh_image_button('button_write_review.gif', mh_lng('IMAGE_BUTTON_WRITE_REVIEW'), 'border="0"');
            break;
    }
    return mh_rewriteImgSrc($review_button, HTTP_CATALOG_SERVER . DIR_WS_HTTP_CATALOG);
}

function mh_redirect()
{
    $args = func_get_args();

    mh_session_write_close();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_redirect', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('redirect', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_redirect', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_redirect', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_call_function()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_call_function', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('call_function', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_call_function', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_call_function', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_not_null()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_not_null', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('not_null', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_not_null', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_not_null', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_draw_separator()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_separator', makeValuesReferenced($args));
            break;
        case 'mercari':
            return;
            break;
        case 'zencart':
            return call_user_func_array('zen_draw_separator', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_separator', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_class_exists()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_class_exists', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('class_exists', makeValuesReferenced($args));
            break;
        case 'zencart':
            if (function_exists('zen_class_exists')) {
                return call_user_func_array('zen_class_exists', makeValuesReferenced($args));
            } else {
                // zencart 1.5.5
                return call_user_func_array('class_exists', makeValuesReferenced($args));
            }
            break;
        case 'xtc':
        case 'gambio':
            if (function_exists('xtc_class_exists')) {
                return call_user_func_array('xtc_class_exists', makeValuesReferenced($args));
            }
            return call_user_func_array('class_exists', makeValuesReferenced($args));

            break;
        default:
            return 'platform not supported';
    }
}

if (!function_exists('mh_image')) {
    function mh_image()
    {
        $args = func_get_args();
        foreach ($args as &$arg) {
            if ($arg === null) {
                $arg = '';
            }
        }

        switch (MH_PLATFORM) {
            case 'oscommerce':
                if (MH_PLATFORM_OSCMAX_25) {
                    $args[0] = preg_replace('#' . MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . '#', '', $args[0]);
                }


                if (defined('MH_PLATFORM_OSC_WPOS') && mh_cfg('MH_CONTEXT') == 'ADMIN') {
                    // wp online store admin
                    if (preg_match('#^' . MH_DIR_WS_CATALOG . '#', $args[0])) {
                        $args[0] = MH_CATALOG_SERVER . $args[0];
                    }
                } elseif (defined('MH_PLATFORM_OSC_WPOS') && mh_cfg('MH_CONTEXT') == 'STORE') {
                    // wp online store store
                    /*
                    echo $args[0];
                    $args[0] = preg_replace('#' . HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG . '#', '', $args[0]);
                    echo $args[0];
                    */
                }


                return call_user_func_array('tep_image', makeValuesReferenced($args));
                break;
            case 'mercari':
                return call_user_func_array('image', makeValuesReferenced($args));
                break;
            case 'creloaded':
                if (mh_cfg('MH_CONTEXT') == 'STORE') {
                    $args[0] = preg_replace('#' . MH_CATALOG_SERVER . MH_DIR_WS_CATALOG . '#', '', $args[0]);
                }
                return call_user_func_array('tep_image', makeValuesReferenced($args));
                break;
            case 'digistore':
                return call_user_func_array('tep_image', makeValuesReferenced($args));
                break;
            case 'zencart':
                if (defined('MH_CATALOG_SERVER')) {
                    $args[0] = str_replace(MH_CATALOG_SERVER, '', $args[0]);
                }
                if (defined('MH_DIR_WS_CATALOG') && MH_DIR_WS_CATALOG != '/' && strpos($args[0], MH_DIR_WS_CATALOG) === 0) {
                    $args[0] = substr($args[0], strlen(MH_DIR_WS_CATALOG));
                }
                $args[0] = ltrim($args[0], '/');

                if (mh_cfg('MH_CONTEXT') == 'STORE') {
                    return call_user_func_array('zen_image_OLD', makeValuesReferenced($args));
                }
                return call_user_func_array('zen_image', makeValuesReferenced($args));
                break;
            case 'xtc':
            case 'gambio':
                return call_user_func_array('xtc_image', makeValuesReferenced($args));
                break;
            default:
                return 'platform not supported';
        }
    }
}


if (!function_exists('mh_product_image')) {
    function mh_product_image($products_array, $type = 'THUMBNAIL')
    {

        $rawurlencode = true;

        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'digistore':
            case 'creloaded':
            case 'zencart':
                $img_folder = DIR_WS_IMAGES;
                $img_folder .= (defined('DYNAMIC_MOPICS_THUMBS_DIR')) ? DYNAMIC_MOPICS_THUMBS_DIR : ''; // osCMax

                if (defined('MH_PLATFORM_OSC_WPOS') && mh_cfg('MH_CONTEXT') == 'STORE') {
                    // wp online store
                    $img_folder = MH_CATALOG_SERVER . DIR_WS_IMAGES;
                }
                $rawurlencode = false;
                break;
            case 'xtc':
            case 'gambio':
            case 'mercari':
                switch ($type) {
                    case 'THUMBNAIL':
                        $img_folder = DIR_WS_THUMBNAIL_IMAGES;
                        break;
                    case 'INFO':
                        $img_folder = DIR_WS_INFO_IMAGES; // full size images
                        break;
                    case 'ORIGINAL':
                        $img_folder = DIR_WS_CATALOG_ORIGINAL_IMAGES;
                        break;
                    case 'POPUP':
                        $img_folder = DIR_WS_CATALOG_POPUP_IMAGES;
                        break;
                }

                break;
            default:
                return 'platform not supported';
        }

        $products_array['products_image'] = str_replace('%20', ' ', $products_array['products_image']);

        $image_path = $rawurlencode ? rawurlencode($products_array['products_image']) : $products_array['products_image'];
        $image = mh_image($img_folder . $image_path, $products_array['products_name'], mh_cfg('SMALL_IMAGE_WIDTH'), mh_cfg('SMALL_IMAGE_HEIGHT'), 'hspace="10" vspace="0" align="left" border="0"');

        if (defined('MH_PLATFORM_OSC_WPOS') && mh_cfg('MH_CONTEXT') == 'STORE') {
            // wp online store store
            return $image;
        } else {
            if (MH_PLATFORM_XTC_SEO && mh_cfg('MH_CONTEXT') == 'ADMIN') {
                return mh_rewriteImgSrc($image, HTTP_CATALOG_SERVER);
            } else {
                if (stristr($image, HTTP_CATALOG_SERVER)) {
                    // full image url
                    return $image;
                } elseif (DIR_WS_HTTP_CATALOG == '' || (DIR_WS_HTTP_CATALOG != '/' && stristr($image, DIR_WS_HTTP_CATALOG))) {
                    return mh_rewriteImgSrc($image, HTTP_CATALOG_SERVER);
                } else {
                    return mh_rewriteImgSrc($image, HTTP_CATALOG_SERVER . DIR_WS_HTTP_CATALOG);
                }
            }
        }
    }
}


function mh_admin_icon($type, $alt_add = '')
{

    $icon_path = DIR_WS_IMAGES;

    switch (MH_PLATFORM) {
        case 'gambio':
            if (MH_PLATFORM_GAMBIO >= 3.1) {
                $icon_path = DIR_WS_ADMIN . 'html/assets/images/legacy/';
            }
            break;
        default:
            $icon_path = DIR_WS_IMAGES;
    }


    switch ($type) {
        case 'status_green':
            // mh_admin_icon('status_green');
            return mh_image($icon_path . 'icon_status_green.gif', mh_lng('IMAGE_ICON_STATUS_GREEN') . $alt_add, 10, 10);
            break;
        case 'status_green_light':
            // mh_admin_icon('status_green_light');
            return mh_image($icon_path . 'icon_status_green_light.gif', mh_lng('IMAGE_ICON_STATUS_GREEN') . $alt_add, 10, 10);
            break;
        case 'status_red':
            // mh_admin_icon('status_red');
            return mh_image($icon_path . 'icon_status_red.gif', mh_lng('IMAGE_ICON_STATUS_RED') . $alt_add, 10, 10);
            break;
        case 'status_red_light':
            // mh_admin_icon('status_red_light');
            return mh_image($icon_path . 'icon_status_red_light.gif', mh_lng('IMAGE_ICON_STATUS_RED') . $alt_add, 10, 10);
            break;
        case 'arrow_right':
            // mh_admin_icon('arrow_right');
            return mh_image($icon_path . 'icon_arrow_right.gif', '' . $alt_add, 10, 10);
            break;
        case 'info':
            // mh_admin_icon('info');
            return mh_image($icon_path . 'icon_info.gif', mh_lng('IMAGE_ICON_INFO') . $alt_add, 10, 10);
            break;
    }


}


function mh_admin_product_image($image_data_array)
{
    $args = func_get_args();

    if (mh_cfg('MH_CONTEXT') == 'STORE') {
        return call_user_func_array('mh_product_image', makeValuesReferenced($args));
    }

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'digistore':
        case 'creloaded':
        case 'zencart':
            return call_user_func_array('mh_product_image', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
        case 'mercari':
            $call_args[0] = $args[0]['products_image'];
            $call_args[1] = $args[0]['products_name'];
            return call_user_func_array('xtc_product_thumb_image', makeValuesReferenced($call_args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_rewriteImgSrc($input, $server)
{

    if (stristr($input, $server)) {
        return $input;
    }
    return preg_replace('#src="#', 'src="' . $server, $input);
//    return preg_replace('#<img src="#', '<img src="' . $server, $input);
}

function mh_product_image_src($image)
{
    $image = str_replace(' ', '%20', $image); // handle blanks in filenames
    $match = [];
    $match_result = preg_match("#src=\"([a-zA-Z0-9%?&.;:/\(\)=+_-]*)\"#", $image, $match);
    return mh_arr_val($match, 1);
}


function mh_date_short()
{
    $args = func_get_args();

    if (!$args[0]) {
        $args[0] = date('Y-m-d h-i-s');
    }

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_date_short', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('date_short', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_date_short', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_date_short', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_datetime_short()
{
    $args = func_get_args();
    if (!$args[0]) {
        $args[0] = date('Y-m-d h-i-s');
    }
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':

            if (!function_exists('tep_datetime_short')) {
                function tep_datetime_short($raw_datetime)
                {
                    if (($raw_datetime == '0001-01-01 00:00:00') || ($raw_datetime == '')) return false;

                    $year = (int)substr($raw_datetime, 0, 4);
                    $month = (int)substr($raw_datetime, 5, 2);
                    $day = (int)substr($raw_datetime, 8, 2);
                    $hour = (int)substr($raw_datetime, 11, 2);
                    $minute = (int)substr($raw_datetime, 14, 2);
                    $second = (int)substr($raw_datetime, 17, 2);

                    return @strftime(DATE_TIME_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
                }
            }

            return call_user_func_array('tep_datetime_short', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('datetime_short', makeValuesReferenced($args));
            break;
        case 'zencart':

            if (!function_exists('zen_datetime_short')) {
                function zen_datetime_short($raw_datetime)
                {
                    if (empty($raw_datetime) || $raw_datetime <= '0001-01-01 00:00:00') return false;

                    $year = (int)substr($raw_datetime, 0, 4);
                    $month = (int)substr($raw_datetime, 5, 2);
                    $day = (int)substr($raw_datetime, 8, 2);
                    $hour = (int)substr($raw_datetime, 11, 2);
                    $minute = (int)substr($raw_datetime, 14, 2);
                    $second = (int)substr($raw_datetime, 17, 2);

                    global $zcDate;

                    if (is_null($zcDate)) {
                        return @strftime(DATE_TIME_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
                    } else {
                        return $zcDate->output(DATE_TIME_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
                    }
                }
            }

            return call_user_func_array('zen_datetime_short', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_datetime_short', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}


function mh_cfg_select_option()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_cfg_select_option', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('cfg_select_option', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_cfg_select_option', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_cfg_select_option', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_cfg_select_option_titled($select_array, $select_title_array, $key_value, $key = '')
{
    $string = '';

    for ($i = 0, $n = sizeof($select_array); $i < $n; $i++) {
        $name = ((mh_not_null($key)) ? 'configuration[' . $key . ']' : 'configuration_value');

        $string .= '<br><input type="radio" name="' . $name . '" value="' . $select_array[$i] . '"';

        if ($key_value == $select_array[$i]) $string .= ' CHECKED';

        $string .= '> ';

        if (isset($select_title_array[$i][1])) {
            if ($select_title_array[$i][1] == 1) {
                $string .= '<b>';
            } else if ($select_title_array[$i][1] == -1) {
                $string .= '<i>';
            }
        }
        $string .= $select_title_array[$i][0];

        if (isset($select_title_array[$i][1])) {
            if ($select_title_array[$i][1] == 1) {
                $string .= ' (' . mh_lng('MAILBEEZ_RECOMMENDED') . ')';
                $string .= '</b>';
            } else if ($select_title_array[$i][1] == -1) {
                $string .= ' (' . mh_lng('MAILBEEZ_LEGACY') . ')';
                $string .= '</i>';
            }
        }

    }

    return $string;
}


function mh_cfg_select_multioption($select_array, $key_value, $key = '')
{
    // thanks to zencart
    $string = '';
    for ($i = 0; $i < sizeof($select_array); $i++) {

        if (!isset($select_array[$i]))
            continue; // in case of label entries the size is 2x

        $name = (($key) ? 'configuration[' . $key . '][]' : 'configuration_value');
        $string .= '<br /><input type="checkbox" name="' . $name . '" value="' . $select_array[$i] . '"';
        $key_values = explode(", ", $key_value);
        if (in_array($select_array[$i], $key_values))
            $string .= ' CHECKED';
        $string .= ' id="' . strtolower($select_array[$i] . '-' . $name) . '"> ' . '<label for="' . strtolower($select_array[$i] . '-' . $name) . '" class="inputSelect">';

        if (getenv('SAAS_ENV')) {
            $string .= $select_array['label' . $i];
        } else {
            $string .= ($select_array['label' . $i] != '') ? $select_array[$i] . ' - ' . $select_array['label' . $i]
                : $select_array[$i];
        }

        $string .= '</label>' . "\n";
    }
    $string .= '<input type="hidden" name="' . $name . '" value="--none--">';
    return $string;
}


function mh_cfg_multiselect_order_status($key_value, $key = '')
{
    $select_array = array();
    if (method_exists('beez_pro', 'getOrderStatus')) {
        $select_array = beez_pro::getOrderStatus(false);
    }
    return mh_cfg_select_multioption($select_array, $key_value, $key);
}


function mh_cfg_pull_down_order_statuses()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_cfg_pull_down_order_statuses', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('cfg_pull_down_order_statuses', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_cfg_pull_down_order_statuses', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_cfg_pull_down_order_statuses', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_get_order_status_name()
{
    if (mh_cfg('MH_CONTEXT') == 'STORE') return; // not defined in storefront

    $args = func_get_args();

    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_get_order_status_name', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('get_order_status_name', makeValuesReferenced($args));
            break;
        case 'zencart':
            $args[0] = (int)$args[0];
            return call_user_func_array('zen_get_order_status_name', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_get_order_status_name', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}


function mh_get_order_status_name_multiple()
{
    $args = func_get_args();
    $list_of_order_status = $args[0];
    $array_of_order_status = array();
    if ($list_of_order_status != '--none--') {
        $array_of_order_status = array_filter(explode(',', $list_of_order_status));
    }

    if (sizeof($array_of_order_status) > 0) {
        foreach ($array_of_order_status as $k => $value) {
            $args[0] = $value;
            $array_of_order_status_names[] = call_user_func_array('mh_get_order_status_name', makeValuesReferenced($args));
        }

        $list_of_order_status_names = implode(',', $array_of_order_status_names);
    } else {

        return mailbeez::formatStatusMsg(mh_lng('MAILBEEZ_STATUS_EMPTY_WARNING', 'NO STATUS CONFIGURED'));
    }
    return $list_of_order_status_names;
}


function mh_update_config_value($config_array)
{
    return mailbeez_configuration_wrapper::update($config_array);
}

/**
 * @param string $key
 * @param string $value
 * @param array $meta
 */

function mh_insert_or_update_config_value($key, $value, $meta = array())
{
    return mailbeez_configuration_wrapper::insertOrUpdate($key, $value, $meta);
}


function mh_insert_config_value($config_array, $do_update = false)
{
    return mailbeez_configuration_wrapper::insert($config_array, $do_update);
}

/**
 * @param string $config_key
 * @return array
 */

function mh_read_config_item($config_key)
{
    return mailbeez_configuration_wrapper::read($config_key);
}

/**
 * @param string $config_key
 * @return boolean
 */


function mh_delete_config_value($config_key)
{
    return mailbeez_configuration_wrapper::delete($config_key);
}

/**
 * @param array $config_keys_array
 * @return boolean
 */

function mh_delete_config_values($config_keys_array)
{
    return mailbeez_configuration_wrapper::delete($config_keys_array);
}

/**
 * @param string $config_key_like
 * @param string $except_config_key
 * @return boolean
 */

function mh_delete_config_values_like($config_key_like, $except_config_key = null)
{
    return mailbeez_configuration_wrapper::deleteLike($config_key_like, $except_config_key);
}


function mh_register_module($module_config_key, $modules)
{

    $add_modules = array();
    if (is_array($modules)) {
        $add_modules = $modules;
    } else {
        $add_modules[] = $modules;
    }

    $return = mh_read_config_item($module_config_key);
    $result = $return['result'];
    if ($result) {
        $installed_modules = explode(';', $return['value']);
        $installed_modules = array_filter(array_unique($installed_modules));
        if (is_array($installed_modules)) {
//                print_r($add_modules);
//                print_r($installed_modules);
//                dd(123);
            if (count(array_intersect($add_modules, $installed_modules)) == 0) {
                $updated_modules = array_merge($installed_modules, $add_modules);
            } else {
                $updated_modules = $installed_modules;
            }
        } else {
            $updated_modules = $add_modules;
        }
        return mh_update_config_value(array('configuration_title' => 'Installed Modules',
            'configuration_key' => $module_config_key,
            'configuration_value' => implode(';', $updated_modules)
        ));
    } else {
        return mh_insert_config_value(array('configuration_title' => 'Installed Modules',
            'configuration_key' => $module_config_key,
            'configuration_value' => implode(';', $add_modules),
            'configuration_description' => 'This is automatically updated. No need to edit.',
            'set_function' => ''
        ));
    }

}


function mh_install_module($module_config_key, $modules)
{
    $install_modules = array();
    if (is_array($modules)) {
        $install_modules = $modules;
    } else {
        $install_modules[] = $modules;
    }
}


function mh_admin_modal($href, $text, $width = null, $height = null, $isTransparent = false) {
    $widthParam = (int)$width ? ',' . (int)$width . ',' : 'null ,';
    $heightParam = (int)$height ? (int)$height . ',' : 'null ,';

    return '<a onclick="return openModal(\'' . $href . '\'' . $widthParam . $heightParam .  (bool)$isTransparent . ')" href="' . $href . '" >' . $text . '</a>';
}

function mb_admin_button($href, $text, $id = '', $mode = 'popup', $type = 'button', $parameters = '', $location = 'document', $ceebox = 'iframe width:1000', $target = '_blank')
{
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
        case 'zencart':
        case 'xtc':
        case 'gambio':
        case 'mercari':
        default:
            if ($mode == 'popup') {
                if ($type == 'button') {
                    if (mh_cfg('MAILBEEZ_MAILHIVE_POPUP_MODE') == 'CeeBox') {
                        if (MH_PLATFORM_OSC_23) {
                            return tep_draw_button($text, 'document', $href, '', array('type' => 'submit', 'params' => $parameters . ' class="ceebox" rel="' . $ceebox . '"'));
                        } else {
                            return '<a id="' . $id . '" class="ceebox button_mailbeez" rel="' . $ceebox . '" ' . $parameters . ' href="' . $href . '" target="' . $target . '"><input class="button mailbeez" type="Button" onclick="return false;" value="' . $text . '"></a>';
                        }
                    } else {
                        return '<a id="' . $id . '" style="border: 1px solid black; padding: 3px; margin: 5px; line-height: 25px; " ' . $parameters . ' href="' . $href . '" target="' . $target . '">' . $text . '</a>';
                    }
                } elseif ($type == 'link') {
                    return '<a id="' . $id . '" ' . $parameters . '  class="ceebox" rel="' . $ceebox . '" ' . $parameters . ' href="' . $href . '" target="' . $target . '">' . $text . '</a>';
                }
            }


            if ($mode == "link") {
                if ($type == 'button') {
                    if (mh_cfg('MAILBEEZ_MAILHIVE_POPUP_MODE') == 'CeeBox') {
                        if (MH_PLATFORM_OSC_23) {
                            return tep_draw_button($text, 'document', $href, '', array('type' => 'submit', 'params' => $parameters));
                        } else {
                            return '<a id="' . $id . '" class="button_mailbeez" ' . $parameters . ' href="' . $href . '"><input class="button mailbeez" href="' . $href . '" type="Button" onclick="' . $location . '.location.href=\'' . $href . '\'; return false;" value="' . $text . '"></a>';
                        }
                    } else {
                        return '<a id="' . $id . '" style="border: 1px solid black; padding: 3px; margin: 5px; line-height: 25px; " href="' . $href . '" ' . $parameters . '  target="' . $target . '">' . $text . '</a>';
                    }
                } elseif ($type == 'link') {
                    return '<a id="' . $id . '" ' . $parameters . ' href="' . $href . '" target="' . $target . '">' . $text . '</a>';
                }
            }
    }
    return '';
}

function mh_get_category_name()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_get_category_name', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('get_category_name', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_get_category_name', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_get_category_name', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_get_category_tree()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_get_category_tree', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('get_category_tree', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_get_category_tree', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_get_category_tree', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_get_products_name()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_get_products_name', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('get_products_name', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_get_products_name', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_get_products_name', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_get_products_special_price()
{
    $result = false;

    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            $result = call_user_func_array('tep_get_products_special_price', makeValuesReferenced($args));
            break;
        case 'mercari':
            $result = call_user_func_array('get_products_special_price', makeValuesReferenced($args));
            break;
        case 'zencart':
            $result = call_user_func_array('zen_get_products_special_price', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':

            // not available in store front
            // declared in 'admin/includes/functions/general.php'
            if (!function_exists('xtc_get_products_special_price')) {
                function xtc_get_products_special_price($product_id)
                {
                    $product_query = xtc_db_query("SELECT specials_new_products_price FROM " . TABLE_SPECIALS . " WHERE products_id = '" . (int)$product_id . "' AND status = 1");
                    $product = xtc_db_fetch_array($product_query);
                    return $product['specials_new_products_price'];
                }
            }
            $result = call_user_func_array('xtc_get_products_special_price', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }

    return $result;
}

function mh_add_tax()
{
    $result = false;

    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            $result = call_user_func_array('tep_add_tax', makeValuesReferenced($args));
            break;
        case 'mercari':
            $result = call_user_func_array('add_tax', makeValuesReferenced($args));
            break;
        case 'zencart':
            $result = call_user_func_array('zen_add_tax', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            if (isset($xtPrice)) {
                $result = $xtPrice->xtcAddTax($args);
            } else {
                $result = call_user_func_array('xtc_add_tax', makeValuesReferenced($args));
            }
            break;
        default:
            return 'platform not supported';
    }
    return $result;
}

function mh_get_tax_rate()
{
    $result = false;

    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            $result = call_user_func_array('tep_get_tax_rate', makeValuesReferenced($args));
            break;
        case 'mercari':
            $result = call_user_func_array('get_tax_rate', makeValuesReferenced($args));
            break;
        case 'zencart':
            $result = call_user_func_array('zen_get_tax_rate', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            $result = call_user_func_array('xtc_get_tax_rate', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
    return $result;
}

function mh_get_all_get_params()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_get_all_get_params', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('get_all_get_params', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_get_all_get_params', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_get_all_get_params', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}


function mh_draw_pull_down_menu()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_draw_pull_down_menu', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('draw_pull_down_menu', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_draw_pull_down_menu', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_draw_pull_down_menu', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_hide_session_id()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_hide_session_id', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('hide_session_id', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_hide_session_id', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_hide_session_id', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_address_format()
{
    $args = func_get_args();
    switch (MH_PLATFORM) {
        case 'oscommerce':
        case 'creloaded':
        case 'digistore':
            return call_user_func_array('tep_address_format', makeValuesReferenced($args));
            break;
        case 'mercari':
            return call_user_func_array('address_format', makeValuesReferenced($args));
            break;
        case 'zencart':
            return call_user_func_array('zen_address_format', makeValuesReferenced($args));
            break;
        case 'xtc':
        case 'gambio':
            return call_user_func_array('xtc_address_format', makeValuesReferenced($args));
            break;
        default:
            return 'platform not supported';
    }
}

function mh_validate_email($email)
{
    if (function_exists('filter_var')) { // PHP 4 compatibility
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $return = false;
        } else {
            $return = true;
        }
    } else {
        $return = preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
    }
    return $return;
}

function mh_tabs($filename, $tab)
{
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}

if (!function_exists('sortbykeylength')) {

    function sortbykeylength($a, $b)
    {
        $alen = strlen($a);
        $blen = strlen($b);
        $r = '';
        if ($alen == $blen)
            $r = 0;
        if ($alen < $blen)
            $r = 1;
        if ($alen > $blen)
            $r = -1;
        return $r;
    }

}

function mh_add_magic_slashes($str)
{
    return addslashes($str);

}

function mh_strip_magic_slashes($str)
{
    return $str;
}


function mhpi()
{
    $args = func_get_args();
    if (function_exists('mh_pro_inc')) {
        return call_user_func_array('mh_pro_inc', makeValuesReferenced($args));
    }
    $id = array_shift($args); // remove args[0]
    return $args;
}

if (!function_exists('mhcc')) {
    function mhcc($c)
    {
        return $c;
    }
}

if (!function_exists('mhpm')) {
    function mhpm($c)
    {
        return false;
    }
}

function mh_setDefaultMessage($messageStack)
{
    if (!mh_template_check_writeable()) {
        $messageStack->add('<b>' . MH_ROOT_PATH . 'common/template_c</b> needs to be writeable (it is not!)', 'error');
    }

    require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_image_engine.php');

    if (!mailbeez_image_engine::checkCacheDirWriteable()) {
        $messageStack->add(sprintf(mh_lng('WARNING_IMG_CACHE_DIR'), mh_lng('MAILBEEZ_CONFIG_IMAGE_CACHE_FS')), 'error');
    }
}


// alias
function mh_session_write_close()
{
    return mh_session_close();
}

function mh_session_close()
{
    if (PHP_VERSION >= '4.0.4') {
        return session_write_close();
    } elseif (function_exists('session_close')) {
        return session_close();
    }
}

function mh_exit()
{
    mh_session_write_close();
    mh_db_close();
    exit();
}

// php 5.3 compatibility
// http://stackoverflow.com/questions/2045875/pass-by-reference-problem-with-php-5-3-1
function makeValuesReferenced(&$arr)
{
    $refs = array();
    foreach ($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    return $refs;

}

function mh_language_documentation_url($url)
{
    // rewrite url to mailbeez.de
    switch ($_SESSION['language']) {
        case "german":
            $url = str_replace('mailbeez.com/documentation', 'mailbeez.de/dokumentation', $url);
            break;
    }
    $url = str_replace('http://', 'https://', $url);
    return $url;
}

/*
 *
 * todo
 *
class mh_splitPageResults
{
    function mh_splitPageResults(&$current_page_number, $max_rows_per_page, &$sql_query, &$query_num_rows)
    {


        // oscommerce
        // (&$current_page_number, $max_rows_per_page, &$sql_query, &$query_num_rows)
        // $arg[0]: $page
        // $arg[1]: $max_rows
        // $arg[2]: $sql_query
        // $arg[3]: $query_num_rows


        // gambio
        // ($query, $page, $max_rows, $count_key = '*')

        $result = false;

        $args = func_get_args();
        switch (MH_PLATFORM) {
            case 'oscommerce':
            case 'creloaded':
            case 'digistore':
            case 'mercari':
                // splitPageResults(&$current_page_number, $max_rows_per_page, &$sql_query, &$query_num_rows)
                return new splitPageResults($current_page_number, $max_rows_per_page, $sql_query, $query_num_rows);
                break;
            case 'zencart':
                $result = new splitPageResults($args[0], MAX_DISPLAY_PRODUCTS_LISTING, 'p.products_id', 'page');
                break;
            case 'xtc':
            case 'gambio':


                // splitPageResults(mh_get(MH_PAGE_NAME), 10, $bewertung_query, $reviews_query_numrows)
                // splitPageResults($voting->getReviewSQL(true, $_GET['display']), (int)mh_get(MH_PAGE_NAME), $voting->entry_per_page_frontend)
                $result = new splitPageResults($args[0], $args[1], $args[2]);
                break;
            default:
                return 'platform not supported';
        }
        return $result;


        new splitPageResults($sql, (int)$_GET['page'], $voting->entry_per_page_frontend);


    }
}
*/

class mh_objectInfo
{
// class constructor

    function __construct($object_array)
    {
        if (is_array($object_array)) {
            reset($object_array);
            foreach ($object_array as $key => $value) {
                $this->$key = mh_objectInfo_prepare($value);
            }
        }
    }
}

function mh_objectInfo_prepare($string)
{
    if (is_string($string)) {
        return trim((stripslashes($string)));
    } elseif (is_array($string)) {
        reset($string);
        foreach ($string as $key => $value) {
            $string[$key] = mh_objectInfo_prepare($value);
        }
        return $string;
    } else {
        return $string;
    }
}

if (!function_exists('mh_smart_force_utf8')) {
    function mh_smart_force_utf8($string, $autofix = true)
    {
        if (strtoupper(mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET')) != 'UTF-8') {
            return mh_force_utf8($string);
        } elseif ($autofix) {
            return mh_fix_utf8($string);
        } else {
            return $string;
        }
    }
}


function mh_force_utf8($string)
{
    $utf8_string = ForceUTF8_Encoding::toUTF8($string);
    return $utf8_string;
}

function mh_fix_utf8($string)
{
    $utf8_string = ForceUTF8_Encoding::fixUTF8($string);
    return $utf8_string;
}

function mh_storage_set($key, $value, $group = 'general')
{
    $id = 'mh_storage_' . $group;
    if (!(isset($GLOBALS[$id]) && is_object($GLOBALS[$id]))) {
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_storage.php');
        $GLOBALS[$id] = new mailbeez_storage($group);
    }
    return $GLOBALS[$id]->set($key, $value);
}


function mh_storage_destroy($key, $group = 'general')
{
    $id = 'mh_storage_' . $group;
    if (!(isset($GLOBALS[$id]) && is_object($GLOBALS[$id]))) {
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_storage.php');
        $GLOBALS[$id] = new mailbeez_storage($group);
    }
    $GLOBALS[$id]->destroy($key);
}

function mh_storage_get($key, $group = 'general')
{
    $id = 'mh_storage_' . $group;
    if (!(isset($GLOBALS[$id]) && is_object($GLOBALS[$id]))) {
        require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_storage.php');
        $GLOBALS[$id] = new mailbeez_storage($group);
    }
    return $GLOBALS[$id]->get($key);
}


if (!function_exists('array_column')) {
    function array_column(array $input, $columnKey, $indexKey = null)
    {
        $array = array();
        foreach ($input as $value) {
            if (!array_key_exists($columnKey, $value)) {
                trigger_error("Key \"$columnKey\" does not exist in array");
                return false;
            }
            if (is_null($indexKey)) {
                $array[] = $value[$columnKey];
            } else {
                if (!array_key_exists($indexKey, $value)) {
                    trigger_error("Key \"$indexKey\" does not exist in array");
                    return false;
                }
                if (!is_scalar($value[$indexKey])) {
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
                    return false;
                }
                $array[$value[$indexKey]] = $value[$columnKey];
            }
        }
        return $array;
    }
}


/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 */
function mh_array_insert_after($key, array &$array, $new_key, $new_value)
{
    if (array_key_exists($key, $array)) {
        $new = array();
        foreach ($array as $k => $value) {
            $new[$k] = $value;
            if ($k === $key) {
                $new[$new_key] = $new_value;
            }
        }
        return $new;
    }
    return FALSE;
}


function mh_free(&$var)
{
//    return true;
    // http://www.srcnix.com/tips/php/7-tips-to-prevent-php-running-out-of-memory/

    if (is_object($var) && (get_class($var) == "mysqli_result")) {
        // https://stackoverflow.com/questions/23695418/how-to-check-if-the-mysqli-object-has-been-freed
        // avoid error mysqli_result object is already closed
        if ($var->num_rows) {
            mh_db_free_result($var);
        }
    } elseif (isset($var)) {
        $var = null;
        unset($var);
    }
}

function mh_saas()
{
    return getenv('SAAS_ENV');
}

function mh_beezui() {
    return mh_cfg('MAILBEEZ_CONFIG_BEEZ_UI') == 'True';
}


if (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING') != '') {
    mh_define('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET', mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING'));
} elseif (isset ($_SESSION['language_charset'])) {
    mh_define('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET', $_SESSION['language_charset']);
} elseif (MH_PLATFORM == 'xtc') {
    $lang_query = "SELECT * FROM " . TABLE_LANGUAGES . " WHERE code = '" . mh_cfg('DEFAULT_LANGUAGE') . "'";
    $lang_query = mh_db_query($lang_query);
    $lang_data = mh_db_fetch_array($lang_query);
    mh_define('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET', $lang_data['language_charset']);
} elseif (mh_cfg('CHARSET')) {
    mh_define('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET', mh_cfg('CHARSET'));
} else {
    // Fallback
    mh_define('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET', 'UTF-8');
}

mh_define('CHARSET', (isset ($_SESSION['language_charset'])) ? $_SESSION['language_charset'] : mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET'));

$cloudbeez_select_package_button = false;

$mh_store_url = (defined('MAILBEEZ_SAAS_CLIENT_URL')) ? MAILBEEZ_SAAS_CLIENT_URL : HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG;

//if (mh_get_conf('MH_CONTEXT') == 'STORE') {
$GLOBALS['mh_template_replace_variables_common'] = array(
    'catalog_server' => HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG,
    'catalog_server_ssl' => HTTPS_CATALOG_SERVER . MH_DIR_WS_CATALOG,
    'root_catalog' => HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG,
    'mailhive_path' => MH_ROOT_PATH,
    'storename' => mh_cfg('STORE_NAME'),
    'storeowner' => mh_cfg('STORE_OWNER'),
    'storecompany' => (mh_cfg('COMPANY_NAME')) ? mh_cfg('COMPANY_NAME') : mh_cfg('STORE_NAME'),
    'storeurl' => $mh_store_url,
    'store_url' => $mh_store_url,
    'page_contact_us' => defined('FILENAME_CONTACT_US') ? mh_href_email_link(FILENAME_CONTACT_US) : 'not defined - modify email_html.tpl template',
    'page_customer_support' => defined('FILENAME_CONTACT_US') ? mh_href_email_link(FILENAME_CONTACT_US) : 'not defined - modify email_html.tpl template',
    'page_my_account' => defined('FILENAME_ACCOUNT') ? mh_href_email_link(FILENAME_ACCOUNT) : 'not defined - modify email_html.tpl template',
    'page_password' => defined('FILENAME_ACCOUNT_PASSWORD') ? mh_href_email_link(FILENAME_ACCOUNT_PASSWORD) : 'not defined - modify email_html.tpl template',
    'blank_img' => HTTP_CATALOG_SERVER . MH_ADMIN_DIR_WS_IMAGES . 'blank.gif',
    'themes_root' => HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'common/templates',
    'modules_root' => HTTP_CATALOG_SERVER . MH_DIR_WS_CATALOG . MH_ROOT_PATH . 'mailbeez/',
    'MAILBEEZ_TRACKER_PIX' => mh_cfg('MH_OPENTRACKER_ENABLED') ? '<img src="' . mh_cfg('MAILBEEZ_TRACKER_URL') . '" width="1" height="1">' : '',
    'MAILBEEZ_TEMPLATE_MANAGER_INSTALLED' => mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_STATUS') == 'True' or mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True' ? true : false,
    'MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET' => mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE_ENCODING_SET'),
    'MAILBEEZ_COMMON_CSS' => '',
    'MH_CIS_URL' => mh_cfg('MH_CIS_URL')
);

if (isset($GLOBALS_OVERRIDES)) {
    if (isset($GLOBALS_OVERRIDES['mh_template_replace_variables_common'])) {
        foreach ($GLOBALS_OVERRIDES['mh_template_replace_variables_common'] as $k => $v) {
            $GLOBALS['mh_template_replace_variables_common'][$k] = $v;
        }
    }
}

//if (defined('MH_PLATFORM_OSC_WPOS') && MH_CONTEXT == 'STORE') {
if (defined('MH_PLATFORM_OSC_WPOS')) {
    $GLOBALS['mh_template_replace_variables_common']['storeurl'] = mh_href_email_link('index.php');
}
//}
if (mh_cfg('MH_CONTEXT') == 'ADMIN') {
    mh_define('MH_CIS_URL', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php&popup=true'));
    mh_define('MAILBEEZ_CONTEXT_VIEW_URL', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php'));

    if (!mh_session('MH_ADMIN_DIR')) {
        $admin_dir = str_replace(DIR_WS_CATALOG, '', DIR_WS_ADMIN);

        $admin_dir = str_replace('//', '/', $admin_dir .= '/');

        mh_insert_config_value(array('configuration_title' => 'Admin Directory',
            'configuration_key' => 'MAILBEEZ_BEEZDESK_ADMIN_DIR',
            'configuration_value' => $admin_dir,
            'configuration_description' => 'Admin Directory of this Store - important for the customer insight window',
            'set_function' => ''
        ));
        $_SESSION['MH_ADMIN_DIR'] = $admin_dir;
    }

} else {
    mh_define('MH_CIS_URL', mh_href_link(mh_session('MH_ADMIN_DIR', 'admin/') .FILENAME_MAILBEEZ, 'app=load_app&app_path=config_customer_insight/admin_application_plugins/context_view.php&popup=true'));
}

mh_define('MH_API_ACTION_PARAM', 'mh_action'); // for zencart it must be different from "action" -> otherwise it is blocked in /includes/init_includes/init_sanitize.php


mh_define('MAILBEEZ_API_KEY', mh_cfg('MAILBEEZ_API_KEY'));
mh_define('MAILBEEZ_API_ENTRYPOINT', mh_cfg('MAILBEEZ_API_ENTRYPOINT'));

mh_define('MH_ADMIN_DIR_WS_IMAGES', mh_cfg('MH_ADMIN_DIR_WS_IMAGES'));
mh_define('MH_CLICKTRACKER_ENABLED', mh_cfg('MH_CLICKTRACKER_ENABLED'));
mh_define('MAILBEEZ_MAILHIVE_GA_ENABLED', mh_cfg('MAILBEEZ_MAILHIVE_GA_ENABLED'));
mh_define('MAILBEEZ_MOUSEFLOW_STATUS', mh_cfg('MAILBEEZ_MOUSEFLOW_STATUS'));
mh_define('MAILBEEZ_MAILHIVE_PIWIK_ENABLED', mh_cfg('MAILBEEZ_MAILHIVE_PIWIK_ENABLED'));
mh_define('MAILBEEZ_MAILHIVE_ECONDA_ENABLED', mh_cfg('MAILBEEZ_MAILHIVE_ECONDA_ENABLED'));
mh_define('MAILBEEZ_THROTTLING_RATE', mh_cfg('MAILBEEZ_THROTTLING_RATE'));
mh_define('MAILBEEZ_THROTTLING_MAX', mh_cfg('MAILBEEZ_THROTTLING_MAX'));
/*

mh_insert_config_value(array(
            'configuration_title' => 'qwe check for empty customer basket',
            'configuration_key' => 'MAILBEEZ_WINBACK_ADVANCED_CB',
            'configuration_value' => 'True',
            'configuration_description' => 'send only when customer basket is empty?',
            'set_function' => 'mh_cfg_select_option(array(\'True\', \'False\'), '
        ));

$r = mh_read_config_item('MAILBEEZ_WINBACK_ADVANCED_CB');
print_r($r );
//dd(1);
mh_update_config_value(array(

            'configuration_key' => 'MAILBEEZ_WINBACK_ADVANCED_CB',
            'configuration_value' => 'False',
            'set_function' => 'mh_cfg_select_option(array(\'123\', \'False\'), '
        ));
echo 123;
$r = mh_read_config_item('MAILBEEZ_WINBACK_ADVANCED_CB');
print_r($r );

dd('5');
dd($r);

*/