Example #1
0
 public function install()
 {
     if (!parent::install() || !$this->installExternalCarrier($this->_config) || !Configuration::updateValue('EXTERNAL_CARRIER_OVERCOST', 5) || !$this->registerHook('updateCarrier') || !$this->registerHook('extraCarrier') || !$this->registerHook('newOrder') || !$this->registerHook('processCarrier') || !$this->registerHook('orderDetailDisplayed') || !$this->registerHook('updateOrderStatus') || !Configuration::updateValue('KIALASMALL_VERSION', $this->version) || !Configuration::updateValue('KIALASMALL_SECURITY_TOKEN', Tools::passwdGen(30)) || !Configuration::updateValue('KIALASMALL_WS_URL', $this->ws_url) || !Configuration::updateValue('KIALASMALL_SEARCH_BY', 'order')) {
         return false;
     }
     // Install SQL
     include dirname(__FILE__) . '/sql-install.php';
     foreach ($sql as $s) {
         if (!Db::getInstance()->Execute($s)) {
             return false;
         }
     }
     // Create country settings
     foreach ($this->countries as $iso_code) {
         $id_country = Country::getByIso($iso_code);
         if ($id_country) {
             $kiala_country = new SmKialaCountry();
             $kiala_country->id_country = $id_country;
             $kiala_country->preparation_delay = $this->default_preparation_delay;
             $kiala_country->active = 0;
             // Is this the merchant home country?
             if ($id_country == Country::getByIso('ES')) {
                 $kiala_country->pickup_country = 1;
                 $kiala_country->dspid = '34600160';
             }
             $kiala_country->save();
         }
     }
     return true;
 }
 public function postProcess()
 {
     if (isset($_GET['delete' . $this->table]) || Tools::getValue('submitDel' . $this->table)) {
         $this->_errors[] = Tools::displayError('You cannot delete a country. If you do not want it available for customers, please disable it.');
     } elseif (Tools::getValue('submitAdd' . $this->table)) {
         if (!Tools::getValue('id_' . $this->table)) {
             if (Validate::isLanguageIsoCode(Tools::getValue('iso_code')) && Country::getByIso(Tools::getValue('iso_code'))) {
                 $this->_errors[] = Tools::displayError('This ISO code already exists, you cannot create two country with the same ISO code');
             }
         } else {
             if (Validate::isLanguageIsoCode(Tools::getValue('iso_code'))) {
                 $id_country = Country::getByIso(Tools::getValue('iso_code'));
                 if (!is_null($id_country) && $id_country != Tools::getValue('id_' . $this->table)) {
                     $this->_errors[] = Tools::displayError('This ISO code already exists, you cannot create two country with the same ISO code');
                 }
             }
         }
         if (Tools::isSubmit('standardization')) {
             Configuration::updateValue('PS_TAASC', (bool) Tools::getValue('standardization', false));
         }
         if (isset($this->_errors) && count($this->_errors)) {
             return false;
         }
     }
     return parent::postProcess();
 }
Example #3
0
/**
 * Set customer address (when not logged in)
 * Used to create user address with PayPal account information
 */
