3D-Secure lookup

@param array $lookup_data_array
@return array
330136
function get3DSecureLookupResponse($lookup_data_array) {
    // Set some defaults
    if (!isset($lookup_data_array['order_desc']) || $lookup_data_array['order_desc'] == '') $lookup_data_array['order_desc'] = 'Zen Cart(R) Transaction';
    if (!isset($lookup_data_array['order_number']) || $lookup_data_array['order_number'] == '') $lookup_data_array['order_number'] = zen_session_id();
    // format the card expiration
    $lookup_data_array['cc3d_exp_year'] = (strlen($lookup_data_array['cc3d_exp_year']) == 2 ? '20' : '') . $lookup_data_array['cc3d_exp_year'];
    // get the ISO 4217 currency
    $iso_currency = $this->getISOCurrency($lookup_data_array['currency']);
    // format the transaction amounts
    $raw_amount = $this->formatRawAmount($lookup_data_array['txn_amount'], $iso_currency);
    // determine the appropriate product code for submission
    $prodCode = FALSE;
    if (isset($_SESSION['cart'])) {
      if ($_SESSION['cart']->get_cart_type == 'virtual') {
        $prodCode = 'DIG';
      } else {
        $prodCode = 'PHY';
      }
    }

    // DEBUG ONLY: $this->zcLog(__FILE__ . '->' . __LINE__, 'session details: ' . print_r(array_merge($_POST, $_SESSION), true));

    // Build the XML cmpi_lookup message
    $data = '<CardinalMPI>';
    $data .= '<MsgType>cmpi_lookup</MsgType>';
    $data .= '<Version>1.7</Version>';
    $data .= '<ProcessorId>' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR) . '</ProcessorId>';
    $data .= '<MerchantId><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]></MerchantId>';
    $data .= '<TransactionPwd><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]></TransactionPwd>';
    $data .= '<TransactionType>CC</TransactionType>';
    $data .= '<TransactionMode>S</TransactionMode>';
    $data .= '<OrderNumber>' . $this->escapeXML($lookup_data_array['order_number']) . '</OrderNumber>';
    $data .= '<OrderDescription>' . $this->escapeXML($lookup_data_array['order_desc']) . '</OrderDescription>';
    $data .= '<Amount>' . $this->escapeXML($raw_amount) . '</Amount>';
    $data .= '<CurrencyCode>' . $this->escapeXML($iso_currency) . '</CurrencyCode>';
    $data .= '<CardNumber>' . $this->escapeXML($lookup_data_array['cc3d_card_number']) . '</CardNumber>';
    $data .= '<Cvv>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</Cvv>';
    $data .= '<CardCode>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</CardCode>';
    $data .= '<CardExpMonth>' . $this->escapeXML($lookup_data_array['cc3d_exp_month']) . '</CardExpMonth>';
    $data .= '<CardExpYear>' . $this->escapeXML($lookup_data_array['cc3d_exp_year']) . '</CardExpYear>';
    $data .= '<UserAgent>' . $this->escapeXML($_SERVER["HTTP_USER_AGENT"]) . '</UserAgent>';
    $ipAddress = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $data .= '<IPAddress>' . $this->escapeXML($ipAddress) . '</IPAddress>';
    $data .= '<BrowserHeader>' . $this->escapeXML($_SERVER["HTTP_ACCEPT"]) . '</BrowserHeader>';
    $data .= '<OrderChannel>' . $this->escapeXML('MARK') . '</OrderChannel>';
    if (isset($lookup_data_array['merchantData'])) $data .= '<MerchantData>' . $this->escapeXML($lookup_data_array['merchantData']) . '</MerchantData>';
    if ($prodCode !== FALSE && $prodCode != '') $data .= '<ProductCode>' . $this->escapeXML($prodCode) . '</ProductCode>';
    $data .= '</CardinalMPI>';
    $debugData = str_replace(array('[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]', '[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]', $this->escapeXML($lookup_data_array['cc3d_card_number']), $this->escapeXML($lookup_data_array['cc3d_checkcode'])), '********', $data);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 1', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup request (' . MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL . ') - ' . $debugData);
    }

    $responseString = $this->send3DSecureHttp(MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL, $data, $debugData);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 2', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup response - ' . $responseString);
    }

    // parse the XML
    $parser = new CardinalXMLParser;
    $parser->deserializeXml($responseString);

    $errorNo = $parser->deserializedResponse['ErrorNo'];
    $errorDesc = $parser->deserializedResponse['ErrorDesc'];
    $enrolled = $parser->deserializedResponse['Enrolled'];

    if ($errorNo != 0) {
      $this->zcLog('Cardinal Lookup 3', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc);
      $errorText = 'Cardinal Lookup 3' . '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc;
      $errorText .= "\n\n" . 'There are 3 steps to configuring your Cardinal 3D-Secure service properly: ' . "\n1-Login to the Cardinal Merchant Admin URL supplied in your welcome package (NOT the test URL), and accept the license agreement.\n2-Set a transaction password.\n3-Copy your Cardinal Merchant ID and Cardinal Transaction Password into your ZC PayPal module.\n\nFor specific help, please contact implement@cardinalcommerce.com to sort out your account configuration issues.";
      $errorText .= "\n\nProblem observed while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication. THEIR PURCHASE WAS NOT SUCCESSFUL. Please resolve this matter to enable future checkouts.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, substr($errorDesc, 0, 75) . ' (' . $errorNo . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
    }

    // default the continue flag to 'N'
    $continue_flag = 'N';

    // determine whether the transaction should continue or fail based upon
    // the enrollment lookup results
    if (strcasecmp(MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ, 'No') == 0) {
      $continue_flag = 'Y';
    } else if (strcmp($errorNo, '0') == 0) {
      if (strcasecmp($enrolled, 'Y') == 0) {
        $continue_flag = 'Y';
      } else if (strcasecmp($enrolled, 'N') == 0) {
        $cardType = $this->determineCardType($this->cc_card_number);
        if (strcasecmp($cardType, 'VISA') == 0 || strcasecmp($cardType, 'JCB') == 0) {
          $continue_flag = 'Y';
        }
      }
    } else if ($errorNo == 1001) { // merchant has an account configuration problem to fix
      $errorText = CENTINEL_ERROR_CODE_1001 . ' - ' . CENTINEL_ERROR_CODE_1001_DESC;
      $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_1001_DESC . ' (' . CENTINEL_ERROR_CODE_1001 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
      $continue_flag = 'Y';
    }

    if (strcasecmp('Y', $continue_flag) == 0) {
      // For validation/security purposes, mark the session that the lookup result was acceptable.
      $_SESSION['3Dsecure_enroll_lookup_attempted'] = 'Y';
    } else {
      // For validation/security purposes, mark the session that the lookup result was not acceptable.
      unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
    }

    $result = array('continue_flag' => $continue_flag,
                    'enrolled' => $enrolled,
                    'transaction_id' => $parser->deserializedResponse['TransactionId'],
                    'error_no' => $errorNo,
                    'error_desc' => $errorDesc,
                    'acs_url' => $parser->deserializedResponse['ACSUrl'],
                    'spa_hidden_fields' => $parser->deserializedResponse['SPAHiddenFields'],
                    'payload' => $parser->deserializedResponse['Payload'],
                    'cc3d_card_number' => $parser->deserializedResponse['CardNumber'],
                    'cc3d_checkcode' => $parser->deserializedResponse['CardCode'],
                    'cc3d_exp_month' => $parser->deserializedResponse['CardExpMonth'],
                    'cc3d_exp_year' => $parser->deserializedResponse['CardExpYear'],
                    'EciFlag' => $parser->deserializedResponse['EciFlag'],
                    'cc3d_merchantdata' => $parser->deserializedResponse['MerchantData']);
    return $result;
  }
