Конвертер валют НБРБ для VirtueMart 2.6

Разработчик потребовал для интернет магазина (на Джумла 2,5 и Virtuemart 2,6) автоматическое обновление валют и их конвертацию.
Долго искала по форумам, много нашла всего интересного, но готового решения для Беларуси не было.
Пришлось на основании решения для РФ слегка подправив его сделать самой файл конвертации для РБ.


Думаю, что он может многим пригодится, поэтому выкладываю его код:


<?php
if( !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
/**
*Модуль конвертера валют НБРБ для Virtuemart 2.6.x,
* основан на оригинальном convertECB.php от Virtuemart 2.0.18a
* Курс = курсу  НБРБ на ТЕКУЩИЙ! день
* Модуль является полностью бесплатным, в случае его модификации
* не допускается его коммерческое использование.
* Последнюю версию можно найти по адресу:
*
* Версия: 2.6 от 2015-08-27
*/
class convertCBRB {
//  var $archive = true;
//  var $last_updated = '';
var $document_address = 'http://www.nbrb.by/Services/XmlExRates.aspx'; var $info_address = 'http://www.nbrb.by';
var $supplier = 'Центральный банк республики Беларусь';
/**
 * Converts an amount from one currency into another using
 * the rate conversion table from the European Central Bank
 *
 * @param float $amountA
 * @param string $currA defaults to $vendor_currency
 * @param string $currB defaults to
 * @return mixed The converted amount when successful, false on failure
 */
//  function convert( $amountA, $currA='', $currB='', $a2b = true ) {
function convert( $amountA, $currA='', $currB='', $a2rC = true, $relatedCurrency = 'EUR') {
// cache subfolder(group) 'convertCBRB', cache method: callback
$cache= JFactory::getCache('convertCBRB','callback');
// save configured lifetime
@$lifetime=$cache->lifetime;
$cache->setLifeTime(86400/24); // check 24 time per day
// save cache conf
$conf = JFactory::getConfig();
// check if cache is enabled in configuration
$cacheactive = $conf->getValue('config.caching');
$cache->setCaching(0); //кеширование отключено!
$globalCurrencyConverter = $cache->call( array( 'convertCBRB', 'getSetExchangeRates' ),$this->document_address );
// revert configuration
$cache->setCaching($cacheactive);
if(!$globalCurrencyConverter ){
//vmdebug('convert convert No $globalCurrencyConverter convert '.$amountA);
return $amountA;
} else {
$valA = isset( $globalCurrencyConverter[$currA] ) ? $globalCurrencyConverter[$currA] : 1.0;
$valB = isset( $globalCurrencyConverter[$currB] ) ? $globalCurrencyConverter[$currB] : 1.0;
$val = (float)$amountA * (float)$valB / (float)$valA;
//vmdebug('convertCBRB with '.$currA.' '.$amountA.' * '.$valB.' / '.$valA.' = '.$val,$globalCurrencyConverter[$currA]);
return $val;
}
}
static function getSetExchangeRates($cbrb_filename){
$archive = true;
setlocale(LC_TIME, "en-GB");
$now = time() + 3600; // Time in ECB (Germany) is GMT + 1 hour (3600 seconds)
if (date("I")) {
$now += 3600; // Adjust for daylight saving time
}
$weekday_now_local = gmdate('w', $now); // week day, important: week starts with sunday (= 0) !!
$date_now_local = gmdate('Ymd', $now);
$time_now_local = gmdate('Hi', $now);
$time_ecb_update = '1415';
if( is_writable(JPATH_BASE.DS.'cache') ) {
$store_path = JPATH_BASE.DS.'cache';
}
else {
$store_path = JPATH_SITE.DS.'media';
}
$archivefile_name = $store_path.'/daily_CBRB.xml';
$val = '';
if(file_exists($archivefile_name) && filesize( $archivefile_name ) > 0 ) {
// timestamp for the Filename
$file_datestamp = date('Ymd', filemtime($archivefile_name));
// check if today is a weekday - no updates on weekends
if( date( 'w' ) > 0 && date( 'w' ) < 6
// compare filedate and actual date
&& $file_datestamp != $date_now_local
// if localtime is greater then ecb-update-time go on to update and write files
&& $time_now_local > $time_ecb_update) {
$curr_filename = $cbrb_filename;
}
else {
$curr_filename = $archivefile_name;
$last_updated = $file_datestamp;
$archive = false;
}
}
else {
$curr_filename = $cbrb_filename;
}
if( !is_writable( $store_path )) {
$archive = false;
vmError( "The file $archivefile_name can't be created. The directory $store_path is not writable" );
}
// JError::raiseNotice(1, "The file $archivefile_name should be in the directory $store_path " );
if( $curr_filename == $cbrb_filename ) {
// Fetch the file from the internet
if(!class_exists('VmConnector')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'connection.php');
// JError::raiseNotice(1, "Updating currency " );
if (!$contents = VmConnector::handleCommunication( $curr_filename )) {
if (isset($file_datestamp)) {
$contents = @file_get_contents( $curr_filename );
}
} else $last_updated = date('Ymd');
}
else {
$contents = @file_get_contents( $curr_filename );
}
if( $contents ) {
// Если надо писать файл
if( $archive ) {
// то пишем его :)
file_put_contents( $archivefile_name, $contents );
}
//добавочная строка о рубле, т.е. номинал одного рубля - 1 рубль
$add_str = '<Currency Id="194"><NumCode>yyy</NumCode><CharCode>BYR</CharCode><Scale>1</Scale><Name>Белорусский рубль</Name><Rate>1</Rate></Currency>';
$contents = str_replace ("</ValCurs>", "$add_str </ValCurs>", $contents); //дополняем базу информацией о рубле
// по регулярному выражению ищем 3 заглавных буквы валюты (напр/ USD)
preg_match_all ("/<CharCode>([A-Z]{3})<\/CharCode>/", $contents, $char_arr);
// по регулярному выражению ищем число возможно  с запятой, номинал валюты
preg_match_all ("/<Scale>(\d+\.?\d*)<\/Scale>/", $contents, $nom_arr);
// по регулярному выражению ищем число возможно с запятой, курс валюты
// (т.е. за номинал тугриков можно купить столькото рублей)
preg_match_all ("/<Rate>(\d+\.?\d*)<\/Rate>/", $contents, $val_arr);
//формируем массив валют
for ($i = 0; $i < count($char_arr[1]); $i++)
{
//т.е. на 1 рубль можно купить = номинал валюты / курс валюты
$currency [$char_arr[1][$i]] = $nom_arr[1][$i]/(str_replace (',', '.', $val_arr[1][$i])); // преобразуем в числе запятую "," в точку "."
}
$globalCurrencyConverter = $currency;
}
else {
$globalCurrencyConverter = false;
vmError( 'Failed to retrieve the Currency Converter XML document.');
//  return false;
}
return $globalCurrencyConverter;
}
}
// pure php no closing tag


Проверено на Джумла 2.5 и Virtuemart 2.6.

Файлы из архива необходимо поместить по пути administrator/components/com_virtuemart/plugins/currency_converter

И в настройках Virtuemart выбрать модуль валюты convertCBRB.

Чтобы сразу увидеть результат, нужно почистить кэш сайта.

Вот ссылка на архив модуля: скачать

Комментарии

Популярные сообщения из этого блога

QuickForm для Джумла - как убрать ссылку

Автогенерация мета-тегов через шаблоны для категорий и товаров в VirtueMart 3.x