Parses the amazon address fields.

@param \stdClass $oAmazonData
@param array     $aResult
429860
protected function _parseAddressFields($oAmazonData, array &$aResult)
    {
        // Cleanup address fields and store them to an array
        $aAmazonAddresses = array(
            1 => is_string($oAmazonData->AddressLine1) ? trim($oAmazonData->AddressLine1) : '',
            2 => is_string($oAmazonData->AddressLine2) ? trim($oAmazonData->AddressLine2) : '',
            3 => is_string($oAmazonData->AddressLine3) ? trim($oAmazonData->AddressLine3) : ''
        );

        // Array of iso2 codes of countries that have another addressline order
        $aReverseOrderCountries = $this->getConfig()->getConfigParam('aAmazonReverseOrderCountries');

        $aMap = array_flip($aReverseOrderCountries);
        $aCheckOrder = isset($aMap[$oAmazonData->CountryCode]) === true ? array (2, 1) : array(1, 2);
        $sStreet = '';
        $sCompany = '';

        foreach ($aCheckOrder as $iCheck) {
            if ($aAmazonAddresses[$iCheck] !== '') {
                if ($sStreet !== '') {
                    $sCompany = $aAmazonAddresses[$iCheck];
                    break;
                }

                $sStreet = $aAmazonAddresses[$iCheck];
            }
        }

        if ($aAmazonAddresses[3] !== '') {
            $sCompany = ($sCompany === '') ? $aAmazonAddresses[3] : "{$sCompany}, {$aAmazonAddresses[3]}";
        }

        $aResult['CompanyName'] = $sCompany;

        $aAddress = $this->_parseSingleAddress($sStreet, $oAmazonData->CountryCode);
        $aResult['Street'] = isset($aAddress['Name']) === true ? $aAddress['Name'] : '';
        $aResult['StreetNr'] = isset($aAddress['Number']) === true ? $aAddress['Number'] : '';
        $aResult['AddInfo'] = isset($aAddress['AddInfo']) === true ? $aAddress['AddInfo'] : '';
    }
1271261
protected function ValidateResponseData($aResponseData, TdbShopOrder &$oOrder, $sMessageConsumer)
    {
        $bIsValid = true;
        $oGlobal = TGlobal::instance();
        // todo: add user messages on invalid response
        if ($bIsValid) {
            // valid hash?
            $sCalculatedHash = hash('sha256', $oOrder->id.$this->GetConfigParameter('project_password'));
            $sPassedHash = (true == array_key_exists('user_variable_3_hash_pass', $aResponseData)) ? $aResponseData['user_variable_3_hash_pass'] : '';
            if (0 != strcmp($sCalculatedHash, $sPassedHash)) {
                TTools::WriteLogEntry("Sofortüberweisung: unable to validate response hash [{$sPassedHash}] against calculated hash [{$sCalculatedHash}]", 1, __FILE__, __LINE__);
                $bIsValid = false;
            }
        }

        if ($bIsValid) {
            // order matches?
            $sOrderId = (true == array_key_exists('user_variable_3', $aResponseData)) ? $aResponseData['user_variable_3'] : '';
            if (0 != strcmp($sOrderId, $oOrder->id)) {
                TTools::WriteLogEntry("Sofortüberweisung: order ID returned [{$sOrderId}] does not match order ID passed to method [{$oOrder->id}]", 1, __FILE__, __LINE__);
                $bIsValid = false;
            }
        }

        if ($bIsValid) {
            // validate amount
            $iAmount = (true == array_key_exists('amount', $aResponseData)) ? $aResponseData['amount'] : '';
            if ($iAmount != $oOrder->fieldValueTotal) {
                TTools::WriteLogEntry("Sofortüberweisung [order id {$oOrder->id}]: invalid amount paid [{$iAmount}] (should have been [".$oOrder->fieldValueTotal.']) '.print_r($aResponseData, true), 1, __FILE__, __LINE__);
                $bIsValid = false;
            }
        }

        return $bIsValid;
    }