1143404
private function prepareDataBits()
    {
        $n              = $this->structureAppendN;
        $m              = $this->structureAppendM;
        $parity         = $this->structureAppendParity;
        $originalData   = $this->structureAppendOriginalData;

        $dataCounter   = 0;

        if ( $this->checkStructureAppend($n, $m) )
        {
            $dataValue[0]  = 3;
            $dataBits[0]   = 4;

            $dataValue[1]  = $m - 1;
            $dataBits[1]   = 4;

            $dataValue[2]  = $n - 1;
            $dataBits[2]   = 4;

            $originalDataLength = strlen($originalData);

            if ( $originalDataLength > 1 )
            {
                $parity = 0;

                $i      = 0;
                while ($i < $originalDataLength)
                {
                    $parity = ($parity ^ ord(substr($originalData, $i, 1)));
                    $i++;
                }
            }

            $dataValue[3]  = $parity;
            $dataBits[3]   = 8;

            $dataCounter   = 4;
        }

        $dataBits[$dataCounter] = 4;

        return $dataBits;
    }
84317
public static function hierarchicalAssocToKeyed($data)
    {
        $h2k = function(&$dest, $orig, $currentKey) use(&$h2k){
            if(is_array($orig) && (count($orig)>0)){
                foreach($orig as $key=>$value){
                    if(is_array($value)){
                        $h2k($dest, $value, ($currentKey ? $currentKey . '.' : '') . $key);
                    }else{
                        $dest[($currentKey ? $currentKey . '.' : '') . $key] = $value;
                    }
                }
            }
        };

        $result = array();
        $h2k($result, $data, '');

        return $result;
    }
