<?php

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

  Copyright (c) 2010, 2011, 2012 MailBeez

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

  Released under the GNU General Public License

  v2.7.1
 */


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

mh_define('_VALID_XTC', true);

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


class mailHive
{

    var $modules, $selected_module;

// class constructor
    function __construct($load_module = '', $track_image = false)
    {
        global $PHP_SELF;

        if ($track_image) {
            return true;
        }

        if (mh_cfg('MAILBEEZ_INSTALLED')) {

            // precheck if email archive DB is working

            $eaFile = MH_DIR_CONFIG . 'config_email_archive.php';
            if (file_exists($eaFile) && mh_cfg('MAILBEEZ_EMAIL_ARCHIVE_STATUS') == 'True') {
                require_once($eaFile);

                if (method_exists('config_email_archive', 'checkDB')) {
                    $result = config_email_archive::checkDB();
                    require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/notificationbeez.php');
                    if (!$result) {
                        $icon_warning = 'background-image: url(' . mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'dashboardbeez/dashboard_status/viewbeez/icon.png); background-color: #f8933c';

                        $msg = 'The Email Archive Database Table appears to be broken. Sending will be paused, until the issue is fixed. Please contact the friendly MailBeez Support';

                        (new notificationbeez())->add(array('module' => 'email_archive',
                                'title' => 'Email Archive broken',
                                'notification_summary' => 'Please check your Database',
                                'notification' => $msg,
                                'ref_id' => date("Ymd"), // once a day
                                'iteration' => 1,
                                'customers_id' => null,
                                'severity' => 2,
                                'link' => '##shownotification##',
                                'link_type' => 'P', // E - external, I - internal, P - popup
                                'panel_click_action' => 'H', // H - hide
                                'channel_id' => 0,
                                'status' => '0',
                                'icon_style' => $icon_warning)
                        );
                        echo($msg);
                        mh_exit();
                    } else {
                        (new notificationbeez())->deleteNotification('email_archive');
                    }
                }
            }

            $this->modules = explode(';', mh_cfg('MAILBEEZ_INSTALLED'));

            // add core modules
            $this->modules[] = 'service_handler_bounce_ubvx.php';
            $this->modules = array_unique($this->modules);


            reset($this->modules);
            foreach ($this->modules as $idx => $mailbee) {
                $module = substr($mailbee, 0, strrpos($mailbee, '.'));
                //if ($mailbee == 'config.php') {
                if (preg_match('/^config/', $mailbee)) {
                    // exclude config modules
                    continue;
                }
                if ($load_module != '' && $load_module != $module) {
                    continue;
                }
                $class = mh_get_class_name($mailbee);
                if (!array_key_exists($module, $GLOBALS) || !is_object($GLOBALS[$module])) {
                    include_once(mh_cfg('MH_DIR_FS_CATALOG') . mh_cfg('MH_ROOT_PATH') . 'mailbeez/' . $mailbee);
                    if (class_exists($class)) {
                        $module_path = mh_get_class_path($class);
                        mh_load_modules_language_files(mh_cfg('MH_MODULE_DIRECTORY'), $module_path);
                        if (!isset($GLOBALS[$class]) || !is_object($GLOBALS[$class])) {
                            $GLOBALS[$module] = new $class;
                        }
//                        echo $module;
                    }
                }
            }
        }
    }

    function mailHive($load_module = '', $track_image = false)
    {
        return self::__construct($load_module, $track_image);
    }

// class methods
    function update_status()
    {
        if (is_array($this->modules)) {
            if (is_object($GLOBALS[$this->selected_module])) {
                if (function_exists('method_exists')) {
                    if (method_exists($GLOBALS[$this->selected_module], 'update_status')) {
                        $GLOBALS[$this->selected_module]->update_status();
                    }
                }
            }
        }
    }

    function process($call_module = '')
    {
        global $request_profiler;
        $request_profiler->restart('mailhive_process');

        $process_lock_timestamp = $this->check_process_lock();


        if ($process_lock_timestamp != false) {
            echo $this->get_process_lock_info($process_lock_timestamp);
            return false;
        }

        $call_module = mh_urldecode($call_module);
        if (is_array($this->modules)) {
            reset($this->modules);
            foreach ($this->modules as $idx => $value) {
                $module_id = substr($value, 0, strrpos($value, '.'));
                if ($call_module != '' && $module_id != $call_module) {
                    continue;
                }

                // not called directly
                if ($call_module == '' && $module_id == 'mb_newsletter' && mh_cfg('MAILBEEZ_NEWSLETTER_WORKER_ENABLED') == 'True') {
                    continue;
                }

                $this->output_flush();
                $this->update_process_lock();
                if ($GLOBALS[$module_id]->enabled && $GLOBALS[$module_id]->do_process && $GLOBALS[$module_id]->get_do_run()) {
                    echo '<a name="1" style="line-height: 0px;">&nbsp;</a>';
                    // call process method of module
                    $result[$module_id] = $GLOBALS[$module_id]->process();
                    $this->output_result($result[$module_id]);
                } elseif ($GLOBALS[$module_id]->enabled && $GLOBALS[$module_id]->do_process && !$GLOBALS[$module_id]->get_do_run()) {
                    echo '<hr><div class="i">MailBeez Module ' . $GLOBALS[$module_id]->get_module_id() . ' not scheduled for this run</div><hr>';
                } elseif (!$GLOBALS[$module_id]->enabled && $GLOBALS[$module_id]->do_process) {
                    if ($GLOBALS[$module_id]->code) {
                        echo '<hr><div class="w"><h2>module ' . $GLOBALS[$module_id]->get_module_id() . ' is disabled - please enable to process</h2></div><hr>';
                    }
                } else {
                    // nothing to do, module is not active

                }
            }
        }
    }