38425
protected function getBillingAddress(TdbShopOrder $order, $cachingEnabled, IMapperCacheTriggerRestricted $cacheTriggerManager)
    {
        $salutation = $order->GetFieldAdrBillingSalutation();
        if ($salutation && $cachingEnabled) {
            $cacheTriggerManager->addTrigger($salutation->table, $salutation->id);
        }
        $address = '';
        $address .= (null !== $salutation) ? $salutation->GetName().' ' : '';
        $address .= $this->getValueOrDefault($order->fieldAdrBillingFirstname, ' ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingLastname, ', ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingAdditionalInfo, ', ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingStreet, ' ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingStreetnr, ', ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingPostalcode, ' ');
        $address .= $this->getValueOrDefault($order->fieldAdrBillingCity);

        return $address;
    }
901972
protected function ExecuteDataTransPaymentCall(TdbShopOrder &$oOrder)
    {
        $sXMLSettlement = $this->GetXMLSettlement();
        $ch = curl_init();
        $settlementurl = trim($this->GetTestLiveModeParameter('settlementurl'));
        curl_setopt($ch, CURLOPT_URL, $settlementurl);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'xmlRequest='.$sXMLSettlement);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $sResponse = curl_exec($ch);
        $sCurlError = curl_error($ch);
        $bPaymentOk = $this->SettlementResponseSuccess($sResponse);
        if (!$bPaymentOk) {
            if (!empty($sCurlError)) {
                TTools::WriteLogEntrySimple('Payment DataTrans: curl failed to ['.$this->GetConfigParameter('settlementurl')."] using xml [{$sXMLSettlement}] with error: ".$sCurlError, 1, __FILE__, __LINE__);
            }
            $iFailure = $this->GetConfigParameter('failure_settlement');
            if ('1' === $iFailure) {
                if ($this->SendFailureSettlementMail($oOrder)) {
                    $bPaymentOk = true;
                } else {
                    TTools::WriteLogEntrySimple('Payment DataTrans: Es konnte keine Abbuchungsfehlere-mail versand werden', 1, __FILE__, __LINE__);
                }
            }
        }
        curl_close($ch);

        return $bPaymentOk;
    }
1121540
protected function LoadFromBasketPostProcessData($oBasket, &$aOrderData)
    {
        // ------------------------------------------------------------------------
        parent::LoadFromBasketPostProcessData($oBasket, $aOrderData);
        if (method_exists($oBasket, 'getUserSelectedNewsletterOptionInOrderStep') && $oBasket->getUserSelectedNewsletterOptionInOrderStep()) {
            $aOrderData['newsletter_signup'] = '1';
        } else {
            $aOrderData['newsletter_signup'] = '0';
        }
    }
238879
protected function parseData()
    {
        if (is_null($this->dataCache)) {
            $patternNamespace  = '(?P<namespace>[a-zA-Z0-9\\\\]+\\\\)?';
            $patternName       = '(?P<name>[a-zA-Z0-9]+)';
            $patternString     = '\"[^\"]*\"|\'[^\']*\'';
            $patternFloat      = '[0-9]+\.[0-9]+';
            $patternInt        = '[0-9]+';
            $patternBool       = 'true|false';
            $patternAttrValues = "({$patternString}|{$patternFloat}|{$patternInt}|{$patternBool})";
            $patternAttributes = "(?P<attr>\(\s*([a-zA-Z0-9]+\={$patternAttrValues}\s*\,?\s*)+\s*\))?";
            $pattern           = "^\@{$patternNamespace}{$patternName}\s*{$patternAttributes}(?P<rawtext>.*)$";
            
            if (preg_match("/{$pattern}/is", $this->getValue(), $matches)) {
                $this->dataCache = array(
                    'namespace'   => $matches['namespace'],
                    'name'        => $matches['name'],
                    'attributes'  => array(),
                    'tags'        => array(),
                );
                
                if (preg_match_all("/(?P<key>[a-zA-Z0-9]+)\s*\=\s*(?P<value>{$patternAttrValues})/is", $matches['attr'], $attributeMatches, PREG_SET_ORDER)) {
                    foreach ($attributeMatches as $attributeMatch) {
                        $key   = $attributeMatch['key'];
                        $value = $attributeMatch['value'];
                        switch(true){
                            case $value === 'true':
                                $value = true;
                                break;
                                
                            case $value === 'false':
                                $value = false;
                                break;
                                
                            case $value[0] === '"':
                            case $value[0] === "'":
                                $value = substr($value, 1, strlen($value)-2);
                                break;
                                
                            case strpos($value, '.')>0:
                                $value = (float)$value;
                                break;
                                
                            case is_numeric($value):
                                $value = (int)$value;
                                break;
                                
                        }
                        $this->dataCache['attributes'][$key] = $value;
                    }
                }
                
                foreach (preg_split("/\s+/is", trim($matches['rawtext'])) as $attributeTag) {
                    $this->dataCache['tags'][] = $attributeTag;
                }
            }
        }
        return $this->dataCache;
    }