196380
protected function resolveNestedRelations($data):array
    {
        if (is_null($data)) {
            return [];
        }

        $data = $data instanceof Model ? [$data] : $data;

        return collect($data)->flatMap(function ($model) {
            $relations = collect($model->getRelations());

            return $relations->keys()->merge($relations->flatMap(function ($relation, $key) {
                return collect($this->resolveNestedRelations($relation))->map(function ($nestedRelation) use ($key) {
                    return $key . '.' . $nestedRelation;
                });
            }));
        })->unique()->toArray();
    }
327202
function GetDetailedUsersArray()
  {
      $users_array = array();
      $result = $this->GetNextUserArray(TRUE);
      if (isset($result['user'])) {
          $users_array[$result['user']] = $result;
      }
      do {
          if ($result = $this->GetNextUserArray()) {
              if (isset($result['user'])) {
                  $users_array[$result['user']] = $result;
              }
          }
      } while (FALSE !== $result);
      return $users_array;
  }
126427
public function is_valid_lookup() {
		if ( strpos( strtolower( $this->lookup_class ), strtolower( $this->namespace ) ) !== false ) {
			if ( false !== $this->option( 'exclude' ) ) {
				foreach ( $this->option( 'exclude' ) as $namespace ) {
					if ( strpos( strtolower( $this->lookup_class ), strtolower( $namespace ) ) !== false ) {
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
371610
public function getDatasourcesAsArray()
    {

        // initialize the array
        $datasources = array();

        // prepare the array with the datasources
        foreach ($this->getDatasources() as $datasource) {
            $datasources[$datasource->getPrimaryKey()] = $datasource;
        }

        // return the array with the datasources
        return $datasources;
    }
104273
protected function pullOutNestedIncludedData(array $data)
    {
        $includedData = [];
        $linkedIds = [];

        foreach ($data as $value) {
            foreach ($value as $includeObject) {
                if (isset($includeObject['included'])) {
                    list($includedData, $linkedIds) = $this->serializeIncludedObjectsWithCacheKey($includeObject['included'], $linkedIds, $includedData);
                }
            }
        }

        return [$includedData, $linkedIds];
    }
515515
public static function getLookupValue($lookup, &$value, $use_private = false)
    {
        if (empty($lookup)) {
            return false;
        }

        $_parts = explode('.', $lookup);
        if (count($_parts) > 1) {
            $_section = array_shift($_parts);
            $_lookup = implode('.', $_parts);
            if (!empty($_section)) {
                switch ($_section) {
                    case 'session':
                        switch ($_lookup) {
                            case 'id':
                            case 'token':
                                $value = static::getSessionToken();

                                return true;

//                            case 'ticket':
//                                $value = static::_generateTicket();
//
//                                return true;
                        }
                        break;

                    case 'user':
                    case 'role':
                        // get fields here
                        if (!empty($_lookup)) {
                            $info = static::get($_section);
                            if (isset($info, $info[$_lookup])) {
                                $value = $info[$_lookup];

                                return true;
                            }
                        }
                        break;

                    case 'app':
                        switch ($_lookup) {
                            case 'id':
                                $value = static::get('app.id');;

                                return true;

                            case 'api_key':
                                $value = static::getApiKey();

                                return true;
                        }
                        break;

                    case 'df':
                        switch ($_lookup) {
                            case 'host_url':
                                $value = Curl::currentUrl(false, false);

                                return true;
                            case 'name':
                                $value = \Config::get('app.name');

                                return true;
                            case 'version':
                                $value = \Config::get('app.version');

                                return true;
                            case 'api_version':
                                $value = \Config::get('df.api_version');

                                return true;
                            case 'confirm_invite_url':
                                $value = url(\Config::get('df.confirm_invite_url'));

                                return true;
                            case 'confirm_register_url':
                                $value = url(\Config::get('df.confirm_register_url'));

                                return true;
                            case 'confirm_reset_url':
                                $value = url(\Config::get('df.confirm_reset_url'));

                                return true;
                        }
                        break;
                }
            }
        }

        if ($use_private) {
            $lookups = static::get('lookup_secret');
            if (array_key_exists($lookup, (array)$lookups)) {
                $value = $lookups[$lookup];

                return true;
            }
        }
        // non-private
        $lookups = static::get('lookup');
        if (array_key_exists($lookup, (array)$lookups)) {
            $value = $lookups[$lookup];

            return true;
        }

        return false;
    }
171266
public function lookup() {
        $r = mt_rand() / mt_getrandmax() * $this->_weightTotal;
        return $this->_values[$this->_binarySearch($r, $this->_lookup)];
    }
19861
public function extractKeys() {
    if (!$this->hasScalarKeys()) {
      throw new \DomainException('Cannot extract non-scalar keys from array lookup ' . $this);
    }
    return array_map(function(ScalarNode $key) { return $key->toValue(); }, $this->getKeys());
  }
1348670
def [](lookup)
      if lookup.is_a?(Integer)
        children.fetch(lookup)
      else
        found = find_all(lookup)
        case found.size
        when 1
          found.first
        when 0
          raise "No children of type #{lookup}"
        else
          raise "Ambiguous lookup #{lookup}, found #{found}."
        end
      end
    end
731534
private function multicallDecode($xml_data) {

        $data = array();

        try {

            $calls = $xml_data->params->param->value->children();

            $calls_array = $this->decodeArray($calls[0]);

            foreach ( $calls_array as $call ) {
                
                $data[] = (!isset($call['methodName']) || !isset($call['params'])) ? null : array($call['methodName'], $call['params']);

            }
            
        } catch (XmlrpcException $xe) {
            
            throw $xe;

        }
        
        return $data;

    }
311536
public function getRedirectData()
    {
        $data = $this->getData();
        $request = $this->getRequest()->getParameters();

        return [
            'PaReq'   => $data['additional']['secure3d']['retransmit']['PaReq'],
            'MD'      => $data['additional']['secure3d']['retransmit']['MD'],
            'TermUrl' => $request['returnUrl'],
        ];
    }
1130947
public function addConstructorLookup($lookup)
    {
        $endPoint = &$this->getEndPoint();
        if (!isset($this->endPoint['args'])) {
            $endPoint['args'] = [];
        }
        $endPoint['args'][] = ['type' => 'lookup', 'item' => $lookup];

        return $this;
    }
603863
protected function PayOne3dSecure_3dScheck()
    {
        $aResponse = array();
        $aResponse['success'] = false;

        $oGlobal = TGlobal::instance();
        $oBasket = TShopBasket::GetInstance();

        // load data from POST
        $aUserPaymentData = $this->GetUserPaymentData();

        // Save to session
        $_SESSION['PayOneResponse']['pseudocardpan'] = $aUserPaymentData['pseudocardpan'];
        $_SESSION['PayOneResponse']['truncatedcardpan'] = $aUserPaymentData['truncatedcardpan'];

        // create success URL
        $aSuccessCall = array('module_fnc' => array($oGlobal->GetExecutingModulePointer()->sModuleSpotName => 'PostProcessExternalPaymentHandlerHook'));

        $aExcludes = array_keys($aSuccessCall);
        $aExcludes[] = 'aShipping';
        $aExcludes[] = 'orderstepmethod';
        $aExcludes[] = 'aPayment';
        $aExcludes[] = 'module_fnc';

        $sSuccessURL = urldecode(str_replace('&amp;', '&', $this->getActivePageService()->getLinkToActivePageAbsolute($aSuccessCall, $aExcludes)));
        $sSuccessURL .= '&payrequest=3dsredirect';

        // Init 3D-Secure params
        $frequest = new financegateRequest();
        $fconnect = new financegateConnect();

        $frequest->setRequest('3dscheck');
        $frequest->setClearingType('cc');
        $frequest->setPortalId($this->GetConfigParameter('portalid'));
        $frequest->setKey($this->GetConfigParameter('key'));
        $frequest->setMId($this->GetConfigParameter('mid'));
        $frequest->setAId($this->GetConfigParameter('aid'));
        $frequest->setMode($this->GetConfigParameter('mode'));
        $request = $this->getCurrentRequest();
        $frequest->setIp(null === $request ? '' : $request->getClientIp());

        $frequest->setExitUrl($sSuccessURL);
        $frequest->setAmount($oBasket->dCostTotal * 100);
        $frequest->setCurrency($this->GetCurrency());
        $frequest->setLanguage($this->GetCurrentLanguageCode());

        $frequest->setPseudocardpan($aUserPaymentData['pseudocardpan']);

        $fconnect->setApiUrl($this->GetConfigParameter('serverApiUrlPayOne'));
        $fresponse = $fconnect->processByRequest($frequest);
        //if(_ES_DEBUG) var_dump($fresponse);

        $sStatus = $fresponse->getStatus();

        $aResponse['success'] = true;
        $aResponse['status'] = $sStatus;

        if ('ENROLLED' == $sStatus) {
            $this->ExecuteExternalPayOneCall($fresponse); // REDIRECT TO EXTERNAL SECURE-PIN-URL!
        } else {
            if ('VALID' == $sStatus) {
                // do nothing
            } else {
                $aResponse['success'] = false;
                $aResponse['status'] = $sStatus;
                $aResponse['errormessage'] = $fresponse->getErrorMessage();
                $aResponse['errortext'] = $fresponse->getCustomerMessage();
                //if(_ES_DEBUG) print_form($_REQUEST,$info);
            }
        }

        return $aResponse;
    }
216752
public static function keys($data = false) {

        if ($data && Validate::isArray($data)) {

            return array_keys($data);
        } else if ($data && Validate::isObject($data)) {

            return get_object_vars($data);
        }

        return false;
    }