<?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 <support@shopmodule.com>
 * @link          http://www.oxidmodule.com
 */

class d3heidelpay_update extends d3install_updatebase
{
    public $sModKey = 'd3heidelpay';

    public $sModName = 'Heidelpay';

    public $sModVersion = '5.1.1.3';

    public $sModRevision = '1111';

    public $sBaseConf = '--------------------------------------------------------------------------------
jgRZGJDd3ZlTVRqNUpyNWlNZENGL2U4QkwvQ3M5bTN1MlhwVWhGcGJ2OUhRYTFpaXhHRG9SbUt6MGpEO
GRtdXovVUpDUjN2aEJUOWZxY2RGekdaTmw5U0ZwRGlKNVgxZTFoMHc5N0tRdTd5NFBCOXlZMnY0UWFNd
08wMlI3NEVVWkVJQTNhbXFrczc0cjYwRGM4am0yaEEzUHliUUEyZ1RGOHNhMW1oSk90ZForcStoNXNQN
FYrNHBuZjdqeUdxMWdGTGdSNzBKQktoZ0FXN0tXWEN3VGpVQzNVVzhWQXFjWnJGZ2dMMDd3eG85NHZhe
Wk1d3BKRkRvRDZlbXBYMDA3WDdWYlFlWlg3SDA4NDlGVFA1NkphVHdWdDVLZjlzSnNoNDNSK3B6eVV6d
jg9
--------------------------------------------------------------------------------';

    public $sRequirements = '';

    public $sBaseValue = ' ';

    protected $_aRefreshMetaModuleIds = array('d3heidelpay');

    protected $_aUpdateMethods = array(

        array(
            'check' => 'hasOldOxconfigEntries',               // Update 3.2.3.1 XE4 => 4.0.0.0 XE4
            'do'    => 'migrateOldOxconfigEntries'
        ),
        array(
            'check' => 'checkModCfgItemExist', // Prueft auf Datenbankeintrag
            'do'    => 'updateModCfgItemExist'
        ),
        array(
            'check' => 'checkTableOxpaylogsExist', // Prueft ob alte Tabellen geloescht werden muessen
            'do'    => 'dropTableOxpaylogsExist'   // Update 3.2.3.1 XE4 => 4.0.0.0 XE4
        ),
        array(
            'check' => 'checkTableOxobject2heidelpayExist', // Prueft ob alte Tabellen geloescht werden muessen
            'do'    => 'migrateOldPaymentAssignments'   // Update 3.2.3.1 XE4 => 4.0.0.0 XE4
        ),
        array(
            'check' => 'checkRenameD3Tables', // Prueft auf umzubenennende Tabellen
            'do'    => 'renameD3Tables'       // Update 3.2.3.1 XE4 => 4.0.0.0 XE4
        ),
        array(
            'check' => 'checkD3hpuidTableExist',
            'do'    => 'updateD3hpuidTableExist'
        ),
        array(
            'check' => 'checkD3hperrortextsTableExist',
            'do'    => 'updateD3hperrortextsTableExist'
        ),
        array(
            'check' => 'checkHPerrortextcontent', // UPDATE `d3hperrortexts` SET `OXTYPE` = '2' WHERE `OXCODE` = '800.100.153';
            'do'    => 'updateHPerrortextcontent' // Update 4.0.1.0 XE4 => 4.0.2.0 XE4
        ),
        array(
            'check' => 'hasLegacyAssigments',
            'do'    => 'updateLegacyAssigments'
        ),
        array(
            'check' => 'ishpprepaymentdataTableExist',
            'do'    => 'deletehpprepaymentdataTableExist'
        ),
        array(
            'check' => 'checkOxcontentEntrysExist', // Pruefte ob oxcontenteintraege schon vorhanden
            'do'    => 'showMessageForCustomerToUpdateManually'
        ),
        array(
            'check' => 'checkOxcontentItemsExist', // sql befehle fuer Tabelle oxcontents
            'do'    => 'insertOxcontentItemsIfNotExist'
        ),
        array(
            'check' => 'checkOxpaymentsItemsExist', // sql befehle fuer Tabelle oxpayments
            'do'    => 'insertOxpaymentsItemsIfNotExist'
        ),
        array(
            'check' => 'checkD3hperrortextsItemsExist', // sql befehle fuer Tabelle d3hperrortexts
            'do'    => 'insertD3hperrortextsItemsIfNotExist'
        ),
        array(
            'check' => 'checkForChangeHaendlerKontoMsg',
            'do'    => 'showForChangeHaendlerKontoMsg'
        ),
        array(
            'check' => 'checkModCfgorderExecutePostFields',
            'do'    => 'updateModCfgorderExecutePostFields'
        ),
        array(
            'check' => 'checkModCfgSameRevision', // Prueft auf nachgezogene Revisionsnummer
            'do'    => 'updateModCfgSameRevision'
        ),
    );

    // Standardwerte zum umbenennen Tables
    public $aRenameTables = array(
        array(
            'mOldTableNames' => 'oxhpuid', // is case insensitive
            'sTableName'     => 'd3hpuid',
        ),
        array(
            'mOldTableNames' => 'oxhperrortexts', // is case insensitive
            'sTableName'     => 'd3hperrortexts',
        ),
    );