1278666
function oAuthParseResponse($responseString) {
    $r = array();
    foreach (explode('&', $responseString) as $param) {
      $pair = explode('=', $param, 2);
      if (count($pair) != 2) continue;
      $r[urldecode($pair[0])] = urldecode($pair[1]);
    }
    return $r;
  }
635945
public function processAuthorization(oxOrder $oOrder, stdClass $oAuthorizationDetails)
    {
        $oAuthorizationStatus = $oAuthorizationDetails->AuthorizationStatus;

        //Update Order with primary response info
        $oOrder->assign(array('oxtransstatus' => 'AMZ-Authorize-'.$oAuthorizationStatus->State));
        $oOrder->save();

        // Handle Declined response
        if ($oAuthorizationStatus->State === 'Declined'
            && $this->getConfig()->getConfigParam('sAmazonMode') === bestitAmazonPay4OxidClient::OPTIMIZED_FLOW
        ) {
            switch ($oAuthorizationStatus->ReasonCode) {
                case "InvalidPaymentMethod":
                    /** @var bestitAmazonPay4Oxid_oxEmail $oEmail */
                    $oEmail = $this->getObjectFactory()->createOxidObject('oxEmail');
                    $oEmail->sendAmazonInvalidPaymentEmail($oOrder);
                    break;
                case "AmazonRejected":
                    /** @var bestitAmazonPay4Oxid_oxEmail $oEmail */
                    $oEmail = $this->getObjectFactory()->createOxidObject('oxEmail');
                    $oEmail->sendAmazonRejectedPaymentEmail($oOrder);
                    $this->closeOrderReference($oOrder, array(), false);
                    break;
                default:
                    $this->closeOrderReference($oOrder, array(), false);
            }
        }

        //Authorize handling was selected Direct Capture after Authorize and Authorization status is Open
        if ($oAuthorizationStatus->State === 'Open'
            && $this->getConfig()->getConfigParam('sAmazonCapture') === 'DIRECT'
        ) {
            $this->capture($oOrder);
        }
    }
1182443
public function parseSpamReportArf()
    {
        $reports = [ ];

        //Seriously spamcop? Newlines arent in the CL specifications
        $this->arfMail['report'] = str_replace("\r", "", $this->arfMail['report']);

        preg_match_all('/([\w\-]+): (.*)[ ]*\r?\n/', $this->arfMail['report'], $regs);
        $report = array_combine($regs[1], $regs[2]);

        //Valueable information put in the body instead of the report, thnx for that Spamcop
        if (strpos($this->arfMail['message'], 'Comments from recipient') !== false) {
            preg_match(
                "/Comments from recipient.*\s]\n(.*)\n\n\nThis/s",
                str_replace(array("\r", "> "), "", $this->arfMail['message']),
                $match
            );
            $report['recipient_comment'] = str_replace("\n", " ", $match[1]);
        }

        // Add the headers from evidence into infoblob
        $parsedEvidence = new MimeParser();
        $parsedEvidence->setText($this->arfMail['evidence']);
        $headers = $parsedEvidence->getHeaders();

        foreach ($headers as $key => $value) {
            if (is_array($value) || is_object(($value))) {
                foreach ($value as $index => $subvalue) {
                    $report['headers']["${key}${index}"] = "$subvalue";
                }
            } else {
                $report['headers']["$key"] = $value;
            }
        }

        /*
         * Sometimes Spamcop has a trouble adding the correct fields. The IP is pretty
         * normal to add. In a last attempt we will try to fetch the IP from the body ourselves
         */
        if (empty($report['Source-IP'])) {
            preg_match(
                "/Email from (?<ip>[a-f0-9:\.]+) \/ " . preg_quote($report['Received-Date']) . "/s",
                $this->arfMail['message'],
                $regs
            );

            if (!empty($regs['ip']) && !filter_var($regs['ip'], FILTER_VALIDATE_IP) === false) {
                $report['Source-IP'] = $regs['ip'];
            }

            preg_match(
                "/from: (?<ip>[a-f0-9:\.]+)\r?\n?\r\n/s",
                $this->parsedMail->getMessageBody(),
                $regs
            );

            if (!empty($regs['ip']) && !filter_var($regs['ip'], FILTER_VALIDATE_IP) === false) {
                $report['Source-IP'] = $regs['ip'];
            }
        }

        $reports[] = $report;

        return $reports;
    }
