Set the state field depending on what PayPal requires for that country.
168438
function setStateAndCountry(&$info) {
    global $db, $messageStack;
    switch ($info['country']['iso_code_2']) {
      case 'AU':
      case 'US':
      case 'CA':
      // Paypal only accepts two character state/province codes for some countries.
      if (strlen($info['state']) > 2) {
        $sql = "SELECT zone_code FROM " . TABLE_ZONES . " WHERE zone_name = :zoneName";
        $sql = $db->bindVars($sql, ':zoneName', $info['state'], 'string');
        $state = $db->Execute($sql);
        if (!$state->EOF) {
          $info['state'] = $state->fields['zone_code'];
        } else {
          $messageStack->add_session('header', MODULE_PAYMENT_PAYPALDP_TEXT_STATE_ERROR, 'error');
        }
      }
      break;
      case 'AT':
      case 'BE':
      case 'FR':
      case 'DE':
      case 'CH':
      $info['state'] = '';
      break;
      case 'GB':
      break;
      default:
      $info['state'] = '';
    }
  }
1289099
protected function validateEditCountryState()
    {
        $this->setSubmitted('state');
        $this->setSubmittedBool('status');
        $this->setSubmitted('update', $this->data_state);
        $this->setSubmitted('country', $this->data_country['code']);

        $this->validateComponent('country_state');

        return !$this->hasErrors();
    }
1217906
public static function onActivate()
    {
        // add additional field to order
        self::addOrderTable();

        // create orders payments table
        self::addOrderPaymentsTable();

        // payment comments
        self::addOrderPaymentsCommentsTable();

        self::addMissingFieldsOnUpdate();
        self::ensureCorrectFieldsEncodingOnUpdate();

        // adding record to oxPayment table
        self::addPaymentMethod();

        // enabling PayPal payment method
        self::enablePaymentMethod();

        // enable PayPal RDF
        self::enablePayPalRDFA();
    }
483531
public function addcountry()
    {
        $sOxId = $this->getEditObjectId();
        $aChosenCntr = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("allcountries");
        if (isset($sOxId) && $sOxId != "-1" && is_array($aChosenCntr)) {
            foreach ($aChosenCntr as $sChosenCntr) {
                $oObject2Payment = oxNew(\OxidEsales\Eshop\Core\Model\BaseModel::class);
                $oObject2Payment->init('oxobject2payment');
                $oObject2Payment->oxobject2payment__oxpaymentid = new \OxidEsales\Eshop\Core\Field($sOxId);
                $oObject2Payment->oxobject2payment__oxobjectid = new \OxidEsales\Eshop\Core\Field($sChosenCntr);
                $oObject2Payment->oxobject2payment__oxtype = new \OxidEsales\Eshop\Core\Field("oxcountry");
                $oObject2Payment->save();
            }
        }
    }
780859
def post_ext_init(state):
    """"""
    app = state.app

    app.config.setdefault(
        'OAUTHCLIENT_SITENAME',
        app.config.get('THEME_SITENAME', 'Invenio'))
    app.config.setdefault(
        'OAUTHCLIENT_BASE_TEMPLATE',
        app.config.get('BASE_TEMPLATE',
                       'invenio_oauthclient/base.html'))
    app.config.setdefault(
        'OAUTHCLIENT_COVER_TEMPLATE',
        app.config.get('COVER_TEMPLATE',
                       'invenio_oauthclient/base_cover.html'))
    app.config.setdefault(
        'OAUTHCLIENT_SETTINGS_TEMPLATE',
        app.config.get('SETTINGS_TEMPLATE',
                       'invenio_oauthclient/settings/base.html'))
534528
public void setCountry(final Country COUNTRY) {
        if (null == country) {
            _country = COUNTRY;
            fireTileEvent(RECALC_EVENT);
        } else {
            country.set(COUNTRY);
        }
    }