    function run($call_module = '')
    {
        global $request_profiler;
        $request_profiler->restart('mailhive_run');
        $call_module = mh_urldecode($call_module);

        if ($call_module == 'mb_newsletter' && mh_cfg('MAILBEEZ_NEWSLETTER_WORKER_ENABLED') == 'True') {
            $worker_id = $this->get_process_worker();
            if (!$worker_id) {
                echo "All Workers are busy";
                return false;
            }
            define('MAILBBEEZ_EVENTLOG_WORKER_ID', $worker_id);
        } else {
            $process_lock_timestamp = $this->check_process_lock();

            if ($process_lock_timestamp != false) {
                echo $this->get_process_lock_info($process_lock_timestamp);
                return false;
            }
        }

        // run all active modules
        // log trigger of mailhive

        $this->start_process_lock();


        mh_event_log('MAILHIVE_RUN_INIT', 'mailhive run initiated', 'mailhive'); // todo: event type
        $result = $this->process($call_module);
        // log trigger of mailhive
        mh_event_log('MAILHIVE_RUN_COMPLETE', 'mailhive run completed', 'mailhive'); // todo: event type
        $this->clear_process_lock();

        $this->maintainance();

        return true;
    }

    function listAudience($call_module = '')
    {
        global $request_profiler;

        $call_module = mh_urldecode($call_module);
        if (is_array($this->modules)) {
            reset($this->modules);
            foreach ($this->modules as $idx => $value) {
                $module_id = substr($value, 0, strrpos($value, '.'));
                if ($call_module != '' && $module_id != $call_module) {
                    continue;
                }
                echo '<a name="1" style="line-height: 0px;">&nbsp;</a>';
                // call process method of module
                $request_profiler->restart('mailhive_listAudience_start:' . $module_id);
                $result[$module_id] = $GLOBALS[$module_id]->listAudience();
                $request_profiler->restart('mailhive_listAudience_end:' . $module_id);
                $this->output_flush();
                $this->output_result($result[$module_id]);
            }
        }
    }

    function sendTest($email, $call_module, $maintemplate_id)
    {
        global $request_profiler;
        $request_profiler->restart('mailhive_sendTest');
        $result = false;

        $call_module = mh_urldecode($call_module);
        mh_event_log('MAILHIVE_TEST_INIT', 'mailhive initiated', 'mailhive'); // todo: event type
        if (is_array($this->modules)) {
            reset($this->modules);
            foreach ($this->modules as $idx => $value) {
                $module_id = substr($value, 0, strrpos($value, '.'));
                if ($call_module != '' && $module_id != $call_module) {
                    continue;
                }
                echo '<a name="1" style="line-height: 0px;">&nbsp;</a>';
                // call process method of module
                if ($maintemplate_id != '') {
                    $GLOBALS[$module_id]->set_preview_maintemplate_id($maintemplate_id);
                }

                $result[$module_id] = $GLOBALS[$module_id]->sendTest($email);
            }
        }
        // log trigger of mailhive
        mh_event_log('MAILHIVE_TEST_COMPLETE', 'mailhive test completed', 'mailhive'); // todo: event type
        return $result;
    }