558938
public function validateDeliveryAddress($oUser)
    {
        $oBasket = $this->_getContainer()->getSession()->getBasket();

        if ($oBasket && (string)$oBasket->getPaymentId() === 'bestitamazon') {
            return 0;
        } else {
            return parent::validateDeliveryAddress($oUser);
        }
    }
1051074
public function parse(array $data, ParsingDispatcher $parsingDispatcher)
    {
        $parsedData = array();

        //@todo XSD has a login element, but it's not possible to update login

        if (array_key_exists('email', $data)) {
            $parsedData['email'] = $data['email'];
        }

        if (array_key_exists('password', $data)) {
            $parsedData['password'] = $data['password'];
        }

        if (array_key_exists('enabled', $data)) {
            $parsedData['enabled'] = $this->parserTools->parseBooleanValue($data['enabled']);
        }

        if (array_key_exists('mainLanguageCode', $data)) {
            $parsedData['mainLanguageCode'] = $data['mainLanguageCode'];
        }

        if (array_key_exists('Section', $data) && is_array($data['Section'])) {
            if (!array_key_exists('_href', $data['Section'])) {
                throw new Exceptions\Parser("Missing '_href' attribute for Section element in UserUpdate.");
            }

            $parsedData['sectionId'] = $this->requestParser->parseHref($data['Section']['_href'], 'sectionId');
        }

        if (array_key_exists('remoteId', $data)) {
            $parsedData['remoteId'] = $data['remoteId'];
        }

        if (array_key_exists('fields', $data)) {
            $userId = $this->requestParser->parseHref($data['__url'], 'userId');

            if (!is_array($data['fields']) || !array_key_exists('field', $data['fields']) || !is_array($data['fields']['field'])) {
                throw new Exceptions\Parser("Invalid 'fields' element for UserUpdate.");
            }

            $parsedData['fields'] = array();
            foreach ($data['fields']['field'] as $fieldData) {
                if (!array_key_exists('fieldDefinitionIdentifier', $fieldData)) {
                    throw new Exceptions\Parser("Missing 'fieldDefinitionIdentifier' element in field data for UserUpdate.");
                }

                if (!array_key_exists('fieldValue', $fieldData)) {
                    throw new Exceptions\Parser("Missing 'fieldValue' element for '{$fieldData['fieldDefinitionIdentifier']}' identifier in UserUpdate.");
                }

                $fieldValue = $this->fieldTypeParser->parseFieldValue($userId, $fieldData['fieldDefinitionIdentifier'], $fieldData['fieldValue']);

                $languageCode = null;
                if (array_key_exists('languageCode', $fieldData)) {
                    $languageCode = $fieldData['languageCode'];
                }

                $parsedData['fields'][$fieldData['fieldDefinitionIdentifier']] = array(
                    'fieldValue' => $fieldValue,
                    'languageCode' => $languageCode,
                );
            }
        }

        $userUpdateStruct = $this->userService->newUserUpdateStruct();

        if (!empty($parsedData)) {
            if (array_key_exists('email', $parsedData)) {
                $userUpdateStruct->email = $parsedData['email'];
            }

            if (array_key_exists('password', $parsedData)) {
                $userUpdateStruct->password = $parsedData['password'];
            }

            if (array_key_exists('enabled', $parsedData)) {
                $userUpdateStruct->enabled = $parsedData['enabled'];
            }

            if (array_key_exists('mainLanguageCode', $parsedData) || array_key_exists('remoteId', $parsedData)) {
                $userUpdateStruct->contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();

                if (array_key_exists('mainLanguageCode', $parsedData)) {
                    $userUpdateStruct->contentMetadataUpdateStruct->mainLanguageCode = $parsedData['mainLanguageCode'];
                }

                if (array_key_exists('remoteId', $parsedData)) {
                    $userUpdateStruct->contentMetadataUpdateStruct->remoteId = $parsedData['remoteId'];
                }
            }

            if (array_key_exists('fields', $parsedData)) {
                $userUpdateStruct->contentUpdateStruct = $this->contentService->newContentUpdateStruct();

                foreach ($parsedData['fields'] as $fieldDefinitionIdentifier => $fieldValue) {
                    $userUpdateStruct->contentUpdateStruct->setField(
                        $fieldDefinitionIdentifier,
                        $fieldValue['fieldValue'],
                        $fieldValue['languageCode']
                    );
                }
            }
        }

        return new RestUserUpdateStruct(
            $userUpdateStruct,
            array_key_exists('sectionId', $parsedData) ? $parsedData['sectionId'] : null
        );
    }