1177547
def init(self, request, paypal_request, paypal_response):
        """"""
        if request is not None:
            from paypal.pro.helpers import strip_ip_port
            self.ipaddress = strip_ip_port(request.META.get('REMOTE_ADDR', ''))
            if (hasattr(request, "user") and request.user.is_authenticated):
                self.user = request.user
        else:
            self.ipaddress = ''

        # No storing credit card info.
        query_data = dict((k, v) for k, v in paypal_request.items() if k not in self.RESTRICTED_FIELDS)
        self.query = urlencode(query_data)
        self.response = urlencode(paypal_response)

        # Was there a flag on the play?
        ack = paypal_response.get('ack', False)
        if ack != "Success":
            if ack == "SuccessWithWarning":
                warn_untested()
                self.flag_info = paypal_response.get('l_longmessage0', '')
            else:
                self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', ''))
1216411
protected function addCountry()
    {
        if (!$this->isError() && !$this->country->add($this->getSubmitted())) {
            $this->errorAndExit($this->text('Unexpected result'));
        }
    }
1181249
public function setExpressCheckout()
    {
        $session = $this->getSession();
        $session->setVariable("oepaypal", "1");
        try {
            $builder = oxNew(\OxidEsales\PayPalModule\Model\PayPalRequest\SetExpressCheckoutRequestBuilder::class);

            $basket = $session->getBasket();
            $user = $this->getUser();

            $basket->setPayment("oxidpaypal");
            $basket->onUpdate();
            $basket->calculateBasket(true);

            $validator = oxNew(\OxidEsales\PayPalModule\Model\PaymentValidator::class);
            $validator->setUser($user);
            $validator->setConfig(\OxidEsales\Eshop\Core\Registry::getConfig());
            $validator->setPrice($basket->getPrice()->getPrice());

            if (!$validator->isPaymentValid()) {
                /**
                 * @var \OxidEsales\PayPalModule\Core\Exception\PayPalException $exception
                 */
                $exception = oxNew(\OxidEsales\PayPalModule\Core\Exception\PayPalException::class);
                $exception->setMessage(\OxidEsales\Eshop\Core\Registry::getLang()->translateString("OEPAYPAL_PAYMENT_NOT_VALID"));
                throw $exception;
            }

            $builder->setPayPalConfig($this->getPayPalConfig());
            $builder->setBasket($basket);
            $builder->setUser($this->getUser());
            $builder->setReturnUrl($this->getReturnUrl());
            $builder->setCancelUrl($this->getCancelUrl());
            $showCartInPayPal = $this->getRequest()->getRequestParameter("displayCartInPayPal");
            $showCartInPayPal = $showCartInPayPal && !$basket->isFractionQuantityItemsPresent();
            $builder->setShowCartInPayPal($showCartInPayPal);
            $builder->setTransactionMode($this->getTransactionMode($basket));

            $request = $builder->buildStandardCheckoutRequest();

            $payPalService = $this->getPayPalCheckoutService();
            $result = $payPalService->setExpressCheckout($request);
        } catch (\OxidEsales\Eshop\Core\Exception\StandardException $excp) {
            // error - unable to set order info - display error message
            $this->getUtilsView()->addErrorToDisplay($excp);

            // return to basket view
            return "basket";
        }

        // saving PayPal token into session
        $this->getSession()->setVariable("oepaypal-token", $result->getToken());

        // extracting token and building redirect url
        $url = $this->getPayPalConfig()->getPayPalCommunicationUrl($result->getToken(), $this->userAction);

        // redirecting to PayPal's login/registration page
        $this->getUtils()->redirect($url, false);
    }
140863
protected function addCountry()
    {
        $this->controlAccess('country_add');

        if ($this->country->add($this->getSubmitted())) {
            $this->redirect('admin/settings/country', $this->text('Country has been added'), 'success');
        }

        $this->redirect('', $this->text('Country has not been added'), 'warning');
    }
