TimeTrex Community Edition v16.2.0

This commit is contained in:
2022-12-13 07:10:06 +01:00
commit 472f000c1b
6810 changed files with 2636142 additions and 0 deletions

View File

@ -0,0 +1,347 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: ExchangeRates.php,v 1.7 2005/06/23 20:29:20 cross Exp $
/**
* @package Services_ExchangeRates
* @category Services
*/
/**#@+
* Error codes
*/
define('SERVICES_EXCHANGERATES_ERROR_RETURN', 1);
define('SERVICES_EXCHANGERATES_ERROR_DIE', 8);
define('SERVICES_EXCHANGERATES_ERROR_INVALID_DRIVER', 101);
define('SERVICES_EXCHANGERATES_ERROR_INVALID_CURRENCY', 102);
define('SERVICES_EXCHANGERATES_ERROR_CONVERSION_ERROR', 103);
define('SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED', 104);
/**#@-*/
/**
* Exchange Rate package
*
* This package converts back and forth between different currencies, in any
* combination. All data used is updated automatically from interchangable
* sources. That is, if there is a source publishing exchange rates that
* isn't supported yet, you could write a driver and use that source
* seamlessly with the rest of the package.
*
* Disclaimer: The rates are nominal quotations - neither buying nor
* selling rates - and are intended for statistical or analytical
* purposes. Rates available from financial institutions will differ.
*
* The United Nations Economic Commission for Europe is implementing new web
* services. Keep an eye on progress here: http://www.unemed.org/edocs/index.htm
*
* @todo Add locale support for different currency formatting
*
* @example ExchangeRates/docs/example.php
*
* @author Marshall Roch <marshall@exclupen.com>
* @author Colin Ross <cross@php.net>
* @copyright Copyright 2003 Marshall Roch
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
class Services_ExchangeRates {
/**
* Sets the number of places to round the currencies to at the end
* @access private
* @var int
*/
var $_roundToDecimal = 2;
/**
* Determines whether the returned conversion is rounded or not
* @access private
* @var bool
*/
var $_roundAutomatically = true;
/**
* Defines single character used to separate each group of thousands in returned conversion
* @access private
* @var string
*/
var $_thousandsSeparator = ",";
/**
* Defines single character to use as a decimal place in returned conversion
* @access private
* @var string
*/
var $_decimalCharacter = ".";
/**
* Sets the path to where cache files are stored (don't forget the trailing slash!)
* @access private
* @var string
*/
var $_cacheDirectory = '/tmp/';
/**
* Sets the length (in seconds) to cache the exchange rate data. This information
* is updated daily. Default is 1 hour.
* @access private
* @var int
*/
var $_cacheLengthRates = 3600;
/**
* Sets the length (in seconds) to cache the list of currencies. This information
* is very rarely updated. Default is 4 weeks.
* @access private
* @var int
*/
var $_cacheLengthCurrencies = 2419200;
/**
* Sets the length (in seconds) to cache the list of countries. This information
* is very rarely updated. Default is 4 weeks.
* @access private
* @var int
*/
var $_cacheLengthCountries = 2419200;
/**
* PEAR error mode (when raiseError is called)
*
* @see setToDebug()
* @access private
* @var int
*/
var $_pearErrorMode = SERVICES_EXCHANGERATES_ERROR_RETURN;
/**
* Constructor
*
* This method overrides any default settings based on the $options
* parameter and retrieves feed data from the cache or their sources.
*
* $options is an associative array:
* <code>
* $options = array(
* 'roundToDecimal' => number of decimal places to round to (int),
* 'roundAutomatically' => whether to automatically round to
* $roundToDecimal digits (bool),
* 'thousandsSeparator' => character to separate every 1000 (string),
* 'decimalCharacter' => character for decimal place (string),
* 'cacheDirectory' => path (with trailing slash) to store cache
* files (string),
* 'cacheLengthRates' => length of time to cache exchange rates
* file (int),
* 'cacheLengthCurrencies' => length of time to cache currency
* list (int),
* 'cacheLengthCountries' => length of time to cache country list (int),
* 'pearErrorMode' => pear error mode (int));
* </code>
*
* @param string Driver name (filename minus 'Rates_' and .php) for exchange rate feed
* @param string Driver name for currency code list
* @param string Driver name for country code list (not yet used for anything)
* @param array Array to override default settings
*/
function __construct($ratesSource = 'ECB',
$currencySource = 'UN',
$countrySource = 'UN',
$options = array(NULL)) {
$availableOptions = array('roundToDecimal',
'roundAutomatically',
'thousandsSeparator',
'decimalCharacter',
'cacheDirectory',
'cacheLengthRates',
'cacheLengthCurrencies',
'cacheLengthCountries');
foreach($options as $key => $value) {
if(in_array($key, $availableOptions)) {
$property = '_'.$key;
$this->$property = $value;
}
}
$rateData = $this->retrieveData('Rates_' . $ratesSource, $this->_cacheLengthRates);
$this->rates = $rateData['rates'];
$this->ratesUpdated = $rateData['date'];
$this->ratesSource = $rateData['source'];
$this->currencies = $this->retrieveData('Currencies_' . $currencySource, $this->_cacheLengthCurrencies);
// not yet implimented, here for future features:
// $this->countries = $this->retrieveData('Countries_' . $countriesSource, $this->_cacheLengthCountries);
$this->validCurrencies = $this->getValidCurrencies($this->currencies, $this->rates);
}
/**
* Factory
*
* Includes the necessary driver, instantiates the class, retrieves the feed,
* and returns an associative array.
*
* @param string Driver filename (minus .php; this includes 'Rates_', etc.)
* @param int Cache length
* @return array Associative array containing the data requested
*/
function retrieveData($source, $cacheLength) {
include_once("Services/ExchangeRates/${source}.php");
$classname = "Services_ExchangeRates_${source}";
if (!class_exists($classname)) {
return $this->raiseError("No driver exists for the source ${source}... aborting.", SERVICES_EXCHANGERATES_ERROR_INVALID_DRIVER);
}
$class = new $classname;
return $class->retrieve($cacheLength, $this->_cacheDirectory);
}
/**
* Get list of currencies with known exchange rates
*
* Creates an array of currency codes and their names, based on
* overlapping elements in $rates and $currencies.
*
* @param array Array of currency codes to currency names
* @param array Array of currency codes to exchange rates
* @return array Array of currency codes to currency names that have a known exchange rate (sorted alphabetically)
*/
function getValidCurrencies($currencies, $rates) {
// loop through list of currencies
$validCurrencies = array();
foreach ($currencies as $code => $currency) {
// check to see if that currency has a known exchange rate
if (in_array($code, array_keys($rates))) {
// if so, add it to the array to return
$validCurrencies[$code] = $currency;
}
}
asort($validCurrencies);
return $validCurrencies;
}
function isValidCurrency($code) {
if (!in_array($code, array_keys($this->validCurrencies))) {
$this->raiseError('Error: Invalid currency: ' . $code, SERVICES_EXCHANGERATES_ERROR_INVALID_CURRENCY);
return false;
}
return true;
}
/**
* Convert currencies
*
* @param string Currency code of original currency
* @param string Currency code of target currency
* @param double Amount of original currency to convert
* @param boolean Format the final currency (add commas, round, etc.)
* @return mixed Currency converted to $to
*/
function convert($from, $to, $amount, $format = true) {
if ($this->isValidCurrency($from) && $this->isValidCurrency($to)) {
// Convert $from to whatever the base currency of the
// exchange rate feed is.
$base = (1 / $this->rates[$from]) * $amount;
// Convert from base currency to $to
$final = $this->rates[$to] * $base;
return ($format) ? $this->format($final) : $final;
}
$this->raiseError('Unable to convert!', SERVICES_EXCHANGERATES_ERROR_CONVERSION_ERROR);
return false;
}
/**
* Formats the converted currency
*
* This method adds $this->_thousandsSeparator between every group of thousands,
* and rounds to $this->_roundToDecimal decimal places. Use the $options parameter
* on the constructor to set these values.
*
* @param double Number to format
* @param mixed Number of decimal places to round to (null for default)
* @param mixed Character to use for decimal point (null for default)
* @param mixed Character to use for thousands separator (null for default)
* @return string Formatted currency
*/
function format($amount, $roundTo = null, $decChar = null, $sep = null) {
$roundTo = (($this->_roundAutomatically) ?
(($roundTo == null) ? $this->_roundToDecimal : $roundTo) :
'');
$decChar = ($decChar == null) ? $this->_decimalCharacter : $decChar;
$sep = ($sep == null) ? $this->_thousandsSeparator : $sep;
return number_format($amount, $roundTo, $decChar, $sep);
}
/**
* Get all rates as compared to a reference currency
*
* Returns an associative array with currency codes as keys and
* formated rates as values, as computed against a reference currency.
*
* @param string $referenceCurrency Reference currency code
* @return array List of currencies => rates
* @see Services_ExchangeRates::convert()
* @access public
*/
function getRates ($referenceCurrency)
{
$rates = array();
foreach ($this->validCurrencies as $code => $name) {
$rates[$code] = $this->convert($referenceCurrency, $code, 1, false);
}
ksort($rates);
return $rates;
}
/**
* Set to debug mode
*
* When an error is found, the script will stop and the message will be displayed
* (in debug mode only).
*/
function setToDebug()
{
self::$_pearErrorMode = SERVICES_EXCHANGERATES_ERROR_DIE;
}
/**
* Trigger a PEAR error
*
* To improve performances, the PEAR.php file is included dynamically.
* The file is so included only when an error is triggered. So, in most
* cases, the file isn't included and performance is much better.
*
* @param string error message
* @param int error code
*/
static function raiseError($msg, $code)
{
include_once('PEAR.php');
PEAR::raiseError($msg, $code, ( isset(self::$_pearErrorMode) ) ? self::$_pearErrorMode : SERVICES_EXCHANGERATES_ERROR_RETURN );
}
}
?>