    // Standardwerte fuer checkFields(), _addTable() und fixFields()
    public $aFields = array(
        'OXID_d3hpuid'              => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXID',
            'sType'       => 'VARCHAR(32)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXUSERID_d3hpuid'          => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXUSERID',
            'sType'       => 'VARCHAR(32)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXPAYMENTID_d3hpuid'       => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXPAYMENTID',
            'sType'       => 'VARCHAR(32)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXUID_d3hpuid'             => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXUID',
            'sType'       => 'VARCHAR(50)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXTIME_d3hpuid'            => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXTIME',
            'sType'       => 'DATETIME',
            'blNull'      => false,
            'sDefault'    => '0000-00-00 00:00:00',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXPAYMENTDATA_d3hpuid'     => array(
            'sTableName'  => 'd3hpuid',
            'sFieldName'  => 'OXPAYMENTDATA',
            'sType'       => 'TEXT',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXID_d3hperrortexts'       => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXID',
            'sType'       => 'VARCHAR(32)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXCODE_d3hperrortexts'     => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXCODE',
            'sType'       => 'VARCHAR(20)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXTYPE_d3hperrortexts'     => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXTYPE',
            'sType'       => 'INT(1)',
            'blNull'      => false,
            'sDefault'    => '0',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXTITLE_d3hperrortexts'    => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXTITLE',
            'sType'       => 'VARCHAR(255)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXTITLE_1_d3hperrortexts'  => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXTITLE_1',
            'sType'       => 'VARCHAR(255)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
        'OXREALTEXT_d3hperrortexts' => array(
            'sTableName'  => 'd3hperrortexts',
            'sFieldName'  => 'OXREALTEXT',
            'sType'       => 'VARCHAR(255)',
            'blNull'      => false,
            'sDefault'    => '',
            'sComment'    => 'D3 Heidelpay',
            'sExtra'      => '',
            'blMultilang' => false,
        ),
    );

    // Standardwerte fuer checkIndizes() und fixIndizes()
    public $aIndizes = array(
        array(
            'sTableName'  => 'd3hpuid',
            'sType'       => 'PRIMARY',
            'sName'       => 'PRIMARY',
            'aFields'     => array(
                'OXID' => 'OXID',
            ),
            'blMultilang' => false,
        ),
        array(
            'sTableName'  => 'd3hperrortexts',
            'sType'       => 'PRIMARY',
            'sName'       => 'PRIMARY',
            'aFields'     => array(
                'OXID' => 'OXID',
            ),
            'blMultilang' => false,
        ),
    );

    public $aMapArraySettings = array(
        'Heidelpay_blCCType__AMEX'         => 'd3heidelpay_aCCTypes',
        'Heidelpay_blCCType__DINERS'       => 'd3heidelpay_aCCTypes',
        'Heidelpay_blCCType__DISCOVER'     => 'd3heidelpay_aCCTypes',
        'Heidelpay_blCCType__JCB'          => 'd3heidelpay_aCCTypes',
        'Heidelpay_blCCType__MASTER'       => 'd3heidelpay_aCCTypes',
        'Heidelpay_blCCType__VISA'         => 'd3heidelpay_aCCTypes',
        'Heidelpay_blDCType__4B'           => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__CARTEBLEUE'   => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__EURO6000'     => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__MAESTRO'      => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__POSTEPAY'     => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__SERVIRED'     => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__SOLO'         => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDCType__VISAELECTRON' => 'd3heidelpay_aDCTypes',
        'Heidelpay_blDDType__AT'           => 'd3heidelpay_aDDTypes',
        'Heidelpay_blDDType__DE'           => 'd3heidelpay_aDDTypes',
    );

    public $aMapSettings = array(
        'Heidelpay_blDebitUnmask'          => 'd3_cfg_mod__d3heidelpay_blDebitUnmask',
        'Heidelpay_blServiceErrors'        => 'd3_cfg_mod__d3heidelpay_blServiceErrors',
        'Heidelpay_blShowStoredHPData'     => 'd3_cfg_mod__d3heidelpay_blShowStoredHPData',
        'Heidelpay_blTestmode'             => 'd3_cfg_mod__d3heidelpay_blTestmode',
        'Heidelpay_iCurlTimeOut'           => 'd3_cfg_mod__d3heidelpay_iCurlTimeOut',
        'Heidelpay_sChannel'               => 'd3_cfg_mod__d3heidelpay_sChannel',
        'Heidelpay_sChannel__eps'          => 'd3_cfg_mod__d3heidelpay_sChannel__eps',
        'Heidelpay_sChannel__giro'         => 'd3_cfg_mod__d3heidelpay_sChannel__giro',
        'Heidelpay_sChannel__ideal'        => 'd3_cfg_mod__d3heidelpay_sChannel__ideal',
        'Heidelpay_sChannel__sofort'       => 'd3_cfg_mod__d3heidelpay_sChannel__sofort',
        'Heidelpay_sCCInputPosition'       => 'd3_cfg_mod__d3heidelpay_sCCInputPosition',
        'Heidelpay_sPassword'              => 'd3_cfg_mod__d3heidelpay_sPassword',
        'Heidelpay_sSecuritySender'        => 'd3_cfg_mod__d3heidelpay_sSecuritySender',
        'Heidelpay_sTransType'             => 'd3_cfg_mod__d3heidelpay_sTransType',
        'Heidelpay_sUserID'                => 'd3_cfg_mod__d3heidelpay_sUserID',
        'Heidelpay_blCCType__AMEX'         => 'AMEX',
        'Heidelpay_blCCType__DINERS'       => 'DINERS',
        'Heidelpay_blCCType__DISCOVER'     => 'DISCOVER',
        'Heidelpay_blCCType__JCB'          => 'JCB',
        'Heidelpay_blCCType__MASTER'       => 'MASTER',
        'Heidelpay_blCCType__VISA'         => 'VISA',
        'Heidelpay_blDCType__4B'           => '4B',
        'Heidelpay_blDCType__CARTEBLEUE'   => 'CARTEBLEUE',
        'Heidelpay_blDCType__EURO6000'     => 'EURO6000',
        'Heidelpay_blDCType__MAESTRO'      => 'MAESTRO',
        'Heidelpay_blDCType__POSTEPAY'     => 'POSTEPAY',
        'Heidelpay_blDCType__SERVIRED'     => 'SERVIRED',
        'Heidelpay_blDCType__SOLO'         => 'SOLO',
        'Heidelpay_blDCType__VISAELECTRON' => 'VISAELECTRON',
        'Heidelpay_blDDType__AT'           => 'AT',
        'Heidelpay_blDDType__DE'           => 'DE',
    );

