<?php
QUnit_Global::includeClass('QCore_Bl_Users');

class QCore_Bl_Communications
{
    function insert($params)
    {
        if($params['accountid'] == '' && is_object($GLOBALS['Auth']))
        {
            $params['accountid'] = $GLOBALS['Auth']->getAccountID();
        }

        if($params['message_type'] == '') $params['message_type'] = 1;

        //if($params['accountid'] == '')
        //    return false;

        $MessageID = QCore_Sql_DBUnit::createUniqueID('wd_g_messages', 'messageid');
        $sql = 'insert into wd_g_messages set '.
               'messageid='._q($MessageID).', '.
               'rtype='._q($params['message_type']).', '.
               'dateinserted='.sqlNow().', '.
               'title='._q($params['subject']).', '.
               'rtext='._q($params['text']).', '.
               'deleted='._q('0').', '.
               'accountid='._q($params['accountid']);
        if ($params['datevalidfrom'] != '') $sql .= ', datevalidfrom='._q($params['datevalidfrom']);
        if ($params['datevalidto'] != '') $sql .= ', datevalidto='._q($params['datevalidto']);
        if ($params['active'] != '') $sql .= ', active='._q($params['active']);
        if ($params['showtoall'] != '') $sql .= ', showtoall='._q($params['showtoall']);

        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        if($params['users'] != '' && is_array($params['users']))
        {
            $mus = array();
            foreach($params['users'] as $user)
            {
                $MessageToUserID = QCore_Sql_DBUnit::createUniqueID('wd_g_messagestousers', 'messagetouserid');
                $sql = 'insert into wd_g_messagestousers ('.
                       'messagetouserid, messageid, userid, email, fromuserid, rstatus'.
                       ') values '.
                       '('._q($MessageToUserID).','._q($MessageID).','._q($user['userid']).
                       ','._q($user['username']).','._q($GLOBALS['Auth']->getUserID()).','._q(MESSAGESTATUS_NOT_READED).')';
                $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
                if(!$ret) {
                    QUnit_Messager::setErrorMessage(L_G_DBERROR);
                    return false;
                }

                $mus[$user['userid']] = $MessageToUserID;
            }
        }
        else if ($params['users'] != '')
        {
            $MessageToUserID = QCore_Sql_DBUnit::createUniqueID('wd_g_messagestousers', 'messagetouserid');
            $sql = 'insert into wd_g_messagestousers ('.
                    'messagetouserid, messageid, userid, email, fromuserid, rstatus'.
                    ') values '.
                    '('._q($MessageToUserID).','._q($MessageID).','._q($params['userid']).
                    ','._q($params['email']).','._q($GLOBALS['Auth']->getUserID()).','._q(MESSAGESTATUS_NOT_READED).')';

            $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }

            $mus = $MessageToUserID;
        } else {
            return true;
        }