View File

@ -0,0 +1,123 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: Common.php,v 1.1.1.1 2003/09/13 15:03:53 mroch Exp $
/**
* @author Marshall Roch <marshall@exclupen.com>
* @copyright Copyright 2003 Marshall Roch
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Cache_Lite is needed to cache the feeds
*/
if ( !class_exists('Cache_Lite') ) {
require_once 'Cache/Lite.php';
}
/**
* Common functions for data retrieval
*
* Provides base functions to retrieve and cache data feeds in different
* formats.
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Common {
/**
* Retrieves data from cache, if it's there. If it is, but it's expired,
* it performs a conditional GET to see if the data is updated. If it
* isn't, it down updates the modification time of the cache file and
* returns the data. If the cache is not there, or the remote file has been
* modified, it is downloaded and cached.
*
* @param string URL of remote file to retrieve
* @param int Length of time to cache file locally before asking the server
* if it changed.
* @return string File contents
*/
function retrieveFile($url, $cacheLength, $cacheDir) {
$cacheID = md5($url);
$cache = new Cache_Lite(array("cacheDir" => $cacheDir,
"lifeTime" => $cacheLength));
if ($data = $cache->get($cacheID)) {
return $data;
} else {
// we need to perform a request, so include HTTP_Request
include_once 'HTTP/Request.php';
// HTTP_Request has moronic redirect "handling", turn that off (Alexey Borzov)
$req = new HTTP_Request($url, array('allowRedirects' => false));
// if $cache->get($cacheID) found the file, but it was expired,
// $cache->_file will exist
if (isset($cache->_file) && file_exists($cache->_file)) {
$req->addHeader('If-Modified-Since', gmdate("D, d M Y H:i:s", filemtime($cache->_file)) ." GMT");
}
$req->addHeader('User-Agent', 'Firefox (WindowsXP) Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
$req->sendRequest();
if (!($req->getResponseCode() == 304)) {
// data is changed, so save it to cache
$data = $req->getResponseBody();
$cache->save($data, $cacheID);
return $data;
} else {
// retrieve the data, since the first time we did this failed
if ($data = $cache->get($cacheID, 'default', true)) {
return $data;
}
}
}
Services_ExchangeRates::raiseError("Unable to retrieve file ${url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED);
return false;
}
/**
* Downloads XML file or returns it from cache
*
* @param string URL of XML file
* @param int Length of time to cache
* @return object XML_Tree object
*/
function retrieveXML($url, $cacheLength, $cacheDir) {
include_once 'XML/Tree.php';
if ($data = $this->retrieveFile($url, $cacheLength, $cacheDir)) {
$tree = new XML_Tree();
$root = $tree->getTreeFromString($data);
return $root;
}
return false;
}
}
?>

View File

@ -0,0 +1,79 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: Countries_UN.php,v 1.1.1.1 2003/09/13 15:03:53 mroch Exp $
/**
*
* @author Marshall Roch <marshall@exclupen.com>
* @copyright Copyright 2003 Marshall Roch
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* United Nations country codes driver
*
* Retrieves the ISO 3166 country codes in XML format from the United
* Nations Economic Commission for Europe. This file is cached for 1 month
* by default, since it hardly ever changes.
*
* @link http://www.unece.org/etrades/unedocs/repository/codelists/xml/CountryCodeList.xml
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Countries_UN extends Services_ExchangeRates_Common {
/**
* URL of XML feed
* @var string
*/
var $feedUrl = 'http://www.timetrex.com/CountryCodeList.xml';
//var $feedUrl = 'http://www.unece.org/etrades/unedocs/repository/codelists/xml/CountryCodeList.xml';
/**
* Retrieves currency codes and their associated names (e.g. USD => US Dollar)
* from the UN or the cache. The default cache length is 1 month.
*
* @param int Optionally override default 1 month cache length (in seconds)
* @return array Array of currency codes to currency names
*/
function retrieve($cacheLength, $cacheDir) {
// retrieve the feed from the server or cache
$root = $this->retrieveXML($this->feedUrl, $cacheLength, $cacheDir);
foreach($root->children as $curr) {
// Filter out blank or unwanted elements
if ($curr->name == "Country") {
// loop through and put them into an array
$countries[$curr->children[0]->content] = $curr->children[1]->content;
}
}
return $countries;
}
}
?>