813399
protected function parse($data)
    {
        $parsed = array();

        // Split into parts
        $parts = explode(
            $this->normaliseWhitespace($this->fieldSeparator),
            $this->normaliseWhitespace(trim($data, " \t"))
        );
        if (sizeof($parts) < 2) {
            throw new DomainException(
                sprintf(
                    'Expected a well-formed line of two fields "name%svalue", got: "%s".',
                    $this->fieldSeparator,
                    $this->originalLine
                )
            );
        }

        $parsed[self::FIELD_NAME] = array_shift($parts);

        $value = implode($this->fieldSeparator, $parts);
        if (substr($value, 0, 1) === '"' && substr($value, -1) === '"') {
            $value = substr($value, 1, -1);
        }
        $parsed[self::FIELD_VALUE] = $value;

        return $parsed;
    }
540784
public function parseResults(LoopResult $loopResult)
    {
        $moduleCode = $this->getModule();

        if (null === $module = ModuleQuery::create()->filterByCode($moduleCode, Criteria::LIKE)->findOne()) {
            throw new \InvalidArgumentException("Module with code '$moduleCode' does not exists.");
        }

        $configValue = ModuleConfigQuery::create()->getConfigValue(
            $module->getId(),
            $this->getVariable(),
            $this->getDefaultValue(),
            $this->getLocale()
        );

        $loopResultRow = new LoopResultRow();

        $loopResultRow
            ->set("VARIABLE", $this->getVariable())
            ->set("VALUE", $configValue)
        ;

        $loopResult->addRow($loopResultRow);

        return $loopResult;
    }