function setCustomerAddress($ppec, $customer, $id = null)
{
    $address = new Address($id);
    $address->id_country = Country::getByIso($ppec->result['COUNTRYCODE']);
    $address->alias = 'Paypal_Address';
    $address->lastname = $customer->lastname;
    $address->firstname = $customer->firstname;
    $address->address1 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET'];
    if (isset($ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET2'])) {
        $address->address2 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET2'];
    }
    $address->city = $ppec->result['PAYMENTREQUEST_0_SHIPTOCITY'];
    $address->id_state = (int) State::getIdByIso($ppec->result['SHIPTOSTATE'], $address->id_country);
    $address->postcode = $ppec->result['SHIPTOZIP'];
    $address->id_customer = $customer->id;
    return $address;
}
    /**
     * Get SmKialaCountry object by id_country
     *
     * @param int $id_country
     * @return boolean|SmKialaCountry fetched object or false
     */
    public static function getByIdCountry($id_country)
    {
        // Luxemburg is grouped with Belgium by Kiala
        if (Country::getIsoById($id_country) == 'LU') {
            $id_country = Country::getByIso('BE');
        }
        $result = Db::getInstance()->getRow('
			SELECT `id_sm_kiala_country`, `id_country`, `dspid`, `sender_id`, `password`, `preparation_delay`, `active`
			FROM `' . _DB_PREFIX_ . 'sm_kiala_country`
			WHERE `id_country` = ' . (int) $id_country);
        if (!$result) {
            return false;
        }
        $kiala_country = new self();
        $kiala_country->setData($result);
        return $kiala_country;
    }
 public function preProcess()
 {
     parent::preProcess();
     if (self::$cookie->isLogged() and !Tools::isSubmit('ajax')) {
         Tools::redirect('my-account.php');
     }
     if (Tools::getValue('create_account')) {
         $create_account = 1;
         self::$smarty->assign('email_create', 1);
     }
     if (Tools::isSubmit('SubmitCreate')) {
         if (!Validate::isEmail($email = Tools::getValue('email_create')) or empty($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (Customer::customerExists($email)) {
             $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             $_POST['email'] = $_POST['email_create'];
             unset($_POST['email_create']);
         } else {
             $create_account = 1;
             self::$smarty->assign('email_create', Tools::safeOutput($email));
             $_POST['email'] = $email;
         }
     }
     if (Tools::isSubmit('submitAccount') or Tools::isSubmit('submitGuestAccount')) {
         $create_account = 1;
         if (Tools::isSubmit('submitAccount')) {
             self::$smarty->assign('email_create', 1);
         }
         /* New Guest customer */
         if (!Tools::getValue('is_new_customer', 1) and !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
             $this->errors[] = Tools::displayError('You cannot create a guest account.');
         }
         if (!Tools::getValue('is_new_customer', 1)) {
             $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
         }
         if (isset($_POST['guest_email']) and $_POST['guest_email']) {
             $_POST['email'] = $_POST['guest_email'];
         }
         /* Preparing customer */
         $customer = new Customer();
         $lastnameAddress = $_POST['lastname'];
         $firstnameAddress = $_POST['firstname'];
         $_POST['lastname'] = $_POST['customer_lastname'];
         $_POST['firstname'] = $_POST['customer_firstname'];
         if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) {
             $this->errors[] = Tools::displayError('You must register at least one phone number');
         }
         if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) {
             $this->errors[] = Tools::displayError('Invalid date of birth');
         }
         $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
         $this->errors = array_unique(array_merge($this->errors, $customer->validateControler()));
         /* Preparing address */
         $address = new Address();
         $_POST['lastname'] = $lastnameAddress;
         $_POST['firstname'] = $firstnameAddress;
         $address->id_customer = 1;
         $this->errors = array_unique(array_merge($this->errors, $address->validateControler()));
         /* US customer: normalize the address */
         if ($address->id_country == Country::getByIso('US')) {
             include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
             $normalize = new AddressStandardizationSolution();
             $address->address1 = $normalize->AddressLineStandardization($address->address1);
             $address->address2 = $normalize->AddressLineStandardization($address->address2);
         }
         $zip_code_format = Country::getZipCodeFormat((int) Tools::getValue('id_country'));
         if (Country::getNeedZipCode((int) Tools::getValue('id_country'))) {
             if ($postcode = Tools::getValue('postcode') and $zip_code_format) {
                 $zip_regexp = '/^' . $zip_code_format . '$/ui';
                 $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
                 $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
                 $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
                 $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
                 $zip_regexp = str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), $zip_regexp);
                 if (!preg_match($zip_regexp, $postcode)) {
                     $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                 }
             } elseif ($zip_code_format) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is required.');
             } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.');
             }
         }
         if (Country::isNeedDniByCountryId($address->id_country) and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) {
             $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
         } elseif (!Country::isNeedDniByCountryId($address->id_country)) {
             $address->dni = NULL;
         }
         if (!sizeof($this->errors)) {
             if (Customer::customerExists(Tools::getValue('email'))) {
                 $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             }
             if (Tools::isSubmit('newsletter')) {
                 $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr());
                 $customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s'));
             }
             if (!sizeof($this->errors)) {
                 if (!($country = new Country($address->id_country, Configuration::get('PS_LANG_DEFAULT'))) or !Validate::isLoadedObject($country)) {
                     die(Tools::displayError());
                 }
                 if ((int) $country->contains_states and !(int) $address->id_state) {
                     $this->errors[] = Tools::displayError('This country requires a state selection.');
                 } else {
                     $customer->active = 1;
                     /* New Guest customer */
                     if (Tools::isSubmit('is_new_customer')) {
                         $customer->is_guest = !Tools::getValue('is_new_customer', 1);
                     } else {
                         $customer->is_guest = 0;
                     }
                     if (!$customer->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                     } else {
                         $address->id_customer = (int) $customer->id;
                         if (!$address->add()) {
                             $this->errors[] = Tools::displayError('An error occurred while creating your address.');
                         } else {
                             if (!$customer->is_guest) {
                                 if (!Mail::Send((int) self::$cookie->id_lang, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                                     $this->errors[] = Tools::displayError('Cannot send email');
                                 }
                             }
                             self::$smarty->assign('confirmation', 1);
                             self::$cookie->id_customer = (int) $customer->id;
                             self::$cookie->customer_lastname = $customer->lastname;
                             self::$cookie->customer_firstname = $customer->firstname;
                             self::$cookie->passwd = $customer->passwd;
                             self::$cookie->logged = 1;
                             self::$cookie->email = $customer->email;
                             self::$cookie->is_guest = !Tools::getValue('is_new_customer', 1);
                             /* Update cart address */
                             self::$cart->secure_key = $customer->secure_key;
                             self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                             self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                             self::$cart->update();
                             Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer));
                             if (Tools::isSubmit('ajax')) {
                                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) self::$cookie->id_customer, 'id_address_delivery' => self::$cart->id_address_delivery, 'id_address_invoice' => self::$cart->id_address_invoice, 'token' => Tools::getToken(false));
                                 die(Tools::jsonEncode($return));
                             }
                             if ($back = Tools::getValue('back')) {
                                 Tools::redirect($back);
                             }
                             Tools::redirect('my-account.php');
                         }
                     }
                 }
             }
         }
         if (sizeof($this->errors)) {
             if (!Tools::getValue('is_new_customer')) {
                 unset($_POST['passwd']);
             }
             if (Tools::isSubmit('ajax')) {
                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => false, 'id_customer' => 0);
                 die(Tools::jsonEncode($return));
             }
         }
     }
     if (Tools::isSubmit('SubmitLogin')) {
         Module::hookExec('beforeAuthentication');
         $passwd = trim(Tools::getValue('passwd'));
         $email = trim(Tools::getValue('email'));
         if (empty($email)) {
             $this->errors[] = Tools::displayError('E-mail address required');
         } elseif (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (empty($passwd)) {
             $this->errors[] = Tools::displayError('Password is required');
         } elseif (Tools::strlen($passwd) > 32) {
             $this->errors[] = Tools::displayError('Password is too long');
         } elseif (!Validate::isPasswd($passwd)) {
             $this->errors[] = Tools::displayError('Invalid password');
         } else {
             $customer = new Customer();
             $authentication = $customer->getByEmail(trim($email), trim($passwd));
             if (!$authentication or !$customer->id) {
                 /* Handle brute force attacks */
                 sleep(1);
                 $this->errors[] = Tools::displayError('Authentication failed');
             } else {
                 self::$cookie->id_compare = isset(self::$cookie->id_compare) ? self::$cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                 self::$cookie->id_customer = (int) $customer->id;
                 self::$cookie->customer_lastname = $customer->lastname;
                 self::$cookie->customer_firstname = $customer->firstname;
                 self::$cookie->id_default_group = $customer->id_default_group;
                 self::$cookie->logged = 1;
                 self::$cookie->is_guest = $customer->isGuest();
                 self::$cookie->passwd = $customer->passwd;
                 self::$cookie->email = $customer->email;
                 if (Configuration::get('PS_CART_FOLLOWING') and (empty(self::$cookie->id_cart) or Cart::getNbProducts(self::$cookie->id_cart) == 0)) {
                     self::$cookie->id_cart = (int) Cart::lastNoneOrderedCart((int) $customer->id);
                 }
                 /* Update cart address */
                 self::$cart->id_carrier = 0;
                 self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                 self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                 // If a logged guest logs in as a customer, the cart secure key was already set and needs to be updated
                 self::$cart->secure_key = $customer->secure_key;
                 self::$cart->update();
                 Module::hookExec('authentication');
                 if (!Tools::isSubmit('ajax')) {
                     if ($back = Tools::getValue('back')) {
                         Tools::redirect($back);
                     }
                     Tools::redirect('my-account.php');
                 }
             }
         }
         if (Tools::isSubmit('ajax')) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
             die(Tools::jsonEncode($return));
         }
     }
     if (isset($create_account)) {
         /* Select the most appropriate country */
         if (isset($_POST['id_country']) and is_numeric($_POST['id_country'])) {
             $selectedCountry = (int) $_POST['id_country'];
         }
         /* FIXME : language iso and country iso are not similar,
         			 * maybe an associative table with country an language can resolve it,
         			 * But for now it's a bug !
         			 * @see : bug #6968
         			 * @link:http://www.prestashop.com/bug_tracker/view/6968/
         			elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
         			{
         				$array = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
         				if (Validate::isLanguageIsoCode($array[0]))
         				{
         					$selectedCountry = Country::getByIso($array[0]);
         					if (!$selectedCountry)
         						$selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT'));
         				}
         			}*/
         if (!isset($selectedCountry)) {
             $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT');
         }
         if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
             $countries = Carrier::getDeliveredCountries((int) self::$cookie->id_lang, true, true);
         } else {
             $countries = Country::getCountries((int) self::$cookie->id_lang, true);
         }
         self::$smarty->assign(array('countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'vat_management' => Configuration::get('VATNUMBER_MANAGEMENT')));
         /* Call a hook to display more information on form */
         self::$smarty->assign(array('HOOK_CREATE_ACCOUNT_FORM' => Module::hookExec('createAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Module::hookExec('createAccountTop')));
     }
     /* Generate years, months and days */
     if (isset($_POST['years']) and is_numeric($_POST['years'])) {
         $selectedYears = (int) $_POST['years'];
     }
     $years = Tools::dateYears();
     if (isset($_POST['months']) and is_numeric($_POST['months'])) {
         $selectedMonths = (int) $_POST['months'];
     }
     $months = Tools::dateMonths();
     if (isset($_POST['days']) and is_numeric($_POST['days'])) {
         $selectedDays = (int) $_POST['days'];
     }
     $days = Tools::dateDays();
     self::$smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0));
     self::$smarty->assign('newsletter', (int) Module::getInstanceByName('blocknewsletter')->active);
 }
 /**
  * Get Instance for Ebay Country
  * @param  string          $key Key of country
  * @param  boolean         $dev If module work in debug
  * @return EbayCountrySpec Ebay country
  */
 public static function getInstanceByKey($key, $dev = false)
 {
     if (isset(self::$country_data[$key])) {
         $iso_code = self::$country_data[$key]['iso_code'];
         $id_country = Country::getByIso($iso_code);
     } else {
         $id_country = Configuration::get('PS_COUNTRY_DEFAULT');
     }
     $ebay_country = new EbayCountrySpec(new Country($id_country));
     $ebay_country->setDev($dev);
     $ebay_country->ebay_iso = is_numeric($key) ? self::getKeyForEbayCountry() : $key;
     return $ebay_country;
 }
Example #7
0
 public static function getCountry($address = null)
 {
     if ($id_country = Tools::getValue('id_country')) {
     } elseif (isset($address) && isset($address->id_country) && $address->id_country) {
         $id_country = $address->id_country;
     } elseif (Configuration::get('PS_DETECT_COUNTRY') && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
         preg_match('#(?<=-)\\w\\w|\\w\\w(?!-)#', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
         if (is_array($array) && isset($array[0]) && Validate::isLanguageIsoCode($array[0])) {
             $id_country = Country::getByIso($array[0], true);
         }
     }
     if (!isset($id_country) || !$id_country) {
         $id_country = Configuration::get('PS_COUNTRY_DEFAULT');
     }
     return (int) $id_country;
 }
 public function postProcess()
 {
     if (!Tools::getValue('id_' . $this->table)) {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code')) && Country::getByIso(Tools::getValue('iso_code'))) {
             $this->errors[] = Tools::displayError('This ISO code already exists.You cannot create two countries with the same ISO code.');
         }
     } else {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code'))) {
             $id_country = Country::getByIso(Tools::getValue('iso_code'));
             if (!is_null($id_country) && $id_country != Tools::getValue('id_' . $this->table)) {
                 $this->errors[] = Tools::displayError('This ISO code already exists.You cannot create two countries with the same ISO code.');
             }
         }
     }
     return parent::postProcess();
 }
 protected function geolocationManagement($default_country)
 {
     if (!in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {
         /* Check if Maxmind Database exists */
         if (file_exists(_PS_GEOIP_DIR_ . 'GeoLiteCity.dat')) {
             if (!isset($this->context->cookie->iso_code_country) || isset($this->context->cookie->iso_code_country) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))) {
                 include_once _PS_GEOIP_DIR_ . 'geoipcity.inc';
                 $gi = geoip_open(realpath(_PS_GEOIP_DIR_ . 'GeoLiteCity.dat'), GEOIP_STANDARD);
                 $record = geoip_record_by_addr($gi, Tools::getRemoteAddr());
                 if (is_object($record)) {
                     if (!in_array(strtoupper($record->country_code), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && !FrontController::isInWhitelistForGeolocation()) {
                         if (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_) {
                             $this->restrictedCountry = true;
                         } elseif (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_) {
                             $this->context->smarty->assign(array('restricted_country_mode' => true, 'geolocation_country' => $record->country_name));
                         }
                     } else {
                         $has_been_set = !isset($this->context->cookie->iso_code_country);
                         $this->context->cookie->iso_code_country = strtoupper($record->country_code);
                     }
                 }
             }
             if (isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country)) {
                 $this->context->cookie->iso_code_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));
             }
             if (isset($this->context->cookie->iso_code_country) && ($id_country = Country::getByIso(strtoupper($this->context->cookie->iso_code_country)))) {
                 /* Update defaultCountry */
                 if ($default_country->iso_code != $this->context->cookie->iso_code_country) {
                     $default_country = new Country($id_country);
                 }
                 if (isset($has_been_set) && $has_been_set) {
                     $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($default_country->id_currency ? (int) $default_country->id_currency : Configuration::get('PS_CURRENCY_DEFAULT'))->id;
                 }
                 return $default_country;
             } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_ && !FrontController::isInWhitelistForGeolocation()) {
                 $this->restrictedCountry = true;
             } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_ && !FrontController::isInWhitelistForGeolocation()) {
                 $this->context->smarty->assign(array('restricted_country_mode' => true, 'geolocation_country' => 'Undefined'));
             }
         } else {
             Configuration::updateValue('PS_GEOLOCATION_ENABLED', 0);
         }
     }
     return false;
 }