View File

@ -0,0 +1,94 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: Currencies_UN.php,v 1.3 2005/06/23 08:10:21 cross Exp $
/**
* Currency code driver - United Nations Economic Commision for Europe
*
* Retrieves the ISO 4217 currency codes in XML format from the United
* Nations Economic Commission for Europe. This file is cached for 4 weeks
* by default, since it hardly ever changes. In the event that a new
* currency is added and there is a known exchange rate for that currency,
* it will be automatically added to the list.
*
* @author Marshall Roch <marshall@exclupen.com>
* @copyright Copyright 2003 Marshall Roch
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* United Nations Currency Codes Driver
*
* @link http://www.unece.org/etrades/uncopyright.htm IMPORTANT COPYRIGHT INFORMATION
* @link http://www.unece.org/etrades/unedocs/repository/codelists/xml/CurrencyCodeList.xml
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Currencies_UN extends Services_ExchangeRates_Common {
/**
* URL of XML feed
* @var string
*/
var $feedUrl = 'http://www.timetrex.com/CurrencyCodeList.xml';
//var $feedUrl = 'http://www.unece.org/etrades/unedocs/repository/codelists/xml/CurrencyCodeList.xml';
/**
* Retrieves currency codes and their associated names (e.g. USD => US Dollar)
* from the UN or the cache. The default cache length is 1 month.
*
* @param int Optionally override default 1 month cache length (in seconds)
* @return array Array of currency codes to currency names
*/
/**
* Downloads exchange rates in terms of the Euro from the European Central Bank. This
* information is updated daily, and is cached by default for 1 hour.
*
* @link http://www.ecb.int/stats/eurofxref/ HTML version
* @link http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml XML version
*
* @param int Length of time to cache (in seconds)
* @return array Array of currency codes to exchange rates
*/
function retrieve($cacheLength, $cacheDir) {
// retrieve the feed from the server or cache
$root = $this->retrieveXML($this->feedUrl, $cacheLength, $cacheDir);
foreach($root->children as $curr) {
// Filter out blank or unwanted elements
if ($curr->name == "Currency") {
// loop through and put them into an array
$currencies[$curr->children[1]->content] = $curr->children[3]->content;
}
}
return $currencies;
}
}
?>