    /**
     * @return bool
     */
    public function checkD3hperrortextsItemsExist()
    {
        $blReturn = $this->_checkUpdateFile('d3/d3heidelpay/setup/d3hp_errortextsQuerys.php');

        return $blReturn;
    }

    /**
     * @return bool
     */
    public function insertD3hperrortextsItemsIfNotExist()
    {
        return $this->_doUpdateFile('d3/d3heidelpay/setup/d3hp_errortextsQuerys.php');
    }

    /****************************************************
     * Tabellen anlegen                                 *
     ****************************************************/
    /**
     * @return bool TRUE, if table is missing
     */
    public function ishpprepaymentdataTableExist()
    {
        return false == $this->_checkTableNotExist('d3hpprepaymentdata') || false == $this->_checkTableNotExist(
            'oxhpprepaymentdata'
        );
    }

    /**
     * @return bool
     */
    public function deletehpprepaymentdataTableExist()
    {
        $blRet = true;

        if ($this->ishpprepaymentdataTableExist()) {
            if (false == $this->_checkTableNotExist('d3hpprepaymentdata')) {
                $aRet  = $this->_dropTable('d3hpprepaymentdata');
                $blRet = $aRet['blRet'];
                $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
            }

            if (false == $this->_checkTableNotExist('oxhpprepaymentdata')) {
                $aRet  = $this->_dropTable('oxhpprepaymentdata');
                $blRet = $aRet['blRet'];
                $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
            }
        }

        return $blRet;
    }

    /**
     * @return bool TRUE, if table is missing
     */
    public function checkD3hpuidTableExist()
    {
        return $this->_checkTableNotExist('d3hpuid');
    }

    /**
     * @return bool
     */
    public function updateD3hpuidTableExist()
    {
        $blRet = true;

        if ($this->checkD3hpuidTableExist()) {
            $aRet  = $this->_addTable('d3hpuid', $this->aFields, $this->aIndizes, 'D3 Heidelpay', 'MyISAM');
            $blRet = $aRet['blRet'];
            $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
        }

        return $blRet;
    }

    /**
     * @return bool TRUE, if table is missing
     */
    public function checkD3hperrortextsTableExist()
    {
        return $this->_checkTableNotExist('d3hperrortexts');
    }

    /**
     * @return bool
     */
    public function updateD3hperrortextsTableExist()
    {
        $blRet = true;

        if ($this->checkD3hperrortextsTableExist()) {
            $aRet  = $this->_addTable('d3hperrortexts', $this->aFields, $this->aIndizes, 'D3 Heidelpay', 'MyISAM');
            $blRet = $aRet['blRet'];
            $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
        }

        return $blRet;
    }

    /****************************************************
     * Tabelle oxcontents & oxpayments                  *
     * if entrys not exist -> insert                    *
     ****************************************************/
    /**
     * @return bool
     */
    public function checkOxcontentItemsExist()
    {
        $blReturn = $this->_hasExecuteFileQuery('d3/d3heidelpay/setup/d3hp_oxcontentsQuerys.php');

        return $blReturn;
    }

    /**
     * @return bool
     */
    public function insertOxcontentItemsIfNotExist()
    {
        oxRegistry::getSession()->setVariable('d3hp_update_skip_oxcontents', 1);

        $blReturn = $this->_executeFileQueries('d3/d3heidelpay/setup/d3hp_oxcontentsQuerys.php');

        return $blReturn;
    }

    /**
     * @return bool
     */
    public function checkOxpaymentsItemsExist()
    {
        // NOTE - Nach RS mit TD:
        // wenn Erstinstallation == true -> Neue Zahlmethoden in oxpayments einfuegen, sonst nicht
        // kein HInweis bei Update und kein Ueberschreiben, nur neu anlegen

        // wird gesetzt in checkModCfgItemExist()
        // $bInsertUpdate = oxRegistry::getSession()->getVariable('d3hp_firstInstallation');

        //if ($bInsertUpdate == 1) {    // wenn erstinstallation
        /*
            funktioniert nicht, wenn Installation unterbrochen wurde und erst irgendwann spaeter
            fertiggestellt wird, daher standard-pruefung ob eitrag existiert, wenn nicht wird dieser angelegt
            kein Hinweis, bei Update wenn Eintrag schon existiert, das dieser ggf. Aktualisiert werden muss
        */
        $blReturn = $this->_checkUpdateFile('d3/d3heidelpay/setup/d3hp_oxpaymentsQuerys.php');

        //}

        return $blReturn;
    }