Example #10
0
 if (!isset($ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET']) || !isset($ppec->result['PAYMENTREQUEST_0_SHIPTOCITY']) || !isset($ppec->result['SHIPTOZIP']) || !isset($ppec->result['COUNTRYCODE'])) {
     $ppec->redirectToCheckout($customer, $ppec->type != 'payment_cart');
 }
 foreach ($customer->getAddresses($ppec->getContext()->language->id) as $address) {
     if ($address['alias'] == 'Paypal_Address') {
         $address = new Address($address['id_address']);
         break;
     }
 }
 // Create address
 if (is_array($address) && isset($address['id_address'])) {
     $address = new Address($address['id_address']);
 }
 if ((!$address || !$address->id) && $customer->id) {
     $address = new Address();
     $address->id_country = Country::getByIso($ppec->result['COUNTRYCODE']);
     $address->alias = 'Paypal_Address';
     $address->lastname = $customer->lastname;
     $address->firstname = $customer->firstname;
     $address->address1 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET'];
     $address->city = $ppec->result['PAYMENTREQUEST_0_SHIPTOCITY'];
     $address->postcode = $ppec->result['SHIPTOZIP'];
     $address->id_customer = $customer->id;
     $address->add();
 }
 if ($customer->id && !$address->id) {
     $ppec->logs[] = $ppec->l('Cannot create Address');
 }
 // Create Order
 if ($address->id && $customer->id) {
     $ppec->getContext()->cart->id_customer = $customer->id;
Example #11
0
    $years = Tools::dateYears();
    if (isset($_POST['months']) and is_numeric($_POST['months'])) {
        $selectedMonths = intval($_POST['months']);
    }
    $months = Tools::dateMonths();
    if (isset($_POST['days']) and is_numeric($_POST['days'])) {
        $selectedDays = intval($_POST['days']);
    }
    $days = Tools::dateDays();
    /* Select the most appropriate country */
    if (isset($_POST['id_country']) and is_numeric($_POST['id_country'])) {
        $selectedCountry = intval($_POST['id_country']);
    } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $array = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        if (Validate::isLanguageIsoCode($array[0])) {
            $selectedCountry = Country::getByIso($array[0]);
            if (!$selectedCountry) {
                $selectedCountry = intval(Configuration::get('PS_COUNTRY_DEFAULT'));
            }
        }
    }
    if (!isset($selectedCountry)) {
        $selectedCountry = intval(Configuration::get('PS_COUNTRY_DEFAULT'));
    }
    $countries = Country::getCountries(intval($cookie->id_lang), true);
    $smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0, 'countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0));
    /* Call a hook to display more information on form */
    $smarty->assign(array('HOOK_CREATE_ACCOUNT_FORM' => Module::hookExec('createAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Module::hookExec('createAccountTop')));
}
include dirname(__FILE__) . '/header.php';
$smarty->assign('errors', $errors);
 /**
  * Get Country object by code
  * @param  string $code Code
  * @return Country      Country object
  */
 protected function getCountryByCode($code)
 {
     $idCountry = (int) Country::getByIso($code);
     $country = new Country($idCountry, (int) $this->context->language->id);
     return $country;
 }
 /**
  * When the customer is back from PayPal after filling his/her credit card info or credentials, this function is preparing the order
  * PayPal is providing us with the customer info (E-mail address, billing address) and we are trying to find a matching customer in the Shop database.
  * If no customer is found, we create a new one and we simulate a logged customer session.
  * Eventually it will redirect the customer to the "Shipping" step/page of the order process
  */
 private function _expressCheckout()
 {
     /* We need to double-check that the token provided by PayPal is the one expected */
     $result = $this->paypal_usa->postToPayPal('GetExpressCheckoutDetails', '&TOKEN=' . urlencode(Tools::getValue('token')));
     if ((strtoupper($result['ACK']) == 'SUCCESS' || strtoupper($result['ACK']) == 'SUCCESSWITHWARNING') && $result['TOKEN'] == Tools::getValue('token') && $result['PAYERID'] == Tools::getValue('PayerID')) {
         /* Checks if a customer already exists for this e-mail address */
         if (Validate::isEmail($result['EMAIL'])) {
             $customer = new Customer();
             $customer->getByEmail($result['EMAIL']);
         }
         /* If the customer does not exist yet, create a new one */
         if (!Validate::isLoadedObject($customer)) {
             $customer = new Customer();
             $customer->email = $result['EMAIL'];
             $customer->firstname = $result['FIRSTNAME'];
             $customer->lastname = $result['LASTNAME'];
             $customer->passwd = Tools::encrypt(Tools::passwdGen());
             $customer->add();
         }
         /* Look for an existing PayPal address for this customer */
         $addresses = $customer->getAddresses((int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($addresses as $address) {
             if ($address['alias'] == 'PayPal') {
                 $id_address = (int) $address['id_address'];
                 break;
             }
         }
         /* Create or update a PayPal address for this customer */
         $address = new Address(isset($id_address) ? (int) $id_address : 0);
         $address->id_customer = (int) $customer->id;
         $address->id_country = (int) Country::getByIso($result['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']);
         $address->id_state = (int) State::getIdByIso($result['PAYMENTREQUEST_0_SHIPTOSTATE'], (int) $address->id_country);
         $address->alias = 'PayPal';
         $address->lastname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], 0, strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '));
         $address->firstname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '), strlen($result['PAYMENTREQUEST_0_SHIPTONAME']) - strlen($address->lastname));
         $address->address1 = $result['PAYMENTREQUEST_0_SHIPTOSTREET'];
         if ($result['PAYMENTREQUEST_0_SHIPTOSTREET2'] != '') {
             $address->address2 = $result['PAYMENTREQUEST_0_SHIPTOSTREET2'];
         }
         $address->city = $result['PAYMENTREQUEST_0_SHIPTOCITY'];
         $address->postcode = $result['PAYMENTREQUEST_0_SHIPTOZIP'];
         $address->save();
         /* Update the cart billing and delivery addresses */
         $this->context->cart->id_address_delivery = (int) $address->id;
         $this->context->cart->id_address_invoice = (int) $address->id;
         $this->context->cart->update();
         /* Update the customer cookie to simulate a logged-in session */
         $this->context->cookie->id_customer = (int) $customer->id;
         $this->context->cookie->customer_lastname = $customer->lastname;
         $this->context->cookie->customer_firstname = $customer->firstname;
         $this->context->cookie->passwd = $customer->passwd;
         $this->context->cookie->email = $customer->email;
         $this->context->cookie->is_guest = $customer->isGuest();
         $this->context->cookie->logged = 1;
         /* Save the Payer ID and Checkout token for later use (during the payment step/page) */
         $this->context->cookie->paypal_express_checkout_token = $result['TOKEN'];
         $this->context->cookie->paypal_express_checkout_payer_id = $result['PAYERID'];
         if (_PS_VERSION_ < '1.5') {
             Module::hookExec('authentication');
         } else {
             Hook::exec('authentication');
         }
         /* Redirect the use to the "Shipping" step/page of the order process */
         Tools::redirectLink($this->context->link->getPageLink('order.php', false, null, array('step' => '3')));
         exit;
     } else {
         foreach ($result as $key => $val) {
             $result[$key] = urldecode($val);
         }
         $this->context->smarty->assign('paypal_usa_errors', $result);
         $this->setTemplate('express-checkout-messages.tpl');
     }
 }
 public function postProcess()
 {
     if (!Tools::getValue('id_' . $this->table)) {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code')) && Country::getByIso(Tools::getValue('iso_code'))) {
             $this->errors[] = Tools::displayError('This ISO code already exists.You cannot create two countries with the same ISO code.');
         }
     } else {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code'))) {
             $id_country = Country::getByIso(Tools::getValue('iso_code'));
             if (!is_null($id_country) && $id_country != Tools::getValue('id_' . $this->table)) {
                 $this->errors[] = Tools::displayError('This ISO code already exists.You cannot create two countries with the same ISO code.');
             }
         }
     }
     if (Tools::isSubmit('standardization')) {
         Configuration::updateValue('PS_TAASC', (bool) Tools::getValue('standardization', false));
     }
     return parent::postProcess();
 }
 public function postProcess()
 {
     if (!Tools::getValue('id_' . $this->table)) {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code')) && Country::getByIso(Tools::getValue('iso_code'))) {
             $this->errors[] = Tools::displayError('This ISO code already exists, you cannot create two country with the same ISO code');
         }
     } else {
         if (Validate::isLanguageIsoCode(Tools::getValue('iso_code'))) {
             $id_country = Country::getByIso(Tools::getValue('iso_code'));
             if (!is_null($id_country) && $id_country != Tools::getValue('id_' . $this->table)) {
                 $this->errors[] = Tools::displayError('This ISO code already exists, you cannot create two country with the same ISO code');
             }
         }
     }
     if (!count($this->errors)) {
         $res = parent::postProcess();
     } else {
         return false;
     }
     if (Tools::getValue('submitAdd' . $this->table) && $res) {
         $id_country = ($id_country = Tools::getValue('id_country')) ? $id_country : $res['id'];
         $tmp_addr_format = new AddressFormat($id_country);
         $save_status = false;
         $is_new = is_null($tmp_addr_format->id_country);
         if ($is_new) {
             $tmp_addr_format = new AddressFormat();
             $tmp_addr_format->id_country = $id_country;
         }
         $tmp_addr_format->format = Tools::getValue('address_layout');
         if (strlen($tmp_addr_format->format) > 0) {
             if ($tmp_addr_format->checkFormatFields()) {
                 $save_status = $is_new ? $tmp_addr_format->save() : $tmp_addr_format->update();
             } else {
                 $error_list = $tmp_addr_format->getErrorList();
                 foreach ($error_list as $num_error => $error) {
                     $this->errors[] = $error;
                 }
             }
             if (!$save_status) {
                 $this->errors[] = Tools::displayError('Invalid address layout' . Db::getInstance()->getMsgError());
             }
         }
         unset($tmp_addr_format);
     }
     return $res;
 }
 private function _displayIntroTpl()
 {
     $this->context->smarty->assign(array('formCredential' => './index.php?tab=AdminModules&configure=merchantware&token=' . Tools::getAdminTokenLite('AdminModules') . '&tab_module=' . $this->tab . '&module_name=merchantware&subscribeMerchantWare', 'states' => State::getStatesByIdCountry(Country::getByIso('US'))));
     return $this->display(__FILE__, 'tpl/intro.tpl');
 }
Example #17
0
 } else {
     if (Configuration::get('QUI_CREATE_ORDER')) {
         if (!$context->customer->isLogged()) {
             $customer = new Customer();
             $customer->passwd = md5(time() . _COOKIE_KEY_);
             $customer->firstname = Tools::getValue('firstname');
             $customer->lastname = ' ';
             $customer->email = '*****@*****.**';
             $customer->active = 1;
             $customer->is_guest = Configuration::get('QUI_CREATE_CUSTOMER') ? '0' : '1';
             $customer->add();
         }
         if (Configuration::get('QUI_CREATE_ADDRESS')) {
             $address = new Address();
             if (Configuration::get('QUI_COUNTRY')) {
                 $address->id_country = Country::getByIso(Configuration::get('QUI_COUNTRY'));
             }
             $address->firstname = Tools::getValue('firstname');
             $address->lastname = ' ';
             $address->phone_mobile = Tools::getValue('phone');
             $address->other = 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Время: ' . Tools::getValue('time');
             $address->address1 = ' ';
             $address->city = ' ';
             $address->alias = 'quickorder_' . substr(md5(time() . _COOKIE_KEY_), 0, 7);
             $address->id_customer = $customer->id;
             $address->save();
             $cart->id_address_invoice = (int) $address->id;
             $cart->id_address_delivery = (int) $address->id;
             $id_address = (int) $address->id;
             $cart->update();
             CartRule::autoRemoveFromCart($context);
 /**
  * getCountryID() method return the country ID
  *
  * @param string $sCountryCode
  * @return int
  */
 protected function getCountryID($sCountryCode)
 {
     // get the country ID if exists - if not get the default one
     $iDefaultCountryId = $iCountryId = (int) Tools::getValue('id_country', Configuration::get('PS_COUNTRY_DEFAULT'));
     // get lang ID
     $iCountryId = Country::getByIso(strtoupper($sCountryCode));
     if (empty($iCountryId)) {
         $iCountryId = $iDefaultCountryId;
     }
     return $iCountryId;
 }
    private function _getAddress($addressNode, $id_customer, $type)
    {
        //alias is limited
        $type = Tools::substr($type, 0, 32);
        $id_address = (int) Db::getInstance()->getValue('SELECT `id_address`
			FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'' . pSQL($type) . '\'');
        if ($id_address) {
            $address = new Address((int) $id_address);
        } else {
            $address = new Address();
        }
        $customer = new Customer((int) $id_customer);
        $street1 = '';
        $street2 = '';
        $line2 = false;
        $streets = Explode(' ', (string) $addressNode->Street);
        foreach ($streets as $street) {
            if (Tools::strlen($street1) + Tools::strlen($street) + 1 < 32 && !$line2) {
                $street1 .= $street . ' ';
            } else {
                $line2 = true;
                $street2 .= $street . ' ';
            }
        }
        $lastname = (string) $addressNode->LastName;
        $firstname = (string) $addressNode->FirstName;
        $address->id_customer = (int) $id_customer;
        $address->id_country = (int) Country::getByIso(trim($addressNode->Country));
        $address->alias = pSQL($type);
        $address->lastname = !empty($lastname) ? pSQL($lastname) : $customer->lastname;
        $address->firstname = !empty($firstname) ? pSQL($firstname) : $customer->firstname;
        $address->address1 = pSQL($street1);
        $address->address2 = pSQL($street2);
        $address->company = pSQL($addressNode->Company);
        $address->postcode = pSQL($addressNode->PostalCode);
        $address->city = pSQL($addressNode->Town);
        $address->phone = Tools::substr(pSQL($addressNode->Phone), 0, 16);
        $address->phone_mobile = Tools::substr(pSQL($addressNode->PhoneMobile), 0, 16);
        if ($id_address) {
            $address->update();
        } else {
            $address->add();
        }
        return $address->id;
    }
Example #20
0
 /**
  * PROCESS : configureShop
  * Set default shop configuration
  */
 public function configureShop(array $data = array())
 {
     //clear image cache in tmp folder
     if (file_exists(_PS_TMP_IMG_DIR_)) {
         foreach (scandir(_PS_TMP_IMG_DIR_) as $file) {
             if ($file[0] != '.' && $file != 'index.php') {
                 Tools::deleteFile(_PS_TMP_IMG_DIR_ . $file);
             }
         }
     }
     $default_data = array('shop_name' => 'My Shop', 'shop_activity' => '', 'shop_country' => 'us', 'shop_timezone' => 'US/Eastern', 'use_smtp' => false, 'smtp_server' => '', 'smtp_login' => '', 'smtp_password' => '', 'smtp_encryption' => 'off', 'smtp_port' => 25);
     foreach ($default_data as $k => $v) {
         if (!isset($data[$k])) {
             $data[$k] = $v;
         }
     }
     Context::getContext()->shop = new Shop(1);
     Configuration::loadConfiguration();
     // use the old image system if the safe_mod is enabled otherwise the installer will fail with the fixtures installation
     if (InstallSession::getInstance()->safe_mode) {
         Configuration::updateGlobalValue('PS_LEGACY_IMAGES', 1);
     }
     $id_country = Country::getByIso($data['shop_country']);
     // Set default configuration
     Configuration::updateGlobalValue('PS_SHOP_DOMAIN', Tools::getHttpHost());
     Configuration::updateGlobalValue('PS_SHOP_DOMAIN_SSL', Tools::getHttpHost());
     Configuration::updateGlobalValue('PS_INSTALL_VERSION', _PS_INSTALL_VERSION_);
     Configuration::updateGlobalValue('PS_LOCALE_LANGUAGE', $this->language->getLanguageIso());
     Configuration::updateGlobalValue('PS_SHOP_NAME', $data['shop_name']);
     Configuration::updateGlobalValue('PS_SHOP_ACTIVITY', $data['shop_activity']);
     Configuration::updateGlobalValue('PS_COUNTRY_DEFAULT', $id_country);
     Configuration::updateGlobalValue('PS_LOCALE_COUNTRY', $data['shop_country']);
     Configuration::updateGlobalValue('PS_TIMEZONE', $data['shop_timezone']);
     Configuration::updateGlobalValue('PS_CONFIGURATION_AGREMENT', (int) $data['configuration_agrement']);
     // Set mails configuration
     Configuration::updateGlobalValue('PS_MAIL_METHOD', $data['use_smtp'] ? 2 : 1);
     Configuration::updateGlobalValue('PS_MAIL_SERVER', $data['smtp_server']);
     Configuration::updateGlobalValue('PS_MAIL_USER', $data['smtp_login']);
     Configuration::updateGlobalValue('PS_MAIL_PASSWD', $data['smtp_password']);
     Configuration::updateGlobalValue('PS_MAIL_SMTP_ENCRYPTION', $data['smtp_encryption']);
     Configuration::updateGlobalValue('PS_MAIL_SMTP_PORT', $data['smtp_port']);
     // Activate rijndael 128 encrypt algorihtm if mcrypt is activated
     Configuration::updateGlobalValue('PS_CIPHER_ALGORITHM', function_exists('mcrypt_encrypt') ? 1 : 0);
     // Set logo configuration
     if (file_exists(_PS_IMG_DIR_ . 'logo.jpg')) {
         list($width, $height) = getimagesize(_PS_IMG_DIR_ . 'logo.jpg');
         Configuration::updateGlobalValue('SHOP_LOGO_WIDTH', round($width));
         Configuration::updateGlobalValue('SHOP_LOGO_HEIGHT', round($height));
     }
     // Active only the country selected by the merchant
     Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'country SET active = 0 WHERE id_country != ' . (int) $id_country);
     // Set localization configuration
     $version = str_replace('.', '', _PS_VERSION_);
     $version = substr($version, 0, 2);
     $localization_file_content = @Tools::file_get_contents('http://api.prestashop.com/localization/' . $version . '/' . $data['shop_country'] . '.xml');
     if (!@simplexml_load_string($localization_file_content)) {
         $localization_file_content = false;
     }
     if (!$localization_file_content) {
         $localization_file = _PS_ROOT_DIR_ . '/localization/default.xml';
         if (file_exists(_PS_ROOT_DIR_ . '/localization/' . $data['shop_country'] . '.xml')) {
             $localization_file = _PS_ROOT_DIR_ . '/localization/' . $data['shop_country'] . '.xml';
         }
         $localization_file_content = file_get_contents($localization_file);
     }
     $locale = new LocalizationPackCore();
     $locale->loadLocalisationPack($localization_file_content, '', true);
     // Create default employee
     if (isset($data['admin_firstname']) && isset($data['admin_lastname']) && isset($data['admin_password']) && isset($data['admin_email'])) {
         $employee = new Employee();
         $employee->firstname = Tools::ucfirst($data['admin_firstname']);
         $employee->lastname = Tools::ucfirst($data['admin_lastname']);
         $employee->email = $data['admin_email'];
         $employee->passwd = md5(_COOKIE_KEY_ . $data['admin_password']);
         $employee->last_passwd_gen = date('Y-m-d h:i:s', strtotime('-360 minutes'));
         $employee->bo_theme = 'default';
         $employee->default_tab = 1;
         $employee->active = true;
         $employee->id_profile = 1;
         $employee->id_lang = Configuration::get('PS_LANG_DEFAULT');
         $employee->bo_show_screencast = 1;
         if (!$employee->add()) {
             $this->setError($this->language->l('Cannot create admin account'));
             return false;
         }
     } else {
         $this->setError($this->language->l('Cannot create admin account'));
         return false;
     }
     // Update default contact
     if (isset($data['admin_email'])) {
         Configuration::updateGlobalValue('PS_SHOP_EMAIL', $data['admin_email']);
         $contacts = new Collection('Contact');
         foreach ($contacts as $contact) {
             $contact->email = $data['admin_email'];
             $contact->update();
         }
     }
     return true;
 }
    public function update_cart_by_junglee_xml($order_id, $data)
    {
        $xml = simplexml_load_string($data);
        $prefix = _DB_PREFIX_;
        $tablename = $prefix . 'orders';
        $total_amount = 0;
        $total_principal = 0;
        $shipping_amount = 0;
        $total_promo = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $total_principal += $principal;
            $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo);
            $shipping_amount += $Shipping;
            $total_promo += $principal_promo + $shipping_promo + $other_promo;
        }
        $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel;
        $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "junglee" where `prestashop_order_id` = "' . $order_id . '" ';
        Db::getInstance()->Execute($sql);
        $email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
        $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" ';
        $results = Db::getInstance()->ExecuteS($sql);
        if (empty($results)) {
            $name = (string) $xml->ProcessedOrder->BuyerInfo->BuyerName;
            $name_arr = explode(' ', $name);
            if (count($name_arr) > 1) {
                $firstname = '';
                for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                    $firstname = $firstname . ' ' . $name_arr[$i];
                }
                $lastname = $name_arr[count($name_arr) - 1];
            } else {
                $firstname = $name;
                $lastname = '.';
            }
            $password = Tools::passwdGen();
            $customer = new Customer();
            $customer->firstname = trim($firstname);
            $customer->lastname = $lastname;
            $customer->email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
            $customer->passwd = md5($password);
            $customer->active = 1;
            if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                $customer->is_guest = 1;
            } else {
                $customer->is_guest = 0;
            }
            $customer->add();
            $customer_id = $customer->id;
            if (Configuration::get('PS_CUSTOMER_CREATION_EMAIL') && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                Mail::Send($this->context->language->id, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $password), $customer->email, $customer->firstname . ' ' . $customer->lastname);
            }
        } else {
            $customer_id = $results[0]['id_customer'];
        }
        $id_country = Country::getByIso((string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
        if ($id_country == 0 || $id_country == '') {
            $id_country = 110;
        }
        $name = (string) $xml->ProcessedOrder->ShippingAddress->Name;
        $name_arr = explode(' ', $name);
        if (count($name_arr) > 1) {
            $firstname = '';
            for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                $firstname = $firstname . ' ' . $name_arr[$i];
            }
            $lastname = $name_arr[count($name_arr) - 1];
        } else {
            $firstname = $name;
            $lastname = '.';
        }
        $address = new Address();
        $address->id_country = $id_country;
        $address->id_state = 0;
        $address->id_customer = $customer_id;
        $address->alias = 'My Address';
        $address->firstname = trim($firstname);
        $address->lastname = $lastname;
        $address->address1 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne;
        $address->address2 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo;
        $address->postcode = (string) $xml->ProcessedOrder->ShippingAddress->PostalCode;
        $address->city = (string) $xml->ProcessedOrder->ShippingAddress->City . ' ' . (string) $xml->ProcessedOrder->ShippingAddress->State;
        $address->active = 1;
        $address->add();
        $address_id = $address->id;
        //$id_order_state = Configuration::get('PS_OS_PREPARATION');
        $id_order_state = 99;
        $reference = Order::generateReference();
        $order = new Order();
        $order->id = $order_id;
        $order->id_customer = (int) $customer_id;
        $order->id_address_invoice = (int) $address_id;
        $carrier = null;
        $sql = 'SELECT id_carrier from  `' . $prefix . 'carrier` where `active` = 1 and `deleted` = 0 limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $id_carrier = $result[0]['id_carrier'];
        $sql = 'SELECT id_currency from  `' . $prefix . 'currency` where `active` = 1 and `deleted` = 0 and `iso_code` = "INR" limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $currency_id = $result[0]['id_currency'];
        $sql = 'UPDATE `' . $tablename . '` set 
			  `id_customer` = ' . (int) $customer_id . ',
			  `id_carrier` = ' . $id_carrier . ',
			  `id_address_invoice` = ' . (int) $address_id . ',
			  `id_address_delivery` = ' . (int) $address_id . ',
			  `id_currency` = ' . $currency_id . ',
			  `reference` = "' . $reference . '",
			  `secure_key` = "' . md5(uniqid()) . '",
			  
			  `total_paid` = ' . $total_amount . ',
			  `total_paid_tax_incl` = ' . $total_amount . ',
			  `total_paid_tax_excl` = ' . $total_amount . ',
			  `total_paid_real` = 0,
			 
			  `total_shipping` = ' . $shipping_amount . ',
			  `total_shipping_tax_incl` = ' . $shipping_amount . ',
			  `total_shipping_tax_excl` = ' . $shipping_amount . ',
			  
			  `total_discounts` = ' . (double) $total_promo . ',
			  `total_discounts_tax_incl` = ' . (double) $total_promo . ',
			  `total_discounts_tax_excl` = ' . (double) $total_promo . ',
			  
			  `total_products` = ' . $total_principal . ',
			  `total_products_wt` = ' . $total_principal . ',
			  
			  `invoice_date` = "0000-00-00 00:00:00",
			  `delivery_date` = "0000-00-00 00:00:00"
			  where `id_order` = ' . $order_id . ' ';
        //`round_mode` = '.Configuration::get('PS_PRICE_ROUND_MODE').',
        /*`total_wrapping_tax_incl` = '.$WrappingAmount.',
          `total_wrapping_tax_excl` = '.$WrappingAmount.',
          `total_wrapping` = '.$WrappingAmount.',*/
        Db::getInstance()->Execute($sql);
        $acknowledge_arr = array();
        $i = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode;
            $acknowledge_arr['items'][$i]['product_id'] = $product_id;
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $sql = 'INSERT into `' . $prefix . 'order_detail` set
							`id_order` = ' . $order_id . ',
							`product_id` = ' . $product_id . ',
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Amount * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Amount . ',
							`original_product_price` = ' . $Amount . '
							';
            Db::getInstance()->Execute($sql);
            $sql = 'UPDATE `' . $prefix . 'stock_available` set
						`quantity` = `quantity` - ' . $Quantity . '
						where `id_product` = ' . $product_id . ' and
						`id_product_attribute` = 0
						';
            Db::getInstance()->Execute($sql);
            $date = date('Y-m-d');
            $sql = 'UPDATE `' . $prefix . 'product_sale` set
						`quantity` = `quantity` + ' . $Quantity . ',
						`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
						`date_upd` = ' . $date . '
						where `id_product` = ' . $product_id . '
						';
            Db::getInstance()->Execute($sql);
            $i++;
        }
        // Adding an entry in order_carrier table
        if (!is_null($carrier)) {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        } else {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        }
        // Set the order status
        $history = new OrderHistory();
        $history->id_order = (int) $order->id;
        $history->changeIdOrderState((int) $id_order_state, $order->id, true);
        $history->addWithemail(true, array());
        $acknowledge_arr['MerchantOrderID'] = (int) $order->id;
    }
Example #22
0
function displayAccount()
{
    global $cookie, $result, $email, $payerID, $errors, $ppExpress, $smarty;
    // Customer does not exists, signup form
    // If customer already logged, unlog him
    if ($cookie->isLogged(true)) {
        $cookie->makeNewLog();
    }
    // Generate years, months and days
    if (isset($_POST['years']) and is_numeric($_POST['years'])) {
        $selectedYears = (int) $_POST['years'];
    }
    $years = Tools::dateYears();
    if (isset($_POST['months']) and is_numeric($_POST['months'])) {
        $selectedMonths = (int) $_POST['months'];
    }
    $months = Tools::dateMonths();
    if (isset($_POST['days']) and is_numeric($_POST['days'])) {
        $selectedDays = (int) $_POST['days'];
    }
    $days = Tools::dateDays();
    // Select the most appropriate country
    if (Tools::getValue('id_country')) {
        $selectedCountry = (int) Tools::getValue('id_country');
    } else {
        if ((int) $result['COUNTRYCODE']) {
            $selectedCountry = Country::getByIso(strval($result['COUNTRYCODE']));
        }
    }
    $countries = Country::getCountries((int) $cookie->id_lang, true);
    // Smarty assigns
    $smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0, 'countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'email' => $email, 'firstname' => Tools::getValue('customer_firstname') ? Tools::htmlentitiesUTF8(strval(Tools::getValue('customer_firstname'))) : $result['FIRSTNAME'], 'lastname' => Tools::getValue('customer_lastname') ? Tools::htmlentitiesUTF8(strval(Tools::getValue('customer_lastname'))) : $result['LASTNAME'], 'street' => Tools::getValue('address1') ? Tools::htmlentitiesUTF8(strval(Tools::getValue('address1'))) : (isset($result['SHIPTOSTREET']) ? $result['SHIPTOSTREET'] : ''), 'city' => Tools::getValue('city') ? Tools::htmlentitiesUTF8(strval(Tools::getValue('city'))) : (isset($result['SHIPTOCITY']) ? $result['SHIPTOCITY'] : ''), 'zip' => Tools::getValue('postcode') ? Tools::htmlentitiesUTF8(strval(Tools::getValue('postcode'))) : (isset($result['SHIPTOZIP']) ? $result['SHIPTOZIP'] : ''), 'payerID' => $payerID, 'ppToken' => strval($cookie->paypal_token), 'errors' => $errors));
    // Display all and exit
    include _PS_ROOT_DIR_ . '/header.php';
    echo $ppExpress->display('paypal.php', 'express/authentication.tpl');
    include _PS_ROOT_DIR_ . '/footer.php';
    die;
}
 /**
  * @param SimpleXMLElement $xml
  * @return bool
  * @throws PrestaShopException
  */
 protected function _installTaxes($xml)
 {
     if (isset($xml->taxes->tax)) {
         $assoc_taxes = array();
         foreach ($xml->taxes->tax as $taxData) {
             /** @var SimpleXMLElement $taxData */
             $attributes = $taxData->attributes();
             if ($id_tax = Tax::getTaxIdByName($attributes['name'])) {
                 $assoc_taxes[(int) $attributes['id']] = $id_tax;
                 continue;
             }
             $tax = new Tax();
             $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = (string) $attributes['name'];
             $tax->rate = (double) $attributes['rate'];
             $tax->active = 1;
             if (($error = $tax->validateFields(false, true)) !== true || ($error = $tax->validateFieldsLang(false, true)) !== true) {
                 $this->_errors[] = Tools::displayError('Invalid tax properties.') . ' ' . $error;
                 return false;
             }
             if (!$tax->add()) {
                 $this->_errors[] = Tools::displayError('An error occurred while importing the tax: ') . (string) $attributes['name'];
                 return false;
             }
             $assoc_taxes[(int) $attributes['id']] = $tax->id;
         }
         foreach ($xml->taxes->taxRulesGroup as $group) {
             /** @var SimpleXMLElement $group */
             $group_attributes = $group->attributes();
             if (!Validate::isGenericName($group_attributes['name'])) {
                 continue;
             }
             if (TaxRulesGroup::getIdByName($group['name'])) {
                 continue;
             }
             $trg = new TaxRulesGroup();
             $trg->name = $group['name'];
             $trg->active = 1;
             if (!$trg->save()) {
                 $this->_errors[] = Tools::displayError('This tax rule cannot be saved.');
                 return false;
             }
             foreach ($group->taxRule as $rule) {
                 /** @var SimpleXMLElement $rule */
                 $rule_attributes = $rule->attributes();
                 // Validation
                 if (!isset($rule_attributes['iso_code_country'])) {
                     continue;
                 }
                 $id_country = (int) Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
                 if (!$id_country) {
                     continue;
                 }
                 if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes)) {
                     continue;
                 }
                 // Default values
                 $id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
                 $id_county = 0;
                 $zipcode_from = 0;
                 $zipcode_to = 0;
                 $behavior = $rule_attributes['behavior'];
                 if (isset($rule_attributes['zipcode_from'])) {
                     $zipcode_from = $rule_attributes['zipcode_from'];
                     if (isset($rule_attributes['zipcode_to'])) {
                         $zipcode_to = $rule_attributes['zipcode_to'];
                     }
                 }
                 // Creation
                 $tr = new TaxRule();
                 $tr->id_tax_rules_group = $trg->id;
                 $tr->id_country = $id_country;
                 $tr->id_state = $id_state;
                 $tr->id_county = $id_county;
                 $tr->zipcode_from = $zipcode_from;
                 $tr->zipcode_to = $zipcode_to;
                 $tr->behavior = $behavior;
                 $tr->description = '';
                 $tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
                 $tr->save();
             }
         }
     }
     return true;
 }
 private function validateCSVCountry($iso_code, $id_carrier)
 {
     if ($iso_code === '*') {
         if ($id_carrier == _DPDPOLAND_CLASSIC_ID_) {
             return true;
         } else {
             return self::STAR_COUNTRY_ERROR;
         }
     }
     if (!Country::getByIso($iso_code)) {
         return self::PRESTASHOP_COUNTRY_ERROR;
     }
     if ($iso_code == self::POLAND_ISO_CODE) {
         if ($id_carrier == _DPDPOLAND_STANDARD_ID_ || $id_carrier == _DPDPOLAND_STANDARD_COD_ID_) {
             return true;
         } else {
             return self::PL_COUNTRY_ERROR;
         }
     } else {
         if ($id_carrier == _DPDPOLAND_CLASSIC_ID_) {
             return true;
         } else {
             return self::NOT_PL_COUNTRY_ERROR;
         }
     }
 }
 /**
  * creates of a dejala carrier corresponding to $dejalaProduct
  */
 public static function createDejalaCarrier($dejalaConfig)
 {
     // MFR091130 - get id zone from the country used in the module (if the store zones were customized) - default is 1 (Europe)
     $id_zone = 1;
     $moduleCountryIsoCode = strtoupper($dejalaConfig->country);
     $countryID = Country::getByIso($moduleCountryIsoCode);
     if ((int) $countryID) {
         $id_zone = Country::getIdZone($countryID);
     }
     //TODO Will have to review this and apply proper code.
     $trg_id = 1;
     /*$vatRate = "19.6";
     		// MFR091130 - get or create the tax & attach it to our zone if needed
     		$id_tax = Tax::getTaxIdByRate((float)$vatRate);
     		$trg_id = 0;
     		if (!$id_tax)
     		{
     			$tax = new Tax();
     			$tax->rate = $vatRate;
     			$defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
     			$tax->name[$defaultLanguage] = $tax->rate . '%';
     			$tax->add();
     			$id_tax = $tax->id;
     
     			$trg = new TaxRulesGroup();
     			$trg->name = 'Dejala '.$tax->name[$defaultLanguage];
     			$trg->active = 1;
     			if ($trg->save())
     			{
     				$trg_id = $trg->id;
     
     				$tr = new TaxRule();
     				$tr->id_tax_rules_group = $trg_id;
     				$tr->id_country = (int) $countryID;
     				$tr->id_state = 0;
     				$tr->id_tax = (int)$tax->id;				
     				$tr->state_behavior = 0;
     				$tr->save();
     			}
     		}*/
     $carrier = new Carrier();
     $carrier->name = 'dejala';
     $carrier->id_tax_rules_group = (int) $trg_id;
     $carrier->url = 'http://tracking.dejala.' . $dejalaConfig->country . '/tracker/@';
     $carrier->active = true;
     $carrier->deleted = 0;
     $carrier->shipping_handling = false;
     $carrier->range_behavior = 0;
     $carrier->is_module = 1;
     $carrier->external_module_name = 'dejala';
     $carrier->shipping_external = 1;
     $carrier->need_range = 0;
     $languages = Language::getLanguages(true);
     foreach ($languages as $language) {
         $carrier->delay[$language['id_lang']] = 'Dejala';
     }
     $carrier->add();
     $carrier->addZone((int) $id_zone);
     /*$sql = 'INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier` , `id_zone`) VALUES ('.(int)($carrier->id).', ' . (int)($id_zone) . ')';
     		Db::getInstance()->Execute($sql);
     
     		$rangeW = new RangeWeight();
     		$rangeW->id_carrier = $carrier->id;
     		$rangeW->delimiter1 = 0;
     		$rangeW->delimiter2 = $dejalaProduct['max_weight'];
     		$rangeW->add();
     		$vat_factor = (1+ ($dejalaProduct['vat'] / 100));
     		$priceTTC = round(($dejalaProduct['price']*$vat_factor) + $dejalaProduct['margin'], 2);
     		$priceHT = round($priceTTC/$vat_factor, 2);
     		$priceList = '(NULL'.','.$rangeW->id.','.$carrier->id.','.$id_zone.','.$priceHT.')';
     		$carrier->addDeliveryPrice($priceList);*/
     return true;
 }
 protected function _installTaxes($xml)
 {
     if (isset($xml->taxes->tax)) {
         $available_behavior = array(PS_PRODUCT_TAX, PS_STATE_TAX, PS_BOTH_TAX);
         $assoc_taxes = array();
         foreach ($xml->taxes->tax as $taxData) {
             $attributes = $taxData->attributes();
             if (Tax::getTaxIdByName($attributes['name'])) {
                 continue;
             }
             $tax = new Tax();
             $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = strval($attributes['name']);
             $tax->rate = (double) $attributes['rate'];
             $tax->active = 1;
             if (!$tax->validateFields()) {
                 $this->_errors[] = Tools::displayError('Invalid tax properties.');
                 return false;
             }
             if (!$tax->add()) {
                 $this->_errors[] = Tools::displayError('An error occurred while importing the tax: ') . strval($attributes['name']);
                 return false;
             }
             $assoc_taxes[(int) $attributes['id']] = $tax->id;
         }
         foreach ($xml->taxes->taxRulesGroup as $group) {
             $group_attributes = $group->attributes();
             if (!Validate::isGenericName($group_attributes['name'])) {
                 continue;
             }
             if (TaxRulesGroup::getIdByName($group['name'])) {
                 continue;
             }
             $trg = new TaxRulesGroup();
             $trg->name = $group['name'];
             $trg->active = 1;
             if (!$trg->save()) {
                 $this->_errors = Tools::displayError('This tax rule cannot be saved.');
                 return false;
             }
             foreach ($group->taxRule as $rule) {
                 $rule_attributes = $rule->attributes();
                 // Validation
                 if (!isset($rule_attributes['iso_code_country'])) {
                     continue;
                 }
                 $id_country = Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
                 if (!$id_country) {
                     continue;
                 }
                 if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes)) {
                     continue;
                 }
                 // Default values
                 $id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
                 $id_county = 0;
                 $state_behavior = 0;
                 $county_behavior = 0;
                 if ($id_state) {
                     if (isset($rule_attributes['state_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior)) {
                         $state_behavior = (int) $rule_attributes['state_behavior'];
                     }
                     if (isset($rule_attributes['county_name'])) {
                         $id_county = County::getIdCountyByNameAndIdState($rule_attributes['county_name'], (int) $id_state);
                         if (!$id_county) {
                             continue;
                         }
                     }
                     if (isset($rule_attributes['county_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior)) {
                         $county_behavior = (int) $rule_attributes['county_behavior'];
                     }
                 }
                 // Creation
                 $tr = new TaxRule();
                 $tr->id_tax_rules_group = $trg->id;
                 $tr->id_country = $id_country;
                 $tr->id_state = $id_state;
                 $tr->id_county = $id_county;
                 $tr->state_behavior = $state_behavior;
                 $tr->county_behavior = $county_behavior;
                 $tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
                 $tr->save();
             }
         }
     }
     return true;
 }
Example #27
0
 /**
  * Returns the default country Id
  *
  * @return integer default country id
  */
 public static function getDefaultCountryId()
 {
     global $cookie;
     if (Configuration::get('PS_GEOLOCATION_ENABLED') && $cookie && isset($cookie->iso_code_country) && Validate::isLanguageIsoCode($cookie->iso_code_country)) {
         $id_country = (int) Country::getByIso($cookie->iso_code_country);
     } else {
         $id_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
     }
     return $id_country;
 }
 protected function getPSAddress(Customer $customer, ShopgateAddress $shopgateAddress)
 {
     // Get country
     $id_country = Country::getByIso($shopgateAddress->getCountry());
     if (!$id_country) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_UNKNOWN_COUNTRY_CODE, 'Invalid country code:' . $id_country, true);
     }
     // Get state
     $id_state = 0;
     if ($shopgateAddress->getState()) {
         $id_state = (int) Db::getInstance()->getValue('SELECT `id_state` FROM `' . _DB_PREFIX_ . 'state` WHERE `id_country` = ' . $id_country . ' AND `iso_code` = \'' . pSQL(Tools::substr($shopgateAddress->getState(), 3, 2)) . '\'');
     }
     // Create alias
     $alias = Tools::substr('Shopgate_' . $customer->id . '_' . sha1($customer->id . '-' . $shopgateAddress->getFirstName() . '-' . $shopgateAddress->getLastName() . '-' . $shopgateAddress->getCompany() . '-' . $shopgateAddress->getStreet1() . '-' . $shopgateAddress->getStreet2() . '-' . $shopgateAddress->getZipcode() . '-' . $shopgateAddress->getCity()), 0, 32);
     // Try getting address id by alias
     $id_address = Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `alias` = \'' . pSQL($alias) . '\' AND `id_customer`=' . $customer->id);
     // Get or create address
     $address = new Address($id_address ? $id_address : null);
     if (!$address->id) {
         $address->id_customer = $customer->id;
         $address->id_country = $id_country;
         $address->id_state = $id_state;
         $address->country = Country::getNameById($this->id_lang, $address->id_country);
         $address->alias = $alias;
         $address->company = $shopgateAddress->getCompany();
         $address->lastname = $shopgateAddress->getLastName();
         $address->firstname = $shopgateAddress->getFirstName();
         $address->address1 = $shopgateAddress->getStreet1();
         $address->address2 = $shopgateAddress->getStreet2();
         $address->postcode = $shopgateAddress->getZipcode();
         $address->city = $shopgateAddress->getCity();
         $address->phone = $shopgateAddress->getPhone();
         $address->phone_mobile = $shopgateAddress->getMobile();
         if (!$address->add()) {
             throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create address', true);
         }
     }
     return $address;
 }