View File

@ -0,0 +1,107 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_ECB.php,v 1.2 2005/06/23 07:44:12 cross Exp $
/**
* Exchange rate driver - European Central Bank
*
* The reference rates are based on the regular daily concertation
* procedure between central banks within and outside the European System
* of Central Banks, which normally takes place at 2.15 p.m. ECB time (CET).
* The reference exchange rates are published both by electronic market
* information providers and on the ECB's website shortly after the
* concertation procedure has been completed.
*
* @link http://www.ecb.int/stats/eurofxref/eurofxref-xml.html About the feed
* @link http://www.ecb.int/copy/copy01.htm IMPORTANT COPYRIGHT INFORMATION
*
* @author Marshall Roch <marshall@exclupen.com>
* @copyright Copyright 2003 Marshall Roch
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* European Central Bank Exchange Rate Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_ECB extends Services_ExchangeRates_Common {
/**
* URL of XML feed
* @access private
* @var string
*/
var $_feedXMLUrl = 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml';
/**
* Downloads exchange rates in terms of the Euro from the European Central Bank. This
* information is updated daily, and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @link http://www.ecb.int/stats/eurofxref/ HTML version
* @link http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml XML version
*
* @param int Length of time to cache (in seconds)
* @return array Multi-dimensional array
*/
function retrieve($cacheLength, $cacheDir) {
// IMPORTANT: defines Euro mapping. Without this, you can't convert
// to or from the Euro!
$return['date'] = NULL;
$return['rates'] = array('EUR' => 1.0);
$return['source'] = $this->_feedXMLUrl;
// retrieve the feed from the server or cache
$root = $this->retrieveXML($this->_feedXMLUrl, $cacheLength, $cacheDir);
if ( is_object( $root ) ) {
// set date published
$return['date'] = $root->children[5]->children[1]->attributes['time'];
// get down to array of exchange rates
$xrates = $root->children[5]->children[1]->children;
// loop through and put them into an array
foreach ($xrates as $rateinfo) {
if ($rateinfo->name == 'Cube') {
$return['rates'][$rateinfo->attributes['currency']] = $rateinfo->attributes['rate'];
}
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,97 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Piotr Klaban <makler@man.torun.pl> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_NBP.php,v 1.1.1.1 2003/09/13 15:03:54 mroch Exp $
/**
* Exchange rate driver - XE.net
*
* Retrieves exchange rates from XE.net
* Snippet from RatesA.html:
*
* @link http://www.xe.net
*
* @author Unknown
* @copyright
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* National Bank of Poland Exchange Rate Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_GOOGLE extends Services_ExchangeRates_Common {
/**
* URL of HTML page where the rates are given
* @var string
*/
var $feedHTMLUrl = 'http://www.google.com/search?num=0&q=';
/**
* Downloads exchange rates from XE.com
* This information is updated daily, and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @param int Length of time to cache (in seconds)
* @return array
*/
function retrieve($cacheLength, $cacheDir) {
$return['rates'] = array('USD' => 1.0);
$return['source'] = $this->feedHTMLUrl;
$return['date'] = time();
$supported_currencies = array('DZD','XAL','ARS','AWG','AUD','BSD','BHD','BDT','BBD','BYR','BZD','BMD','BTN','BOB','BWP','BRL','GBP','BND','BGN','BIF','KHR','CAD','CVE','KYD','XOF','XAF','CLP','CNY','COP','KMF','XCP','CRC','HRK','CUP','CYP','CZK','DKK','DJF','DOP','XCD','ECS','EGP','SVC','ERN','EEK','ETB','EUR','FKP','FJD','GMD','GHC','GIP','XAU','GTQ','GNF','GYD','HTG','HNL','HKD','HUF','ISK','INR','IDR','IRR','IQD','ILS','JMD','JPY','JOD','KZT','KES','KRW','KWD','LAK','LVL','LBP','LSL','LRD','LYD','LTL','MOP','MKD','MWK','MYR','MVR','MTL','MRO','MUR','MXN','MDL','MNT','MAD','MMK','NAD','NPR','ANG','TRY','NZD','ZWN','NIO','NGN','KPW','NOK','OMR','XPF','PKR','XPD','PAB','PGK','PYG','PEN','PHP','XPT','PLN','QAR','RON','RUB','RWF','WST','STD','SAR','SCR','SLL','SGD','SKK','SIT','SBD','SOS','ZAR','LKR','SHP','SDD','SZL','SEK','CHF','SYP','TWD','TZS','THB','TOP','TTD','TND','USD','AED','UGX','UAH','UYU','VUV','VEB','VND','YER','ZMK');
if ( is_array($supported_currencies) AND count($supported_currencies) > 0 ) {
foreach( $supported_currencies as $currency ) {
$feed_url = $this->feedHTMLUrl . urlencode('1.0 USD in '. $currency);
var_dump($feed_url);
$htmlpage = $this->retrieveFile( $feed_url, $cacheLength, $cacheDir);
var_dump($htmlpage);
preg_match_all('/<b>1.0 U.S. dollar = ([0-9\.,]{2,20}) .*<\/b>/i', $htmlpage, $matches);
if ( is_array($matches) AND isset($matches[1][0]) AND is_numeric($matches[1][0]) ) {
$return['rates'][$currency] = (float)$matches[1][0];
}
break;
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,98 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Simon Br<42>chner <powtac@gmx.de> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_NBI.php,v 1.1 2004/02/22 14:11:54 mroch Exp $
/**
* Exchange rate driver - National Bank of Israel
*
* The Excange Rates of the National Bank of Israel are updated daily.
*
* @link http://www.bankisrael.gov.il/eng.shearim/
*
* @author Simon Br<42>chner <powtac@gmx.de>
* @copyright Copyright 2003 Simon Br<42>chner
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* National Bank of Israel Currency Exchange Rates Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_NBI extends Services_ExchangeRates_Common {
/**
* URL of XML feed
* @access private
* @var string
*/
var $_feedXMLUrl = 'http://www.bankisrael.gov.il/heb.shearim/currency.php';
/**
* Downloads exchange rates in terms of the ILS (New Israeli Shequel) from
* the National Bank of Israel. This information is updated daily,
* and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @link http://www.bankisrael.gov.il/eng.shearim/ HTML version
* @link http://www.bankisrael.gov.il/heb.shearim/currency.php XML version
*
* @param int Length of time to cache (in seconds)
* @return array Multi-dimensional array
*/
function retrieve($cacheLength, $cacheDir) {
// IMPORTANT: defines ILS mapping. Without this, you can't convert
// to or from ILS!
$return['rates'] = array('ILS' => 1.0);
$return['source'] = $this->_feedXMLUrl;
// retrieve the feed from the server or cache
$root = $this->retrieveXML($this->_feedXMLUrl, $cacheLength, $cacheDir);
// set date published
$return['date'] = $root->children[0]->content;
// get down to array of exchange rates
$xrates = $root->children;
// loop through and put them into an array
foreach ($xrates as $rateinfo) {
if ($rateinfo->children[4]->content != 0) {
$return['rates'][$rateinfo->children[2]->content] =
1 / $rateinfo->children[4]->content
* $rateinfo->children[1]->content;
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,129 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Piotr Klaban <makler@man.torun.pl> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_NBP.php,v 1.1.1.1 2003/09/13 15:03:54 mroch Exp $
/**
* Exchange rate driver - National Bank of Poland
*
* Retrieves daily exchange rates from the National Bank of Poland
* Snippet from RatesA.html:
*
* Current average exchange rates of foreign currencies in zlotys defined in 2
* para. 1 and 2 of the Resolution No. 51/2002 of the Management Board of the
* National Bank of Poland on the way of calculating and announcing current
* exchange rates of foreign currencies, of September 23, 2002 (Dziennik
* Urzedowy NBP no. 14, item 39 and no. 20, item 51)
*
* @link http://www.nbp.pl/Kursy/RatesA.html English HTML version
* @link http://www.nbp.pl/Kursy/KursyA.html Polish HTML version (with link to XML)
*
* @author Piotr Klaban <makler@man.torun.pl>
* @copyright Copyright 2003 Piotr Klaban
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* National Bank of Poland Exchange Rate Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_NBP extends Services_ExchangeRates_Common {
/**
* URL of XML feed
* @var string
*/
var $feedXMLUrl;
/**
* URL of HTML page where the XML feed URL is given
* @var string
*/
var $feedHTMLUrl = 'http://www.nbp.pl/Kursy/KursyA.html';
/**
* Directory in which the XML file is located
* @var string
*/
var $feedDir = 'http://www.nbp.pl/Kursy/';
/**
* Downloads exchange rates in terms of the PLN from the National Bank of
* Poland (NBP). This information is updated daily, and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @link http://www.nbp.pl/Kursy/RatesA.html English HTML version
* @link http://www.nbp.pl/Kursy/KursyA.html Polish HTML version (with link to XML)
*
* @param int Length of time to cache (in seconds)
* @return array
*/
function retrieve($cacheLength, $cacheDir) {
$return['rates'] = array('PLN' => 1.0);
// retrieve XML address
$htmlpage = $this->retrieveFile($this->feedHTMLUrl, $cacheLength, $cacheDir);
// Example line is:
// <div class="file"><a href="xml/a055z020319.xml">powysza tabela w formacie .xml</a></div>
if (!preg_match('#href="(xml/a\d+z\d+\.xml)"#', $htmlpage, $match))
{
Services_ExchangeRates::raiseError("Retrieved url " . $this->feedHTMLUrl . " has no link to XML page", SERVICES_EXCHANGERATES_RETRIEVAL_FAILED);
return false;
}
$this->feedXMLUrl = $this->feedDir . $match[1];
$return['source'] = $this->_feedXMLUrl;
// retrieve the feed from the server or cache
$root = $this->retrieveXML($this->feedXMLUrl, $cacheLength, $cacheDir);
// get down to array of exchange rates
foreach ($root->children as $rateinfo) {
if ($rateinfo->name == 'pozycja')
{
$rateinfo->children[4]->content = strtr($rateinfo->children[4]->content, ',', '.');
$value = $rateinfo->children[2]->content // przelicznik (conversion rate)
/ $rateinfo->children[4]->content; // currency rate
$return['rates'][$rateinfo->children[3]->content] = $value;
} elseif ($rateinfo->name == 'data_publikacji')
{
// set date published
$return['date'] = $rateinfo->content;
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,102 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Piotr Klaban <makler@man.torun.pl> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_NBP.php,v 1.1.1.1 2003/09/13 15:03:54 mroch Exp $
/**
* Exchange rate driver - XE.net
*
* Retrieves exchange rates from XE.net
* Snippet from RatesA.html:
*
* @link http://www.xe.net
*
* @author Unknown
* @copyright
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* National Bank of Poland Exchange Rate Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_XE extends Services_ExchangeRates_Common {
/**
* URL of HTML page where the rates are given
* @var string
*/
var $feedHTMLUrl = 'http://www.xe.com/ict/?basecur=USD&hide_inverse=true&historical=false';
/**
* Downloads exchange rates from XE.com
* This information is updated daily, and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @param int Length of time to cache (in seconds)
* @return array
*/
function retrieve($cacheLength, $cacheDir) {
$return['rates'] = array('USD' => 1.0);
$return['source'] = $this->feedHTMLUrl;
// retrieve XML address
$htmlpage = $this->retrieveFile($this->feedHTMLUrl, $cacheLength, $cacheDir);
//Get date rates were generated
preg_match('/rates as of <b>(.*)<\/td>/i', $htmlpage, $raw_date);
if ( isset($raw_date[1]) )
{
$return['date'] = strtotime( $raw_date[1] );
}
//Remove any HTML comments.
$htmlpage = preg_replace('/<!--\s+.*\s+-->/i','', $htmlpage );
//Get actual rates here
preg_match_all('/<td align="left" class="bbl">([A-Z]{3,5})<\/td><td align="left" class="bbr">(.*)<\/td><td align="right" class="bbr">([0-9\.,]{9,20})<\/td>/i', $htmlpage, $matches);
if ( is_array($matches) )
{
foreach( $matches[1] as $key => $val ) {
if ( isset($matches[3][$key]) ){
$return['rates'][trim($val)] = str_replace( array(' ', ','), '', $matches[3][$key] );
}
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,147 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Piotr Klaban <makler@man.torun.pl> |
// +----------------------------------------------------------------------+
//
// $Id: Rates_NBP.php,v 1.1.1.1 2003/09/13 15:03:54 mroch Exp $
/**
* Exchange rate driver - Yahoo.com
*
* Retrieves exchange rates from Yahoo.com
* Snippet from RatesA.html:
*
* @link http://www.yahoo.com
*
* @author Unknown
* @copyright
* @license http://www.php.net/license/2_02.txt PHP License 2.0
* @package Services_ExchangeRates
*/
/**
* Include common functions to handle cache and fetch the file from the server
*/
require_once 'Services/ExchangeRates/Common.php';
/**
* National Bank of Poland Exchange Rate Driver
*
* @package Services_ExchangeRates
*/
class Services_ExchangeRates_Rates_YAHOO extends Services_ExchangeRates_Common {
/**
* URL of HTML page where the rates are given
* @var string
*/
var $feedHTMLUrl = 'http://download.finance.yahoo.com/d/quotes.csv?f=sl1d1t1ba&e=.csv&';
//For some reason Yahoo won't return more then one currency at a time if we use PEAR HTTP_Request class.
//Very strange.
function _retrieveFile($url, $cacheLength, $cacheDir) {
$cacheID = md5($url);
$cache = new Cache_Lite(array("cacheDir" => $cacheDir,
"lifeTime" => $cacheLength));
if ($data = $cache->get($cacheID)) {
return $data;
} else {
$fp = fopen($url,'r');
$data = stream_get_contents($fp);
if ( strlen($data) > 10 ) {
// data is changed, so save it to cache
$cache->save($data, $cacheID);
return $data;
} else {
// retrieve the data, since the first time we did this failed
if ($data = $cache->get($cacheID, 'default', true)) {
return $data;
}
}
}
Services_ExchangeRates::raiseError("Unable to retrieve file ${url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED);
return false;
}
/**
* Downloads exchange rates from XE.com
* This information is updated daily, and is cached by default for 1 hour.
*
* Returns a multi-dimensional array containing:
* 'rates' => associative array of currency codes to exchange rates
* 'source' => URL of feed
* 'date' => date feed last updated, pulled from the feed (more reliable than file mod time)
*
* @param int Length of time to cache (in seconds)
* @return array
*/
function retrieve($cacheLength, $cacheDir) {
$return['rates'] = array('USD' => 1.0);
$return['source'] = $this->feedHTMLUrl;
$return['date'] = time();
$supported_currencies = array('ALL','DZD','XAL','ARS','AWG','AUD','BSD','BHD','BDT','BBD','BYR','BZD','BMD','BTN','BOB','BWP','BRL','GBP','BND','BGN','BIF','KHR','CAD','CVE','KYD','XOF','XAF','CLP','CNY','COP','KMF','XCP','CRC','HRK','CUP','CYP','CZK','DKK','DJF','DOP','XCD','ECS','EGP','SVC','ERN','EEK','ETB','EUR','FKP','FJD','GMD','GHC','GIP','XAU','GTQ','GNF','GYD','HTG','HNL','HKD','HUF','ISK','INR','IDR','IRR','IQD','ILS','JMD','JPY','JOD','KZT','KES','KRW','KWD','LAK','LVL','LBP','LSL','LRD','LYD','LTL','MOP','MKD','MWK','MYR','MVR','MTL','MRO','MUR','MXN','MDL','MNT','MAD','MMK','NAD','NPR','ANG','TRY','NZD','ZWN','NIO','NGN','KPW','NOK','OMR','XPF','PKR','XPD','PAB','PGK','PYG','PEN','PHP','XPT','PLN','QAR','RON','RUB','RWF','WST','STD','SAR','SCR','SLL','SGD','SKK','SIT','SBD','SOS','ZAR','LKR','SHP','SDD','SZL','SEK','CHF','SYP','TWD','TZS','THB','TOP','TTD','TND','USD','AED','UGX','UAH','UYU','VUV','VEB','VND','YER','ZMK');
//Loop through all currencies making URLs in batch of 10
//YAHOO stopped allowing batch downloads it seems 06-Apr-08.
$batch_size = 10;
if ( is_array($supported_currencies) AND count($supported_currencies) > 0 ) {
$i=1;
$max = count($supported_currencies);
foreach( $supported_currencies as $currency ) {
$batch_currency[] = 's=USD'. $currency . urlencode('=X');
if ( $i % $batch_size == 0 OR $i == $max ) {
$batch_currency_url = implode('&',$batch_currency);
$feed_url = $this->feedHTMLUrl . $batch_currency_url;
//echo "Feed URL: $feed_url<br>\n";
$htmlpage = $this->_retrieveFile( $feed_url, $cacheLength, $cacheDir);
//echo "Page: $htmlpage<br>\n";
$lines = explode("\n", $htmlpage);
if ( is_array($lines) ) {
foreach($lines as $line) {
$values = explode(',', $line);
if ( is_array($values) AND isset($values[1]) AND is_numeric($values[1]) AND $values[1] > 0 ) {
$currency = substr($values[0],4,3);
$return['rates'][$currency] = (float)$values[1];
}
}
}
unset($batch_currency);
}
$i++;
}
}
return $return;
}
}
?>

View File

@ -0,0 +1,100 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Marshall Roch <marshall@exclupen.com> |
// +----------------------------------------------------------------------+
//
// $Id: example.php,v 1.3 2005/06/23 08:10:19 cross Exp $
/**
* Example using Services_ExchangeRates to create a form-based currency converter
*
* @package Services_ExchangeRates
*/
/**
* Requires Services_ExchangeRates to function
*/
require_once 'Services/ExchangeRates.php';
/**
* Creates new instance of currency converter
*
* @param string Choose where the exchange rates are coming from. In this case,
* it's the European Central Bank.
* @param string Choose where the currency rates are coming from. In this case,
* it's the United Nations.
*/
$conv = new Services_ExchangeRates('ECB', 'UN');
?>
<html>
<head>
<title>Currency Converter - PEAR::Services_ExchangeRates Example</title>
</head>
<body>
<h1>Currency Converter</h1>
<?php
if (!empty($_POST['amount'])) {
echo "<h1>";
echo $conv->format($_POST['amount']) . ' ' . $_POST['from'];
echo " = ";
echo $conv->convert($_POST['from'], $_POST['to'], $_POST['amount']) . ' ' . $_POST['to'];
echo "</h1>";
} else {
echo "<h1>Enter how much you want to convert!</h1>";
}
$options = array();
foreach ($conv->validCurrencies as $code => $label) {
$options .= '<option value="' . $code . '">' . $label . '</option>';
}
?>
<h2>I want to convert...</h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table style="border-collapse: separate; border-spacing: 1em;">
<tr style="text-align: center;">
<td>
<label for="amount">this amount</label><br />
<input type="text" name="amount" id="amount" value="1" />
</td>
<td>
<label for="from">of this type of currency</label><br />
<select name="from" id="from">
<?php echo $options; ?>
</select>
</td>
<td>
<label for="to">to this type of currency</label><br />
<select name="to" id="to">
<?php echo $options; ?>
</select>
</td>
</tr>
<tr style="text-align: center;">
<td colspan="3">
<input type="submit" value="Convert my money!" />
</td>
</tr>
</table>
</form>
</body>
</html>