<?php
QUnit_Global::includeClass('QCore_Bl_GlobalDb');
QUnit_Global::includeClass('QUnit_UI_TemplatePage');

class QCore_ForgotPassword extends QUnit_UI_TemplatePage
{
    var $userType;
    var $settings = array();
    var $objSettings;

    function QCore_ForgotPassword()
    {
        $this->objSettings =& QUnit_Global::newObj('QCore_Settings');
    }

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

    function process()
    {
        if(!empty($_REQUEST['action']))
        {
            switch($_REQUEST['action'])
            {
                case 'check_user':
                    $this->processCheckUser();
                break;
            }
        }

        $this->showFormForgotPassword();
    }

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

    function showFormForgotPassword()
    {
        $_POST['action'] = 'check_user';

        $this->addContent('forgot_password');
    }

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

    function processCheckUser()
    {
        if($_POST['commited'] == 'yes')
        {
            switch($_POST['postaction']) {
                case 'step1':
                    return $this->processStepOne();
                    break;

                case 'step2':
                    if($this->processStepTwo()) {
                        return true;
                    }
                return false;
                break;
            }
        }
        return false;
    }

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

    function processStepOne()
    {
        if($_POST['username'] == '')
        {
            QUnit_Messager::setErrorMessage(L_G_YOUHAVETOENTEREMAIL);
            return false;
        }

        //$puname = preg_replace('/[^a-zA-Z0-9_@\.\-]/', '', $_POST['username']);
        $puname = $_POST['username'];
        if(($rs = $this->checkUserExists($puname)) === false) {
            return false;
        }

        $this->getSettings($rs->fields('accountid'));

        if(($code = $this->saveCode($rs->fields('accountid'), $rs->fields('userid'))) === false) {
            return false;
        }

        return $this->sendPasswordByEmail($rs->fields('userid'), $rs->fields('accountid'), $rs->fields('email'), $code, 'AFF_EMAIL_FORGOTPAS1');
    }

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

    function processStepTwo()
    {
        if(($rs = $this->checkCode()) === false) {
            return false;
        }

        if(($pwd = $this->resetPassword($rs->fields('username'), $rs->fields['userid'])) === false) {
            return false;
        }

        $this->getSettings($rs->fields('accountid'));

        if($this->sendPasswordByEmail($rs->fields('userid'), $rs->fields('accountid'), $rs->fields('username'), $pwd, 'AFF_EMAIL_FORGOTPAS2') === false) {
            return false;
        }

        if(($code = $this->saveCode($rs->fields('accountid'), $rs->fields('userid'))) === false) {
            return false;
        }

        $this->assign('a_passwordResetSuccess', true);
        return true;
    }

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

    function saveCode($accountId, $userId) {
        $code = substr(md5(uniqid(rand(), true)), 0, 8);

        if($this->objSettings->_update('Aff_forgotpassword_code', md5($code), $this->user_type, $accountId, $userId) === false) {
            QCore_History::DebugMsg(WLOG_ERROR, L_G_SAVECODEERROR, __FILE__, __LINE__);
            QUnit_Messager::setErrorMessage(L_G_CONTACTADMINISTRATOR);
            return false;
        }
        return $code;
    }

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

    function checkCode()
    {
        if($_POST['code'] == '') {
            QUnit_Messager::setErrorMessage(L_G_YOUHAVETOENTERCODE);
            return false;
        }
        $sql = 'select u.userid, u.username, u.rtype, u.accountid '.
               'from wd_g_settings s, wd_g_users u '.
               'where s.code='._q('Aff_forgotpassword_code').
               '  and s.value='._q(md5($_POST['code'])).
               '  and s.userid=u.userid';

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

        if($rs->EOF) {
            QUnit_Messager::setErrorMessage(L_G_CODEDOESNTMATCH);
            return false;
        }

        $this->userType = $rs->fields['rtype'];

        return $rs;
    }

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

    function checkUserExists($puname) {
        // first check, if there is not already user with the same name
        if(QUnit_Messager::getErrorMessage() != '')
        return false;

        $sql = 'select * from wd_g_users '.
            'where deleted=0 '.
            '  and rtype='._q($this->user_type).
            '  and ( username='._q($puname).' or email='._q($puname).' or refid='._q($puname).' ) ';

        //if($this->user_type == USERTYPE_USER) $sql .= '  and rstatus='._q(AFFSTATUS_APPROVED);
        /*if($this->user_type == USERTYPE_ADMIN) $sql .= '  and rstatus='._q(STATUS_ENABLED);
        else if($this->user_type == USERTYPE_SUPERADMIN) $sql .= '  and rstatus='._q(STATUS_ENABLED);
        else
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }
        */

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

        if($rs->EOF)
        {
            QUnit_Messager::setErrorMessage(L_G_USERDOESNTEXIST);
            return false;
        }
        return $rs;
    }

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

    function resetPassword($puname, $userid = '') {
        $pwd = substr(md5(uniqid(rand(), true)), 0, 8);

        $sql = 'update wd_g_users '.
            'set rpassword='._q(($this->userType == USERTYPE_ADMIN ? md5($pwd) : $pwd)).
            'where username='._q($puname);
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }


        $globalDb =& QCore_Bl_GlobalDb::getInstance();
        $params = array('userid' => $userid,
                        'liteaccountid' => $GLOBALS['Auth']->getLiteAccountId(),
                        'password' => $pwd);
        $globalDb->updateUser($params);

        $siteReplication = QUnit_Global::newObj('Affiliate_Scripts_Bl_ReplicatedSite');
        $siteReplication->createFile($userid);

        return $pwd;

    }

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

    function sendPasswordByEmail($userId, $accountId, $userName, $pwd, $template)
    {
        $params = array();
        $params['pwd'] = $pwd;
        $objEmailTemplates =& QUnit_Global::newObj('QCore_EmailTemplates');
        $emaildata = $objEmailTemplates->getFilledEmailMessage($userId, $accountId, $template, $_SESSION[SESSION_PREFIX.'lang'], $params);

        if($emaildata != false && !empty($emaildata['subject']) && !empty($emaildata['text']))
        {
            $objBlCommunications =& QUnit_Global::newObj('QCore_Bl_Communications');

            $emaildata['email'] = $userName;
            $emaildata['settings'] = $this->settings;

            if(!$objBlCommunications->sendEmail($emaildata))
            {
                QUnit_Messager::setErrorMessage(L_G_EMAILSEND);
                return false;
            }
            else
            {
                if($template == 'AFF_EMAIL_FORGOTPAS1') {
                    QUnit_Messager::setOkMessage(L_G_EMAILWITHVEFIFYCATIONCODESENT);
                } else {
                    QUnit_Messager::setOkMessage(L_G_EMAILWITHPWDSENT);
                }
                return true;
            }
        }
        else
        {
            QCore_History::DebugMsg(WLOG_ERROR, L_G_EMAILTEMPERR, __FILE__, __LINE__);
            QUnit_Messager::setErrorMessage(L_G_CONTACTADMINISTRATOR);
            return false;
        }
    }

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

    function getSettings($AccountID)
    {
        if($this->user_type == USERTYPE_USER || $this->user_type == USERTYPE_ADMIN)
            $this->settings = $this->objSettings->getAccountSettings(SETTINGTYPE_ACCOUNT, $AccountID);
        else if($this->user_type == USERTYPE_SUPERADMIN)
            $this->settings = $this->objSettings->getGlobalSettings();
    }
}
?>