        return $mus;
    }

    //--------------------------------------------------------------------------

    function update($params)
    {
        if($params['mid'] == '') {
            return false;
        }

        $sql = 'select * from wd_g_messages where'.
               ' messageid='._q($params['mid']).
               ' and deleted=\'0\'';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs || $rs->EOF)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        $oldParams = $rs->fields;

        $sql = 'update wd_g_messages set'.
               ' title='._q($params['subject']).','.
               ' rtext='._q($params['text']).','.
               ' datevalidfrom='._q($params['datevalidfrom']).','.
               ' datevalidto='._q($params['datevalidto']).','.
               ' active='._q($params['active']).','.
               ' showtoall='._q($params['showtoall']).
               ' where messageid='._q($params['mid']);
        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        // new user assigment
        if ($params['showtoall'] != '1') {
            $p = array('accountid' => $params['accountid'],
                       'messageid' => $params['mid']);
            $oldUsers = $this->getOnlyUserIDsOfMessageAsArray($p);
            $newUsers = $params['users'];

            $usersToDelete = array_diff($oldUsers, $newUsers);
            $usersToCreate = array_diff($newUsers, $oldUsers);

            if (count($usersToDelete) > 0) {
                $chunkedUserIDs = my_array_chunk($usersToDelete, WD_MAX_PROCESSED_IDS);

                foreach($chunkedUserIDs as $userIDsArray)
                {
                    $userid_str = "('".implode("','", $userIDsArray)."')";

                    if($userid_str == '') return false;

                    $sql = 'delete from wd_g_messagestousers '.
                           'where messageid='._q($params['mid']).
                           '  and userid in '.$userid_str;
                    $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
                    if(!$ret) {
                        QUnit_Messager::setErrorMessage(L_G_DBERROR);
                        return false;
                    }
                }
            }
            if (count($usersToCreate) > 0) {
                foreach ($usersToCreate as $userid) {
                    if (($userInfo = $this->getUserInfo($userid)) == false)
                        continue;

                    $MessageToUserID = QCore_Sql_DBUnit::createUniqueID('wd_g_messagestousers', 'messagetouserid');
                    $sql = 'insert into wd_g_messagestousers ('.
                       'messagetouserid, messageid, userid, email, rstatus'.
                       ') values '.
                       '('._q($MessageToUserID).','._q($params['mid']).','._q($userid).
                       ','._q($userInfo['username']).','._q(MESSAGESTATUS_NOT_READED).')'; // username
                    $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
                    if(!$ret) {
                        QUnit_Messager::setErrorMessage(L_G_DBERROR);
                        return false;
                    }
                }
            }
        }

        // show again
        if ($params['show_again'] == '1') {
            $sql = 'update wd_g_messagestousers set'.
            ' rstatus='._q(MESSAGESTATUS_NOT_READED).
            ' where messageid='._q($params['mid']);
            $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function getUserInfo($userid) {
        $sql = 'select * from wd_g_users '.
               'where deleted=0 '.
               '  and userid='._q($userid).
               '  and rtype='._q(USERTYPE_USER);
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if (!$rs)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        if(!$rs->EOF)
        {
            return $rs->fields;
        }

        return false;
    }

    //--------------------------------------------------------------------------

    function getUsersOfMessageAsArray($params)
    {
        if($params['accountid'] == '') return array();

        $sql = 'select mu.*, u.name, u2.name as "fromuser" '.
               'from wd_g_messagestousers mu, wd_g_users u, wd_g_users u2 '.
               'where  u.deleted=\'0\' and u2.deleted=\'0\''.
               '  and u.userid=mu.userid and u2.userid=mu.fromuserid';
        if(isset($params['accountid']) && $params['accountid'] != SA_ACCOUNT_ID)
        	$sql .= ' and u.accountid='._q($params['accountid']);
        if($params['messageid'] != '') $sql .= '  and mu.messageid='._q($params['messageid']);
               ' order by u.name, u.surname';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return array();
        }

        $mus = array();

        while(!$rs->EOF)
        {
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['messagetouserid'] = $rs->fields['messagetouserid'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['messageid'] = $rs->fields['messageid'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['rstatus'] = $rs->fields['rstatus'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['userid'] = $rs->fields['userid'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['email'] = $rs->fields['email'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['name'] = $rs->fields['name'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['fromuserid'] = $rs->fields['fromuserid'];
            $mus[$rs->fields['messageid']][$rs->fields['messagetouserid']]['fromuser'] = $rs->fields['fromuser'];

            $rs->MoveNext();
        }

        return $mus;
    }

    //--------------------------------------------------------------------------

    function getOnlyUserIDsOfMessageAsArray($params)
    {
        if($params['accountid'] == '' || $params['messageid'] == '') return array();

        $sql = 'select mu.messageid, mu.userid '.
               'from wd_g_messagestousers mu, wd_g_users u '.
               'where u.accountid='._q($params['accountid']).
               '  and u.deleted=\'0\''.
               '  and u.userid=mu.userid'.
               '  and mu.messageid='._q($params['messageid']).
               ' order by u.name, u.surname';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return array();
        }

        $mus = array();

        while(!$rs->EOF)
        {
            $mus[] = $rs->fields['userid'];

            $rs->MoveNext();
        }

        return $mus;
    }

    //--------------------------------------------------------------------------

    function checkOldNewsExist($params)
    {
        if($params['accountid'] == '' || $params['userid'] == '') return false;

        $sql = 'select mu.messagetouserid, mu.messageid, m.dateinserted, m.title, mu.userid '.
               'from wd_g_messagestousers mu, wd_g_messages m '.
               'where m.accountid='._q($params['accountid']).
               '  and m.messageid=mu.messageid'.
               '  and mu.userid='._q($params['userid']).
               '  and m.active='._q('1').
               '  and m.datevalidfrom < NOW() < m.datevalidto'.
               '  and m.deleted=\'0\''.
               '  and m.rtype='._q(MESSAGETYPE_NEWS).
               '  and (mu.rstatus='._q(MESSAGESTATUS_NOT_SHOW).' or mu.rstatus='._q(MESSAGESTATUS_SHOW).')';
        $sql .= ' order by m.dateinserted, m.title';

        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return array();
        }

        if($rs->EOF) {
            return false;
        } else {
            return true;
        }
    }

    //--------------------------------------------------------------------------

    function getUserNews($params)
    {
        if($params['accountid'] == '') return false;

        $user = QCore_Bl_Users::getUserData($params['userid']);

        if($user === false) return false;

        $sql = 'select m.dateinserted, m.title, m.messageid '.
               'from wd_g_messages m left join wd_g_messagestousers mu on (m.messageid = mu.messageid and mu.userid='._q($params['userid']).')'.
               'where m.accountid='._q($params['accountid']).
               '  and m.active='._q('1').
               '  and m.datevalidfrom < NOW()'.
               '  and NOW() < m.datevalidto';
        if($params['userid'] != '') $sql .= '  and (mu.userid='._q($params['userid']).' or (mu.userid is null and m.showtoall='._q('1').'))';
        $sql .= '  and m.deleted=\'0\''.
               '  and (m.rtype='._q(MESSAGETYPE_NEWS).' or m.rtype='._q(SA_MESSAGETYPE_NEWS).')';
        if($params['view_old'] != '1')
            $sql .= '  and (mu.rstatus='._q(MESSAGESTATUS_NOT_READED).' or mu.rstatus='._q(MESSAGESTATUS_SHOW).' or (mu.rstatus is null and m.showtoall='._q('1').') )';
        $sql .= ' order by m.dateinserted desc, m.title';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return array();
        }

        $news = array();

        while(!$rs->EOF)
        {
            //$news[$params['userid']][$rs->fields['messageid']]['messagetouserid'] = $rs->fields['messagetouserid'];
            $news[$params['userid']][$rs->fields['messageid']]['messageid'] = $rs->fields['messageid'];
            $news[$params['userid']][$rs->fields['messageid']]['dateinserted'] = $rs->fields['dateinserted'];
            $news[$params['userid']][$rs->fields['messageid']]['title'] = $rs->fields['title'];

            $strs = array('title' => $news[$params['userid']][$rs->fields['messageid']]['title']);

            $strs = QCore_Bl_Communications::replaceInNews($user, $strs);

            $news[$params['userid']][$rs->fields['messageid']]['title'] = $strs['title'];

            $rs->MoveNext();
        }

        return $news;
    }

    //--------------------------------------------------------------------------

    function getNews($params)
    {
        $user = QCore_Bl_Users::getUserData($params['userid']);

        if($user_data === false) return false;

        $sql = 'select m.*, mu.messagetouserid as messagetouserid, mu.rstatus as rstatus '.
               'from wd_g_messages m left join wd_g_messagestousers mu on (m.messageid = mu.messageid and mu.userid='._q($params['userid']).')'.
               'where m.accountid='._q($params['accountid']).
               '  and m.active='._q('1').
               '  and m.datevalidfrom < NOW() < m.datevalidto'.
               '  and m.messageid='._q($params['messageid']).
               '  and (mu.userid='._q($params['userid']).' or (mu.userid is null and m.showtoall='._q('1').'))'.
               '  and m.deleted=\'0\''.
               '  and m.rtype='._q(MESSAGETYPE_NEWS).
               '  and (mu.rstatus='._q(MESSAGESTATUS_NOT_READED).' or mu.rstatus='._q(MESSAGESTATUS_SHOW).' or (mu.rstatus is null and m.showtoall='._q('1').') )';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return false;
        }

        $news = array();

        $news['messagetouserid'] = $rs->fields['messagetouserid'];
        $news['messageid'] = $rs->fields['messageid'];
        $news['dateinserted'] = $rs->fields['dateinserted'];
        $news['title'] = $rs->fields['title'];
        $news['status'] = $rs->fields['rstatus'];
        $news['rtext'] = $rs->fields['rtext'];
        if ($news['status'] == '') $news['status'] = MESSAGESTATUS_NOT_READED;

        $strs = array('title' => $news['title'], 'rtext' => $news['rtext']);

        $strs = QCore_Bl_Communications::replaceInNews($user, $strs);

        $news['title'] = $strs['title'];
        $news['rtext'] = $strs['rtext'];

        return $news;
    }

    //--------------------------------------------------------------------------

    function replaceInNews($user, $strs)
    {
        if(!is_array($strs) || count($strs) < 1) return false;

        foreach($strs as $key => $str)
        {
            $str = str_replace('$Date', date("Y-m-d"), $str);
            $str = str_replace('$Time', date("h:i:s"), $str);
            $str = str_replace('$Account_id', $GLOBALS['Auth']->getLiteAccountID(), $str);
            $str = str_replace('$Affiliate_id', $user['userid'], $str);
            $str = str_replace('$Affiliate_refid', $user['refid'], $str);
            $str = str_replace('$Affiliate_name', $user['name'].' '.$user['surname'], $str);
            $str = str_replace('$Affiliate_firstname', $user['name'], $str);
            $str = str_replace('$Affiliate_lastname', $user['surname'], $str);
            $str = str_replace('$Affiliate_username', $user['username'], $str);
            $str = str_replace('$Affiliate_password', $user['rpassword'], $str);
            $str = str_replace('$Affiliate_company', $user['company_name'], $str);
            $str = str_replace('$Affiliate_weburl', $user['weburl'], $str);
            $str = str_replace('$Affiliate_street', $user['street'], $str);
            $str = str_replace('$Affiliate_city', $user['city'], $str);
            $str = str_replace('$Affiliate_state', $user['state'], $str);
            $str = str_replace('$Affiliate_country', $user['country'], $str);
            $str = str_replace('$Affiliate_zipcode', $user['zipcode'], $str);
            $str = str_replace('$Affiliate_phone', $user['phone'], $str);
            $str = str_replace('$Affiliate_fax', $user['fax'], $str);
            $str = str_replace('$Affiliate_taxssn', $user['tax_ssn'], $str);
            $str = str_replace('$Affiliate_data1', $user['data1'], $str);
            $str = str_replace('$Affiliate_data2', $user['data2'], $str);
            $str = str_replace('$Affiliate_data3', $user['data3'], $str);
            $str = str_replace('$Affiliate_data4', $user['data4'], $str);
            $str = str_replace('$Affiliate_data5', $user['data5'], $str);

            $str = str_replace('$Merchant_username', $user['username'], $str);
            $str = str_replace('$Merchant_password', $user['rpassword'], $str);
            $str = str_replace('$Merchant_name', $user['name'], $str);
            $str = str_replace('$Merchant_surname', $user['surname'], $str);

            $strs[$key] = $str;
        }

        return $strs;
    }

    //--------------------------------------------------------------------------

    function replaceDateTime($strs)
    {
        if(!is_array($strs) || count($strs) < 1) return false;

        foreach($strs as $key => $str)
        {
            $str = str_replace('$Date', date("Y-m-d"), $str);
            $str = str_replace('$Time', date("h:i:s"), $str);

            $strs[$key] = $str;
        }

        return $strs;
    }


    //--------------------------------------------------------------------------

    function checkMessageType($params)
    {
        if($params['messageid'] == '' || $params['messagetype'] == '') return false;

        $sql = 'select rtype from wd_g_messages m '.
               'where messageid='._q($params['messageid']).
               '  and rtype='._q($params['messagetype']);
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return false;
        }

        if($params['checknegate']) {
            if($rs->EOF) return true;
            else return false;
        }
        else {
            if($rs->EOF) return false;
            else return true;
        }

    }

    //--------------------------------------------------------------------------

    function loadMessageInfoToPost($params)
    {
        if($params['messageid'] == '' || $params['accountid'] == '') return false;

        $sql = 'select * from wd_g_messages where accountid='._q($params['accountid']).
               ' and messageid='._q($params['messageid']).
               ' and deleted=\'0\'';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs || $rs->EOF)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return false;
        }

        $_POST['mid'] = $rs->fields['messageid'];
        $_POST['message_type'] = $rs->fields['rtype'];
        $_POST['dateinserted'] = $rs->fields['dateinserted'];
        $_POST['emailsubject'] = $rs->fields['title'];
        $_POST['emailtext'] = $rs->fields['rtext'];
        $_POST['deleted'] = $rs->fields['deleted'];
        $_POST['datevalidfrom'] = $rs->fields['datevalidfrom'];
        $_POST['datevalidto'] = $rs->fields['datevalidto'];
        $_POST['active'] = $rs->fields['active'];
        $_POST['showtoall'] = $rs->fields['showtoall'];

        return true;
    }

    //--------------------------------------------------------------------------

    function deleteMessage($params)
    {
        if($params['accountid'] == '') return false;

        $sql = 'delete from wd_g_messagestousers '.
               'where 1=1';
        if($params['messageid'] != '') $sql .= ' and messageid='._q($params['messageid']);
        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return false;
        }

        QCore_History::DebugMsg(WLOG_ACTION, $sql, __FILE__, __LINE__);

        $sql = 'update wd_g_messages '.
               'set deleted='._q('1').
               'where accountid='._q($params['accountid']);
        if($params['messageid'] != '') $sql .= ' and messageid='._q($params['messageid']);
        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            QCore_History::DebugMsg(WLOG_DBERROR, $sql, __FILE__, __LINE__);
            return false;
        }

        QCore_History::DebugMsg(WLOG_ACTION, $sql, __FILE__, __LINE__);

        return true;
    }

    //--------------------------------------------------------------------------

    function changeMessageStatus($mid, $userid, $status = MESSAGESTATUS_SHOW)
    {
        $sql = 'select messagetouserid from wd_g_messagestousers'.
               ' where messageid='._q($mid).
               '   and userid='._q($userid);
        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        if ($ret->fields['messagetouserid'] != '') {
            $sql = 'update wd_g_messagestousers set rstatus='._q($status).
                   ' where messagetouserid='._q($ret->fields['messagetouserid']);
            $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        } else {
            $MessagetouserID = QCore_Sql_DBUnit::createUniqueID('wd_g_messagestousers', 'messagetouserid');
            $sql = 'insert into wd_g_messagestousers '.
                   '(messagetouserid, messageid, userid, email, rstatus) values '.
                   '('._q($MessagetouserID).','._q($mid).','._q($userid).
                     ','._q($GLOBALS['Auth']->getUsernameForUser($userid)).','._q($status).')';
            $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function changeMessageActiveStatus($mid, $active)
    {
        $sql = 'update wd_g_messages set active='._q(($active) ? '1' : '0').
               ' where messageid='._q($mid);
        $ret = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function sendEmail($params)
    {
        if($params['email'] == '')
        {
            $errorMsg = "Email sending failed, because the recipient email address was empty. Subject of email: '".$params['subject']."'";
            LogError($errorMsg, __FILE__, __LINE__);
            return true;
        }

        if($params['subject'] == '' && $params['text'] == '')
        {
            $errorMsg = "Email sending failed, because both subject and text of email were empty. Email recipient: '".$params['email']."'";
            LogError($errorMsg, __FILE__, __LINE__);
            return true;
        }

        $messageToUserID = QCore_Bl_Communications::insert($params);

        $sent = QCore_Bl_Communications::sendEmailDirect($params, $messageToUserID);

        return $sent;
    }

    //----------------------------------------------------------------------------

    function sendEmailDirect($params, $messageToUserID = '')
    {
        if($GLOBALS['Test_mode'] == '1')
            return true;

        if(!isset($params['settings']) && is_object($GLOBALS['Auth'])) {
            $params['settings'] = $GLOBALS['Auth']->getSettings();
        }

        $sentBySmtp = ($params['settings']['Aff_mail_send_type'] == EMAILBY_SMTP) ? true : false;
        $sentBySmtp = true;

        $mail = QUnit_Global::newObj('QUnit_Net_Mail');

        $paramsSmtp = array();
    	if ($sentBySmtp) {
    		$paramsSmtp['host'] = ($params['settings']['Aff_smtp_server_tls'] == 1 ? 'tls://' : '') . $params['settings']['Aff_smtp_server'];
			$paramsSmtp['port'] = (trim($params['settings']['Aff_smtp_server_port']) == '' ? 25 : $params['settings']['Aff_smtp_server_port']);
			$paramsSmtp['auth'] = ($params['settings']['Aff_smtp_username'] != '' && $params['settings']['Aff_smtp_password'] != '');
			$paramsSmtp['username'] = $params['settings']['Aff_smtp_username'];
			$paramsSmtp['password'] = $params['settings']['Aff_smtp_password'];
		}

		$headers = array();

		$headers['Date'] = date('j M Y H:i:s O');

		$from = $params['settings']['Aff_system_email'];
        if(strlen(trim($params['settings']['Aff_system_email_name']))) {
            $from = '"' . $params['settings']['Aff_system_email_name'] . '" <' . $from . '>';
        }

    	$headers['User-Agent'] = 'www.marketools.cn MT';

		$headers['To'] = $params['email'];

		$replyTo = $params['returnpath'];
		if (strlen(trim($replyTo))) {
		    if(strlen(trim($params['returnpath_name']))) {
		        $replyTo = '"' . $params['returnpath_name'] . '" <' . $replyTo . '>';
		    }
			$headers['Reply-To'] = $replyTo;
		} else {
			$headers['Reply-To'] = $from;
		}

        if($params['settings']['Aff_mail_type'] == MAIL_HTML) {
        	if (strstr($params['text'], '<html') === false) {
        	   // replace new lines with <br> tags
        	   $params['text'] = str_replace("\n", "<br>", $params['text']);
        	   $params['text'] = "<html>\n<body>\n".$params['text']."\n</body>\n</html>";
        	}
		}

		$mail->set('from', $from);
		$mail->set('subject', $params['subject']);
		$mail->set('body', $params['text']);
		$mail->set('recipients', $params['email']);
        $mail->set('headers', $headers);
        $mail->set('txt_mail', $params['settings']['Aff_mail_type'] == MAIL_TEXT);

        if($params['settings']['Aff_mail_charset'] != 'no_charset') {
            $mail->set('html_charset', $params['settings']['Aff_mail_charset']);
            $mail->set('text_charset', $params['settings']['Aff_mail_charset']);
            if($params['settings']['Aff_mail_encode_subject'] == 1 && $params['settings']['Aff_mail_charset'] != 'no_charset') {
                $mail->set('head_charset', $params['settings']['Aff_mail_charset']);
            }
        }

        $method = $sentBySmtp ? 'smtp' : 'mail';
	    $sent = $mail->send($method, $paramsSmtp);

    	if($sent && $messageToUserID != '') {
            QUnit_Global::includeClass('QCore_Bl_Communications');

            QCore_Bl_Communications::changeMessageStatus($messageToUserID, MESSAGESTATUS_SHOW);
        }

        return $sent;
    }
}
?>