1349606
protected function setRequiredFields()
    {
        $requiredFields = [
            'transaction_id',
            'amount',
            'currency',
            'customer_email',
            'holder_name',
            'billing_country'
        ];

        $this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);

        $requiredFieldValues = [
            'billing_country' => [
                'АЕ', 'AT', 'AU', 'BE', 'BG', 'CA', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES',
                'FI', 'FR', 'GB', 'GF', 'GP', 'GR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV',
                'MC', 'MQ', 'MT', 'MX', 'NL', 'PL', 'PT', 'RE', 'SE', 'SI', 'SK'
            ],
            'currency'        => \Genesis\Utils\Currency::getList()
        ];

        $this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);

        $this->setRequiredFieldsConditional();
    }
535241
function paypaldp() {
    include_once(zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/payment/', 'paypaldp.php', 'false'));
    global $order;
    $this->code = 'paypaldp';
    $this->codeTitle = MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_WPP;
    $this->codeVersion = '1.5.1';
    $this->enableDirectPayment = true;
    $this->enabled = (MODULE_PAYMENT_PAYPALDP_STATUS == 'True');
    // Set the title & description text based on the mode we're in
    if (IS_ADMIN_FLAG === true) {
      $this->description = sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_DESCRIPTION, ' (rev' . $this->codeVersion . ')');
      $country = (defined('MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY')) ? MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY : STORE_COUNTRY;
      $this->title = $country == '223' || $country == 'USA' ? MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_WPP : MODULE_PAYMENT_PAYPALDP_TEXT_ADMIN_TITLE_NONUSA;
      $this->title .= (defined('MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY') ? ' (' . MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY . ')' : '');
      if ($this->enabled) {
        if ( ((MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'US' || MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'Canada') && (MODULE_PAYMENT_PAYPALWPP_APISIGNATURE == '' || MODULE_PAYMENT_PAYPALWPP_APIUSERNAME == '' || MODULE_PAYMENT_PAYPALWPP_APIPASSWORD == ''))
              || (!defined('MODULE_PAYMENT_PAYPALWPP_STATUS') || MODULE_PAYMENT_PAYPALWPP_STATUS != 'True')
          ) $this->title .= '<span class="alert"><strong> NOT CONFIGURED YET</strong></span>';
        if (MODULE_PAYMENT_PAYPALDP_SERVER =='sandbox') $this->title .= '<strong><span class="alert"> (sandbox active)</span></strong>';
        if (MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email') $this->title .= '<strong> (Debug)</strong>';
        if (!function_exists('curl_init')) $this->title .= '<strong><span class="alert"> CURL NOT FOUND. Cannot Use.</span></strong>';
      }
    } else {
      $this->description = MODULE_PAYMENT_PAYPALDP_TEXT_DESCRIPTION;
      $this->title = MODULE_PAYMENT_PAYPALDP_TEXT_TITLE; //cc
    }

    if ((!defined('PAYPAL_OVERRIDE_CURL_WARNING') || (defined('PAYPAL_OVERRIDE_CURL_WARNING') && PAYPAL_OVERRIDE_CURL_WARNING != 'True')) && !function_exists('curl_init')) $this->enabled = false;

    $this->enableDebugging = (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email');
    $this->emailAlerts = (MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALDP_DEBUGGING =='Log and Email' || MODULE_PAYMENT_PAYPALDP_DEBUGGING == 'Alerts Only');
    $this->sort_order = MODULE_PAYMENT_PAYPALDP_SORT_ORDER;

    $this->buttonSource = (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') ? 'ZenCart-DP_uk' : 'ZenCart-DP_us';

    $this->order_pending_status = MODULE_PAYMENT_PAYPALDP_ORDER_PENDING_STATUS_ID;
    if ((int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;
    }
//    $this->new_acct_notify = MODULE_PAYMENT_PAYPALDP_NEW_ACCT_NOTIFY;
    $this->zone = (int)MODULE_PAYMENT_PAYPALDP_ZONE;
    if (is_object($order)) $this->update_status();

    if (PROJECT_VERSION_MAJOR != '1' && substr(PROJECT_VERSION_MINOR, 0, 3) != '5.0') $this->enabled = false;

    // offer credit card choices for pull-down menu -- only needed for UK version
    $this->cards = array();
    if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
      if (CC_ENABLED_VISA=='1')    $this->cards[] = array('id' => 'Visa', 'text' => 'Visa');
      if (CC_ENABLED_MC=='1')      $this->cards[] = array('id' => 'MasterCard', 'text' => 'MasterCard');
      if (CC_ENABLED_MAESTRO=='1') $this->cards[] = array('id' => 'Maestro', 'text' => 'Maestro');
      if (CC_ENABLED_SWITCH=='1')  $this->cards[] = array('id' => 'Switch', 'text' => 'Switch');
      if (CC_ENABLED_SOLO=='1')    $this->cards[] = array('id' => 'Solo', 'text' => 'Solo');
    }

    // debug setup
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_CATALOG . $this->_logDir;
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_SQL_CACHE;
    // Regular mode:
    if ($this->enableDebugging) $this->_logLevel = 2;
    // DEV MODE:
    if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $this->_logLevel = 3;

    if (IS_ADMIN_FLAG === true) $this->tableCheckup();

  }
270372
def set_state(self, entity_id, new_state, **kwargs):
        ""
        return remote.set_state(self.api, new_state, **kwargs)
411971
function ec_step2_finish($paypal_ec_payer_info, $new_acct_notify) {
    global $db, $order;

    // register the payer_info in the session
    $_SESSION['paypal_ec_payer_info'] = $paypal_ec_payer_info;

    // debug
    $this->zcLog('ec_step2_finish - 1', 'START: paypal_ec_payer_info= ' . print_r($_SESSION['paypal_ec_payer_info'], true));

    /**
     * Building customer zone/address from returned data
     */
    // set some defaults, which will be updated later:
    $country_id = '223';
    $address_format_id = 2;
    $state_id = 0;
    $acct_exists = false;
    // store default address id for later use/reference
    $original_default_address_id = $_SESSION['customer_default_address_id'];

    // Get the customer's country ID based on name or ISO code
    $sql = "SELECT countries_id, address_format_id, countries_iso_code_2, countries_iso_code_3
                FROM " . TABLE_COUNTRIES . "
                WHERE countries_iso_code_2 = :countryId
                   OR countries_name = :countryId
                LIMIT 1";
    $sql1 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_name'], 'string');
    $country1 = $db->Execute($sql1);
    $sql2 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_code'], 'string');
    $country2 = $db->Execute($sql2);

    // see if we found a record, if yes, then use it instead of default American format
    if ($country1->RecordCount() > 0) {
      $country_id = $country1->fields['countries_id'];
      if (!isset($paypal_ec_payer_info['ship_country_code']) || $paypal_ec_payer_info['ship_country_code'] == '') $paypal_ec_payer_info['ship_country_code'] = $country1->fields['countries_iso_code_2'];
      $country_code3 = $country1->fields['countries_iso_code_3'];
      $address_format_id = (int)$country1->fields['address_format_id'];
    } elseif ($country2->RecordCount() > 0) {
      // if didn't find it based on name, check using ISO code (ie: in case of no-shipping-address required/supplied)
      $country_id = $country2->fields['countries_id'];
      $country_code3 = $country2->fields['countries_iso_code_3'];
      $address_format_id = (int)$country2->fields['address_format_id'];
    } else {
      // if defaulting to US, make sure US is valid
      $sql = "SELECT countries_id FROM " . TABLE_COUNTRIES . " WHERE countries_id = :countryId: LIMIT 1";
      $sql = $db->bindVars($sql, ':countryId:', $country_id, 'integer');
      $result = $db->Execute($sql);
      if ($result->EOF) {
        $this->notify('NOTIFY_PAYPAL_CUSTOMER_ATTEMPT_TO_USE_INVALID_COUNTRY_CODE');
        $this->zcLog('ec-step2-finish - 1b', 'Cannot use address due to country lookup/match failure.');
        $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
      }
    }
    // Need to determine zone, based on zone name first, and then zone code if name fails check. Otherwise uses 0.
    $sql = "SELECT zone_id
                  FROM " . TABLE_ZONES . "
                  WHERE zone_country_id = :zCountry
                  AND zone_code = :zoneCode
                   OR zone_name = :zoneCode
                  LIMIT 1";
    $sql = $db->bindVars($sql, ':zCountry', $country_id, 'integer');
    $sql = $db->bindVars($sql, ':zoneCode', $paypal_ec_payer_info['ship_state'], 'string');
    $states = $db->Execute($sql);
    if ($states->RecordCount() > 0) {
      $state_id = $states->fields['zone_id'];
    }
    /**
     * Using the supplied data from PayPal, set the data into the order record
     */
    // customer
    $order->customer['name']            = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
    $order->customer['company']         = $paypal_ec_payer_info['payer_business'];
    $order->customer['street_address']  = $paypal_ec_payer_info['ship_street_1'];
    $order->customer['suburb']          = $paypal_ec_payer_info['ship_street_2'];
    $order->customer['city']            = $paypal_ec_payer_info['ship_city'];
    $order->customer['postcode']        = $paypal_ec_payer_info['ship_postal_code'];
    $order->customer['state']           = $paypal_ec_payer_info['ship_state'];
    $order->customer['country']         = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
    $order->customer['format_id']       = $address_format_id;
    $order->customer['email_address']   = $paypal_ec_payer_info['payer_email'];
    $order->customer['telephone']       = $paypal_ec_payer_info['ship_phone'];
    $order->customer['zone_id']         = $state_id;

    // billing
    $order->billing['name']             = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
    $order->billing['company']          = $paypal_ec_payer_info['payer_business'];
    $order->billing['street_address']   = $paypal_ec_payer_info['ship_street_1'];
    $order->billing['suburb']           = $paypal_ec_payer_info['ship_street_2'];
    $order->billing['city']             = $paypal_ec_payer_info['ship_city'];
    $order->billing['postcode']         = $paypal_ec_payer_info['ship_postal_code'];
    $order->billing['state']            = $paypal_ec_payer_info['ship_state'];
    $order->billing['country']          = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
    $order->billing['format_id']        = $address_format_id;
    $order->billing['zone_id']          = $state_id;

    // delivery
    if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
      $order->delivery['name']          = $paypal_ec_payer_info['ship_name'];
      $order->delivery['company']       = trim($paypal_ec_payer_info['ship_name'] . ' ' . $paypal_ec_payer_info['payer_business']);
      $order->delivery['street_address']= $paypal_ec_payer_info['ship_street_1'];
      $order->delivery['suburb']        = $paypal_ec_payer_info['ship_street_2'];
      $order->delivery['city']          = $paypal_ec_payer_info['ship_city'];
      $order->delivery['postcode']      = $paypal_ec_payer_info['ship_postal_code'];
      $order->delivery['state']         = $paypal_ec_payer_info['ship_state'];
      $order->delivery['country']       = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
      $order->delivery['country_id']    = $country_id;
      $order->delivery['format_id']     = $address_format_id;
      $order->delivery['zone_id']       = $state_id;
    }

    // process submitted customer notes
    if (isset($paypal_ec_payer_info['order_comment']) && $paypal_ec_payer_info['order_comment'] != '') {
      $_SESSION['comments'] = (isset($_SESSION['comments']) && $_SESSION['comments'] != '' ? $_SESSION['comments'] . "\n" : '') . $paypal_ec_payer_info['order_comment'];
      $order->info['comments'] = $_SESSION['comments'];
    }
    // debug
    $this->zcLog('ec_step2_finish - 2', 'country_id = ' . $country_id . ' ' . $paypal_ec_payer_info['ship_country_name'] . ' ' . $paypal_ec_payer_info['ship_country_code'] ."\naddress_format_id = " . $address_format_id . "\nstate_id = " . $state_id . ' (original state tested: ' . $paypal_ec_payer_info['ship_state'] . ')' . "\ncountry1->fields['countries_id'] = " . $country1->fields['countries_id'] . "\ncountry2->fields['countries_id'] = " . $country2->fields['countries_id'] . "\n" . '$order->customer = ' . print_r($order->customer, true));

    // check to see whether PayPal should still be offered to this customer, based on the zone of their address:
    $this->update_status();
    if (!$this->enabled) {
      $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
    }

    // see if the user is logged in
    if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
      // They're logged in, so forward them straight to checkout stages, depending on address needs etc
      $order->customer['id'] = $_SESSION['customer_id'];

      // set the session value for express checkout temp
      $_SESSION['paypal_ec_temp'] = false;

      // if no address required for shipping, leave shipping portion alone
      if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE' && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
        // set the session info for the sendto
        $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];

        // This is the address matching section
        // try to match it first
        // note: this is by no means 100%
        $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));

        // no match, so add the record
        if (!$address_book_id) {
          $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
        }
        // if couldn't add the record, perhaps due to removed country, or some other error, abort with message
        if (!$address_book_id) {
          $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
        }

        // set the address for use
        $_SESSION['sendto'] = $address_book_id;
      }
      // set the users billto information (default address)
      if (!isset($_SESSION['billto'])) {
        $_SESSION['billto'] = $_SESSION['customer_default_address_id'];
      }

      // debug
      $this->zcLog('ec_step2_finish - 3', 'Exiting ec_step2_finish logged-in mode.' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . $original_default_address_id);


      // select a shipping method, based on cheapest available option
      if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();

      // send the user on
      if ($_SESSION['paypal_ec_markflow'] == 1) {
        $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
      } else {
        $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
      }
    } else {
      // They're not logged in.  Create an account if necessary, and then log them in.
      // First, see if they're an existing customer, and log them in automatically

      // If Paypal didn't supply us an email address, something went wrong
      if (trim($paypal_ec_payer_info['payer_email']) == '') $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE, true);

      // attempt to obtain the user information using the payer_email from the info returned from PayPal, via email address
      $sql = "SELECT customers_id, customers_firstname, customers_lastname, customers_paypal_payerid, customers_paypal_ec
              FROM " . TABLE_CUSTOMERS . "
              WHERE customers_email_address = :emailAddress ";
      $sql = $db->bindVars($sql, ':emailAddress', $paypal_ec_payer_info['payer_email'], 'string');
      $check_customer = $db->Execute($sql);

      // debug
      $this->zcLog('ec_step2_finish - 4', 'Not logged in. Looking for account.' . "\n" . (int)$check_customer->RecordCount() . ' matching customer records found.');

      if (!$check_customer->EOF) {
        $acct_exists = true;

        // see if this was only a temp account -- if so, remove it
        if ($check_customer->fields['customers_paypal_ec'] == '1') {
          // Delete the existing temporary account
          $this->ec_delete_user($check_customer->fields['customers_id']);
          $acct_exists = false;

          // debug
          $this->zcLog('ec_step2_finish - 5', 'Found temporary account - deleting it.');

        }
      }

      // Create an account, if the account does not exist
      if (!$acct_exists) {

        // debug
        $this->zcLog('ec_step2_finish - 6', 'No ZC account found for this customer. Creating new account.' . "\n" . '$this->new_acct_notify =' . $this->new_acct_notify);

        // Generate a random 8-char password
        $password = zen_create_random_value(8);

        $sql_data_array = array();

        // set the customer information in the array for the table insertion
        $sql_data_array = array(
            'customers_firstname'           => $paypal_ec_payer_info['payer_firstname'],
            'customers_lastname'            => $paypal_ec_payer_info['payer_lastname'],
            'customers_email_address'       => $paypal_ec_payer_info['payer_email'],
            'customers_email_format'        => (ACCOUNT_EMAIL_PREFERENCE == '1' ? 'HTML' : 'TEXT'),
            'customers_telephone'           => $paypal_ec_payer_info['ship_phone'],
            'customers_fax'                 => '',
            'customers_gender'              => $paypal_ec_payer_info['payer_gender'],
            'customers_newsletter'          => '0',
            'customers_password'            => zen_encrypt_password($password),
            'customers_paypal_payerid'      => $_SESSION['paypal_ec_payer_id']);

        // insert the data
        $result = zen_db_perform(TABLE_CUSTOMERS, $sql_data_array);

        // grab the customer_id (last insert id)
        $customer_id = $db->Insert_ID();

        // set the Guest customer ID -- for PWA purposes
        $_SESSION['customer_guest_id'] = $customer_id;

        // set the customer address information in the array for the table insertion
        $sql_data_array = array(
            'customers_id'              => $customer_id,
            'entry_gender'              => $paypal_ec_payer_info['payer_gender'],
            'entry_firstname'           => $paypal_ec_payer_info['payer_firstname'],
            'entry_lastname'            => $paypal_ec_payer_info['payer_lastname'],
            'entry_street_address'      => $paypal_ec_payer_info['ship_street_1'],
            'entry_suburb'              => $paypal_ec_payer_info['ship_street_2'],
            'entry_city'                => $paypal_ec_payer_info['ship_city'],
            'entry_zone_id'             => $state_id,
            'entry_postcode'            => $paypal_ec_payer_info['ship_postal_code'],
            'entry_country_id'          => $country_id);
        if (isset($paypal_ec_payer_info['ship_name']) && $paypal_ec_payer_info['ship_name'] != ''  && $paypal_ec_payer_info['ship_name'] != $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname']) {
          $sql_data_array['entry_company'] = $paypal_ec_payer_info['ship_name'];
        }
        if ($state_id > 0) {
          $sql_data_array['entry_zone_id'] = $state_id;
          $sql_data_array['entry_state'] = '';
        } else {
          $sql_data_array['entry_zone_id'] = 0;
          $sql_data_array['entry_state'] = $paypal_ec_payer_info['ship_state'];
        }

        // insert the data
        zen_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

        // grab the address_id (last insert id)
        $address_id = $db->Insert_ID();

        // set the address id lookup for the customer
        $sql = "UPDATE " . TABLE_CUSTOMERS . "
                SET customers_default_address_id = :addrID
                WHERE customers_id = :custID";
        $sql = $db->bindVars($sql, ':addrID', $address_id, 'integer');
        $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
        $db->Execute($sql);

        // insert the new customer_id into the customers info table for consistency
        $sql = "INSERT INTO " . TABLE_CUSTOMERS_INFO . "
                       (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_date_of_last_logon)
                VALUES (:custID, 1, now(), now())";
        $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
        $db->Execute($sql);

        // send Welcome Email if appropriate
        if ($this->new_acct_notify == 'Yes') {
          // require the language file
          global $language_page_directory, $template_dir;
          if (!isset($language_page_directory)) $language_page_directory = DIR_WS_LANGUAGES . $_SESSION['language'] . '/';
          if (file_exists($language_page_directory . $template_dir . '/create_account.php')) {
            $template_dir_select = $template_dir . '/';
          } else {
            $template_dir_select = '';
          }
          require($language_page_directory . $template_dir_select . '/create_account.php');

          // set the mail text
          $email_text = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) . EMAIL_WELCOME . "\n\n" . EMAIL_TEXT;
          $email_text .= "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n";
          $email_text .= EMAIL_CONTACT;
          // include create-account-specific disclaimer
          $email_text .= "\n\n" . sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, STORE_OWNER_EMAIL_ADDRESS). "\n\n";
          $email_html = array();
          $email_html['EMAIL_GREETING']      = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) ;
          $email_html['EMAIL_WELCOME']       = EMAIL_WELCOME;
          $email_html['EMAIL_MESSAGE_HTML']  = nl2br(EMAIL_TEXT . "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n");
          $email_html['EMAIL_CONTACT_OWNER'] = EMAIL_CONTACT;
          $email_html['EMAIL_CLOSURE']       = nl2br(EMAIL_GV_CLOSURE);
          $email_html['EMAIL_DISCLAIMER']    = sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, '<a href="mailto:' . STORE_OWNER_EMAIL_ADDRESS . '">'. STORE_OWNER_EMAIL_ADDRESS .' </a>');

          // send the mail
          if (trim(EMAIL_SUBJECT) != 'n/a') zen_mail($paypal_ec_payer_info['payer_firstname'] . " " . $paypal_ec_payer_info['payer_lastname'], $paypal_ec_payer_info['payer_email'], EMAIL_SUBJECT, $email_text, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $email_html, 'welcome');

          // set the express checkout temp -- false means the account is no longer "only" for EC ... it'll be permanent
          $_SESSION['paypal_ec_temp'] = false;
        } else {
          // Make it a temporary account that'll be deleted once they've checked out
          $sql = "UPDATE " . TABLE_CUSTOMERS . "
                  SET customers_paypal_ec = 1
                  WHERE customers_id = :custID ";
          $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
          $db->Execute($sql);

          // set the boolean ec temp value since we created account strictly for EC purposes
          $_SESSION['paypal_ec_temp'] = true;
        }

        // hook notifier class vis a vis account-creation
        $this->notify('NOTIFY_LOGIN_SUCCESS_VIA_CREATE_ACCOUNT');

      } else {
        // set the boolean ec temp value for the account to false, since we didn't have to create one
        $_SESSION['paypal_ec_temp'] = false;
      }

      // log the user in with the email sent back from paypal response
      $this->user_login($_SESSION['paypal_ec_payer_info']['payer_email'], false);

      // debug
      $this->zcLog('ec_step2_finish - 7', 'Auto-Logged customer in. (' . $_SESSION['paypal_ec_payer_info']['payer_email'] . ') (' . $_SESSION['customer_id'] . ')' . "\n" . '$_SESSION[paypal_ec_temp]=' . $_SESSION['paypal_ec_temp']);


      // This is the address matching section
      // try to match it first
      // note: this is by no means 100%
      $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));
      // no match add the record
      if (!$address_book_id) {
        $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
        if (!$address_book_id) {
          $address_book_id = $_SESSION['customer_default_address_id'];
        }
      }
      // if couldn't add the record, perhaps due to removed country, or some other error, abort with message
      if ($address_book_id == FALSE) {
        $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
      }

      // set the sendto to the address
      $_SESSION['sendto'] = $address_book_id;
      // set billto in the session
      $_SESSION['billto'] = $_SESSION['customer_default_address_id'];

      // select a shipping method, based on cheapest available option
      if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();

      // debug
      $this->zcLog('ec_step2_finish - 8', 'Exiting via terminateEC (from originally-not-logged-in mode).' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . (int)$original_default_address_id . "\nprepared data: " . print_r($order->customer, true));

      // send the user on
      if ($_SESSION['paypal_ec_markflow'] == 1) {
        $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
      } else {
        $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
      }
    }
  }
524970
function in_special_checkout() {
    if ((defined('MODULE_PAYMENT_PAYPALWPP_STATUS') && MODULE_PAYMENT_PAYPALWPP_STATUS == 'True') &&
             !empty($_SESSION['paypal_ec_token']) &&
             !empty($_SESSION['paypal_ec_payer_id']) &&
             !empty($_SESSION['paypal_ec_payer_info'])) {
      $this->flagDisablePaymentAddressChange = true;
      return true;
    }
  }
929193
def set_state(self, state):
        
        _field = self.binary_state_name()
        values = {"desired_state": {_field: state}}
        response = self.api_interface.local_set_state(self, values, type_override="binary_switche")
        self._update_state_from_response(response)
386493
def country_code_select(priority_countries, options)
			selected = object.send(@method_name)

			countries = ""
			if priority_countries
				countries += options_for_select(priority_countries, selected)
				countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
      elsif options[:include_blank]
        countries += "<option value=\"\">" + options[:include_blank] + "</options>\n"
				countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
			end

			countries = countries + options_for_select(COUNTRIES, selected)
      content_tag(:select, countries, options.merge(id: "#{@object_name}_#{@method_name}", :name => "#{@object_name}[#{@method_name}]"), false)
		end