    /**
     * @return bool
     */
    public function insertOxpaymentsItemsIfNotExist()
    {
        return $this->_doUpdateFile('d3/d3heidelpay/setup/d3hp_oxpaymentsQuerys.php');
    }

    /****************************************************
     * Tabelle oxcontents                               *
     * No Autoupdate if exist -> Message                *
     ****************************************************/
    /**
     * @return bool
     */
    public function checkOxcontentEntrysExist()
    {
        $blRet       = false;
        $bSkipUpdate = oxRegistry::getSession()->getVariable('d3hp_update_skip_oxcontents');

        if ($bSkipUpdate == 1) {
            return $blRet;
        }

        foreach ($this->_getShopList() as $oShop) {
            /** @var $oShop oxshop */
            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_cust_text',
                'oxshopid' => $oShop->getId(),
            );
            $blRet1 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_cust_subject',
                'oxshopid' => $oShop->getId(),
            );
            $blRet2 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_cust_plain',
                'oxshopid' => $oShop->getId(),
            );
            $blRet3 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_owner_text',
                'oxshopid' => $oShop->getId(),
            );
            $blRet4 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_owner_subject',
                'oxshopid' => $oShop->getId(),
            );
            $blRet5 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $aWhere = array(
                'oxloadid' => 'd3_hp_vorkassemail_owner_plain',
                'oxshopid' => $oShop->getId(),
            );
            $blRet6 = $this->_checkTableItemNotExist('oxcontents', $aWhere);

            $blRetX = $this->checkModCfgSameRevision();

            if ((!$blRet1 || !$blRet2 || !$blRet3 || !$blRet4 || !$blRet5 || !$blRet6) && $blRetX) {
                $blRet = true;
            }
        }

        return $blRet;
    }

    /**
     * Message for manuelle Updates for CMS-Sites
     *
     * @return bool
     */
    public function showMessageForCustomerToUpdateManually()
    {
        $sMessage = 'D3_HEIDELPAY_UPDATE_OXCONTENTITEMS';
        $blRet    = $this->_confirmMessage($sMessage);

        oxRegistry::getSession()->setVariable('d3hp_update_skip_oxcontents', 1);

        return $blRet;
    }

    /****************************************************
     * Update 4.0.1.0 => 4.0.2.0                        *
     *                                                  *
     * UPDATE `d3hperrortexts` SET `OXTYPE` = '2'       *
     * WHERE `OXCODE` = '800.100.153';                  *
     ****************************************************/
    /**
     * @return bool
     */
    public function checkHPerrortextcontent()
    {
        $blRet                         = false;
        $bSkipUpdate                   = oxRegistry::getSession()->getVariable('d3hp_HPerrortext_skip_update');
        $bSkipUpdateCauseTableNotExist = !$this->checkD3hperrortextsTableExist();

        if ($bSkipUpdate == 1 || $bSkipUpdateCauseTableNotExist) {
            return $blRet;
        }

        $aWhere = array(
            'oxcode' => '800.100.153',
        );
        $blRet1 = $this->_checkTableItemNotExist('d3hperrortexts', $aWhere);

        $blRetX = $this->checkModCfgSameRevision();

        if ($blRet1 && $blRetX) {
            $blRet = true;
        }

        return $blRet;
    }

    /**
     * @return bool
     */
    public function updateHPerrortextcontent()
    {
        $blRet = false;

        if ($this->checkHPerrortextcontent()) {
            $aWhere = array(
                'oxcode' => '800.100.153',
            );

            if ($this->_checkTableItemNotExist('d3hperrortexts', $aWhere)) {
                // update don't use this property
                unset($aWhere['oxnewrevision']);

                $aInsertFields = array(
                    'OXID'       => array(
                        'content'      => "366",
                        'force_update' => true,
                        'use_quote'    => false,
                    ),
                    'OXCODE'     => array(
                        'content'      => '800.100.153',
                        'force_update' => true,
                        'use_quote'    => true,
                    ),
                    'OXTYPE'     => array(
                        'content'      => "2",
                        'force_update' => true,
                        'use_quote'    => true,
                    ),
                    'OXTITLE'    => array(
                        'content'      => "Ung&uuml;ltige Pr&uuml;fziffer",
                        'force_update' => true,
                        'use_quote'    => true,
                    ),
                    'OXTITLE_1'  => array(
                        'content'      => "transaction declined (invalid CVV)",
                        'force_update' => false,
                        'use_quote'    => false,
                    ),
                    'OXREALTEXT' => array(
                        'content'      => "transaction declined (invalid CVV)",
                        'force_update' => true,
                        'use_quote'    => true,
                    )
                );
                $aRet          = $this->_updateTableItem('d3hperrortexts', $aInsertFields, $aWhere);
                $blRet         = $aRet['blRet'];

                $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
                $this->_setUpdateBreak(false);
            }
        }

        // if actually updatet dont update entry a second time
        oxRegistry::getSession()->setVariable('d3hp_HPerrortext_skip_update', 1);

        return $blRet;
    }

    /****************************************************
     * Tabellen umbenennen - 3.2.3.1 => 4.0.0.0         *
     ****************************************************/
    /**
     * @return bool
     */
    public function checkRenameD3Tables()
    {
        return $this->checkRenameTables();
    }

    /**
     * @return bool
     */
    public function renameD3Tables()
    {
        /** @param string $sMethodName */
        return $this->fixRenameTables(__METHOD__);
    }

    /****************************************************
     * Alte Tabellen loeschen - 3.2.3.1 => 4.0.0.0       *
     ****************************************************/
    /**
     * @return bool
     * FALSE, if table is missing, so nothing is to do
     * TRUE, if table is not missing, delete it

     */
    public function checkTableOxpaylogsExist()
    {
        $blRet = !($this->_checkTableNotExist('oxpaylogs'));

        return $blRet;
    }

    /**
     * @return bool
     */
    public function dropTableOxpaylogsExist()
    {
        $blRet = true;

        if ($this->checkTableOxpaylogsExist()) {
            $blRet = $this->_dropTable('oxpaylogs');
        }

        return $blRet;
    }

    /**
     * @return bool
     * FALSE, if table is missing, so nothing is to do
     * TRUE, if table is not missing, delete it

     */
    public function checkTableOxobject2heidelpayExist()
    {
        $blRet = !($this->_checkTableNotExist('oxobject2heidelpay'));

        return $blRet;
    }

    /**
     * @return bool
     */
    public function migrateOldPaymentAssignments()
    {
        $blReturn = true;

        if ($this->checkTableOxobject2heidelpayExist()) {
            $oDb             = oxDb::getDb(oxDB::FETCH_MODE_ASSOC);
            $sOriginalShopid = oxRegistry::getConfig()->getShopId();

            foreach ($this->_getShopList() as $oShop) {
                /** @var $oShop oxshop */
                if($blReturn === false) {
                    //if error occured, do not keep working
                    continue;
                }

                $sGetAllPaymentAssigments = <<<MYSQL
SELECT oxpaymentid AS oxpaymentid, oxtype AS oxtype
FROM oxobject2heidelpay
WHERE oxshopid = {$oDb->quote($oShop->getId())}
MYSQL;
                $aOldAssigments           = $oDb->getArray($sGetAllPaymentAssigments);
                oxRegistry::getConfig()->setShopId($oShop->getId());

                if (false == isset($aOldAssigments[0])) {
                    continue;
                }

                $oModuleConfiguration = d3_cfg_mod::get($this->sModKey);
                $this->_convertOldAssignmentsToSettings($aOldAssigments, $oModuleConfiguration);

                $aInsertFields = array(
                    'OXVALUE' => array(
                        'content'      => $oModuleConfiguration->getFieldData('oxvalue'),
                        'force_update' => true,
                        'use_quote'    => true,
                    )
                );
                $aWhereFields  = array('oxshopid' => $oShop->getId(), 'oxmodid' => $this->sModKey);

                $this->_setInitialExecMethod(__METHOD__);
                $blReturn = $this->_updateTableItem2('d3_cfg_mod', $aInsertFields, $aWhereFields);
            }

            oxRegistry::getConfig()->setShopId($sOriginalShopid);

            if ($blReturn) {
                $blReturn = $this->_dropTable('oxobject2heidelpay');
            }

        }

        return $blReturn;
    }

    /****************************************************
     * Mod-Cfg-Eintrag kontrollieren / aktualisieren    *
     ****************************************************/
    /**
     * @return bool
     */
    public function checkModCfgItemExist()
    {
        $blRet = false;
        foreach ($this->_getShopList() as $oShop) {
            /** @var $oShop oxshop */
            $aWhere = array(
                'oxmodid'       => $this->sModKey,
                'oxnewrevision' => $this->sModRevision,
                'oxshopid'      => $oShop->getId(),
            );

            $blRet = $this->_checkTableItemNotExist('d3_cfg_mod', $aWhere);
            if ($blRet) {
                // setze session-cookie wenn es sich um eine erstinstallation handelt
                // wird benoetigt fuer
                oxRegistry::getSession()->setVariable('d3hp_firstInstallation', 1);

                return $blRet;
            }
        }

        return $blRet;
    }

    /**
     * @return bool
     */
    public function updateModCfgItemExist()
    {
        $blRet = false;

        if ($this->checkModCfgItemExist()) {
            foreach ($this->_getShopList() as $oShop) {
                /** @var $oShop oxshop */
                $aWhere = array(
                    'oxmodid'       => $this->sModKey,
                    'oxshopid'      => $oShop->getId(),
                    'oxnewrevision' => $this->sModRevision,
                );

                if ($this->_checkTableItemNotExist('d3_cfg_mod', $aWhere)) {
                    // update don't use this property
                    unset($aWhere['oxnewrevision']);

                    $aInsertFields = array(
                        'OXID'           => array(
                            'content'      => "md5('" . $this->sModKey . " " . $oShop->getId() . " de')",
                            'force_update' => true,
                            'use_quote'    => false,
                        ),
                        'OXSHOPID'       => array(
                            'content'      => $oShop->getId(),
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXMODID'        => array(
                            'content'      => $this->sModKey,
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXNAME'         => array(
                            'content'      => $this->sModName,
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXACTIVE'       => array(
                            'content'      => "0",
                            'force_update' => false,
                            'use_quote'    => false,
                        ),
                        'OXBASECONFIG'   => array(
                            'content'      => $this->sBaseConf,
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXSERIAL'       => array(
                            'content'      => "",
                            'force_update' => false,
                            'use_quote'    => true,
                        ),
                        'OXINSTALLDATE'  => array(
                            'content'      => "NOW()",
                            'force_update' => true,
                            'use_quote'    => false,
                        ),
                        'OXVERSION'      => array(
                            'content'      => $this->sModVersion,
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXSHOPVERSION'  => array(
                            'content'      => oxRegistry::getConfig()->getEdition(),
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXREQUIREMENTS' => array(
                            'content'      => $this->sRequirements,
                            'force_update' => true,
                            'use_quote'    => true,
                        ),
                        'OXVALUE'        => array(
                            'content'      => $this->sBaseValue,
                            'force_update' => false,
                            'use_quote'    => true,
                        ),
                        'OXNEWREVISION'  => array(
                            'content'      => $this->sModRevision,
                            'force_update' => true,
                            'use_quote'    => true,
                        )
                    );
                    $aRet          = $this->_updateTableItem('d3_cfg_mod', $aInsertFields, $aWhere);
                    $blRet         = $aRet['blRet'];

                    $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
                    $this->_setUpdateBreak(false);
                }
            }
        }

        return $blRet;
    }

    /**
     * @return bool
     */
    public function checkModCfgSameRevision()
    {
        $blRet = $this->_checkModCfgSameRevision($this->sModKey);

        return $blRet;
    }

    /**
     * @return bool
     */
    public function updateModCfgSameRevision()
    {
        $blRet = false;

        if ($this->checkModCfgSameRevision($this->sModKey)) {
            $aRet = $this->_updateModCfgSameRevision($this->sModKey);

            $this->_setActionLog('SQL', $aRet['sql'], __METHOD__);
            $this->_setUpdateBreak(false);
            $blRet = $aRet['blRet'];
        }

        return $blRet;
    }

    /**
     * @return bool
     */
    public function hasLegacyAssigments()
    {
        $aOldPayments = unserialize(d3_cfg_mod::get($this->sModKey)->getValue('d3heidelpay_aPaymentList'));
        foreach ($aOldPayments as $sOldValue) {
            if (in_array(
                $sOldValue,
                array(
                     0  => 'IV__billsafe',
                     1  => 'CC',
                     2  => 'DC',
                     3  => 'DD',
                     4  => 'OT__eps',
                     5  => 'OT__giro',
                     6  => 'OT__ideal',
                     7  => 'VA__paypal',
                     8  => 'PP',
                     9  => 'OT__sofort',
                     10 => 'IV__assuredinv',
                     11 => 'IV__nassuredinv',
                )
            )
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * @return bool
     */
    public function updateLegacyAssigments()
    {

        if ($this->_hasExecute() && $this->hasLegacyAssigments()) {

            $aOldPayments = unserialize(d3_cfg_mod::get($this->sModKey)->getValue('d3heidelpay_aPaymentList'));
            $aMapPayments = array(
                'IV__billsafe'    => 'd3_d3heidelpay_models_payment_billsafe',
                'CC'              => 'd3_d3heidelpay_models_payment_creditcard',
                'DC'              => 'd3_d3heidelpay_models_payment_debitcard',
                'DD'              => 'd3_d3heidelpay_models_payment_directdebit',
                'OT__eps'         => 'd3_d3heidelpay_models_payment_eps',
                'OT__giro'        => 'd3_d3heidelpay_models_payment_giropay',
                'OT__ideal'       => 'd3_d3heidelpay_models_payment_ideal',
                'VA__paypal'      => 'd3_d3heidelpay_models_payment_paypal',
                'PP'              => 'd3_d3heidelpay_models_payment_prepayment',
                'OT__sofort'      => 'd3_d3heidelpay_models_payment_sofortueberweisung',
                'IV__assuredinv'  => 'd3_d3heidelpay_models_payment_invoice_secured',
                'IV__nassuredinv' => 'd3_d3heidelpay_models_payment_invoice_unsecured',
            );

            $aResult = array();

            foreach ($aOldPayments as $sPaymentId => $sOldKey) {
                if ($sOldKey) {
                    $aResult[$sPaymentId] = $aMapPayments[$sOldKey];
                }
            }

            d3_cfg_mod::get($this->sModKey)->setValue('d3heidelpay_aPaymentList', serialize($aResult));
            d3_cfg_mod::get($this->sModKey)->save();
        }

        if ('autoinstall' != $this->_getAction()) {
            $this->_setActionLog(
                'MSG',
                oxRegistry::getLang()->translateString('d3_d3heidelpay_models_update_legacy_assigments_updatemessage'),
                __METHOD__
            );
            $this->_setUpdateBreak(false);
        }

        return true;
    }

    /**
     *
     * @return bool
     */
    public function hasOldOxconfigEntries()
    {
        $oDb             = oxDb::getDb(ADODB_FETCH_ASSOC);
        $sOriginalShopid = oxRegistry::getConfig()->getShopId();

        foreach ($this->_getShopList() as $oShop) {
            /** @var $oShop oxshop */
            oxRegistry::getConfig()->setShopId($oShop->getId());

            if (false == version_compare(d3_cfg_mod::get($this->sModKey)->getModVersion(), '4.0.0.0', '<')) {
                continue;
            }

            $sCountHeidelpayEntries = <<<MYSQL
SELECT count(*)
FROM `oxconfig`
WHERE
    `OXVARNAME` LIKE {$oDb->quote('Heidelpay_%')}
    AND `OXSHOPID` LIKE {$oDb->quote($oShop->getId())}
MYSQL;
            if (false == $oDb->getOne($sCountHeidelpayEntries)) {
                continue;
            }

            oxRegistry::getConfig()->setShopId($sOriginalShopid);

            return true;
        }

        oxRegistry::getConfig()->setShopId($sOriginalShopid);

        return false;
    }

    /**
     * @return bool
     */
    public function migrateOldOxconfigEntries()
    {
        if (false == $this->hasOldOxconfigEntries()) {
            return false;
        }

        $blReturn        = false;
        $oDb             = oxDb::getDb(ADODB_FETCH_ASSOC);
        $sOriginalShopid = oxRegistry::getConfig()->getShopId();

        foreach ($this->_getShopList() as $oShop) {
            /** @var $oShop oxshop */
            $sGetOldHeidelpayOxconfigEntries = <<<MYSQL
SELECT `OXVARNAME` as oxvarname
FROM `oxconfig`
WHERE
    `OXVARNAME` LIKE {$oDb->quote('Heidelpay_%')}
    AND `OXSHOPID` LIKE {$oDb->quote($oShop->getId())}
MYSQL;
            $aOldSettings                    = $oDb->getArray($sGetOldHeidelpayOxconfigEntries);
            oxRegistry::getConfig()->setShopId($oShop->getId());

            if (false == isset($aOldSettings[0])) {
                continue;
            }

            $oModuleConfiguration = d3_cfg_mod::get($this->sModKey);
            $this->_convertOldSettingsToModuleConfiguration($aOldSettings, $oModuleConfiguration);

            $aInsertFields = array(
                'OXVALUE'        => array(
                    'content'      =>  $oModuleConfiguration->getFieldData('oxvalue'),
                    'force_update' => true,
                    'use_quote'    => true,
                )
            );
            $aWhereFields  = array('oxshopid' => $oShop->getId(), 'oxmodid' => $this->sModKey);

            $this->_setInitialExecMethod(__METHOD__);
            $blReturn = $this->_updateTableItem2('d3_cfg_mod', $aInsertFields, $aWhereFields);

            if($blReturn) {
                $sDeleteOldHeidelpayOxconfigEntries  = <<<MYSQL
DELETE
FROM `oxconfig`
WHERE
    `OXVARNAME` LIKE {$oDb->quote('Heidelpay_%')}
    AND `OXSHOPID` LIKE {$oDb->quote($oShop->getId())}
MYSQL;
                $blRet = $this->_sqlExecute($sDeleteOldHeidelpayOxconfigEntries);
                $aRet = array('sql' => $sDeleteOldHeidelpayOxconfigEntries, 'blRet' => $blRet);

                $this->_setUpdateBreak(FALSE);
                $this->_setActionLog('SQL', $aRet['sql'],$this->_getInitialExecMethod(__METHOD__));
            }
        }
        oxRegistry::getConfig()->setShopId($sOriginalShopid);

        return $blReturn;
    }

    /**
     * @param array      $aOldSettings
     * @param d3_cfg_mod $oModuleConfiguration
     *
     */
    protected function _convertOldSettingsToModuleConfiguration(array $aOldSettings, d3_cfg_mod $oModuleConfiguration)
    {
        foreach ($aOldSettings as $aOldSetting) {
            if (false == isset($aOldSetting['oxvarname'])) {
                continue;
            }

            $sSettingsName = $aOldSetting['oxvarname'];

            if (isset($this->aMapArraySettings[$sSettingsName])) {
                $aSettings = $oModuleConfiguration->getValue($this->aMapArraySettings[$sSettingsName]);
                if (false == $aSettings) {
                    $aSettings = 'a:0:{}';
                }

                $aSettings = unserialize($aSettings);

                $aSettings[$this->aMapSettings[$sSettingsName]]         = oxRegistry::getConfig()->getConfigParam(
                    $sSettingsName
                );
                $oModuleConfiguration->setValue($this->aMapArraySettings[$sSettingsName], serialize($aSettings));

            } elseif (isset($this->aMapSettings[$sSettingsName])) {
                $oModuleConfiguration->setValue(
                    $this->aMapSettings[$sSettingsName],
                    oxRegistry::getConfig()->getConfigParam($sSettingsName)
                );
            }
        }

    }

    /**
     * @param array      $aOldAssignments
     * @param d3_cfg_mod $oModuleConfiguration
     *
     * @return array
     */
    protected function _convertOldAssignmentsToSettings(array $aOldAssignments, d3_cfg_mod $oModuleConfiguration)
    {
        $aPayments = array();
        foreach ($aOldAssignments as $aOldAssignment) {
            if (false == isset($aOldAssignment['oxpaymentid']) || false == isset($aOldAssignment['oxtype'])) {
                continue;
            }

            $sOxidPaymentId             = $aOldAssignment['oxpaymentid'];
            $sPaymentType               = $aOldAssignment['oxtype'];
            $aPayments[$sOxidPaymentId] = $sPaymentType;
        }

        $oModuleConfiguration->setValue('d3_cfg_mod__d3heidelpay_aPaymentList', serialize($aPayments));
    }

    /**
     * @param $sFileName
     *
     * @return bool
     */
    protected function _hasExecuteFileQuery($sFileName)
    {
        startProfile(__METHOD__);

        $aList = $this->_parseUpdateFile($sFileName);
        $sShopid = oxRegistry::getConfig()->getShopId();
        foreach ($aList['check'] as $sCheckQuery) {

            $sShopSpecificQuery = str_replace(
            'WHERE',
            'WHERE oxshopid = ' . oxDb::getDb()->quote($sShopid) . ' AND ',
            $sCheckQuery
            );
            if (oxDb::getDb(oxDb::FETCH_MODE_ASSOC)->getOne($sShopSpecificQuery)) {
                stopProfile(__METHOD__);

                return true;
            }
        }
        stopProfile(__METHOD__);

        return false;
    }

    /**
     * @param $sFileName
     *
     * @return bool
     */
    protected function _executeFileQueries($sFileName)
    {
        startProfile(__METHOD__);

        $blRet   = true;
        $aDoList = array();
        $aList   = $this->_parseUpdateFile($sFileName);
        $sShopid = oxRegistry::getConfig()->getShopId();

        if (oxRegistry::getConfig()->isUtf()) {
            /** @var d3str $oD3Str */
            $oD3Str = oxNew('d3str');
            $oD3Str->convert2utf_8($aList, false);
        }

        foreach ($aList['check'] as $sKey => $sCheckQuery) {
            $sShopSpecificQuery = str_replace(
            'WHERE',
            'WHERE oxshopid = ' . oxDb::getDb()->quote($sShopid) . ' AND ',
            $sCheckQuery
            );
            if (oxDb::getDb(oxDb::FETCH_MODE_ASSOC)->getOne($sShopSpecificQuery)) {
                $aDoList[] = str_replace('oxbaseshop', $sShopid, $aList['do'][$sKey]);
            }
        }

        if ($aDoList && is_array($aDoList) && count($aDoList)) {
            $this->setInitialExecMethod(__METHOD__);
            $blUseCombinedLogItem = $this->hasExecute() ? false : true;
            $blRet                = $this->_executeMultipleQueries($aDoList, $blUseCombinedLogItem);
        }

        stopProfile(__METHOD__);

        return $blRet;
    }

    /**
     * @return bool
     */
    public function checkForChangeHaendlerKontoMsg()
    {
        return false == oxRegistry::getConfig()->getConfigParam('blD3checkForModHaendlerKontoMsg');
    }

    /**
     * @return bool
     */
    public function showForChangeHaendlerKontoMsg()
    {
        $blRet = $this->_confirmMessage('D3_HEIDELPAY_UPDATE_CHANGE_HAENDLERKONTO');

        if (false == $this->getUpdateBreak() && true == $this->hasExecute()) {
            $sName   = 'blD3checkForModHaendlerKontoMsg';
            $sValue  = true;
            $sShopId = oxRegistry::getConfig()->getShopId();
            #$sModule = 'module:' . $this->sModKey;
            $sModule = '';
            $sType   = 'bool';
            oxRegistry::getConfig()->saveShopConfVar($sType, $sName, $sValue, $sShopId, $sModule);
        }

        return $blRet;
    }

    /**
     * @return bool
     */
    public function checkModCfgorderExecutePostFields()
    {

        $blReturn = false;

        if (false == is_string(
                d3_cfg_mod::get($this->sModKey)->getValue('d3_cfg_mod__d3heidelpay_orderExecutePostFields')
            ) || strlen(
                d3_cfg_mod::get($this->sModKey)->getValue('d3_cfg_mod__d3heidelpay_orderExecutePostFields')
            ) == 0
        ) {
            $blReturn = true;
        }

        return $blReturn;
    }

    /**
     * @return bool
     */
    public function updateModCfgorderExecutePostFields()
    {
        $aDefaultConfig = unserialize(rawurldecode(base64_decode($this->sBaseValue)));

        foreach ($this->getShopList() as $oShop) {
            /** @var $oShop oxshop */
            $oModCfg = d3_cfg_mod::get($this->sModKey);
            $oModCfg->setValue(
                'd3_cfg_mod__d3heidelpay_orderExecutePostFields',
                $aDefaultConfig->d3_cfg_mod__d3heidelpay_orderExecutePostFields
            );

            if (false == $this->getUpdateBreak() && true == $this->hasExecute()) {
                $oModCfg->save();
            }

            $sQuery = 'UPDATE ' . $oModCfg->getViewName() //
                . ' SET oxvalue = ' //
                . oxDb::getDb(oxDb::FETCH_MODE_ASSOC)->quote($oModCfg->getFieldData('oxvalue')) //
                . " WHERE oxmodid = " . oxDb::getDb(oxDb::FETCH_MODE_ASSOC)->quote($this->sModKey) //
                . " AND oxshopid = " . oxDb::getDb(oxDb::FETCH_MODE_ASSOC)->quote($oShop->getId()) . ";";

            $this->setUpdateBreak(false);
            $this->setActionLog(
                'SQL',
                $sQuery,
                $this->getInitialExecMethod(__METHOD__)
            );
        }

        return true;
    }
}
