<?php

/**
 * This Software is the property of Data Development and is protected
 * by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * http://www.shopmodule.com
 *
 * @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
 * @author    D3 Data Development - Daniel Seifert <support@shopmodule.com>
 * @link      http://www.oxidmodule.com
 */

class d3usermanager_response extends oxSuperCfg
{
    private $_sModId = 'd3usermanager';

    /**
     * @return bool
     */
    public function init()
    {
        startProfile(__METHOD__);

        $blExceptionThrown = $this->_startExecution();

        if ($this->isBrowserCall() && false == $blExceptionThrown) {
            echo "script successfully finished".PHP_EOL;
        }

        oxRegistry::getSession()->freeze();

        stopProfile(__METHOD__);

        $this->_getSet()->d3getLog()->d3GetProfiling();
    }

    /**
     * @return bool
     */
    protected function _startExecution()
    {
        startProfile(__METHOD__);

        $blExc = false;

        try {
            $iStartTime = microtime(true);
            $this->_getSet()->d3getLog()->log(d3log::INFO, __CLASS__, __FUNCTION__, __LINE__, "start cron", "");

            $this->_checkUnavailableCronjob();
            $this->_getSet()->setValue($this->_getCronTimestampVarName(), date('Y-m-d H:i:s'));
            $this->_getSet()->saveNoLicenseRefresh();

            $this->_startJobs();

            $iExecTime = microtime(true) - $iStartTime;
            $this->_getSet()->d3getLog()->log(
                d3log::INFO,
                __CLASS__,
                __FUNCTION__,
                __LINE__,
                "end cron",
                'execution time: '.$iExecTime." sec"
            );

        } catch (d3usermanager_cronUnavailableException $oEx) {
            /** @var d3usermanager_cronunavailableexception $oEx */
            $oEx->d3showMessage();
            $blExc = true;
        } catch (Exception $oEx) {
            /** @var oxException $oEx */
            $oEx->debugOut();
            $blExc = true;
        }

        stopProfile(__METHOD__);

        return $blExc;
    }

    protected function _startJobs()
    {
        startProfile(__METHOD__);

        /** @var $oManagerList d3usermanagerList */
        $oManagerList = oxNew('d3usermanagerlist');
        $oManagerList->setCronJobId($this->_getCronJobIdParameter());
        $oManagerList->setCustomSorting('oxsort ASC');
        $oManagerList->getList();

        /** @var d3UserManager $oHandleManager */
        $oHandleManager = oxNew('d3usermanager');
        /** @var d3usermanager_execute $oHandleManagerExec */
        $oHandleManagerExec = oxNew('d3usermanager_execute', $oHandleManager);

        // disable admin mode for using active check
        $blOldAdminMode = self::$_blIsAdmin;
        self::$_blIsAdmin = false;

        $oHandleManager->d3getLog()->log(
            d3log::INFO,
            __CLASS__,
            __FUNCTION__,
            __LINE__,
            'manager count',
            $oManagerList->count()
        );

        /** @var $oManager d3usermanager */
        foreach ($oManagerList->getList() as $oManager) {
            $oHandleManager = oxNew('d3usermanager');
            $oHandleManager->load($oManager->getId());
            $oHandleManagerExec->setManager($oHandleManager);

            self::$_blIsAdmin = $blOldAdminMode;
            $oHandleManagerExec->startJobExecution();
            self::$_blIsAdmin = false;
        }

        self::$_blIsAdmin = $blOldAdminMode;
        $oHandleManagerExec->finishJobExecution();

        stopProfile(__METHOD__);
    }

    /**
     * @return bool
     */
    protected function _checkAccessKey()
    {
        $sSetCronPassword = $this->_getSet()->getValue('sCronPassword');

        /** @var d3usermanager $oManager */
        $oManager = oxNew('d3usermanager');
        $sGetAccessKey  = oxRegistry::getConfig()->getRequestParameter("key");
        $sRegisteredAccessKey = $sSetCronPassword ? $sSetCronPassword : $oManager->getBaseCronPW();

        if ($this->hasValidAccessKey($sRegisteredAccessKey, $sGetAccessKey)) {
            return false;
        }

        return true;
    }

    /**
     * @return d3_cfg_mod
     */
    protected function _getSet()
    {
        return d3_cfg_mod::get($this->_sModId);
    }

    /**
     * @return bool
     */
    public function showDisabledMessage()
    {
        return false == $this->_getSet()->getValue('blCronActive') &&
        ($this->_getSet()->hasDebugMode() || $this->isBrowserCall());
    }

    /**
     * @return bool
     */
    public function isBrowserCall()
    {
        return $_SERVER['REMOTE_ADDR'] || $_SERVER['HTTP_USER_AGENT'];
    }

    /**
     * @param $sRegisteredAccessKey
     * @param $sGetAccessKey
     *
     * @return bool
     */
    protected function hasValidAccessKey($sRegisteredAccessKey, $sGetAccessKey)
    {
        return (
            $_SERVER['REMOTE_ADDR'] ||
            $_SERVER['HTTP_USER_AGENT']
        ) && $sRegisteredAccessKey != $sGetAccessKey;
    }

    /**
     * @throws d3usermanager_cronunavailableexception
     */
    protected function _checkUnavailableCronjob()
    {
        if (false == $this->_getSet()->isActive()) {
            /** @var d3usermanager_cronunavailableexception $oEx */
            $oEx = oxNew('d3usermanager_cronunavailableexception');
            $oEx->setMessage('user manager module is disabled');
            $oEx->d3enableScreenMessage();
            $oEx->debugOut();
            throw $oEx;
        } elseif (false == $this->_checkAccessKey()) {
            /** @var d3usermanager_cronunavailableexception $oEx */
            $oEx = oxNew('d3usermanager_cronunavailableexception');
            $oEx->setMessage('cron via browser: missing or wrong identification');
            $oEx->d3enableScreenMessage();
            $oEx->debugOut();
            throw $oEx;
        } else {
            $this->_checkDisabledCronjob();
        }
    }

    /**
     * @throws d3usermanager_cronunavailableexception
     */
    public function _checkDisabledCronjob()
    {
        if ($this->showDisabledMessage()) {
            /** @var d3usermanager_cronunavailableexception $oEx */
            $oEx = oxNew('d3usermanager_cronunavailableexception');
            $oEx->setMessage('cronjob script is disabled');
            $oEx->d3enableScreenMessage();
            $oEx->debugOut();
            throw $oEx;
        } elseif (false == $this->_getSet()->getValue('blCronActive')) {
            /** @var d3usermanager_cronunavailableexception $oEx */
            $oEx = oxNew('d3usermanager_cronunavailableexception');
            $oEx->setMessage('cron via browser: missing or wrong identification');
            $oEx->d3disableScreenMessage();
            $oEx->debugOut();
            throw $oEx;
        }
    }

    /**
     * @return string
     */
    protected function _getCronJobIdParameter()
    {
        $iCjId = (int) oxRegistry::getConfig()->getRequestParameter('cjid');

        if (false === $iCjId || null === $iCjId) {
            $iCjId = 0;
        }

        return $iCjId;
    }

    /**
     * @return string
     */
    protected function _getCronTimestampVarName()
    {
        $sVarName = "sCronExecTimestamp";

        if ($this->_getCronJobIdParameter() !== false) {
            $sVarName .= $this->_getCronJobIdParameter();
        }

        return $sVarName;
    }
}
