AAAAPK %A\4 helpers/define.phpnu W+A set_language($HTTP_GET_VARS['language']);
} else {
$lng->get_browser_language();
}
$language = $lng->language['directory'];
$languages_id = $lng->language['id'];
$product_info_query = tep_db_query("select p.products_id, pd.products_name, pd.products_description, p.products_model, p.products_quantity, p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_date_available, p.manufacturers_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . (int)$mProductId . "' and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'");
$aProduct_info = tep_db_fetch_array($product_info_query);
$sArtNo = (MODULE_PAYMENT_KLARNA_ARTNO == 'id' || MODULE_PAYMENT_KLARNA_ARTNO == '' ? $aProduct_info['id'] : $aProduct_info['name']);
$iTax = tep_get_tax_rate($aProduct_info['products_tax_class_id']);
if(DISPLAY_PRICE_WITH_TAX == 'true') {
$iPrice_with_tax = $currencies->get_value($currency) * $aProduct_info['products_price'];
} else {
$iPrice_with_tax = $currencies->get_value($currency) * $aProduct_info['products_price'] * (($iTax/100)+1);
}
// Add goods
$this->oKlarna->addArticle(
1, //Quantity
$sArtNo, //Article number
$aProduct_info['products_name'], //Article name/title
$iPrice_with_tax, // Price
$iTax, //25% VAT
0, // Discount
KlarnaFlags::INC_VAT // Flag incl. excl vat
);
$this->iSum += $iPrice_with_tax;
}
/**
* When a purchase is made, the script returns an redirect-URL or a message. When the URL is returned, the user is re-directed to this page.
* This could be an URL to a downloadable file (WARNING! SHOULD ALWAYS BE A DYNAMIC URL!), or a link to a "Thank you"/confirmation page (Comon for donation purposes)
*
* @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality
* @return mixed Either NULL or FALSE if no URL is available, or STRING with full URL when URL is available.
*/
protected function fetchRedirectUrl ($mProductId) {
return "http://www.klarna.com";
}
/**
* When a purchase is made (approved as well) it might needs to be added to the merchants order system. In this function you can define how the order of a product should be handled.
*
* @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality
* @param integer $iKlarnaReference The reference returned by Klarna
* @param string $sTelNo The telephone number used to make a purchase
* @return void
*/
protected function processOrder ($mProductId, $iKlarnaReference, $iTelNo) {
// Here you should implement the functionality of how the product is managed.
}
}
PK %A\3m m helpers/klarnaapi.phpnu W+A sPath = $sPath;
if ($a_sLangISO == NULL) {
$aLangArray = array(
"swe" => "sv",
"deu" => "de",
"dnk" => "da",
"nld" => "nl",
"nor" => "nb",
"fin" => "fi",
"en" => "en");
$a_sLangISO = @$aLangArray[strtolower ($a_sCountry)];
}
// Set the klarna object
$this->oKlarna = &$a_oKlarna;
// Validate the submitted values
$this->setCountry ($a_sCountry);
$this->setLanguage ($a_sLangISO);
$this->validateType ($a_sType);
/*
// Set the default input names
$this->aInputParameters['street'] = "street";
$this->aInputParameters['homenumber'] = "homenumber";
$this->aInputParameters['paymentPlan'] = "paymentPlan";
$this->aInputParameters['gender'] = "gender";
$this->aInputParameters['male'] = "male";
$this->aInputParameters['female'] = "female";
$this->aInputParameters['birth_day'] = "birth_day";
$this->aInputParameters['birth_month'] = "birth_month";
$this->aInputParameters['birth_year'] = "birth_year";
$this->aInputParameters['bd_jan'] = "1";
$this->aInputParameters['bd_feb'] = "2";
$this->aInputParameters['bd_mar'] = "3";
$this->aInputParameters['bd_apr'] = "4";
$this->aInputParameters['bd_may'] = "5";
$this->aInputParameters['bd_jun'] = "6";
$this->aInputParameters['bd_jul'] = "7";
$this->aInputParameters['bd_aug'] = "8";
$this->aInputParameters['bd_sep'] = "9";
$this->aInputParameters['bd_oct'] = "10";
$this->aInputParameters['bd_nov'] = "11";
$this->aInputParameters['bd_dec'] = "12";
$this->aInputParameters['socialNumber'] = "socialNumber";
$this->aInputParameters['phoneNumber'] = "phoneNumber";
$this->aInputParameters['year_salary'] = "year_salary";
$this->aInputParameters['house_extension'] = "house_extension";
$this->aInputParameters['shipmentAddressInput'] = "shipment_address";
$this->aInputParameters['emailAddress'] = "emailAddress";
$this->aInputParameters['invoiceType'] = "invoiceType";
$this->aInputParameters['reference'] = "reference";
$this->aInputParameters['companyName'] = "companyName";
$this->aInputParameters['firstName'] = "firstName";
$this->aInputParameters['lastName'] = "lastName";
$this->aInputParameters['invoice_type'] = "invoice_type";
$this->aInputParameters['consent'] = "consent";
$this->aInputParameters['city'] = "city";
$this->aInputParameters['zipcode'] = "zipcode";
// Set the default setup values
$this->aSetupSettings['langISO'] = $this->sLangISO;
$this->aSetupSettings['countryCode'] = $this->sCountryCode;
$this->aSetupSettings['sum'] = $a_iSum;
$this->aSetupSettings['flag'] = $a_iFlag;
$this->aSetupSettings['payment_id'] = "payment";
$this->aSetupSettings['invoice_name'] = 'klarna_invoice';
$this->aSetupSettings['part_name'] = 'klarna_partPayment';
$this->aSetupSettings['spec_name'] = 'klarna_SpecCamp';
*/
// $this->aSetupSettings['web_root'] = "/";
//$this->setPaths();
//$this->country=$this->getCountry(); //??????
// Fetch PClasses in case type is invoice
if (($this->sType == 'part' || $this->sType == 'spec') && $this->oKlarna != NULL) {
$this->fetchPClasses ($a_iSum, $a_iFlag, $aTypes);
}
}
// public function setPaths() {
// $this->aSetupSettings['path_css'] = $this->aSetupSettings['web_root'].VMKLARNAPLUGINWEBROOT. '/klarna/assets/css/';
// $this->aSetupSettings['path_js'] = $this->aSetupSettings['web_root'] .VMKLARNAPLUGINWEBROOT. '/klarna/assets/js/';
// $this->aSetupSettings['path_img'] = $this->aSetupSettings['web_root'] .VMKLARNAPLUGINWEBROOT. '/klarna/assets/images/';
// }
/**
* Add/Overwrite extra setup values.
*
* @param string $sName The name of the value
* @param string $sValue The value
* @return void
* @deprecated
*/
public function addSetupValue ($sName, $sValue) {
$this->aSetupSettings[$sName] = $sValue;
}
/**
* Add multiple setup values at once
*
* @param array $aSetupValues The setup values as array. Key is name, value is value.
* @return void
* * @deprecated
*/
public function addMultipleSetupValues ($aSetupValues) {
foreach ($aSetupValues as $sName => $sValue) {
$this->aSetupSettings[$sName] = $sValue;
}
}
public function getSetupValues () {
return $this->aSetupSettings;
}
/**
* Add/Overwrite input values.
*
* @param string $sName The name of the value
* @param string $sValue The value
* @return void
* @deprecated
*/
public function addInputValue ($sName, $sValue) {
$this->aInputValue[$sName] = $sValue;
}
/**
* Add multiple input values at once
*
* @param array $aSetupValues The setup values as array. Key is name, value is value.
* @return void
*/
public function addMultipleInputValues ($aInputValues) {
foreach ($aInputValues as $sName => $sValue) {
$this->aInputValue[$sName] = $sValue;
}
}
/*
* * @deprecated
*/
public function getInputValues () {
return $this->aInputValues;
}
/*
* @deprecated
* */
public function setInvoiceFee ($fee) {
if ($this->sType != 'invoice') {
throw new KlarnaApiException("Invoice fee only supported when payment type is invoice");
}
$this->aSetupSettings['fee'] = round (floatval ($fee), 1);
}
/**
* Retrieve the finished HTML
*
* @param array $a_aParams The input field names. Only submitted for those that should be different from default values
* @param string $a_sHTMLFile (Optional) The file to import. If not submitted, which HTML file will be decides by the class
* @return string
* @deprecated
*/
public function retrieveHTML ($a_aParams = NULL, $a_aValues = NULL, $a_sHTMLFile = NULL, $aTemplateData = NULL) {
if ($a_aValues != NULL) {
$this->aInputValues = array_merge (
$this->aInputValues, $a_aValues);
}
if ($a_aParams != NULL) {
$this->aInputParameters = array_merge (
$this->aInputParameters, $a_aParams);
}
// print_r($this->aInputValues);
// Backwards compability
// using input values for red baloon is DEPRECATED
if (array_key_exists ('red_baloon_content', $this->aInputValues)) {
$this->aSetupSettings['red_baloon_content'] = $this->aInputValues['red_baloon_content'];
}
if (array_key_exists ('red_baloon_paymentBox', $this->aInputValues)) {
$this->aSetupSettings['red_baloon_paymentBox'] = $this->aInputValues['red_baloon_paymentBox'];
}
if (is_array ($this->aPClasses)) {
foreach ($this->aPClasses as $pclass) {
if ($pclass['default'] === TRUE) {
$this->aInputValues['paymentPlan'] = $pclass['pclass']->getId ();
break;
}
}
}
$sTemplate = $this->loadTemplate ($a_sHTMLFile, $aTemplateData);
Klarna::printDebug (__METHOD__ . ' setup settings', $this->aSetupSettings);
Klarna::printDebug (__METHOD__ . ' input values', $this->aInputValues);
return $this->translateInputFields ($sTemplate);
}
/**
* @param null $a_sHTMLFile
* @param null $aTemplateData
* @return string
* @deprecated
*/
public function loadTemplate ($a_sHTMLFile = NULL, $aTemplateData = NULL) {
$sFilename = '';
/**
* @todo Check for file and trow error if missing
*/
if ($a_sHTMLFile != NULL) {
$sFilename = $a_sHTMLFile;
}
else {
if ($this->sType != "spec") {
$sFilename = ($this->sPath != NULL ? $this->sPath : "") . "/klarna/tmpl/" . $this->sType . "_" . strtolower ($this->sCountryCode) . ".html";
}
else {
$this->aSetupSettings['conditionsLink'] = $aTemplateData['conditions'];
$sFilename = ($this->sPath != NULL ? $this->sPath : "") . '/klarna/tmpl/' . $this->sType . "_" . strtolower ($this->sCountryCode) . ".html";
}
}
Klarna::printDebug (__METHOD__ . 'loading template', $sFilename);
return file_get_contents ($sFilename);
}
/**
* Fetch the PClasses from file
*
* @param integer $iSum The sum of the objects to be bought
* @param integer $iFlag The KlarnaFlag to be used. Either Checkout or ProductPage flag.
* @return void
*/
public function fetchPClasses ($iSum, $iFlag, $aTypes = NULL) {
if ($this->oKlarna == NULL) {
throw new KlarnaApiException("No klarna class is set.", "1000");
}
$aPClasses = array();
$default = NULL;
foreach ($this->oKlarna->getPClasses () as $pclass) {
if ($aTypes == NULL || in_array ($pclass->getType (), $aTypes)) {
$sType = $pclass->getType ();
if ($sType != KlarnaPClass::SPECIAL) {
if ($iSum < $pclass->getMinAmount ()) {
continue;
}
if ($pclass->getType () == KlarnaPClass::FIXED) {
if ($iFlag == KlarnaFlags::PRODUCT_PAGE) {
continue;
}
$iMonthlyCost = -1;
}
else {
$lowest_payment = KlarnaCalc::get_lowest_payment_for_account ($pclass->getCountry ());
$iMonthlyCost = KlarnaCalc::calc_monthly_cost ($iSum, $pclass, $iFlag);
if ($iMonthlyCost < 0.01) {
continue;
}
if ($iFlag == KlarnaFlags::CHECKOUT_PAGE && $pclass->getType () == KlarnaPClass::ACCOUNT && $iMonthlyCost < $lowest_payment) {
$iMonthlyCost = $lowest_payment;
}
if ($pclass->getType () == KlarnaPClass::CAMPAIGN && $iMonthlyCost < $lowest_payment) {
continue;
}
}
}
else {
$iMonthlyCost = -1;
}
if ($this->sType == 'part') {
if ($sType == KlarnaPClass::ACCOUNT) {
$default = $pclass;
}
else {
if ($sType == KlarnaPClass::CAMPAIGN) {
if ($default === NULL || $default->getType () != KlarnaPClass::ACCOUNT) {
$default = $pclass;
}
}
else {
if ($sType == KlarnaPClass::FIXED) {
if ($default === NULL) {
$default = $pclass;
}
}
else {
continue;
}
}
}
}
else {
if ($this->sType == 'spec') {
if ($sType != KlarnaPClass::SPECIAL) {
continue;
}
$default = $pclass;
}
}
$aPClasses[$pclass->getId ()]['pclass'] = $pclass;
$aPClasses[$pclass->getId ()]['monthlyCost'] = $iMonthlyCost;
$aPClasses[$pclass->getId ()]['default'] = FALSE;
}
}
if ($default !== NULL) {
$aPClasses[$default->getId ()]['default'] = TRUE;
}
$this->aPClasses = $aPClasses;
}
/**
* Checks whether the country code is accepted by the API
*
* @throws KlarnaApiException
* @param string $sCountryCode The country code ISO-2
* @return boolean
*/
private function validateCountry ($sCountryCode) {
if (in_array (strtolower ($sCountryCode), array("nl", "se", "de", "dk", "no", "fi"))) {
$this->sCountryCode = strtolower ($sCountryCode);
switch ($this->sCountryCode) {
case "nl":
$this->iKlarnaCountry = KlarnaCountry::NL;
$this->iKlarnaCurrency = KlarnaCurrency::EUR;
break;
case "se":
$this->iKlarnaCountry = KlarnaCountry::SE;
$this->iKlarnaCurrency = KlarnaCurrency::SEK;
break;
case "de":
$this->iKlarnaCountry = KlarnaCountry::DE;
$this->iKlarnaCurrency = KlarnaCurrency::EUR;
break;
case "dk":
$this->iKlarnaCountry = KlarnaCountry::DK;
$this->iKlarnaCurrency = KlarnaCurrency::DKK;
break;
case "no":
$this->iKlarnaCountry = KlarnaCountry::NO;
$this->iKlarnaCurrency = KlarnaCurrency::NOK;
break;
case "fi":
$this->iKlarnaCountry = KlarnaCountry::FI;
$this->iKlarnaCurrency = KlarnaCurrency::EUR;
break;
default:
break;
}
return TRUE;
}
else {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid country code submitted!');
}
}
/**
* Checks whether the country code is accepted by the API
*
* @throws KlarnaApiException
* @param string $sType The type. Either "part", "spec" or "invoice"
* @return boolean
*/
private function validateType ($sType) {
if (in_array (strtolower ($sType), array("part", "invoice", "spec"))) {
$this->sType = strtolower ($sType);
return TRUE;
}
else {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid type submitted!');
}
}
/**
* Sets the active country from a ISO country string
* or a KlarnaCountry constant
*/
public function setCountry ($country) {
if (!is_numeric ($country)) {
$country = KlarnaCountry::fromCode ($country);
}
else {
$country = intval ($country);
}
if ($this->oKlarna == NULL) {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Klarna instance not set');
}
$this->iKlarnaCountry = $country;
$this->iKlarnaCurrency = $this->oKlarna->getCurrencyForCountry ($country);
$this->sCountryCode = $this->oKlarna->getCountryCode ($country);
}
public function getCountry () {
return $this->iKlarnaCountry;
}
/**
* Sets the active country from a ISO country string
* or a KlarnaLanguage constant
*/
public function setLanguage ($language) {
if (!is_numeric ($language)) {
$language = Klarna::getLanguageForCode ($language);
}
else {
$language = intval ($language);
}
$this->iKlarnaLanguage = $language;
if ($this->oKlarna == NULL) {
throw new KlarnaApiException('Error in ' . __METHOD__ .
': Klarna instance not set');
}
$this->sLangISO = $this->oKlarna->getLanguageCode ($language);
}
public function getLanguage () {
return $this->iKlarnaLanguage;
}
/**
* Checks whether the country code is accepted by the API
*
* @throws KlarnaApiException
* @param string $a_sLangISO The language in ISO-2 format
* @return boolean
* @deprecated
*/
private function validateLangISO ($a_sLangISO) {
if (in_array (strtolower ($a_sLangISO), array("sv", "da", "en", "de", "nl", "nb", "fi"))) {
$this->sLangISO = strtolower ($a_sLangISO);
switch ($this->sLangISO) {
case "sv":
$this->iKlarnaLanguage = KlarnaLanguage::SV;
break;
case "da":
$this->iKlarnaLanguage = KlarnaLanguage::DA;
break;
case "de":
$this->iKlarnaLanguage = KlarnaLanguage::DE;
break;
case "nl":
$this->iKlarnaLanguage = KlarnaLanguage::NL;
break;
case "nb":
$this->iKlarnaLanguage = KlarnaLanguage::NB;
break;
case "fi":
$this->iKlarnaLanguage = KlarnaLanguage::FI;
break;
default:
break;
}
return TRUE;
}
else {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid language (' . $a_sLangISO . ') ISO submitted!');
}
}
/**
* Translating the fetched HTML agains dynamic values set in this class
*
* @param string $sHtml The HTML to translate
* @return string
*/
private function translateInputFields ($sHtml) {
$sHtml = preg_replace_callback ("@{{(.*?)}}@", array($this, 'changeText'), $sHtml);
return $sHtml;
}
/**
* Changing the text from a HTML {{VALUE}} to the actual value decided by the array
*
* @param array $aText The result from the match in function translateInputFields
* @return mixed
* @deprecated
*/
private function changeText ($aText) {
// Split them
$aExplode = explode (".", $aText[1]);
$sType = $aExplode[0];
$sName = @$aExplode[1];
if ($sType == "input") {
if (array_key_exists ($sName, $this->aInputParameters)) {
return $this->aInputParameters[$sName];
}
else {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid inputfield value (' . $sName . ') found in HTML code!');
}
}
else {
if ($sType == "lang") {
return JText::_ ('VMPAYMENT_KLARNA_' . strtoupper ($sName)); //$this->fetchFromLanguagePack($sName);
}
else {
if ($sType == "setup") {
if ($sName == "pclasses") {
return $this->renderPClasses ();
}
if ($sName == 'threatmetrix') {
if (!array_key_exists ('threatmetrix', $this->aSetupSettings)) {
$this->aSetupSettings['threatmetrix'] = $this->oKlarna->
checkoutHTML ();
}
return @$this->aSetupSettings['threatmetrix'];
}
if ($sName == 'additional_information') {
$key = @$this->aSetupSettings['additional_information'];
$key = 'VMPAYMENT_KLARNA_' . strtoupper ($key);
$lang = JFactory::getLanguage ();
if ($lang->hasKey ($key)) {
$frmt = @JText::_ ($key); //$this->fetchFromLanguagePack($key);
return @$this->translateInputFields ($frmt);
}
else {
return '';
}
}
return @$this->aSetupSettings[$sName];
}
else {
if ($sType == "value") {
return (@$this->aInputValues[$sName]);
}
else {
throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid field name (' . $sType . ') found in HTML code!');
}
}
}
}
}
/**
* Redender the PClasses to HTML
*
* @deprecated
*
* @return string
*/
public function renderPClasses () {
$sString = '';
foreach ($this->aPClasses as $sPClassId => $aPClassData) {
$value = $this->getPresentableValuta ($aPClassData['monthlyCost']);
$pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH');
$sString .= '
' . $aPClassData['pclass']->getDescription () .
($aPClassData['monthlyCost'] > 0 ?
" - $value $pm" : '') .
($aPClassData['default'] ?
'
' :
'') .
'
' . $sPClassId . '
';
}
return $sString;
}
/**
* Redender the PClasses to HTML
*
* @return string
*/
public function getPClassesInfo () {
$pClasses = array();
$i = 0;
foreach ($this->aPClasses as $sPClassId => $aPClassData) {
$value = $this->getPresentableValuta ($aPClassData['monthlyCost']);
$pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH');
$pClasses[$i]['class'] = $aPClassData['default'] ? 'id="click"' : "";
$sString = $aPClassData['pclass']->getDescription () .
($aPClassData['monthlyCost'] > 0 ?
" - $value $pm" : '') .
($aPClassData['default'] ?
' ' :
'');
$pClasses[$i]['string'] = $sString;
$pClasses[$i]['classId'] = $sPClassId;
$i++;
}
return $pClasses;
}
/**
* Redender the PClasses to HTML
*
* @return string
*/
public function renderPClass ($pid) {
$sString = "";
foreach ($this->aPClasses as $sPClassId => $aPClassData) {
if ($aPClassData['pclass']->getId () == $pid) {
$value = $this->getPresentableValuta ($aPClassData['monthlyCost']);
$pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH');
$sString .= $aPClassData['pclass']->getDescription () . ($aPClassData['monthlyCost'] > 0 ? " - $value $pm" : '');
return $sString;
}
}
return $sString;
}
/**
* Make the sum shown presentable
*
* @param integer $iSum The sum to present
* @return string
*/
/* private */
function getPresentableValuta ($iSum) {
$sBefore = "";
$sAfter = "";
switch (strtolower($this->sCountryCode)) {
case 'se':
$sAfter = " kr";
break;
case 'no':
$sAfter = " NOK";
break;
case 'dk':
$sAfter = " DKK";
break;
case 'fi';
$sBefore = "EUR";
break;
case 'de';
case 'nl';
$sBefore = "€";
break;
}
return $sBefore . $iSum . $sAfter;
}
public function setCurrency ($currency) {
if (!is_numeric ($currency)) {
$currency = KlarnaCurrency::fromCode ($currency);
}
else {
$currency = intval ($currency);
}
switch ($currency) {
case KlarnaCurrency::SEK:
case KlarnaCurrency::NOK:
case KlarnaCurrency::DKK:
$this->addSetupValue ('currency_suffix', ' kr');
$this->addSetupValue ('currency_prefix', '');
break;
case KlarnaCurrency::EUR:
$this->addSetupValue ('currency_prefix', '€');
$this->addSetupValue ('currency_suffix', '');
break;
default:
$this->addSetupValue ('currency_suffix', '');
$this->addSetupValue ('currency_prefix', '');
break;
}
}
/**
* Fetch data from the language pack
*
* @param string $sText The text to fech
* @param null $sISO
* @param null $sPath
* @return string
* @deprecated
*/
public function fetchFromLanguagePack ($sText, $sISO = NULL, $sPath = NULL) {
if ($sISO == NULL) {
if ($this != NULL && $this->sLangISO != NULL) {
$sISO = strtolower ($this->sLangISO);
}
else {
$sISO = KlarnaAPI::getISOCode ();
}
}
else {
$sISO = KlarnaAPI::getISOCode ($sISO);
}
if ($this->sPath != NULL) {
$sPath = $this->sPath;
}
if ($this->languagePack == NULL) {
$this->languagePack = new KlarnaLanguagePack(JPATH_VMKLARNAPLUGIN . '/klarna/language/klarna_language.xml');
}
return $this->languagePack->fetch ($sText, $sISO);
}
/**
* Returns the country code for the set country constant.
*
* @return string
*/
public function getISOCode ($sCode = NULL) {
switch (strtolower ($sCode)) {
case "se":
case "sv":
return "sv";
case "no":
case "nb":
return "nb";
case "dk":
case "da":
return "da";
case "fi":
return "fi";
case "de":
return "de";
case "nl":
return "nl";
case "us":
case "uk":
case "en":
default:
return "en";
}
}
public function displayError ($message, $field = NULL) {
// Append message
if (array_key_exists ('red_baloon_content', $this->aSetupSettings)) {
$this->aSetupSettings['red_baloon_content'] =
$this->aSetupSettings['red_baloon_content'] .
' ' . $message;
}
else {
$this->aSetupSettings['red_baloon_content'] = $message;
}
// fall back to logo on multiple messages
if (array_key_exists ('red_baloon_paymentBox', $this->aSetupSettings)) {
$this->aSetupSettings['red_baloon_paymentBox'] = '';
}
else {
$this->aSetupSettings['red_baloon_paymentBox'] = $field;
}
}
/**
*
* @param $address
* @return
*/
public static function splitAddress ($address) {
$numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$characters = array(
'-', '/', ' ', '#', '.', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z');
$specialchars = array('-', '/', ' ', '#', '.');
//Where do the numbers start? Allow for leading numbers
$numpos = self::strpos_arr ($address, $numbers, 2);
//Get the streetname by splitting off the from the start of the numbers
$streetname = substr ($address, 0, $numpos);
//Strip off spaces at the end
$streetname = trim ($streetname);
//Get the housenumber+extension
$numberpart = substr ($address, $numpos);
//and strip off spaces
$numberpart = trim ($numberpart);
//Get the start position of the extension
$extpos = self::strpos_arr ($numberpart, $characters, 0);
//See if there is one, if so
if ($extpos != '') {
//get the housenumber
$housenumber = substr ($numberpart, 0, $extpos);
// and the extension
$houseextension = substr ($numberpart, $extpos);
// and strip special characters from it
$houseextension = str_replace ($specialchars, '', $houseextension);
}
else {
//Otherwise, we already have the housenumber
$housenumber = $numberpart;
}
return array($streetname, $housenumber, $houseextension);
}
/**
*
* @param $haystack
* @param $needle
* @param $where
* @return
*/
private static function strpos_arr ($haystack, $needle, $where) {
$defpos = 10000;
if (!is_array ($needle)) {
$needle = array($needle);
}
foreach ($needle as $what) {
if (($pos = strpos ($haystack, $what, $where)) !== FALSE) {
if ($pos < $defpos) {
$defpos = $pos;
}
}
}
return $defpos;
}
public function setAddress (KlarnaAddr $addr) {
if (!$addr instanceof KlarnaAddr) {
throw new KlarnaApiException(__METHOD__ . ': must be passed a KlarnaAddr');
}
$reference = @($addr->getFirstName () . ' ' . $addr->getLastName ());
$cellno = $addr->getCellno ();
$telno = $addr->getTelno ();
$phone = (strlen ($cellno) > 0) ? $cellno : $telno;
$values = &$this->aInputValues;
$values['firstName'] = $addr->getFirstName ();
$values['lastName'] = $addr->getLastName ();
$values['phoneNumber'] = $phone;
$values['zipcode'] = $addr->getZipCode ();
$values['city'] = $addr->getCity ();
$values['street'] = $addr->getStreet ();
$values['homenumber'] = $addr->getHouseNumber ();
$values['house_extension'] = $addr->getHouseExt ();
$values['reference'] = $reference;
}
/**
* Given a ISO 8601 date string (YYYY-MM-DD) sets birth_year, birth_month
* and birth_day
*/
public function setBirthday ($dob) {
$splitbday = explode ('-', $dob);
$values['birth_year'] = @$splitbday[0];
$values['birth_month'] = @$splitbday[1];
$values['birth_day'] = @$splitbday[2];
}
}
/**
* KlarnaApiException class, only used so it says "KlarnaApiException" instead of Exception.
*
* @package Klarna Standard Kassa API
* @author Paul Peelen
* @version 1.0
* @since 1.0 - 14 mar 2011
* @link http://integration.klarna.com/
* @copyright Copyright (c) 2011 Klarna AB (http://klarna.com)
*/
class KlarnaApiException extends Exception {
public function __construct ($sMessage, $code = 0) {
parent::__construct ($sMessage, $code);
}
public function __toString () {
return __CLASS__ . ":[Error: {$this->code}]: {$this->message}
\n";
}
}
PK %A\`/ / helpers/klarna_payments.phpnu W+A shipTo = $shipTo;
$this->country = $cData['country_code'];
$this->country_code_3 = $cData['country_code_3'];
$this->currency = $cData['currency_code'];
$this->virtuemart_currency_id = $cData['virtuemart_currency_id'];
//$this->currency = $vendor_currency;
// Get EID and Secret
$this->eid = $cData['eid'];
$this->secret = $cData['secret'];
$this->lang = $cData['language_code'];
// Is Invoice enabled?
$this->enabled = TRUE;
// Set modes
$this->mode = $cData['mode'];
$this->ssl = KlarnaHandler::getKlarnaSSL ($this->mode);
$this->web_root = JURI::base ();
try {
$this->klarna = new Klarna_virtuemart();
$this->klarna->config ($this->eid, $this->secret, $this->country, $this->lang, $this->currency, $this->mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $this->ssl);
}
catch (Exception $e) {
VmError ('klarna_payments', $e);
unset($this->klarna);
}
}
/**
* Attempt to fill in some of what we've already filled in if we
* come back after failing a purchase.
*/
private function setPreviouslyFilledIn ($klarna_data) {
if (($this->country == "nl" ) && isset($klarna_data['pno'])) {
$pno = $klarna_data['pno'];
$this->klarna_bday['year'] = substr ($pno, 4, 4);
$this->klarna_bday['month'] = substr ($pno, 2, 2);
$this->klarna_bday['day'] = substr ($pno, 0, 2);
}
elseif ( $this->country == "de") {
$pno = $klarna_data['pno'];
$this->klarna_bday['year'] = $klarna_data['birth_year'];
$this->klarna_bday['month'] = $klarna_data['birth_month'];
$this->klarna_bday['day'] = $klarna_data['birth_day'];
} else {
$this->socialNumber=$klarna_data['socialNumber'];
}
$this->klarna_street = ((isset($klarna_data['street']) &&
!isset($this->klarna_street)) ? $klarna_data['street'] :
$this->klarna_street);
$this->klarna_houseNr = ((isset($klarna_data['house_no']) &&
!isset($this->klarna_houseNr)) ? $klarna_data['house_no'] :
$this->klarna_houseNr);
$this->klarna_houseExt = ((isset($klarna_data['house_ext']) &&
!isset($this->klarna_houseExt)) ? $klarna_data['house_ext'] :
$this->klarna_houseExt);
$this->klarna_gender = ((isset($klarna_data['gender']) &&
!isset($this->klarna_gender)) ? $klarna_data['gender'] :
$this->klarna_gender);
$this->klarna_year_salary = ((isset($klarna_data['year_salary']) && !isset($this->klarna_year_salary)) ? $klarna_data['year_salary'] : $this->klarna_year_salary);
}
/**
* Build the Payment params
*/
public function get_payment_params ($method, $payment_type, $cart = NULL, $country_currency_code = '', $vendor_currency='') {
if (!class_exists ('CurrencyDisplay')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
}
if (!class_exists ('KlarnaAPI')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php');
}
$payment_params = array();
$invoice_fee = 0;
if (!isset($this->klarna) || !($this->klarna instanceof Klarna_virtuemart)) {
return NULL;
}
$payment_params['payment_currency_info'] = "";
if ($cart->pricesCurrency != $this->virtuemart_currency_id) {
$payment_params['payment_currency_info'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_CURRENCY_INFO');
}
if ($payment_type == 'invoice') {
KlarnaHandler::getInvoiceFeeInclTax ($method, $this->country_code_3, $cart->pricesCurrency, $this->virtuemart_currency_id, $display_invoice_fee, $invoice_fee);
$billTotalInCountryCurrency = 0;
$aTypes = NULL;
$payment_params['pClasses'] = NULL;
} else {
$display_fee = 0;
$billTotalInCountryCurrency = 0;
if (isset($cart->pricesUnformatted['billTotal'])) {
$billTotalInCountryCurrency = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $vendor_currency, $country_currency_code, $cart->pricesCurrency);
}
if ($billTotalInCountryCurrency <= 0) {
return NULL;
}
//$aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN, KlarnaPClass::FIXED);
$aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN);
}
$payment_params['sType'] = $payment_type;
$kCheckout = new KlarnaAPI($this->country, $this->lang, $payment_type, $billTotalInCountryCurrency, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, $aTypes, JPATH_VMKLARNAPLUGIN);
if ($payment_type == 'invoice') {
if ($invoice_fee) {
$payment_params['module'] = JText::sprintf ('VMPAYMENT_KLARNA_INVOICE_TITLE', $display_invoice_fee);
} else {
$payment_params['module'] = JText::_ ('VMPAYMENT_KLARNA_INVOICE_TITLE_NO_PRICE');
}
$payment_params['pClasses'] = NULL;
$payment_params['id'] = 'klarna_invoice';
} elseif ($payment_type == 'part') {
KlarnaHandler::getCheapestPclass ($kCheckout, $cheapest, $minimum);
if ($billTotalInCountryCurrency < $minimum) {
return NULL;
}
if (!class_exists ('VirtueMartModelCurrency')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php');
}
// Cheapest is in the Klarna country currency, convert it to the current currency display
//$currencyDisplay = CurrencyDisplay::getInstance( );
//$countryCurrencyId = $this->virtuemart_currency_id;
//$sFee = $currencyDisplay->priceDisplay($cheapest, 0, 1,false);
$sFee = $kCheckout->getPresentableValuta ($cheapest);
$payment_params['module'] = JText::sprintf ('VMPAYMENT_KLARNA_PARTPAY_TITLE', $sFee);
$payment_params['pClasses'] = $kCheckout->getPClassesInfo ();
$payment_params['id'] = 'klarna_partPayment';
}
else {
$pclasses = $kCheckout->aPClasses;
if (empty($pclasses)) {
return NULL;
}
$payment_params['module'] = JText::_ ('VMPAYMENT_KLARNA_SPEC_TITLE');
$payment_params['pClasses'] = $kCheckout->getPClassesInfo ();
$payment_params['id'] = 'klarna_SpecCamp';
}
$payment_params['payment_link'] = "https://online.klarna.com/villkor.yaws?eid=" . $this->eid . "&charge=" . $invoice_fee;
if (strtolower ($this->country) == 'de') {
$vendor_id = 1;
$payment_params['agb_link'] = JRoute::_ ('index.php?option=com_virtuemart&view=vendor&layout=tos&virtuemart_vendor_id=' . $vendor_id);
}
//$lang = KlarnaHandler::getLanguageForCountry($method, $this->country);
$symbol = KlarnaHandler::getCurrencySymbolForCountry ($method, $this->country);
if (KlarnaHandler::getKlarnaError ($klarnaError, $klarnaOption)) {
if ($klarnaOption == 'klarna_' . $payment_type) {
$payment_params['red_baloon_content'] = $klarnaError;
$payment_params['red_baloon_paymentBox'] = 'klarna_box_' . $klarnaOption;
//KlarnaHandler::clearKlarnaError ();
}
}
// Something went wrong, refill what we can.
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
if (!empty($sessionKlarna)) {
$sessionKlarnaData = unserialize ($sessionKlarna);
if (isset($sessionKlarnaData->KLARNA_DATA)) {
$klarnaData = $sessionKlarnaData->KLARNA_DATA;
$this->setPreviouslyFilledIn ($klarnaData);
}
}
$payment_params['paymentPlan'] = '';
if (is_array ($kCheckout->aPClasses)) {
foreach ($kCheckout->aPClasses as $pclass) {
if ($pclass['default'] === TRUE) {
$payment_params['paymentPlan'] = $pclass['pclass']->getId ();
break;
}
}
}
if ($payment_type != "spec") {
//$payment_params['conditionsLink'] = $aTemplateData['conditions'];
}
$payment_params['fields'] = $this->shipTo;
$payment_params['payment_id'] = 'virtuemart_paymentmethod_id';
$payment_params['checkout'] = $this->klarna->checkoutHTML ();
$payment_params['eid'] = $this->eid;
$payment_params['year_salary'] = $this->klarna_year_salary;
$payment_params['agreement_link'] = $this->payment_charge_link;
$payment_params['sum'] = $invoice_fee;
$payment_params['fee'] = $invoice_fee;
$payment_params['invoice_fee'] = $invoice_fee;
$payment_params['langISO'] = $this->lang;
$payment_params['countryCode'] = $this->country;
$payment_params['flag'] = KlarnaFlags::CHECKOUT_PAGE;
$payment_params['payment_id'] = "payment";
$payment_params['invoice_name'] = 'klarna_invoice';
$payment_params['part_name'] = 'klarna_partPayment';
$payment_params['spec_name'] = 'klarna_SpecCamp';
$payment_params['fields']['socialNumber'] = isset($this->socialNumber)?$this->socialNumber:"";
return $payment_params;
}
/**
* Build the Payment params
*/
public function getCheapestMonthlyCost ($cart = NULL, $cData) {
if (!class_exists ('CurrencyDisplay')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
}
if (!class_exists ('KlarnaAPI')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php');
}
if (!isset($this->klarna) || !($this->klarna instanceof Klarna_virtuemart)) {
return NULL;
}
$display_fee = 0;
$billTotalInCountryCurrency = 0;
if (isset($cart->pricesUnformatted['billTotal'])) {
$billTotalInCountryCurrency = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $cData['vendor_currency'], $cData['virtuemart_currency_id'], $cart->pricesCurrency);
}
if ($billTotalInCountryCurrency <= 0) {
return NULL;
}
$aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN);
$kCheckout = new KlarnaAPI($this->country, $this->lang, 'part', $billTotalInCountryCurrency, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, $aTypes, JPATH_VMKLARNAPLUGIN);
KlarnaHandler::getCheapestPclass ($kCheckout, $cheapest, $minimum);
vmdebug('getCheapestMonthlyCost',$cart->pricesUnformatted['billTotal'], $billTotalInCountryCurrency , $cheapest,$minimum);
if ($billTotalInCountryCurrency < $minimum) {
return NULL;
}
if (!class_exists ('VirtueMartModelCurrency')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php');
}
$sFee = $kCheckout->getPresentableValuta ($cheapest);
return $sFee;
}
/**
* @return string
*/
public function getTermsLink () {
return 'https://static.klarna.com/external/html/' . KLARNA_SPECIAL_CAMPAIGN . '_' . strtolower ($this->country) . '.html';
}
/**
* @param $pid
* @param $totalSum
* @return string
*/
function displayPclass ($pid, $totalSum) {
if (!class_exists ('KlarnaAPI')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php');
}
$kCheckout = new KlarnaAPI($this->country, $this->lang, 'part', $totalSum, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN, KlarnaPClass::FIXED), JPATH_VMKLARNAPLUGIN);
return $kCheckout->renderPClass ($pid);
}
}
PK %A\:/ / helpers/index.htmlnu W+A
PK %A\BU} helpers/klarna_virtuemart.phpnu W+A VERSION = 'PHP'.phpversion().':2.0.26d';
Klarna::$debug = false;
}
}
PK %A\UZ6 6 helpers/klarna_productprice.phpnu W+A path = JPATH_VMKLARNAPLUGIN . '/klarna/';
if (!class_exists ('ShopFunctions')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php');
}
$this->cData = $cData;
//$this->currencyId = ShopFunctions::getCurrencyIDByName($this->cData['currency_code']);
//vmdebug ('klarna_productPrice', $this->cData);
try {
$this->klarna_virtuemart = new Klarna_virtuemart();
$this->klarna_virtuemart->config ($this->cData['eid'], $this->cData['secret'], $this->cData['country'], $this->cData['language'], $this->cData['currency'], $this->cData['mode'], VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), FALSE);
}
catch (Exception $e) {
vmDebug ('klarna_productPrice', $e->getMessage (), $e->getFile() , $e->getLine(), $this->cData);
vmError ('klarna_productPrice', 'klarna_productPrice: '.$e->getMessage (). " country:".$this->cData['country_code_3'] );
unset($this->klarna);
}
}
/**
* @param $product
* @return bool
*/
private function showPP ($product, $cart) {
if (!isset($this->klarna_virtuemart) || !($this->klarna_virtuemart instanceof Klarna_virtuemart)) {
return FALSE;
}
if (!VMKLARNA_SHOW_PRODUCTPRICE) {
vmDebug ('Klarna: showPP', 'dont show price because VMKLARNA_SHOW_PRODUCTPRICE');
return FALSE;
}
// the price is in the vendor currency
// convert price in NLD currency= euro
$price = KlarnaHandler::convertPrice ($product->prices['salesPrice'], $this->cData['vendor_currency'], 'EUR', $cart->pricesCurrency);
if (strtolower ($this->cData['country_code']) == 'nl' && !KlarnaHandler::checkNLpriceCondition ($price )) {
vmDebug ('showPP', 'dont show price for NL', $this->cData['country_code'], $price);
return FALSE;
}
if ($price <= $this->cData['min_amount'] AND !empty($this->cData['min_amount'])) {
return FALSE;
}
return TRUE;
}
/**
* @param $product
* @return array|null
*/
public function showProductPrice ($product, $cart) {
if (!$this->showPP ($product, $cart)) {
return NULL;
}
$viewData = $this->getViewData ($product);
return $viewData;
}
/**
* @param $product
* @return array|null
*/
private function getViewData ($product) {
if (!class_exists ('KlarnaAPI')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php');
}
if (!class_exists ('VirtueMartModelCurrency')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php');
}
$price = $product->prices['salesPrice'];
$country = $this->cData['country'];
$lang = $this->cData['language_code'];
$types = array(KlarnaPClass::CAMPAIGN, KlarnaPClass::ACCOUNT, KlarnaPClass::FIXED);
try {
$kCheckout = new KlarnaAPI($country, $lang, 'part', $price, KlarnaFlags::PRODUCT_PAGE, $this->klarna_virtuemart, $types, $this->path);
}
catch(Exception $e) {
VmDebug('getViewData','Error in ' . __METHOD__ . ': ' . $e->getMessage(), $e->getCode());
VmError( $e->getMessage(), 'getViewData'.'Error in ' . __METHOD__ . ': ' . $e->getMessage(), $e->getCode());
return NULL;
}
$kCheckout->setCurrency ($this->cData['currency']);
// TODO : Not top to get setup values here!
$this->settings = $kCheckout->getSetupValues ();
if ($price > 0 && count ($kCheckout->aPClasses) > 0) {
$currencydisplay = CurrencyDisplay::getInstance ();
$sMonthDefault = NULL;
$sTableHtml = "";
$monthTable = array();
// either in vendor's currency, or shipTo Currency
$countryCurrencyId = $this->cData['virtuemart_currency_id'];
$currency = CurrencyDisplay::getInstance ($countryCurrencyId);
$fromCurrency = $currency->getCurrencyForDisplay ();
//$paymentCurrency = CurrencyDisplay::getInstance($this->cart->paymentCurrency);
//$totalInPaymentCurrency = $paymentCurrency->priceDisplay( $this->cart->pricesUnformatted['billTotal'],$this->cart->paymentCurrency) ;
//$currencyDisplay = CurrencyDisplay::getInstance($this->cart->pricesCurrency);
$i = 0;
foreach ($kCheckout->aPClasses as $pclass) {
if ($sMonthDefault === NULL || $pclass['monthlyCost'] < $sMonthDefault) {
$sMonthDefault = $currency->priceDisplay ($pclass['monthlyCost'], $countryCurrencyId);
}
if ($pclass['pclass']->getType () == KlarnaPClass::ACCOUNT) {
$pp_title = JText::_ ('VMPAYMENT_KLARNA_PPBOX_ACCOUNT');
}
else {
$pp_title = $pclass['pclass']->getMonths () . " " . JText::_ ('VMPAYMENT_KLARNA_PPBOX_TH_MONTH');
}
$pp_price = $currency->priceDisplay ($pclass['monthlyCost'], $countryCurrencyId);
$monthTable[$i] = array(
'pp_title' => html_entity_decode ($pp_title),
'pp_price' => $pp_price,
'country' => $country);
$i++;
}
$cd = CurrencyDisplay::getInstance ($fromCurrency);
$aInputValues = array();
$aInputValues['defaultMonth'] = $sMonthDefault;
$aInputValues['monthTable'] = $monthTable;
$aInputValues['eid'] = $this->cData['eid'];
$aInputValues['country'] = KlarnaCountry::getCode ($country);
if ($country == KlarnaCountry::DE) {
$aInputValues['asterisk'] = '*';
}
else {
$aInputValues['asterisk'] = '';
}
return $aInputValues;
}
return NULL;
}
}
PK %A\) helpers/.htaccessnu W+A
Order allow,deny
Deny from all
PK %A\Y# # helpers/impl.klarna_mobile.phpnu W+A oKlarna = &$oKlarna;
$this->sTemplate = $sTemplate;
$this->sPath = $sPath;
$this->sCountryCode = $sCountry;
$this->sLangISO = 'sv';
}
/**
* Fetches the product and adds it as an article to the klarna class. No need to return any data.
* Articles need to be set for fraud purpose, incorrect article means no_risk invoice. Hereby klarna will not take any risks.
*
* @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality
* @param Klarna $oKlarna The Klarna class object. Used to set any articles
* @return void
*/
abstract protected function fetchProduct($mProductId);
/**
* When a purchase is made, the script returns an redirect-URL or a message. When the URL is returned, the user is re-directed to this page.
* This could be an URL to a downloadable file (WARNING! SHOULD ALWAYS BE A DYNAMIC URL!), or a link to a "Thank you"/confirmation page (Comon for donation purposes)
*
* @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality
* @return mixed Either NULL or FALSE if no URL is available, or STRING with full URL when URL is available.
*/
abstract protected function fetchRedirectUrl ($mProductId);
/**
* When a purchase is made (approved as well) it might needs to be added to the merchants order system. In this function you can define how the order of a product should be handled.
*
* @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality
* @param integer $iKlarnaReference The reference returned by Klarna
* @param string $sTelNo The telephone number used to make a purchase
* @return void
*/
abstract protected function processOrder ($mProductId, $iKlarnaReference, $iTelNo);
/**
* Fetch the HTML from the template theme
*
* @return string The HTML completed as string
*/
public function retrieveHTML () {
// Get template
$sTemplate = ($this->sPath != null ? $this->sPath : "") . '/html/mobile/' . $this->sTemplate . "/" . strtolower($this->sCountryCode) . "/template.html";
return $this->translateInputFields(file_get_contents($sTemplate));
}
/**
* Adding an input value
*
* @param string $sParamName The name of an paramteter to set
* @param mixed $mParamValue The value of the parameter
* @return void
*/
public function addInput ($sParamName, $mParamValue) {
$this->aInputParameters[$sParamName] = $mParamValue;
}
/**
* Translating the fetched HTML agains dynamic values set in this class
*
* @param string $sHtml The HTML to translate
* @return string
*/
private function translateInputFields ($sHtml) {
$sHtml = preg_replace_callback("@{{(.*?)}}@", array($this, 'changeText'), $sHtml);
return $sHtml;
}
/**
* Changeing the text from a HTML {{VALUE}} to the acual value decided by the array
*
* @param array $aText The result from the match in function translateInputFields
* @return mixed
*/
private function changeText ($aText) {
// Split them
$aExplode = explode(".", $aText[1]);
$sType = $aExplode[0];
$sName = $aExplode[1];
if ($sType == "input")
{
if (array_key_exists($sName, $this->aInputParameters))
return $this->aInputParameters[$sName];
else
{
throw new KlarnaMobileApiException('Error in ' . __METHOD__ . ': Invalid inputfield value ('.$sName.') found in HTML code!');
return false;
}
}
else if($sType == "lang")
{
return JText::_($sName); //$this->fetchFromLanguagePack($sName);
}
else if($sType == "setup")
{
return @$this->aSetupSettings[$sName];
}
else if ($sType == "value")
{
return @$this->aInputValues[$sName];
}
else {
throw new KlarnaMobileApiException('Error in ' . __METHOD__ . ': Invalid field name ('.$sType.') found in HTML code!');
return false;
}
}
/**
* Fetch data from the language pack
*
* @param string $sText The text to fech
* @return string
*/
public function fetchFromLanguagePack ($sText) {
if ($this != null && $this->sLangISO != null)
$sISO = strtolower($this->sLangISO);
else
$sISO = KlarnaAPI::getISOCode();
$oXml = simplexml_load_file($this->sPath . '/klarna_files/klarna_language.xml');
$aResult= (array)@$oXml->xpath("//string[@id='$sText']/$sISO");
$aResult= (array)@$aResult[0];
return @$aResult[0];
}
/**
* Request the code for the mobile phone
*
* @param string $sTelNo The telephone number
* @param int $iSum The sum to request
* @return mixed BOOLEAN true if success, message or exception if error
*/
public function requestCode ($iPid, $sTelNo) {
$this->sTelNo = $sTelNo;
try {
$this->fetchProduct($iPid);
//Transmit all the specified data, from the steps above, to Klarna.
$aResult = $this->oKlarna->reserveAmount(
$this->sTelNo,
null,
$this->iSum,
KlarnaFlags::RSRV_PHONE_TRANSACTION+KlarnaFlags::RSRV_SEND_PHONE_PIN,
-1
);
return $this->translateSuccesToXml($aResult[0], $aResult[1]);
}
catch(Exception $e) {
return $this->translateErrorToXML($e->getCode(), utf8_encode($e->getMessage()));
}
}
/**
* Request the code for the mobile phone
*
* @param string $sTelNo The telephone number
* @param int $iSum The sum to request
* @return mixed BOOLEAN true if success, message or exception if error
*/
public function makePurchase ($iPid, $sTelNo, $sPinCode, $iRefNo) {
$this->sTelNo = $sTelNo;
try {
$this->fetchProduct($iPid);
$this->oKlarna->setExtraInfo('pin', $sPinCode);
$aResult = $this->oKlarna->activateReservation(
$this->sTelNo,
$iRefNo,
null,
null,
KlarnaFlags::RSRV_PHONE_TRANSACTION+KlarnaFlags::RSRV_SEND_PHONE_PIN,
-1
);
$sUrl = $this->fetchRedirectUrl($iPid);
$this->processOrder($iPid, $iRefNo, $sTelNo);
array_push($aResult, $sUrl);
return $aResult;
}
catch(Exception $e) {
return array("-1", utf8_encode($e->getMessage()), $e->getCode());
}
}
private function translateErrorToXML ($iError, $sErrorMessage) {
$sReturn = <<
-1
$iError
$sErrorMessage
EOD;
return $sReturn;
}
private function translateSuccesToXml ($iStatusCode, $sMessage) {
$sReturn = <<
$iStatusCode
$sMessage
EOD;
return $sReturn;
}
}
/**
* KlarnaMobileApiException class.
*
* @package Klarna Standard Kassa API
* @version 1.0
* @since 1.0 - 14 mar 2011
* @link http://integration.klarna.com/
* @copyright Copyright (c) 2011 Klarna AB (http://klarna.com)
*/
class KlarnaMobileApiException extends Exception
{
public function __construct($sMessage, $code=0, Exception $previous = null)
{
parent::__construct($sMessage,$code, $previous);
}
public function __toString()
{
return __CLASS__ . ":[Error: {$this->code}]: {$this->message}
\n";
}
}PK %A\T0 0 helpers/klarna_ajax.phpnu W+A api = $api;
$this->eid = $eid;
$this->path = $path;
$this->coSetup = array();
}
/**
* @param $template
*/
public function __setTemplate($template) {
if (is_array($template)) {
$this->template = array_merge($this->template, $template);
} else {
$this->template['name'] = $template;
}
}
/**
* @param $arr
*/
public function __addSetupValues($arr) {
if (is_array($arr)) {
$this->coSetup = array_merge($this->coSetup, $arr);
}
}
/**
* @return null
* @throws KlarnaApiException
*/
public function languagepack() {
$sSubAction = JRequest::getWord('subAction');
if (!isset($this->template['name']) || $this->template['name'] == '') {
$this->template['name'] = "default";
}
if ($sSubAction == "klarna_box") {
$sNewISO = JRequest::getWord('newIso');
$sCountry = JRequest::getWord('country');
$iSum = JRequest::getFloat('sum', 0);
$iInvoiceFee = JRequest::getFloat('fee', 0);
$iFlag = JRequest::getInt('flag');
$sType = JRequest::getWord('type');
$aParams = JRequest::getVar('params');
$aValues = JRequest::getVar('values');
// foreach($aValues as $key => $value) {
// $aValues[$key] = utf8_encode($value);
// }
// foreach($aParams as $key => $value) {
// $aParams[$key] = utf8_decode($value);
// }
if ($sType != "part" && $sType != "invoice" && $sType != "spec") {
throw new KlarnaApiException("Invalid parameters");
}
$this->api->setCountry($sCountry);
if ($sType == 'spec') {
$types = array(KlarnaPClass::SPECIAL);
} else {
$types = array(KlarnaPClass::CAMPAIGN, KlarnaPClass::ACCOUNT, KlarnaPClass::FIXED);
}
$oApi = new KlarnaAPI ($sCountry, $sNewISO, $sType, $iSum, $iFlag, $this->api, $types, VMKLARNAPLUGINWEBROOT);
// $oApi->addSetupValue ('web_root', $this->webroot);
// $oApi->setPaths ();
$oApi->addSetupValue('eid', $this->eid);
if ($sType == 'invoice') {
$oApi->setInvoiceFee($iInvoiceFee);
}
$oApi->setCurrency($this->api->getCurrency());
if (count($this->coSetup) > 0) {
$oApi->addMultipleSetupValues($this->coSetup);
}
return $oApi->retrieveLayout($aParams, $aValues);
// if ($sType == 'spec') {
// return $oApi->retrieveHTML($aParams, $aValues, null, $this->template);
// } else {
// return $oApi->retrieveHTML ($aParams, $aValues);
// }
}
else {
if ($sSubAction == 'jsLanguagePack') {
$sNewISO = JRequest::getWord('newIso');
$sFetch = "";
}
else {
throw new KlarnaApiException("Invalid sub-action");
}
}
}
public
function getAddress() {
$aSessionCalls = array();
// Check the session for calls
if (array_key_exists('klarna_address', $_SESSION)) {
$sSessionCalls = base64_decode($_SESSION['klarna_address']);
$aSessionCalls = unserialize($sSessionCalls);
}
$sPNO = JRequest::getWord('socialNumber'); //JRequest::getWord('pno');
$sCountry = strtolower(JRequest::getWord('country'));
if (array_key_exists($sPNO, $aSessionCalls)) {
$addrs = $aSessionCalls[$sPNO];
}
else {
$addrs = $this->api->getAddresses($sPNO, NULL, KlarnaFlags::GA_GIVEN);
$aSessionCalls[$sPNO] = $addrs;
$_SESSION['klarna_address'] = base64_encode(serialize($aSessionCalls));
}
$sString = "\n"; //eval breaks at question-mark gt
$sString .= "\n";
//This example only works for GA_GIVEN.
foreach ($addrs as $index => $addr) {
if ($addr->isCompany) {
$implode = array(
'companyName' => $addr->getCompanyName(),
'street' => $addr->getStreet(),
'zip' => $addr->getZipCode(),
'city' => $addr->getCity(),
'countryCode' => $addr->getCountryCode()
);
}
else {
$implode = array(
'first_name' => $addr->getFirstName(),
'last_name' => $addr->getLastName(),
'street' => $addr->getStreet(),
'zip' => $addr->getZipCode(),
'city' => $addr->getCity(),
'countryCode' => $addr->getCountryCode()
);
}
$sString .= "\n";
foreach ($implode as $key => $val) {
$sString .= "<" . $key . ">" . Klarna::num_htmlentities($val) . "" . $key . ">\n";
}
$sString .= " \n";
}
$sString .= " ";
return array(
'type' => 'text/xml',
'value' => $sString);
}
}
PK %A\r4 helpers/klarnahandler.phpnu W+A array(
'pno_encoding' => 3,
'language' => 97,
'language_code' => 'nb',
'country' => 164,
'currency' => 1,
'currency_code' => 'NOK',
'currency_symbol' => 'kr',
'country_code' => 'no'),
'SWE' => array(
'pno_encoding' => 2,
'language' => 138,
'language_code' => 'sv',
'country' => 209,
'country_code' => 'se',
'currency' => 0,
'currency_code' => 'SEK',
'currency_symbol' => 'kr'),
'DNK' => array(
'pno_encoding' => 5,
'language' => 27,
'language_code' => 'da',
'country' => 59,
'country_code' => 'dk',
'currency' => 3,
'currency_code' => 'DKK',
'currency_symbol' => 'kr',
),
'FIN' => array(
'pno_encoding' => 4,
'language' => 37,
'language_code' => 'fi',
'country' => 73,
'country_code' => 'fi',
'currency' => 2,
'currency_code' => 'EUR',
'currency_symbol' => '€'
),
'NLD' => array(
'pno_encoding' => 7,
'language' => 101,
'language_code' => 'nl',
'country' => 154,
'country_code' => 'nl',
'currency' => 2,
'currency_code' => 'EUR',
'currency_symbol' => '€',
),
'DEU' => array(
'pno_encoding' => 6,
'language' => 28,
'language_code' => 'de',
'country' => 81,
'country_code' => 'de',
'currency' => 2,
'currency_code' => 'EUR',
'currency_symbol' => '€'
));
return $countriesData;
}
/**
* @static
* @param $method
* @param $country
* @return array|null
*/
static function countryData ($method, $country) {
$countriesData = self::countriesData ();
$lower_country = strtolower ($country);
if (array_key_exists (strtoupper ($country), $countriesData)) {
$cData = $countriesData[strtoupper ($country)];
$eid = 'klarna_merchantid_' . $lower_country;
$secret = 'klarna_sharedsecret_' . $lower_country;
$invoice_fee = 'klarna_invoicefee_' . $lower_country;
$min_amount = 'klarna_min_amount_part_' . $lower_country;
$payment_activated = 'klarna_payments_' . $lower_country;
$active = 'klarna_active_' . $lower_country;
$cData['eid'] = $method->$eid;
$cData['secret'] = $method->$secret;
$cData['invoice_fee'] = (double)$method->$invoice_fee;
$cData['country_code_3'] = $country;
$cData['virtuemart_currency_id'] = ShopFunctions::getCurrencyIDByName ($cData['currency_code']);
$cData['virtuemart_country_id'] = ShopFunctions::getCountryIDByName ($country);
$cData['mode'] = KlarnaHandler::getKlarnaMode ($method, $country);
$cData['min_amount'] = $method->$min_amount;
$cData['active'] = $method->$active;
if (empty($method->$payment_activated)){
$method->$payment_activated=array('invoice', 'part');
}
$cData['payments_activated'] = $method->$payment_activated;
if (!class_exists ('VirtueMartModelVendor')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php');
}
$vendor_id = 1;
$cData['vendor_currency'] = VirtueMartModelVendor::getVendorCurrency ($vendor_id)->vendor_currency;
return $cData;
} else {
return NULL;
}
}
/**
* @static
* @param $method
* @param $country
* @return array|null
*/
public static function getCountryData ($method, $country) {
//$country = self::convertToThreeLetterCode($country);
return self::countryData ($method, $country);
}
/**
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function convertCountry ($method, $country) {
$country_data = self::countryData ($method, $country);
return $country_data['country_code'];
}
/**
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function getLanguageForCountry ($method, $country) {
$country = self::convertToThreeLetterCode ($country);
$country_data = self::countryData ($method, $country);
return $country_data['language_code'];
}
/**
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function getCurrencySymbolForCountry ($method, $country) {
$country_data = self::countryData ($method, $country);
return $country_data['currency_symbol'];
}
/**
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function getInvoiceFee ($method, $country) {
$invoice_fee = 'klarna_invoicefee_' . strtolower ($country);
return $method->$invoice_fee;
}
/**
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function getInvoiceTaxId ($method, $country) {
$invoice_fee_tax = 'klarna_invoice_tax_id_' . strtolower ($country);
return $method->$invoice_fee_tax;
}
/**
* The invoice fee is in the vendor currency, and should be converted to the payment currency
*
* @static
* @param $method
* @param $country
* @return mixed
*/
public static function getInvoiceFeeInclTax ($method, $country, $cartPricesCurrency, $cartPaymentCurrency, &$display_invoice_fee, &$invoice_fee) {
$method_invoice_fee = self::getInvoiceFee ($method, $country);
$invoice_tax_id = self::getInvoiceTaxId ($method, $country);
vmdebug ('getInvoiceFeeInclTax', $cartPaymentCurrency, $invoice_fee);
if (!class_exists ('calculationHelper')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php');
}
if (!class_exists ('CurrencyDisplay')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
}
if (!class_exists ('VirtueMartModelVendor')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php');
}
$vendor_id = 1;
$vendor_currency = VirtueMartModelVendor::getVendorCurrency ($vendor_id);
//$currency = CurrencyDisplay::getInstance ();
$paymentCurrency = CurrencyDisplay::getInstance ($cartPaymentCurrency);
$invoice_fee = (double)round ($paymentCurrency->convertCurrencyTo ($cartPaymentCurrency, $method_invoice_fee, FALSE), 2);
$currencyDisplay = CurrencyDisplay::getInstance ($cartPricesCurrency);
$paymentCurrency = CurrencyDisplay::getInstance ($cartPaymentCurrency);
$display_invoice_fee = $paymentCurrency->priceDisplay ($method_invoice_fee, $cartPaymentCurrency);
$currencyDisplay = CurrencyDisplay::getInstance ($cartPricesCurrency);
vmdebug ('getInvoiceFeeInclTax', $cartPaymentCurrency, $invoice_fee, $invoice_tax_id, $display_invoice_fee);
return;
}
/*
* @depredecated
*/
/**
* @static
* @param $country
* @return string
*/
public static function convertToThreeLetterCode ($country) {
switch (strtolower ($country)) {
case "se":
return "swe";
case "de":
return "deu";
case "dk":
return "dnk";
case "nl":
return "nld";
case "fi":
return "fin";
case "no":
return "nor";
default:
return $country;
}
}
/**
* @static
* @return array
*/
public static function getKlarnaCountries () {
$klarna_countries = array("swe", "deu", "dnk", "nld", "fin", "nor");
return $klarna_countries;
}
/**
* @static
* @return array
*/
static function getDataFromEditPayment () {
VmConfig::loadJLang('com_virtuemart_shoppers', true);
$kIndex = 'klarna_';
$klarna['klarna_paymentmethod'] = JRequest::getVar ($kIndex . 'paymentmethod');
if ($klarna['klarna_paymentmethod'] == 'klarna_invoice') {
$klarna_option = 'invoice';
} elseif ($klarna['klarna_paymentmethod'] == 'klarna_partPayment') {
$klarna_option = 'part';
} elseif ($klarna['klarna_paymentmethod'] == 'klarna_speccamp') {
$klarna_option = 'spec';
} else {
return NULL;
}
$prefix=$klarna_option . '_' . $kIndex ;
//Removes spaces, tabs, and other delimiters.
$klarna['pno'] = preg_replace ('/[ \t\,\.\!\#\;\:\r\n\v\f]/', '', JRequest::getVar ($prefix . 'pnum', ''));
$klarna['socialNumber'] = preg_replace ('/[ \t\,\.\!\#\;\:\r\n\v\f]/', '', JRequest::getVar ($prefix . 'socialNumber'));
$klarna['phone'] = JRequest::getVar ($prefix . 'phone');
$klarna['email'] = JRequest::getVar ($prefix . 'emailAddress');
$klarna['street'] = JRequest::getVar ($prefix . 'street');
$klarna['house_no'] = JRequest::getVar ($prefix . 'homenumber');
$klarna['house_ext'] = JRequest::getVar ($prefix . 'house_extension');
$klarna['year_salary'] = JRequest::getVar ($prefix . 'ysalary');
$klarna['reference'] = JRequest::getVar ($prefix . 'reference');
$klarna['city'] = JRequest::getVar ($prefix . 'city');
$klarna['zip'] = JRequest::getVar ($prefix . 'zipcode');
$klarna['first_name'] = JRequest::getVar ($prefix . 'firstName');
$klarna['last_name'] = JRequest::getVar ($prefix . 'lastName');
$klarna['invoice_type'] = JRequest::getVar ('klarna_invoice_type');
$klarna['company_name'] = JRequest::getVar ('klarna_company_name');
$klarna['phone'] = JRequest::getVar ($prefix . 'phone');
$klarna['consent'] = JRequest::getVar ($prefix . 'consent');
$klarna['gender'] = JRequest::getVar ($prefix . 'gender');
switch ($klarna['gender']) {
case KlarnaFlags::MALE :
$klarna['title'] = JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR');
break;
case KlarnaFlags::FEMALE:
//$this->klarna_gender = KlarnaFlags::FEMALE;
$klarna['title'] = JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS');
break;
}
$klarna['birth_day'] = JRequest::getVar ($prefix . 'birth_day', '');
$klarna['birth_month'] = JRequest::getVar ($prefix . 'birth_month', '');
$klarna['birth_year'] = JRequest::getVar ($prefix . 'birth_year', '');
if (isset($klarna['birth_year']) and !empty($klarna['birth_year'])) {
// due to the select list
if ($klarna['birth_month'] != 0 and $klarna['birth_month'] != 0) {
$klarna['birthday'] = $klarna['birth_year'] . "-" . $klarna['birth_month'] . "-" . $klarna['birth_day'];
$klarna['pno_frombirthday'] = JRequest::getVar ($prefix . 'birth_day') .
JRequest::getVar ($prefix . 'birth_month') .
JRequest::getVar ($prefix . 'birth_year');
} else {
$klarna['birthday'] = '';
}
} else {
$klarna['birthday'] = '';
}
return $klarna;
}
/**
* @static
* @param $cData
* @param $order
* @return KlarnaAddr
*/
private static function getBilling ($cData, $order) {
$bt = $order['BT'];
$bill_country = shopFunctions::getCountryByID ($bt['virtuemart_country_id'], 'country_2_code');
//$cData = self::countryData($method, $country);
$bill_street = $bt['address_1'];
$bill_ext = "";
$bill_number = "";
if (strtolower ($bill_country) == "de" || strtolower ($bill_country) == "nl") {
$splitAddress = array('', '', '');
$splitAddress = self::splitAddress ($bt['address_1']);
$bill_street = $splitAddress[0];
$bill_number = $splitAddress[1];
switch ($bt['title']) {
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR'):
//$this->klarna_gender = KlarnaFlags::MALE;
break;
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MISS'):
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS'):
//$this->klarna_gender = KlarnaFlags::FEMALE;
break;
default:
//$this->klarna_gender = NULL;
break;
}
if (strtolower ($bill_country) == "nl") {
$bill_ext = $splitAddress[2];
}
}
$billing = new KlarnaAddr(
$bt['email'],
$bt['phone_1'],
@$bt['phone_2'],
utf8_decode ($bt['first_name']),
utf8_decode ($bt['last_name']), '',
utf8_decode ($bill_street),
$bt['zip'],
utf8_decode ($bt['city']),
$bill_country,
$bill_number,
$bill_ext
);
return $billing;
}
/**
* @static
* @param $method
* @param $order
* @param $klarna_pclass
* @return array|bool
* @throws Exception
*/
public static function addTransaction ($method, $order, $klarna_pclass) {
if (!class_exists ('KlarnaAddr')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnaaddr.php');
}
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
$sessionKlarnaData = unserialize ($sessionKlarna);
if (!isset($sessionKlarnaData)) {
throw new Exception("No klarna Session data set");
}
$klarnaData = $sessionKlarnaData->KLARNA_DATA;
if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) {
$shipTo = $order['details']['BT'];
} else {
$shipTo = (!isset($order['details']['ST']) or empty($order['details']['ST']) or count ($order['details']['ST']) == 0) ? $order['details']['BT'] : $order['details']['ST'];
}
$billTo = $order['details']['BT'];
$country = shopFunctions::getCountrybyID ($shipTo->virtuemart_country_id, 'country_3_code');
$cData = self::countryData ($method, $country);
//$total_price_excl_vat = self::convertPrice($order['details']['BT']->order_subtotal, $cData['currency_code']);
//$total_price_incl_vat = self::convertPrice($order['details']['BT']->order_subtotal + $order['details']['BT']->order_tax, $cData['currency_code'], $order['details']['BT']->order_currency);
$mode = KlarnaHandler::getKlarnaMode ($method, $cData['country_code_3']);
$ssl = KlarnaHandler::getKlarnaSSL ($mode);
// Instantiate klarna object.
$klarna = new Klarna_virtuemart();
$klarna->config ($cData['eid'], $cData['secret'], $cData['country_code'], $cData['language'], $cData['currency_code'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $ssl);
// Sets order id's from other systems for the upcoming transaction.
$klarna->setEstoreInfo ($order['details']['BT']->order_number);
// Fill the good list the we send to Klarna
foreach ($order['items'] as $item) {
if ($item->product_basePriceWithTax!=0.0) {
if ( $item->product_basePriceWithTax != $item->product_final_price) {
$price= $item->product_basePriceWithTax;
} else {
$price= $item->product_final_price;
}
} else {
if ( $item->product_priceWithoutTax != $item->product_item_price) {
$price= $item->product_item_price;
} else {
$price= $item->product_discountedPriceWithoutTax;
}
}
$item_price = self::convertPrice ($price, $order['details']['BT']->order_currency, $cData['currency_code']);
$item_price = (double)(round ($item_price, 2));
$item_tax_percent=0;
foreach ($order['calc_rules'] as $calc_rule) {
if ($calc_rule->virtuemart_order_item_id==$item->virtuemart_order_item_id AND $calc_rule->calc_kind== 'VatTax') {
$item_tax_percent=$calc_rule->calc_value;
break;
}
}
//$item_discount_percent = (double)(round (abs (($item->product_subtotal_discount / $item->product_quantity) * 100 / $price), 2));
$item_discount_percent=0.0;
$discount_tax_percent=0.0;
$klarna->addArticle ($item->product_quantity, utf8_decode ($item->order_item_sku), utf8_decode (strip_tags ($item->order_item_name)), $item_price, (double)$item_tax_percent, $item_discount_percent, KlarnaFlags::INC_VAT);
$discount_tax_percent=0.0;
$includeVat=KlarnaFlags::INC_VAT;
if ($item->product_subtotal_discount != 0.0) {
if ($item->product_subtotal_discount > 0.0) {
$discount_tax_percent=$item_tax_percent;
$includeVat=0;
}
$name=utf8_decode (strip_tags ($item->order_item_name)). ' ('.JText::_('VMPAYMENT_KLARNA_PRODUCTDISCOUNT'). ')';
$discount = self::convertPrice (abs($item->product_subtotal_discount), $order['details']['BT']->order_currency, $cData['currency_code']);
$discount = (double)(round (abs($discount), 2)) * -1 ;
$klarna->addArticle (1, utf8_decode ($item->order_item_sku), $name, $discount, (double)$discount_tax_percent, $item_discount_percent, $includeVat);
}
}
// this is not correct yet
/*
foreach($order['calc_rules'] as $rule){
if ($rule->calc_kind == 'DBTaxRulesBill' or $rule->calc_kind == 'taxRulesBill' or $rule->calc_kind == 'DATaxRulesBill') {
$klarna->addArticle (1, "", $rule->calc_rule_name, $rule->calc_amount, 0.0, 0.0, 0);
}
}
*/
// Add shipping
$shipment = self::convertPrice ($order['details']['BT']->order_shipment + $order['details']['BT']->order_shipment_tax, $order['details']['BT']->order_currency, $cData['currency_code']);
foreach ($order['calc_rules'] as $calc_rule) {
if ($calc_rule->calc_kind== 'shipment') {
$shipment_tax_percent=$calc_rule->calc_value;
break;
}
}
$klarna->addArticle (1, "shippingfee", JText::_ ('VMPAYMENT_KLARNA_SHIPMENT'), ((double)(round (($shipment), 2))), round ($shipment_tax_percent, 2), 0, KlarnaFlags::IS_SHIPMENT + KlarnaFlags::INC_VAT);
// Add invoice fee
if ($klarna_pclass == -1) { //Only for invoices!
$payment_without_tax = self::convertPrice ($order['details']['BT']->order_payment, $order['details']['BT']->order_currency, $cData['currency_code']);
$payment_with_tax = self::convertPrice ($order['details']['BT']->order_payment + $order['details']['BT']->order_payment_tax, $order['details']['BT']->order_currency, $cData['currency_code']);
foreach ($order['calc_rules'] as $calc_rule) {
if ( $calc_rule->calc_kind== 'payment') {
$payment_tax_percent=$calc_rule->calc_value;
break;
}
}
if ($payment_without_tax > 0) {
//vmdebug('invoicefee', $payment, $payment_tax);
$klarna->addArticle (1, "invoicefee", utf8_decode(JText::_ ('VMPAYMENT_KLARNA_INVOICE_FEE_TITLE')), ((double)(round (($payment_with_tax), 2))), (double)round ($payment_tax_percent, 2), 0, KlarnaFlags::IS_HANDLING + KlarnaFlags::INC_VAT);
}
}
// Add coupon if there is any
if (abs ($order['details']['BT']->coupon_discount) > 0.0) {
$coupon_discount = self::convertPrice (round ($order['details']['BT']->coupon_discount), $order['details']['BT']->order_currency, $cData['currency_code']);
$coupon_discount =(double)(round (abs($coupon_discount), 2)) * -1 ;
//vmdebug('discount', $coupon_discount);
$klarna->addArticle (1, 'discount',utf8_decode(JText::_ ('VMPAYMENT_KLARNA_DISCOUNT')) . ' ' . utf8_decode($order['details']['BT']->coupon_code), $coupon_discount , 0, 0, KlarnaFlags::INC_VAT);
}
try {
$klarna_shipping = new KlarnaAddr(
$order['details']['BT']->email,
$shipTo->phone_1,
isset($shipTo->phone_2) ? $shipTo->phone_2 : "",
utf8_decode ($shipTo->first_name),
utf8_decode ($shipTo->last_name), '',
utf8_decode ($shipTo->address_1),
$shipTo->zip,
utf8_decode ($shipTo->city),
utf8_decode ($cData['country']),
KlarnaHandler::setHouseNo (isset($shipTo->house_no) ? $shipTo->house_no : "", $cData['country_code_3']),
KlarnaHandler::setAddress2 ($shipTo->address_2, $cData['country_code_3'])
);
}
catch (Exception $e) {
VmInfo ($e->getMessage ());
return FALSE;
}
$klarna_reference = ""; // what is that?
if ($klarnaData['invoice_type'] == 'company') {
$klarna_shipping->isCompany = TRUE;
$klarna_shipping->setCompanyName ($shipTo->company);
$klarna_comment = $shipTo->first_name . ' ' . $shipTo->last_name; //$klarnaData['reference'];
if ($klarna_shipping->getLastName () == "") {
$klarna_shipping->setLastName ("-");
}
if ($klarna_shipping->getFirstName () == "") {
$klarna_shipping->setFirstName ("-");
}
} else {
$klarna_reference = "";
$klarna_comment = "";
}
// Only allow billing and shipping to be the same for Germany and the Netherlands
if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) {
$klarna_billing = $klarna_shipping;
} else {
$klarna_billing = self::getBilling ($cData, $order);
}
$klarna_flags = KlarnaFlags::RETURN_OCR; // get ocr back from KO.
$klarna->setComment ($klarna_comment);
$klarna->setReference ($klarna_reference, "");
$pno = self::getPNOfromSession ($sessionKlarnaData->KLARNA_DATA, $country);
try {
$klarna->setAddress (KlarnaFlags::IS_SHIPPING, $klarna_shipping);
$klarna->setAddress (KlarnaFlags::IS_BILLING, $klarna_billing);
if (isset($klarnaData['year_salary'])) {
$klarna->setIncomeInfo ("'yearly_salary'", $klarnaData['year_salary']);
}
$result = $klarna->addTransaction ($pno, ($klarna->getCountry () == KlarnaCountry::DE || $klarna->getCountry () == KlarnaCountry::NL) ? $klarnaData['gender'] : NULL, $klarna_flags, $klarna_pclass);
$result['eid'] = $cData['eid'];
$result['status_code'] = $result[2];
$result['status_text'] = JText::_ ('VMPAYMENT_KLARNA_ORDER_STATUS_TEXT_' . $result[2]);
return $result; //return $result;
}
catch (Exception $e) {
$result['status_code'] = KlarnaFlags::DENIED;
$result['status_text'] = mb_convert_encoding ($e->getMessage (), 'UTF-8', 'ISO-8859-1'). " (#" . $e->getCode () . ")";
return $result; //return $result;
//self::redirectPaymentMethod('error', htmlentities($e->getMessage()) . " (#" . $e->getCode() . ")");
}
}
private static function setAddress2 ($address2, $country) {
if ($country == 'NLD') {
return $address2;
} else {
return NULL;
}
}
private static function setHouseNo ($houseNo, $country) {
if (($country == 'DEU') or ($country == 'NLD')) {
return $houseNo;
} else {
return NULL;
}
}
/**
* Returns a collection of addresses that are connected to the
* supplied SSN
*
* @param $pno The SSN of the user. This method is only available
* for swedish customers
* @return array
*/
public static function getAddresses ($pno, $settings, $method) {
// Only available for sweden.
$addresses = array();
$klarna = new Klarna_virtuemart();
$mode = KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']);
$klarna->config ($settings['eid'], $settings['secret'], KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $mode);
try {
$addresses = $klarna->getAddresses ($pno, NULL, KlarnaFlags::GA_GIVEN);
}
catch (Exception $e) {
// the message is returned NOT in UTF-8
$msg = mb_convert_encoding ($e->getMessage (), 'UTF-8', 'ISO-8859-1');
VmInfo ($msg);
}
unset($klarna);
return $addresses;
}
/**
* @static
* @param $method
* @return array
*/
public static function fetchAllPClasses ($method) {
$message = '';
$success = '';
$results = array();
$countries = self::getKlarnaCountries ();
$pc_type = KlarnaHandler::getKlarna_pc_type ();
if (empty($pc_type)) {
return FALSE;
} else {
// delete the file directly
if (file_exists ($pc_type)) {
unlink ($pc_type);
}
}
foreach ($countries as $country) {
$active_country = "klarna_active_" . $country;
if ($method->$active_country) {
// country is CODE 3==> converting to 2 letter country
//$country = self::convertCountryCode($method, $country);
$lang = self::getLanguageForCountry ($method, $country);
$flagImg = JURI::root (TRUE) . '/administrator/components/com_virtuemart/assets/images/flag/' . strtolower ($lang) . '.png';
$flag = " ";
try {
$settings = self::getCountryData ($method, $country);
$klarna = new Klarna_virtuemart();
$klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']), VMKLARNA_PC_TYPE, $pc_type, TRUE);
$klarna->fetchPClasses ($country);
$success .= shopFunctions::getCountryByID ($settings['virtuemart_country_id']);
}
catch (Exception $e) {
$message .= $flag . " " . shopFunctions::getCountryByID ($settings['virtuemart_country_id']) .
": " . $e->getMessage () . ' Error Code #' .
$e->getCode () . '';
}
}
}
$results['msg'] = $message;
$results['notice'] = $success;
return $results;
//echo $notice;
}
static function createKlarnaFolder () {
$safePath = VmConfig::get ('forSale_path', '');
if ($safePath) {
$exists = JFolder::exists ($safePath . 'klarna');
if (!$exists) {
$created = JFolder::create ($safePath . 'klarna');
if ($created) {
return TRUE;
}
} else {
return TRUE;
}
}
$uri = JFactory::getURI ();
$link = $uri->root () . 'administrator/index.php?option=com_virtuemart&view=config';
VmError (JText::sprintf ('VMPAYMENT_KLARNA_CANNOT_STORE_CONFIG', '' . $link . ' ', JText::_ ('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH')));
return FALSE;
}
/**
* Redirects user to payment method stage.
*
* @param $type e.g. 'error', ...
* @param $message
*/
public static function redirectPaymentMethod ($type = NULL, $message = NULL) {
$log = utf8_encode ($message);
//Display the error.
if (strlen ($log) > 0) {
if ($type === NULL) {
$type = 'message';
}
$app = JFactory::getApplication ();
$app->enqueueMessage (JText::_ (urldecode ($log)), $type);
}
//Redirect to previous page.
$session = JFactory::getSession ();
$sessionKlarna = new stdClass();
$sessionKlarna->klarna_error = addslashes ($message);
$session->set ('Klarna', serialize ($sessionKlarna), 'vm');
if (isset($_SESSION['klarna_paymentmethod'])) {
$pid = $_SESSION['klarna_paymentmethod'];
unset($_SESSION['klarna_paymentmethod']);
}
//$_SESSION['klarna_error'] = addslashes($message);
$app = JFactory::getApplication ();
$app->enqueueMessage ($message);
$app->redirect (JRoute::_ ('index.php?option=com_virtuemart&view=cart',FALSE), JText::_ ('COM_VIRTUEMART_CART_ORDERDONE_DATA_NOT_VALID'));
}
/**
*
* @param $address
* @return
*/
public static function splitAddress ($address) {
$numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$characters = array(
'-', '/', ' ', '#', '.', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z');
$specialchars = array('-', '/', ' ', '#', '.');
//Where do the numbers start? Allow for leading numbers
$numpos = self::strpos_arr ($address, $numbers, 2);
//Get the streetname by splitting off the from the start of the numbers
$streetname = substr ($address, 0, $numpos);
//Strip off spaces at the end
$streetname = trim ($streetname);
//Get the housenumber+extension
$numberpart = substr ($address, $numpos);
//and strip off spaces
$numberpart = trim ($numberpart);
//Get the start position of the extension
$extpos = self::strpos_arr ($numberpart, $characters, 0);
//See if there is one, if so
if ($extpos != '') {
//get the housenumber
$housenumber = substr ($numberpart, 0, $extpos);
// and the extension
$houseextension = substr ($numberpart, $extpos);
// and strip special characters from it
$houseextension = str_replace ($specialchars, '', $houseextension);
} else {
//Otherwise, we already have the housenumber
$housenumber = $numberpart;
}
return array($streetname, $housenumber, $houseextension);
}
/**
*
* @param $haystack
* @param $needle
* @param $where
* @return
*/
private static function strpos_arr ($haystack, $needle, $where) {
$defpos = 10000;
if (!is_array ($needle)) {
$needle = array($needle);
}
foreach ($needle as $what) {
if (($pos = strpos ($haystack, $what, $where)) !== FALSE) {
if ($pos < $defpos) {
$defpos = $pos;
}
}
}
return $defpos;
}
/**
* gets Eid and Secret for activated countries.
*/
public static function getEidSecretArray ($method) {
$eid_array = array();
if (isset($method->klarna_merchantid_swe) && $method->klarna_merchantid_swe != "" && $method->klarna_sharedsecret_swe != "") {
$eid_array['swe']['secret'] = $method->klarna_sharedsecret_swe;
$eid_array['swe']['eid'] = (int)$method->klarna_merchantid_swe;
}
if (isset($method->klarna_merchantid_nor) && $method->klarna_merchantid_nor != "" && $method->klarna_sharedsecret_nor != "") {
$eid_array['nor']['secret'] = $method->klarna_sharedsecret_nor;
$eid_array['nor']['eid'] = $method->klarna_merchantid_nor;
}
if (isset($method->klarna_merchantid_deu) && $method->klarna_merchantid_deu != "" && $method->klarna_sharedsecret_deu != "") {
$eid_array['deu']['secret'] = $method->klarna_sharedsecret_deu;
$eid_array['deu']['eid'] = $method->klarna_merchantid_deu;
}
if (isset($method->klarna_nld_merchantid) && $method->klarna_nld_merchantid != "" && $method->klarna_sharedsecret_nld != "") {
$eid_array['nld']['secret'] = $method->klarna_sharedsecret_nld;
$eid_array['nld']['eid'] = $method->klarna_nld_merchantid;
}
if (isset($method->klarna_merchantid_dnk) && $method->klarna_merchantid_dnk != "" && $method->klarna_sharedsecret_dnk != "") {
$eid_array['dnk']['secret'] = $method->klarna_sharedsecret_dnk;
$eid_array['dnk']['eid'] = $method->klarna_merchantid_dnk;
}
if (isset($method->klarna_merchantid_fin) && $method->klarna_merchantid_fin != "" && $method->klarna_sharedsecret_fin != "") {
$eid_array['fin']['secret'] = $method->klarna_sharedsecret_fin;
$eid_array['fin']['eid'] = $method->klarna_merchantid_fin;
}
return $eid_array;
}
/**
* @param $obj
* @param int $level
* @return array
*/
public function xmlToArray ($obj, $level = 0) {
$aResult = array();
if (!is_object ($obj)) {
return $aResult;
}
$aChild = (array)$obj;
if (sizeof ($aChild) > 1) {
foreach ($aChild as $sName => $mValue) {
if ($sName == "@attributes") {
$sName = "_attributes";
}
if (is_array ($mValue)) {
foreach ($mValue as $ee => $ff) {
if (!is_object ($ff)) {
$aResult[$sName][$ee] = $ff;
} else {
if (get_class ($ff) == 'SimpleXMLElement') {
$aResult[$sName][$ee] = self::xmlToArray ($ff, $level + 1);
}
}
}
} else {
if (!is_object ($mValue)) {
$aResult[$sName] = $mValue;
} else {
if (get_class ($mValue) == 'SimpleXMLElement') {
$aResult[$sName] = self::xmlToArray ($mValue, $level + 1);
}
}
}
}
} else {
if (sizeof ($aChild) > 0) {
foreach ($aChild as $sName => $mValue) {
if ($sName == "@attributes") {
$sName = "_attributes";
}
if (!is_array ($mValue) && !is_object ($mValue)) {
$aResult[$sName] = $mValue;
} else {
if (is_object ($mValue)) {
$aResult[$sName] = self::xmlToArray ($mValue, $level + 1);
} else {
foreach ($mValue as $sNameTwo => $sValueTwo) {
if (!is_object ($sValueTwo)) {
$aResult[$obj->getName ()][$sNameTwo] = $sValueTwo;
} else {
if (get_class ($sValueTwo) == 'SimpleXMLElement') {
$aResult[$obj->getName ()][$sNameTwo] =
self::xmlToArray ($sValueTwo, $level + 1);
}
}
}
}
}
}
}
}
return $aResult;
}
/**
* @static
* @param $settings
* @param $mode
* @param $klarna_invoice_no
* @return string
*/
public static function checkOrderStatus ($settings, $mode, $orderNumber) {
try {
$klarna = new Klarna_virtuemart();
$klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE);
vmdebug ('checkOrderStatus', $klarna);
$os = $klarna->checkOrderStatus ($orderNumber, 1);
}
catch (Exception $e) {
$msg = $e->getMessage () . ' #' . $e->getCode () . ' ';
VmError ($msg);
return $msg;
}
//$os = self::getStatusForCode($os);
return $os;
}
/**
* Return pclasses stored in json file.
*/
public static function getPClasses ($type = NULL, $mode, $settings) {
//$settings = self::countryData($method, $country);
try {
$klarna = new Klarna_virtuemart();
$klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE);
return $klarna->getPClasses ($type);
}
catch (Exception $e) {
}
}
static function getCheapestPclass ($kCheckout, &$cheapest, &$minimum) {
$pclasses = $kCheckout->aPClasses;
if (empty($pclasses)) {
$minimum = 0;
return;
}
$cheapest = 0;
$minimum = '';
foreach ($pclasses as $pclass) {
if ($cheapest == 0 || $pclass['monthlyCost'] < $cheapest) {
$cheapest = $pclass['monthlyCost'];
}
if ($pclass['pclass']->getMinAmount () < $minimum || $minimum === '') {
$minimum = $pclass['pclass']->getMinAmount ();
}
}
}
/**
* @param string $fld
* @return string
*/
public static function getVendorCountry ($fld = 'country_3_code') {
if (!class_exists ('VirtueMartModelVendor')) {
JLoader::import ('vendor', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models');
}
$virtuemart_vendor_id = 1;
$model = VmModel::getModel ('vendor');
$vendorAddress = $model->getVendorAdressBT ($virtuemart_vendor_id);
$vendor_country = ShopFunctions::getCountryByID ($vendorAddress->virtuemart_country_id, $fld);
return $vendor_country;
}
/**
* @param $klarnaError
* @param $klarnaOption
* @return bool
*/
function getKlarnaError (&$klarnaError, &$klarnaOption) {
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
if (empty($sessionKlarna)) {
return FALSE;
}
$sessionKlarnaData = unserialize ($sessionKlarna);
if (isset($sessionKlarnaData->klarna_error) and isset($sessionKlarnaData->klarna_paymentmethod)) {
$klarnaError = $sessionKlarnaData->klarna_error; // it is a message to display
$klarnaOption = $sessionKlarnaData->klarna_paymentmethod;
return TRUE;
} else {
return FALSE;
}
return FALSE;
}
function setKlarnaErrorInSession ($msg, $option) {
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
if (empty($sessionKlarna)) {
$sessionKlarnaData = new stdClass();
} else {
$sessionKlarnaData = unserialize ($sessionKlarna);
}
$sessionKlarnaData->klarna_error = $msg;
//$sessionKlarnaData->klarna_option = $option;
$session->set ('Klarna', serialize ($sessionKlarnaData), 'vm');
}
/**
*
*/
function clearKlarnaError () {
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
if ($sessionKlarna) {
$sessionKlarnaData = unserialize ($sessionKlarna);
if (isset($sessionKlarnaData->klarna_error)) {
unset($sessionKlarnaData->klarna_error);
//unset($sessionKlarnaData->klarna_option);
$session->set ('Klarna', serialize ($sessionKlarnaData), 'vm');
}
}
}
/**
* @static
* @param $method
* @return int
*/
static function getKlarnaMode ($method, $country) {
//return Klarna::BETA;
// It is the VM specific store ID to test
$merchant_id = strtolower ('klarna_merchantid_' . $country);
if ($method->$merchant_id == VMPAYMENT_KLARNA_MERCHANT_ID_VM or $method->$merchant_id == VMPAYMENT_KLARNACHECKOUT_MERCHANT_ID_VM or $method->$merchant_id == VMPAYMENT_KLARNA_MERCHANT_ID_DEMO) {
return Klarna::BETA;
} else {
return Klarna::LIVE;
}
}
/**
* @static
* @param $mode
* @return bool
*/
static function getKlarnaSSL ($mode) {
return ($mode == Klarna::LIVE);
}
/**
* @static
* @param $price
* @param string $toCurrency
* @return float
*/
static function convertPrice ($price, $fromCurrency, $toCurrency = '', $cartPricesCurrency = '') {
if (!(is_int ($toCurrency) or is_numeric ($toCurrency)) && !empty($toCurrency)) {
$toCurrency = ShopFunctions::getCurrencyIDByName ($toCurrency);
}
if ($fromCurrency == $toCurrency) {
return $price;
}
// product prices or total in cart is always in vendor currency
$priceInNewCurrency = vmPSPlugin::getAmountInCurrency($price,$toCurrency);
// set back the currency display
if (empty($cartPricesCurrency)) {
$cartPricesCurrency = $fromCurrency;
}
$cd = CurrencyDisplay::getInstance ($cartPricesCurrency);
vmDebug ('convertPrice', $price, $toCurrency, $fromCurrency, $cartPricesCurrency,$priceInNewCurrency);
return $priceInNewCurrency['value'];
}
/*
* if client has not given address then get cdata depending on the currency
* otherwise get info depending on the country
*/
/**
* @static
* @param $method
* @param $address
* @return array|null
*/
static function getcData ($method, $address) {
if (!isset($address['virtuemart_country_id'])) {
$vendor_country = KlarnaHandler::getVendorCountry ();
$cData = self::countryData ($method, $vendor_country);
} else {
$cart_country_code_3 = ShopFunctions::getCountryByID ($address['virtuemart_country_id'], 'country_3_code');
// the user gave an address, get info according to his country
$cData = self::countryData ($method, $cart_country_code_3);
}
return $cData;
}
/**
* @static
* @return null|string
*/
static function getKlarna_pc_type () {
$safePath = VmConfig::get ('forSale_path', '');
if ($safePath) {
return $safePath . "klarna/klarna.json";
} else {
$uri = JFactory::getURI ();
$link = $uri->root () . 'administrator/index.php?option=com_virtuemart&view=config';
VmError (JText::sprintf ('VMPAYMENT_KLARNA_CANNOT_STORE_CONFIG', '' . $link . ' ', JText::_ ('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH')));
return NULL;
}
}
/**
* Sweden: yymmdd-nnnn, it can be sent with or without dash "-" or with or without the two first numbers in the year.
* Finland: ddmmyy-nnnn
* Denmark: ddmmyynnnn
* Norway: ddmmyynnnnn
* Germany: ddmmyyyy
* Netherlands: ddmmyyyy
*
* @static
* @param $billTo
* @param $country
* @return string
*/
static function getPNOfromSession ($sessionData, $country) {
if (($country == "NLD" || $country == "DEU")) {
$pno = $sessionData['pno_frombirthday'];
} else {
$pno = $sessionData['socialNumber'];
}
return $pno;
}
/**
* @param $data
* @return bool
*/
static function checkDataFromEditPayment ($data, $country3) {
if (!class_exists ('VirtueMartModelUserfields')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'userfields.php');
}
$errors = array();
/*
if ($country3 == "DEU") {
$consent = JRequest::getVar ('klarna_consent');
if ($consent != 'on') {
$errors = JText::_ ('VMPAYMENT_KLARNA_NO_CONSENT');
}
}
// todo later
$userFieldsModel = VmModel::getModel ('userfields');
$userFields = $userFieldsModel->getUserFields (
'account'
, array('required' => FALSE,
'delimiters' => TRUE,
'captcha' => TRUE,
'system' => FALSE)
, array('delimiter_userinfo', 'name', 'username', 'password', 'password2', 'address_type_name', 'address_type', 'user_is_vendor', 'agreed'));
$required_shopperfields_vm = Klarnahandler::getKlarnaVMGenericShopperFields (FALSE);
$required_shopperfields_bycountry = KlarnaHandler::getKlarnaSpecificShopperFields ();
$required_shopperfields = array_merge ($required_shopperfields_vm, $required_shopperfields_bycountry[$country3]);
foreach ($userFields as $userField) {
if (in_array ($userField->name, $required_shopperfields)) {
if (empty($data[$userField->name])) {
$errors[] = JText::_($userField->title);
}
}
}
*/
// Quick and durty .. but it works
$kIndex = "klarna_";
if ($country3 == "SWE") {
if (JRequest::getVar ('klarna_invoice_type') == 'company') {
if (strlen (trim ((string)JRequest::getVar ('klarna_company_name'))) == 0) {
$errors[] = 'VMPAYMENT_KLARNA_COMPANY_NAME';
}
} else {
if (!KlarnaEncoding::checkPNO ($data['socialNumber'], KlarnaEncoding::PNO_SE)) {
$errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER';
}
}
} else {
if ($data['phone'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_PHONE_NUMBER';
}
if ($data['street'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_STREET_ADRESS';
}
if ($data['first_name'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_FIRST_NAME';
}
if ($data['last_name'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_LAST_NAME';
}
if ($data['city'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_ADDRESS_CITY';
}
if ($data['zip'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_ADDRESS_ZIP';
}
}
// German and dutch
if ($country3 == "NLD" || $country3 == "DEU") {
if ($data['street'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_STREET_ADRESS';
}
if ($data['house_no'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_ADDRESS_HOMENUMBER';
}
if ($country3 == "DEU") {
if ($data['consent'] != 'on') {
$errors[] = 'VMPAYMENT_KLARNA_NO_CONSENT';
}
}
if ($data['pno_frombirthday'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER';
}
if ($data['gender'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_SEX';
}
}
// General
/* the email is not in the payment form
if ($data['emailAddress'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_EMAIL';
}
*/
// Norwegian, Danish and Finnish
if (($country3 == "NOR") || ($country3 == "DNK") || $country3 == "FIN") {
if ($data['socialNumber'] == '') {
$errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER';
}
}
if (!empty($errors)) {
$msg = JText::_ ('VMPAYMENT_KLARNA_ERROR_TITLE_2');
foreach ($errors as $error) {
$msg .= "" . JText::_ ($error) . " ";
}
$option=NULL;
self::setKlarnaErrorInSession ($msg, $option);
return $msg;
}
return NULL;
}
/**
* @static
* @return array
*/
static function getKlarnaSpecificShopperFields () {
return array(
"SWE" => array( "email"),
"DNK" => array(), // should not be given to the shopper year_salary
"NOR" => array(),
"FIN" => array(),
"NLD" => array( "address_2", "house_no"),
"DEU" => array( "house_no")
);
}
/**
* @return array
*/
static function getKlarnaVMGenericShopperFields ($all = TRUE) {
$required = array("first_name", "last_name", "address_1", "city", "zip", "phone_1", "virtuemart_country_id");
if ($all) {
$required = array_merge ($required, array("company"));
}
return $required;
}
static function getKlarnaShopperFieldsType () {
return array("socialNumber"=> "text",
"email" => "email",
"birthday" => "date",
"address_2" => "text",
"house_no" => "text",
);
}
/**
*
*/
function getByFieds () {
$required_shopperfields_byfields = array(
"socialNumber" => array("SWE", "DNK", "NOR", "FIN"),
"year_salary" => array("DNK"),
"address_2",
"birthday" => array("DEU", "NLD"),
"house_no" => array("NLD"),
"email" => array("SWE")
);
}
/**
* Get the shipToAddress which might differ from default address.
* From VM shopperFields to Klarna Fields
*/
public static function getShipToAddress ($cart) {
//vmdebug('getShipToAddress',$cart);
if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) {
$shipTo = $cart->BT;
} else {
$shipTo = (($cart->ST == 0 or empty($cart->ST)) ? $cart->BT : $cart->ST);
}
return self::getKlarnaFieldsFromVmShopperFields ($shipTo, $cart->BT['email']);
}
/**
* @static
* @param $from
* @param $from_email
* @return array
*/
static function getKlarnaFieldsFromVmShopperFields ($from, $from_email) {
$klarnaFields = array();
switch ($from['title']) {
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR'):
$klarnaFields['gender'] = KlarnaFlags::MALE;
break;
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MISS'):
case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS'):
$klarnaFields['gender'] = KlarnaFlags::FEMALE;
break;
default:
$klarnaFields['gender'] = NULL;
break;
}
$country_code_3 = ShopFunctions::getCountryByID ($from['virtuemart_country_id'], 'country_3_code');
$klarnaFields['email'] = $from_email;
$klarnaFields['country'] = @ShopFunctions::getCountryByID (@$from['virtuemart_country_id'], 'country_3_code');
$klarnaFields['socialNumber'] = @$from['socialNumber'];
$klarnaFields['houseNr'] = @$from['house_no'];
$klarnaFields['houseExt'] = @$from['address_2'];
$klarnaFields['first_name'] = @$from['first_name'];
if ($country_code_3 == 'NLD') {
$klarnaFields['last_name'] = @$from['middle_name'] . " " . @$from['last_name'];
} else {
$klarnaFields['last_name'] = @$from['last_name'];
}
$klarnaFields['reference'] = $from['first_name'] . ' ' . $from['last_name'];
$klarnaFields['company_name'] = @$from['company_name'];
$klarnaFields['phone'] = @$from['phone_1'];
$klarnaFields['street'] = @$from['address_1'];
$klarnaFields['city'] = @$from['city'];
$klarnaFields['country'] = $country_code_3;
$klarnaFields['state'] = @$from['state'];
$klarnaFields['zip'] = @$from['zip'];
$klarnaFields['birthday'] = @$from['birthday'];
if (isset($from['birthday']) and !empty($from['birthday'])) {
$date = explode ("-", $from['birthday']);
if (is_array ($date)) {
$klarnaFields['birth_year'] = $date['0'];
$klarnaFields['birth_month'] = $date['1'];
$klarnaFields['birth_day'] = $date['2'];
}
}
return $klarnaFields;
}
function checkNLpriceCondition ($price) {
// Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros.
if ($price > 250) {
// We can't show our payment options for Dutch customers
// if price exceeds 250 euro. Will be replaced with ILT in
// the future.
return FALSE;
}
return TRUE;
}
function checkPartNLpriceCondition ($cart) {
// Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros.
// convert price in euro
//$euro_currency_id = ShopFunctions::getCurrencyByName( 'EUR');
$price = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $cart->pricesCurrency, 'EUR',$cart->pricesCurrency);
return self::checkNLpriceCondition ($price);
}
}
PK %A\ helpers/klarna.cfgnu W+A
PK %A\c\ \ assets/js/klarna_invoice.jsnu W+A // Load when document finished loading
jQuery( function (){
klarna.invoiceReady();
});
PK %A\Q assets/js/klarna_admin.jsnu W+A jQuery(function($){
setTimeout('showCountries()', 10);
flagListener();
//setTimeout('setExtraInfo()', 10);
setTimeout('showPclasses()', 10);
$(".update_pclasses a").click( function(e){
e.preventDefault();
form = $(this).parents("form") ;
var link = $(this).attr("href");
var datas = $(this).parents("form").serializeArray();
datas.push({"name":"redirect","value":"no"});
datas.push({"name":"task","value":"save"});
$.post(link,datas,function(data) {
if (data = "ok") {
console.log("update table");
datas.push({"name":"view","value":"plugin"});
datas.push({"name":"name","value":"klarna"});
datas.push({"name":"task","value":"plugin"});
$.getJSON(link , datas,function(update) {
// update json array msg,notice,pclasses
$('#PClassesSuccessResult').hide().html(update.msg+''+update.notice).slideToggle(1000).delay(2000).slideToggle(500);
//console.log("update pclasse");
$('#pclasses').html(update.pclasses);
});
}
});
return false;
});
});
function showCountries() {
jQuery('select[name=KLARNA_SELECTED_COUNTRIES[]] option:selected').each(function() {
var value = jQuery(this).attr('value');
var code = convert(value);
var field = 'fieldset#'+code+'_settings';
jQuery(field).removeClass('hide');
jQuery('img#'+code).removeClass('inactive');
});
}
// The ExtraInfo box in the backend empties itself every time you enter the
// backend if it contains php code, this function puts it back.
function setExtraInfo() {
var einfo = "<"+"?php include(JPATH_SITE . '/components/com_klarna/extrainfo.php'); "+"?"+">";
var current = jQuery('textarea').attr('name', 'payment_extrainfo').text();
if (current.search('JPATH_SITE') <0 ) {
jQuery('textarea').attr('name','payment_extrainfo').text(einfo+current);
}
}
function showPclasses() {
jQuery('#pclass_field').click(function(){
var pclass_field=jQuery(this);
jQuery('#pclasses').slideToggle("fast", function() {
if (pclass_field.find('span').hasClass('expand_arrow'))
pclass_field.find('span').addClass('collapse_arrow').removeClass('expand_arrow')
else
pclass_field.find('span').addClass('expand_arrow').removeClass('collapse_arrow')
// jQuery(this).parent().find('#arrow').html(' ');
});
});
}
function convert(country) {
switch(country) {
case "SWE":
return "SE";
case "NOR":
return "NO";
case "DNK":
return "DK";
case "FIN":
return "FI";
case "NLD":
return "NL";
case "DEU":
return "DE";
default:
return null; // not supported by Klarna yet
}
}
function convert_twoletter(country) {
switch(country) {
case "SE":
return "SWE";
case "NO":
return "NOR";
case "DK":
return "DNK";
case "FI":
return "FIN";
case "NL":
return "NLD";
case "DE":
return "DEU";
default:
return null; // not supported by Klarna yet
}
}
function flagListener() {
jQuery('#klarna_countries').find('span').click(function() {
var code = jQuery(this).attr('id');
toggleActive(code);
});
}
function toggleActive(code) {
var field = 'fieldset#'+code+'_settings';
var tlc = convert_twoletter(code);
if (jQuery(field).is(':hidden')) {
jQuery(field).removeClass('hide');
jQuery('img#'+code).removeClass('inactive').addClass('active');
jQuery('span#'+code).removeClass('inactive').addClass('active');
jQuery('#KLARNA_SELECTED_COUNTRIES > option[value='+tlc+']').attr('selected', 'selected');
} else if (jQuery(field).is(':visible')) {
jQuery(field).addClass('hide');
jQuery('img#'+code).addClass('inactive').removeClass('active');
jQuery('span#'+code).addClass('inactive').removeClass('active');
jQuery('#KLARNA_SELECTED_COUNTRIES > option[value='+tlc+']').removeAttr('selected');
}
}
PK %A\z`k k assets/js/klarna_general.jsnu W+A
var klarna_js_loaded = true;
if (typeof klarna == "undefined") {
var $$ = $;
var $ = jQuery;
var klarna = {
invoice_fee: 0,
sum : 0,
gender : '',
klarnaGeneralLoaded : true,
different_language : false,
currentMinHeight_part : 0,
currentMinHeight_spec : 0,
currentMinHeight_invoice : 0,
red_baloon_busy : false,
blue_baloon_busy : false,
address_busy : false,
baloons_moved : false,
changeLanguage_busy : false,
showing_companyNotAlowed_box : false,
gChoice : '',
stype : '',
errorHandler: {
show: function(parentBox, message, code, type) {
var errorHTML = ''+message+'
';
errorHTML += '';
if ( type != '' ) {
errorHTML += ''+type+' ';
}
if ( code != '' ) {
errorHTML += '#'+code+'
';
}
if (jQuery('#klarna_red_baloon').length == 0) {
klarna.errorHandler.create(parentBox);
}
jQuery('#klarna_red_baloon_content').html(errorHTML);
if (typeof showRedBaloon != 'undefined')
showRedBaloon(parentBox);
},
/**
* Creates the red baloon used to show error messages
*/
create: function(parentBox) {
jQuery(
'').appendTo(parentBox);
},
prepareRedBaloon: function () {
if ((typeof klarna.global.red_baloon_content != 'undefined') &&
(klarna.global.red_baloon_content != '')
) {
var box;
if (klarna.global.red_baloon_box != '') {
box = jQuery('#' + klarna.global.red_baloon_box)
}
this.show(box, klarna.global.red_baloon_content);
}
},
showRedBaloon: function (box) {
if (this.busy)
return;
this.busy = true;
var field;
if (typeof box == 'undefined') {
if (gChoice == klarna.global.invoice_name) {
box = jQuery(document).find('#klarna_box_invoice');
} else if (gChoice == klarna.global.part_name) {
box = jQuery(document).find('#klarna_box_part');
} else if (gChoice == klarna.global_spec_name) {
box = jQuery(document).find('#klarna_box_spec');
}
}
if (typeof box != 'undefined') {
field = box.find('.klarna_logo');
}
if (typeof field == 'undefined' || field.length == 0) {
field = jQuery('.klarna_logo:visible');
}
if (field.length > 0) {
var callback = this.fadeRedBaloon;
var position = field.offset();
var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6);
if (top < 0) top = 10;
position.top = top;
var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2);
position.left = left;
jQuery('#klarna_red_baloon').css(position);
jQuery('#klarna_red_baloon').fadeIn('slow', function () {
setTimeout(callback, 3000);
});
} else {
this.busy = false;
}
},
fadeRedBaloon: function () {
this.busy = false;
jQuery('#klarna_red_baloon').addClass('klarna_fading_baloon');
},
hideRedBaloon: function () {
this.busy = false;
this.showing_address_error = false;
jQuery('#klarna_red_baloon').remove();
}
},
hidePaymentOption : function (box, animate) {
if (typeof animate == 'undefined') {
animate = false;
}
if (animate) {
jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom').
hide();
} else {
jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom').
fadeOut('fast');
}
jQuery(box).animate({'min-height': '55px'}, 200);
klarna.showHideIlt(jQuery(box).find('.klarna_box_ilt'), false, animate);
},
showPaymentOption : function (box, animate, currentMinHeight, different_language) {
if (typeof animate == 'undefined') {
animate = false;
}
if (animate) {
jQuery(box).animate({"min-height": currentMinHeight}, 200, function () {
klarna.showHideIlt(jQuery(this).find('.klarna_box_ilt'), true);
jQuery(this).find('.klarna_box_bottom').fadeIn('fast', function () {
jQuery('.klarna_box_bottom_content_loader').fadeOut();
if (klarna.showing_companyNotAlowed_box)
{
klarna.hideRedBaloon();
}
});
jQuery(this).find('.klarna_box_top_right').fadeIn('fast');
if (different_language) {
jQuery(this).find('.klarna_box_bottom_languageInfo').fadeIn('fast');
jQuery('.klarna_box_bottom_languageInfo').fadeIn('fast');
}
});
} else {
jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom').show('fast');
klarna.showHideIlt(jQuery(box).find('.klarna_box_ilt'), true, animate);
}
},
initPaymentSelection : function (choice) {
var isklarna = choice.hasClass('klarnaPayment');
klarna.gChoice = '';
klarna.stype = choice.data("stype");
if ( isklarna ) klarna.gChoice = choice.attr('id');
//jQuery('input[value="'+choice+'"]').attr("id");
var klarnaBox = jQuery('#paymentForm .klarnaPayment');
klarnaBox.each(function () {
var thisStype = jQuery(this).data("stype");
if (klarna.stype != thisStype)
klarna.hidePaymentOption('#klarna_box_'+thisStype);
else klarna.choosePaymentOption(klarna.stype);
});
},
choosePaymentOption : function (choice) {
klarna.hideRedBaloon();
klarna.hideBlueBaloon();
klarna.showPaymentOption(jQuery('#klarna_box_'+choice), true,
klarna['currentMinHeight_'+klarna.stype], klarna.different_language);
},
setGender : function (context, gender) {
// This should be refactored to not be able to set other non-gender radio buttons
var value;
if (gender == 'f' || gender == '0')
{
jQuery('.Klarna_radio[value=0]', context).attr('checked', 'checked');
}
else //if (gender == 'm' || gender == '1')
{
jQuery('.Klarna_radio[value=1]', context).attr('checked', 'checked');
}
},
/**
* Hook up jQuery callbacks for the given klarna_box_container(s) or
* all klarna options in the document
*/
initPaymentOptions : function (opts) {
if (typeof opts == 'undefined') {
opts = jQuery(document);
}
// specialCampaign only
if(typeof InitKlarnaSpecialPaymentElements != 'undefined')
InitKlarnaSpecialPaymentElements('specialCampaignPopupLink', klarna.eid, klarna.countryCode);
// P-Classes box actions
jQuery('.klarna_box', opts).find('ol').find('li').mouseover(function (){
jQuery(this).not('.klarna_box_click').addClass('klarna_box_over');
}).mouseout(function (){
jQuery(this).not('.klarna_box_click').removeClass('klarna_box_over')
}).click(function (){
// Reset list and move chosen icon to newly selected pclass
chosen = jQuery(this).parent("ol").find('img')
klarna.resetListBox(jQuery(this).parent("ol"));
chosen.appendTo(jQuery(this).find('div'));
jQuery(this).attr("class", "klarna_box_click");
// Update input field with pclass id
var value = jQuery(this).find('span').html();
var name = jQuery(this).parent("ol").attr("id");
jQuery(this).closest('.klarna_box').find("input.paymentPlan").attr("value", value);
});
if (klarna.countryCode == "de" || klarna.countryCode == "nl")
{
klarna.setGender(opts, klarna.gender);
}
// Input field on focus
jQuery('.klarna_box', opts).find('input').focusin(function () {
klarna.setBaloonInPosition(jQuery(this), false);
}).focusout(function () {
klarna.hideBaloon();
});
jQuery('.klarna_box_top_flag_list img', opts).click(function (){
if (klarna.changeLanguage_busy == false)
{
klarna.changeLanguage_busy = true;
var newIso = jQuery(this).attr("alt");
jQuery('.box_active_language', opts).attr("src", jQuery(this).attr("src"));
var box = jQuery(this).parents('.klarna_box_container');
var params;
var values;
var boxType = box.find('.klarna_box').attr("id");
var Type = boxType.substring( 11 );//'klarna_box_'
if (!Type) {
console.log(boxType);
return ;
}
klarna.changeLanguage(box, klarna.params, newIso, klarna.countryCode, Type);
}
});
setTimeout('klarna.prepareRedBaloon()', 1000);
jQuery('.klarna_box_bottom_languageInfo', opts).mousemove(function (e) {
klarna.showBlueBaloon(e.pageX, e.pageY, jQuery(this).find('img').attr("alt"));
});
jQuery('.klarna_box_bottom_languageInfo', opts).mouseout(function () {
klarna.hideBlueBaloon();
});
jQuery('input.gender.Klarna_radio', opts).bind('change', function () {
klarna.gender = jQuery(this).val();
});
jQuery('.Klarna_pnoInputField', opts).each(function (){
var pnoField = jQuery(this);
jQuery(this).bind("keyup change blur focus", function (){
klarna.pnoUpdated(jQuery(this),
(jQuery(this).parents('.klarna_box').attr("id") == "klarna_box_invoice"));
});
});
},
doDocumentIsReady : function (klarnaBox)
{
klarnaBox.each(function () {
var type = jQuery(this).parents('table').find('.klarnaPayment').data("stype");
klarna['currentMinHeight_'+type] = jQuery(this).children('.klarna_box_top').height();
});
klarna.initPaymentOptions();
},
pnoUpdated : function (box, companyAllowed) {
var pno_value = jQuery.trim(jQuery(box).val());
// Set the PNO to the other fields
jQuery('.Klarna_pnoInputField').val(pno_value);
// Do check
if (pno_value != "") {
jQuery('.klarna_box_bottom_content_loader').is(":hidden").fadeIn('fast');
if (!validateSocialSecurity(pno_value)) {
jQuery('.klarna_box_bottom_content_loader').fadeOut('fast');
jQuery('.klarna_box_bottom_address').is(":visible").slideUp('fast');
} else {
klarna.getAddress (jQuery(box).closest('.klarna_box'), pno_value, companyAllowed);
}
} else {
jQuery('.referenceDiv').is(":visible").slideUp('fast');
// jQuery('.referenceDiv').is(":hidden").css({"display":"none"}); //Ilogic !
jQuery('.klarna_box_bottom_content_loader').fadeOut('fast');
jQuery('.klarna_box_bottom_address').is(":visible").slideUp('fast');
//jQuery('.klarna_box_bottom_address').is(":hidden").css({"display":"none"}); // Ilogic !
}
},
/**
* Showing and hiding the ILT questions
*
* @param field
* @param show
* @param animate
*/
showHideIlt : function (field, show, animate)
{
if (show == false)
{
if (animate == true)
field.slideUp('fast');
else
field.hide();
}
else {
var length = field.find('.klarna_box_iltContents').find('.klarna_box_ilt_question').length;
if (length > 0)
{
if (animate == true)
field.slideDown('fast');
else
field.show();
}
}
},
prepareRedBaloon: function ()
{
if (klarna.red_baloon_content != '') {
if ( typeof code == 'undefined' ) {
code = '';
}
klarna.errorHandler.show(jQuery('#'+klarna.red_baloon_box), klarna.red_baloon_content, code, '');
}
},
showRedBaloon : function (box) {
if (klarna.red_baloon_busy)
return;
klarna.red_baloon_busy = true;
var field;
if (typeof box == 'undefined') {
if (klarna.gChoice == "klarna_invoice") {
box = jQuery('#klarna_box_invoice');
} else if (klarna.gChoice == "klarna_partPayment") {
box = jQuery('#klarna_box_part');
} else if (klarna.gChoice == "klarna_SpecCamp") {
box = jQuery('#klarna_box_spec');
}
}
if (typeof box != 'undefined') {
field = box.find('.klarna_logo');
}
if (typeof field == 'undefined' || field.length == 0) {
field = jQuery('.klarna_logo:visible');
}
var position = field.offset();
var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6);
if (top < 0) top = 10;
position.top = top;
var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2);
position.left = left;
jQuery('#klarna_red_baloon').css(position);
jQuery('#klarna_red_baloon').fadeIn('slow', function () {
klarna.red_baloon_busy = false;
setTimeout('klarna.fadeRedBaloon()', 3000);
});
},
getAddress : function (parentBox, pno_value, companyAllowed)
{
if (!klarna.address_busy)
{
klarna.address_busy = true;
data = {
action: 'getAddress',
country: klarna.countryCode,
pno: pno_value
}
// Get the new klarna_box
jQuery.ajax({
type: "GET",
url: ajax_path,
data: data,
success: function(xml){
jQuery(xml).find('error').each(function() {
var msg = jQuery(this).find('message').text();
var code = jQuery(this).find('code').text();
var type = jQuery(this).find('type').text();
jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () {
klarna.address_busy = false;
});
klarna.errorHandler.show(parentBox, msg, code, type);
});
jQuery(xml).find('getAddress').each(function() {
addresses = AddressCollection.fromXML(this);
if (typeof klarna.params_invoice != "undefined")
addresses.render('#klarna_box_invoice', klarna.params_invoice['shipmentAddressInput']);
if (typeof klarna.params_part != "undefined")
addresses.render('#klarna_box_part', klarna.params_part['shipmentAddressInput']);
if (typeof klarna.params_spec != "undefined")
addresses.render('#klarna_box_spec', klarna.params_spec['shipmentAddressInput']);
jQuery.each(addresses.addresses, function(i, addr) {
if (addr.isCompany) {
jQuery('#invoiceType').val("company");
jQuery('.referenceDiv').slideDown('fast');
if (addresses.mode == Address.Single)
{
jQuery('.klarna_box_bottom').animate({"min-height": "300px"},'fast');
}
if (companyAllowed == false && typeof klarna.lang_companyNotAllowed != "")
{
showRedBaloon(jQuery(box));
jQuery('#klarna_red_baloon_content div').html(klarna.lang_companyNotAllowed);
klarna.showing_companyNotAlowed_box = true;
}
else {
klarna.hideRedBaloon();
}
} else {
jQuery('#invoiceType').val("private");
jQuery('.referenceDiv').slideUp('fast');
jQuery('.klarna_box_bottom').animate({"min-height": "250px"},'fast');
if (klarna.showing_companyNotAlowed_box)
klarna.hideRedBaloon();
}
});
jQuery('.klarna_box_bottom_address').slideDown('fast');
jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () {
klarna.address_busy = false;
klarna.hideRedBaloon();
});
});
klarna.address_busy = false;
}
});
}
},
showBlueBaloon : function (x, y, text)
{
jQuery('#klarna_blue_baloon_content div').html(text);
var top = (y - jQuery('#klarna_blue_baloon').height())-5;
var left = (x - (jQuery('#klarna_blue_baloon').width()/2)+5);
jQuery('#klarna_blue_baloon').css({"left": left, "top": top});
jQuery('#klarna_blue_baloon').show();
},
hideBlueBaloon : function ()
{
jQuery('#klarna_blue_baloon').hide();
},
showRedBaloonX : function (box) {
if (klarna.red_baloon_busy)
return;
klarna.red_baloon_busy = true;
var field;
if (typeof box == 'undefined') {
if (klarna.gChoice == "klarna_invoice") {
box = jQuery('#klarna_box_invoice');
} else if (klarna.gChoice == "klarna_partPayment") {
box = jQuery('#klarna_box_part');
} else if (klarna.gChoice == "klarna_SpecCamp") {
box = jQuery('#klarna_box_spec');
}
}
if (typeof box != 'undefined') {
field = box.find('.klarna_logo');
}
if (typeof field == 'undefined' || field.length == 0) {
field = jQuery('.klarna_logo:visible');
}
var position = field.offset();
var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6);
if (top < 0) top = 10;
position.top = top;
var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2);
position.left = left;
jQuery('#klarna_red_baloon').css(position);
jQuery('#klarna_red_baloon').fadeIn('slow', function () {
klarna.red_baloon_busy = false;
setTimeout('klarna.fadeRedBaloon()', 3000);
});
},
fadeRedBaloon : function ()
{
if (klarna.red_baloon_busy)
return;
jQuery('#klarna_red_baloon').addClass('klarna_fading_baloon');
},
hideRedBaloon : function ()
{
if (klarna.red_baloon_busy)
return;
if (jQuery('#klarna_red_baloon').is(':visible') && !klarna.red_baloon_busy)
{
jQuery('#klarna_red_baloon').fadeOut('fast', function () {
klarna.red_baloon_busy = false;
klarna.showing_companyNotAlowed_box = false;
});
}
},
/**
* This function is only available for swedish social security numbers
*/
validateSocialSecurity : function (vPNO)
{
if (typeof vPNO == 'undefined')
return false;
return vPNO.match(/^([1-9]{2})?[0-9]{6}[-\+]?[0-9]{4}$/)
},
resetListBox : function (listBox)
{
listBox.find('li').each(function (){
if (jQuery(this).attr("id") == "click")
{
jQuery(this).attr("id", "");
}
jQuery(this).find('div img').remove();
});
},
hideBaloon : function (callback)
{
if (jQuery('#klarna_baloon').is(":visible"))
{
jQuery('#klarna_baloon').fadeOut('fast', function (){
if( callback ) callback();
return true;
});
}
else {
if( callback ) callback();
return true;
}
},
setBaloonInPosition : function (field, red_baloon)
{
klarna.hideBaloon(function (){
var position = field.offset();
var name = field.attr('name');
var value = field.attr('alt');
if (!value && !red_baloon)
{
return false;
}
if (!red_baloon)
{
jQuery('#klarna_baloon_content div').html(value);
var top = position.top - jQuery('#klarna_baloon').height();
if (top < 0) top = 10;
position.top = top;
var left = (position.left + field.width()) - (jQuery('#klarna_baloon').width() - 50);
position.left = left;
jQuery('#klarna_baloon').css(position);
jQuery('#klarna_baloon').fadeIn('fast');
}
else {
var top = position.top - jQuery('#klarna_red_baloon').height();
if (top < 0) top = 10;
position.top = top;
var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() - 50);
position.left = left;
jQuery('#klarna_red_baloon').css(position);
jQuery('#klarna_red_baloon').fadeIn('fast');
}
});
},
saveDates : function (replaceBox) {
klarna['select_bday']= jQuery(replaceBox).find('.selectBox_bday').val();
klarna['select_bmonth'] = jQuery(replaceBox).find('.selectBox_bmonth').val();
klarna['select_year'] = jQuery(replaceBox).find('.selectBox_year').val();
},
changeLanguage : function (replaceBox, params, newIso, country, Type)
{
var paramString = "";
var valueString = "";
data = {
action: 'languagepack',
subAction: 'klarna_box',
type: Type,
newIso: newIso,
country: country,
sum: klarna.sum,
fee: klarna.invoice_fee,
flag: klarna.flag
}
// include current field values in request so that the values can be used
// in the translation
for (var attr in params) {
data['params[' + attr + ']'] = params[attr];
var inputValue = jQuery(replaceBox).find('input[name=' + params[attr] + ']').val();
if (typeof inputValue != "undefined") {
data['values[' + attr + ']'] = inputValue;
}
}
virtuemart_paymentmethod_id = jQuery(replaceBox).parents('table').find('.klarnaPayment').val();
data['cid'] = virtuemart_paymentmethod_id;
klarna.saveDates(replaceBox);
jQuery.ajax({
type: "GET",
url: klarna.ajaxPath,
data: data,
success: function(response){
//console.log(response);
if (jQuery(response).find('.klarna_box'))
{
replaceBox.find('.klarna_box').remove();
replaceBox.append(jQuery(response).find('.klarna_box'));
if(newIso != klarna.language)
replaceBox.find('.klarna_box_bottom_languageInfo').fadeIn('slow', function () {
klarna.changeLanguage_busy = false;
klarna.language = newIso ;
});
else
replaceBox.find('.klarna_box_bottom_languageInfo').fadeOut('slow', function () {
klarna.changeLanguage_busy = false;
});
klarna.methodReady(Type);
klarna.initPaymentOptions(replaceBox);
} else {
alert("Error, block not found. Response:\n\n"+response);
}
}
});
},
methodReady : function (Type)
{
var foundBox = false;
box = jQuery('#klarna_box_'+Type);
var currentMinHeight = box.height();
// Select birthdate and fill years box
// console.log(Type, klarna.countryCode);
if (klarna.countryCode == "de" || klarna.countryCode == "nl")
{
// Years box
var date = new Date();
for (i = date.getFullYear(); i >= 1900; i--)
{
jQuery(' ').val(i).text(i).appendTo( box.find('.selectBox_year') )
}
box.find('.selectBox_bday').val(klarna.select_bday);
box.find('.selectBox_bmonth').val(klarna.select_bmonth);
box.find('.selectBox_year').val(klarna.select_byear);
}
// Chosing the active language
box.find('.box_active_language').click(function () {
jQuery(this).next('.klarna_box_top_flag_list').slideToggle('fast', function () {
if (jQuery(this).is(':visible'))
{
jQuery(this).parent('.klarna_box_top_flag').animate({opacity: 1.0}, 'fast');
}
else {
jQuery(this).parent('.klarna_box_top_flag').animate({opacity: 0.4}, 'fast');
}
});
});
if (Type == 'invoice') {
jQuery('input[name='+klarna.invoice_ITId+']').change(function (){
var val = jQuery(this).val();
if (val == "private")
{
jQuery('#invoice_perOrg_title').text(klarna.lang_personNum);
jQuery('#invoice_box_private').slideDown('fast');
jQuery('#invoice_box_company').slideUp('fast');
}
else if (val == "company")
{
jQuery('#invoice_perOrg_title').text(klarna.lang_orgNum);
jQuery('#invoice_box_company').slideDown('fast');
jQuery('#invoice_box_private').slideUp('fast');
}
});
}
}
}
var $ = $$;
};
Address = function (companyName, firstName, lastName, street, zip, city, countryCode) {
this.companyName = companyName;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.zip = zip;
this.city = city;
this.countryCode = countryCode;
this.isCompany = (this.companyName.length > 0);
};
Address.fromXML = function (elem) {
return new Address(
jQuery(elem).find('companyName').text(),
jQuery(elem).find('first_name').text(),
jQuery(elem).find('last_name').text(),
jQuery(elem).find('street').text(),
jQuery(elem).find('zip').text(),
jQuery(elem).find('city').text(),
jQuery(elem).find('countryCode').text()
);
};
Address.Mode = function Mode() {}
Address.Single = new Address.Mode();
Address.Multi = new Address.Mode();
Address.prototype.inputValue = function () {
return [(this.isCompany
? this.companyName
: (this.firstName + '|' + this.lastName)),
this.street,
this.zip,
this.city,
this.countryCode].join('|');
}
Address.prototype.render = function (mode) {
if (mode == Address.Single) {
return '' +
(this.isCompany
? this.companyName
: (this.firstName + ' ' + this.lastName)) + '
' +
'' + this.street + '
' +
'' + this.zip + ' ' + this.city + '
' +
'' + this.countryCode + '
';
} else if (mode == Address.Multi) {
return '' +
(this.isCompany
? this.companyName
: (this.firstName + ' ' + this.lastName)) +
', ' + this.street +
', ' + this.zip + ' ' + this.city +
', ' + this.countryCode;
}
}
AddressCollection = function (addresses) {
this.addresses = addresses;
this.mode = addresses.length > 1 ? Address.Multi : Address.Single;
}
AddressCollection.fromXML = function (elem) {
var multi = (jQuery('address', elem).length > 1);
return new AddressCollection(jQuery('address', elem).map(function () {
var addr = Address.fromXML(this);
return addr;
}));
}
AddressCollection.prototype.render = function (to, inputName) {
var box = jQuery(to).find('.klarna_box_bottom_address_content');
box.empty();
if (this.mode == Address.Single) {
var inputValue = this.addresses[0].inputValue();
var input = jQuery(' ')
box.append(input);
box.append(this.addresses[0].render(Address.Single));
} else if (this.mode == Address.Multi) {
var select = jQuery('')
box.append(select);
jQuery.each(this.addresses, function(i, addr) {
select.append(addr.render(Address.Multi));
});
}
}
//Load when document finished loading
jQuery(document).ready(function ($){
var baloon = $('.klarna_baloon').clone();
$('.klarna_baloon').remove();
var baloon3 = $('.klarna_blue_baloon').clone();
$('.klarna_blue_baloon').remove();
$('body').append(baloon);
$('body').append(baloon3);
klarna.doDocumentIsReady(jQuery('.klarna_box'));
$('.klarna_box_bottom_languageInfo').remove();
if (!klarna.unary_checkout) {
var pList = jQuery('#paymentForm input[type=radio][name=virtuemart_paymentmethod_id]');
klarna.initPaymentSelection(pList.filter(":checked"));
pList.click( function (){
if ( klarna.stype != jQuery(this).data("stype") )
klarna.initPaymentSelection( jQuery(this) );
});
}
$('.klarnaPayment').parents('form').submit( function(){
var vmmethod = $(this).find('input:radio[name=virtuemart_paymentmethod_id]:checked');
if (!vmmethod.hasClass('klarnaPayment')) return ;
var action = vmmethod.parents('form').attr('action');
//$.post(action,fields);
var selectedTable= vmmethod.parents('table');
var fields = selectedTable.find('*').serializeArray();
fields.push({"name":"task","value":"setpayment"});
fields.push({"name":"view","value":"cart"});
fields.push({"name":"klarna_paymentmethod","value":vmmethod.next('input').val()});
var form = $('');
form.attr("method", "post");
form.attr("action", action);
//fields
$.each(fields, function(key, value) {
var field = $(' ');
field.attr("type", "hidden");
field.attr("name", value["name"]);
field.attr("value", value["value"]);
form.append(field);
});
// The form needs to be apart of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
return false;
});
klarna.baloons_moved = true;
});
PK %A\:/ / assets/js/index.htmlnu W+A
PK %A\) assets/js/.htaccessnu W+A
Order allow,deny
Deny from all
PK %A\@ assets/js/klarna_pp.jsnu W+A
jQuery(function () {
// unbind click to prevent duplicate click functions in case of more
// than one pp box
jQuery('.klarna_PPBox_pull,.klarna_PPBox_top').unbind('click');
jQuery('.klarna_PPBox_pull,.klarna_PPBox_top').click(function () {
var kParent = jQuery(this).closest('.klarna_PPBox');
var kBottom = kParent.find('.klarna_PPBox_bottom');
if (kBottom.is(':visible')) {
kBottom.slideUp('fast');
kParent.find('#klarna_PPBox_pullUp').fadeOut('fast');
kParent.find('#klarna_PPBox_pullDown').show();
} else {
kBottom.slideDown('fast');
kParent.find('#klarna_PPBox_pullUp').fadeIn('fast');
kParent.find('#klarna_PPBox_pullDown').hide();
}
});
});
PK %A\) assets/.htaccessnu W+A
Order allow,deny
Deny from all
PK %A\:/ / assets/index.htmlnu W+A
PK %A\:/ / assets/css/index.htmlnu W+A
PK %A\) assets/css/.htaccessnu W+A
Order allow,deny
Deny from all
PK %A\