Example #29
0
 /**
  * Assign template vars related to countries display
  */
 protected function assignCountries()
 {
     // Get selected country
     if (Tools::isSubmit('id_country') && !is_null(Tools::getValue('id_country')) && is_numeric(Tools::getValue('id_country'))) {
         $selected_country = (int) Tools::getValue('id_country');
     } else {
         if (isset($this->_address) && isset($this->_address->id_country) && !empty($this->_address->id_country) && is_numeric($this->_address->id_country)) {
             $selected_country = (int) $this->_address->id_country;
         } else {
             if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
                 // get all countries as language (xy) or language-country (wz-XY)
                 $array = array();
                 preg_match("#(?<=-)\\w\\w|\\w\\w(?!-)#", $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
                 if (!Validate::isLanguageIsoCode($array[0]) || !($selected_country = Country::getByIso($array[0]))) {
                     $selected_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
                 }
             } else {
                 $selected_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
             }
         }
     }
     // Generate countries list
     if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
         $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
     } else {
         $countries = Country::getCountries($this->context->language->id, true);
     }
     // @todo use helper
     $list = '';
     foreach ($countries as $country) {
         $selected = $country['id_country'] == $selected_country ? 'selected="selected"' : '';
         $list .= '<option value="' . (int) $country['id_country'] . '" ' . $selected . '>' . htmlentities($country['name'], ENT_COMPAT, 'UTF-8') . '</option>';
     }
     // Assign vars
     $this->context->smarty->assign(array('countries_list' => $list, 'countries' => $countries));
 }
 private function generateEuropeTaxRule()
 {
     $euro_vat_array = self::$europe_vat_array;
     $euro_tax_rule_grp_id = TaxRulesGroup::getIdByName((string) $this->european_vat_name);
     if (!$euro_tax_rule_grp_id) {
         // Create it
         $trg = new TaxRulesGroup();
         $trg->name = (string) $this->european_vat_name;
         $trg->active = 1;
         if (!$trg->save()) {
             $this->_errors[] = Tools::displayError('Tax rule cannot be saved.');
             return false;
         }
         $euro_tax_rule_grp_id = (int) $trg->id;
     }
     $tax_rules_euro_group = TaxRule::getTaxRulesByGroupId((int) Context::getContext()->language->id, (int) $euro_tax_rule_grp_id);
     $euro_group_taxes_rules = array();
     foreach ($tax_rules_euro_group as $tax_rule) {
         $euro_group_taxes_rules[] = $tax_rule;
     }
     foreach ($euro_vat_array as $euro_vat_name => $euro_vat_details) {
         $posted_euro_vat = 'euro_vat_' . (string) $euro_vat_details['iso_country'];
         $posted_available_vat = 'available_vat_' . (string) $euro_vat_details['iso_country'];
         $country_id = Country::getByIso((string) $euro_vat_details['iso_country']);
         if (Tools::isSubmit($posted_euro_vat)) {
             if (!Tools::isSubmit($posted_available_vat)) {
                 $id_tax_found = Tax::getTaxIdByName((string) $euro_vat_name);
                 if ($id_tax_found !== false) {
                     $tax = new Tax((int) $id_tax_found);
                 } else {
                     $tax = new Tax();
                 }
                 $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = (string) $euro_vat_name;
                 $tax->rate = (double) $euro_vat_details['rate'];
                 $tax->active = 1;
                 if ($tax->validateFields(false, true) !== true || $tax->validateFieldsLang(false, true) !== true) {
                     $this->_errors[] = Tools::displayError('Invalid tax properties.');
                     continue;
                 }
                 if (!$tax->save()) {
                     $this->_errors[] = Tools::displayError('An error occurred while saving the tax: ');
                     continue;
                 }
                 $id_tax_rule = $this->getTaxRuleIdFromUnique($euro_tax_rule_grp_id, $country_id, $id_tax_found);
                 if ($id_tax_rule !== false) {
                     $tr = new TaxRule((int) $id_tax_rule);
                 } else {
                     $tr = new TaxRule();
                 }
                 $tr->id_tax_rules_group = (int) $euro_tax_rule_grp_id;
                 $tr->id_country = (int) $country_id;
                 $tr->id_state = 0;
                 $tr->id_county = 0;
                 $tr->zipcode_from = 0;
                 $tr->zipcode_to = 0;
                 $tr->behavior = 0;
                 $tr->description = '';
                 $tr->id_tax = (int) $tax->id;
                 $tr->save();
             } else {
                 $assoc_id_tax = (int) Tools::getValue($posted_available_vat);
                 $id_tax_rule = $this->getTaxRuleIdFromUnique($euro_tax_rule_grp_id, $country_id, $assoc_id_tax);
                 if ($id_tax_rule !== false) {
                     $tr = new TaxRule((int) $id_tax_rule);
                 } else {
                     $tr = new TaxRule();
                 }
                 $tr->id_tax_rules_group = (int) $euro_tax_rule_grp_id;
                 $tr->id_country = (int) $country_id;
                 $tr->id_state = 0;
                 $tr->id_county = 0;
                 $tr->zipcode_from = 0;
                 $tr->zipcode_to = 0;
                 $tr->behavior = 0;
                 $tr->description = '';
                 $tr->id_tax = (int) $assoc_id_tax;
                 $tr->save();
             }
         } else {
             $this->_errors[] = Tools::displayError('Invalid parameters received');
         }
     }
 }