    function viewMail($call_module = '', $format = 'html', $theme_id = '', $template_id = '', $maintemplate_id = '')
    {
        global $request_profiler;
        $request_profiler->restart('mailhive_viewMail');
        $result = [];
        if ($call_module == 'MAIN') {
            if (file_exists(MH_DIR_CONFIG . 'config_tmplmngr_lng/mb_main.php')) {
                include_once(MH_DIR_CONFIG . 'config_tmplmngr_lng/mb_main.php');
            } elseif (file_exists(MH_DIR_CONFIG . 'config_tmplmngr/mb_main.php')) {
                include_once(MH_DIR_CONFIG . 'config_tmplmngr/mb_main.php');
            } else {
                return false;
            }

            $class = 'mb_main';
            $GLOBALS[$class] = new $class;
            if ($maintemplate_id != '') {
                $GLOBALS[$class]->set_preview_maintemplate_id($maintemplate_id);
            }
            $result = ['MAIN' => $GLOBALS[$class]->viewMail($format)];
            return $result;
        }

        $call_module = mh_urldecode($call_module);
        if (is_array($this->modules)) {
            reset($this->modules);
            foreach ($this->modules as $idx => $value) {
                $module_id = substr($value, 0, strrpos($value, '.'));

                if ($call_module != '' && $module_id != $call_module) {
                    continue;
                }

                // legacy
                if ($format == 'html') {
                    if ($theme_id != '' || $template_id != '') {
                        $GLOBALS[$module_id]->apply_theme($theme_id, $template_id);
                    }
                }

                if ($maintemplate_id != '') {
                    $GLOBALS[$module_id]->set_preview_maintemplate_id($maintemplate_id);
                }

                $result[$module_id] = $GLOBALS[$module_id]->viewMail($format);
            }
        }

        if (count($result) == 0) {
            return false;
        }

        return $result;
    }

    // call an action on the module
    function moduleAction($call_module, $module_action, $module_params)
    {
        $call_module = mh_urldecode($call_module);
        if (is_array($this->modules)) {
            reset($this->modules);
            foreach ($this->modules as $idx => $value) {
                $module_id = substr($value, 0, strrpos($value, '.'));
                if ($call_module != '' && $module_id != $call_module) {
                    continue;
                }
                mh_log('module', $module_id);
                // call process method of module
                if (method_exists($GLOBALS[$module_id], $module_action)) {
                    $result[$module_id] = $GLOBALS[$module_id]->$module_action($module_params);
                    if ($call_module != '' && $module_id == $call_module) {
                        return $result;
                    }
                }
                if ($call_module != '' && $module_id == $call_module) {
                    return false;
                }
            }
        }
    }

    static function output_flush()
    {
        echo str_repeat(" ", 4096); // force a flush
        echo '<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
      <!--
      scrolldown();
      //-->
      </SCRIPT>';
        ob_flush();
        flush();
    }

    static function output_result($result)
    {
        if ($result > -1) {
            echo '<div class="result">';
            echo sprintf(mh_lng('MAILBEEZ_RESULT_MAILS', 'Result: %s Contacts'), $result);
            if ($result == 0) {
                echo '<br>' . mh_lng('MAILBEEZ_RESULT_MAILS_NOCONTACTS', 'no matching Contacts or all Mails have been sent');
            }
            echo '</div>';
        }
    }


    static function start_process_lock()
    {
        $GLOBALS['MAILBEEZ_MAILHIVE_PROCESS_CONTROL_INIT'] = true;
        return mailbeez::update_process_lock('', 'mailhive_open');
    }

    static function update_process_lock()
    {
        return mailbeez::update_process_lock('', 'mailhive_running');
    }

    static function clear_process_lock()
    {
        return mailbeez::update_process_lock(1, 'mailhive_closed');
    }

    static function check_process_lock()
    {
        mailbeez::gc_process(); // gc
        return mailbeez::check_process_lock();
    }

    static function get_process_worker()
    {
        mailbeez::gc_process(); // gc
        return mailbeez::get_process_worker();
    }

    static function get_process_lock_info($process_lock_timestamp)
    {
        return mailbeez::get_process_lock_info($process_lock_timestamp);
    }

    function maintainance()
    {
        // maintainance tasks

        // coupons
        if (class_exists('couponbeez')) {
            // fix missing coupon_ids
            $sql_query_raw = "select c.message_id, c.coupon_id from " . TABLE_MAILBEEZ_TRACKING_COUPONS . " c join " . TABLE_MAILBEEZ_TRACKING . " mt on ( c.message_id = mt.message_id) where mt.coupon_id is null and length(c.message_id) > 5 limit 1000";
            $sql_query = mh_db_query($sql_query_raw);
            while ($query = mh_db_fetch_array($sql_query)) {
                if ($query['message_id'] != '') {
                    couponbeez::_add_coupon_to_tracking($query['message_id'], $query['coupon_id']);
                }
            }


            // fix mailbeez_tracking.coupon_redeemed
            $sql_raw = "SELECT cr.coupon_id, count(*) as coupon_redeemed FROM " . TABLE_MAILBEEZ_TRACKING_COUPONS_REDEMPTION . " cr join " . TABLE_MAILBEEZ_TRACKING . " mt on (cr.coupon_id = mt.coupon_id) where coupon_redeemed = 0 and length(mt.message_id) > 5 group by coupon_id limit 1000";
            $sql = mh_db_query($sql_raw);
            while ($qrow = mh_db_fetch_array($sql)) {
                mh_db_query("update " . TABLE_MAILBEEZ_TRACKING . " set coupon_redeemed = '" . $qrow['coupon_redeemed'] . "' where coupon_id = '" . $qrow['coupon_id'] . "'");
            }
            echo "<br>maintainance tasks: done<br>";
        }

    }

}