180657
public function parseResults(LoopResult $loopResult)
    {
        /** @var FeatureType $entry */
        foreach ($loopResult->getResultDataCollection() as $entry) {
            $row = new LoopResultRow($entry);
            $row
                ->set("ID", $entry->getId())
                ->set("SLUG", $entry->getSlug())
                ->set("TITLE", $entry->getVirtualColumn('i18n_TITLE'))
                ->set("DESCRIPTION", $entry->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("CSS_CLASS", $entry->getCssClass())
                ->set("PATTERN", $entry->getPattern())
                ->set("INPUT_TYPE", $entry->getInputType())
                ->set("MIN", $entry->getMin())
                ->set("MAX", $entry->getMax())
                ->set("STEP", $entry->getStep())
                ->set("IMAGE_MAX_WIDTH", $entry->getImageMaxWidth())
                ->set("IMAGE_MAX_HEIGHT", $entry->getImageMaxHeight())
                ->set("IMAGE_RATIO", $entry->getImageRatio())
                ->set("IS_MULTILINGUAL_FEATURE_AV_VALUE", $entry->getIsMultilingualFeatureAvValue())
                ->set("HAS_FEATURE_AV_VALUE", $entry->getHasFeatureAvValue())
            ;

            $this->addOutputFields($row, $entry);

            $loopResult->addRow($row);
        }

        return $loopResult;
    }
488424
public function parseResults(LoopResult $loopResult)
    {
        /** @var DealerContact $contact */
        foreach ($loopResult->getResultDataCollection() as $contact) {
            $loopResultRow = new LoopResultRow($contact);

            $loopResultRow
                ->set('ID', $contact->getId())
                ->set('DEALER_ID', $contact->getDealerId())
                ->set('IS_DEFAULT', $contact->getIsDefault());

            if ($contact->hasVirtualColumn('i18n_LABEL')) {
                $loopResultRow->set("LABEL", $contact->getVirtualColumn('i18n_LABEL'));
            }

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }
1279998
protected function GetShippingAddressData($sReturnThisParameterOnly = null)
    {
        $aReturnVal = false;
        if (array_key_exists('aShipping', $this->aUserData)) {
            $aAddress = $this->aUserData['aShipping'];
            if (array_key_exists('id', $aAddress) && !array_key_exists('selectedAddressId', $aAddress)) {
                $aAddress['selectedAddressId'] = $aAddress['id'];
            }
            $oActiveUser = self::getExtranetUserProvider()->getActiveUser();
            if ($oActiveUser && !empty($oActiveUser->id)) {
                $aAddress['data_extranet_user_id'] = $oActiveUser->id;
            }
            $aCheckboxFields = $this->GetShippingAddressCheckboxFields();
            foreach ($aCheckboxFields as $sFieldName) {
                if (!array_key_exists($sFieldName, $aAddress)) {
                    $aAddress[$sFieldName] = '0';
                }
            }

            if (!is_null($sReturnThisParameterOnly)) {
                if (array_key_exists($sReturnThisParameterOnly, $aAddress)) {
                    $aReturnVal = $aAddress[$sReturnThisParameterOnly];
                }
            } else {
                $aReturnVal = $aAddress;
            }
        }

        return $aReturnVal;
    }
516168
protected function getVoucherList(TdbShopOrder $oOrder, $bSponsored = false, IMapperCacheTriggerRestricted $oCacheTriggerManager, $bCachingEnabled)
    {
        $aVoucherList = array();

        // get vouchers
        $oVoucherUseList = &$oOrder->GetFieldShopVoucherUseList();
        $oVoucherUseList->GoToStart();
        if (0 < $oVoucherUseList->Length()) {
            while ($oVoucherUse = &$oVoucherUseList->Next()) {
                if ($bCachingEnabled) {
                    $oCacheTriggerManager->addTrigger($oVoucherUse->table, $oVoucherUse->id);
                }
                $oVoucher = $oVoucherUse->GetFieldShopVoucher();
                if (null !== $oVoucher) {
                    if ($bCachingEnabled) {
                        $oCacheTriggerManager->addTrigger($oVoucher->table, $oVoucher->id);
                    }
                    if (false === $oVoucher->IsSponsored() && false === $bSponsored) {
                        $aVoucher = $this->getDataFromVoucher($oVoucherUse, $oVoucher, $oCacheTriggerManager, $bCachingEnabled);
                        $aVoucherList[] = $aVoucher;
                    } elseif (true === $oVoucher->IsSponsored() && true === $bSponsored) {
                        $aVoucher = $this->getDataFromVoucher($oVoucherUse, $oVoucher, $oCacheTriggerManager, $bCachingEnabled);
                        $aVoucherList[] = $aVoucher;
                    }
                } else {
                    $aVoucher = $this->getDataFromVoucher($oVoucherUse, null, $oCacheTriggerManager);
                    $aVoucherList[] = $aVoucher;
                }
            }
            $oVoucherUseList->GoToStart();
        }

        return $aVoucherList;
    }