CurrencyLib.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * other webservices:
  4. * - http://www.webservicex.net/WS/WSDetails.aspx?WSID=10 (XML)
  5. * - http://www.webserviceshare.com/business/financial/currency/service/Noon-Foreign-Exchange-Rates.htm (XML)
  6. */
  7. App::uses('HttpSocket', 'Network/Http');
  8. App::uses('Xml', 'Utility');
  9. /**
  10. * Component to retreive calculate currencies
  11. *
  12. * example:
  13. * $result = $this->Currency->convert(2.5, 'EUR', 'USD');
  14. *
  15. * from: http://www.studiocanaria.com/articles/cakephp_currency_conversion_component
  16. * alternativly: http://www.currencyserver.de/webservice/CurrencyServerWebService.asmx/getXmlStream?provider=AVERAGE
  17. *
  18. * @author Mark Scherer
  19. * @license MIT
  20. * @cakephp 2.x
  21. * 2009-11-23 ms
  22. */
  23. class CurrencyLib {
  24. const URL = 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml';
  25. const URL_HISTORY = 'http://www.ecb.int/stats/eurofxref/eurofxref-hist.xml';
  26. //TODO: get information about a currency (name, ...)
  27. const URL_TABLE = 'http://www.ecb.int/rss/fxref-{currency}.html';
  28. public $baseCurrency = 'EUR';
  29. public $includeBitcoin = true;
  30. public $cacheFileUsed = false;
  31. public $cacheTime = DAY;
  32. /**
  33. * convert
  34. *
  35. * Converts the $amount from $fromCurrency to $toCurrency, formatted to
  36. * $decimals decimal places
  37. *
  38. * @return float [Converted Currency Amount] or boolean FALSE on failure
  39. * @param $amount float
  40. * @param $fromCurrency string
  41. * @param $toCurrency string
  42. * @param $decimals integer[optional]default=2
  43. */
  44. public function convert($amount, $fromCurrency, $toCurrency, $decimals = 2) {
  45. //Get the rate table
  46. $rates = $this->_retrieveCurrencies();
  47. //Return result of conversion
  48. if (!array_key_exists($fromCurrency, $rates) || !array_key_exists($toCurrency, $rates)) {
  49. return false;
  50. }
  51. return number_format($amount/$rates[$fromCurrency]*$rates[$toCurrency], $decimals);
  52. }
  53. /**
  54. * table
  55. *
  56. * Returns an array of rates in comparison the the $base currency given to $decimals
  57. * number of decimal places
  58. *
  59. * @return array $table or boolean FALSE on failure
  60. * @param $base string[optional]default='EUR'
  61. * @param $decimals integer[optional]default=2
  62. */
  63. public function table($base = 'EUR', $decimals = 2) {
  64. //Create array to holds rates
  65. $rateTable = array();
  66. //Get rate table array
  67. $rates = $this->_retrieveCurrencies();
  68. if (!array_key_exists($base, $rates)) {
  69. return false;
  70. }
  71. //Iterate throught each rate converting it against $base
  72. foreach ($rates as $key => $value) {
  73. $rate = 0;
  74. if ($value > 0) {
  75. $rate = 1 / $rates[$base] * $rates[$key];
  76. }
  77. $rateTable[$key] = number_format($rate, $decimals);
  78. }
  79. //Return result array
  80. return $rateTable;
  81. }
  82. /**
  83. * CurrencyComponent::isAvailable()
  84. *
  85. * @param mixed $currency
  86. * @return bool Success
  87. */
  88. public function isAvailable($currency) {
  89. $rates = $this->_retrieveCurrencies();
  90. return array_key_exists($currency, $rates);
  91. }
  92. /**
  93. * @param string $name: "" (none), "history", "full" (both)
  94. * 2010-09-19 ms
  95. */
  96. public function reset($name = 'full') {
  97. if ($name === 'full') {
  98. $name = '';
  99. Cache::delete('currencyListHistory');
  100. }
  101. return Cache::delete('currencyList' . ucfirst($name));
  102. }
  103. public function cacheFileUsed() {
  104. return $this->cacheFileUsed;
  105. }
  106. /**
  107. * @param string $code (3digit - e.g. EUR)
  108. * @param mixed $default (defaults to bool false)
  109. */
  110. public function getName($currency, $default = false) {
  111. if (empty($currency)) {
  112. return $default;
  113. }
  114. $currency = strtoupper($currency);
  115. $currencies = $this->currencies;
  116. if ($this->includeBitcoin) {
  117. $currencies['BTC'] = 'Bitcoin';
  118. }
  119. if (array_key_exists($currency, $currencies)) {
  120. return $currencies[$currency];
  121. }
  122. return $default;
  123. }
  124. /**
  125. * CurrencyComponent::_retrieveHistory()
  126. *
  127. * @return array
  128. */
  129. protected function _retrieveHistory() {
  130. if ($historyList = $this->_retrieve('history')) {
  131. return $historyList;
  132. }
  133. //Create an http socket
  134. $Xml = Xml::build(self::URL_HISTORY);
  135. $currencies = Xml::toArray($Xml);
  136. //Filter down to just the rates
  137. $currencies = $currencies['Envelope']['Cube']['Cube']['Cube'];
  138. $historyList = array();
  139. //European Central bank gives us everything against Euro so add this manually
  140. $historyList[$this->baseCurrency] = 1;
  141. //Now iterate through and add the rates provided
  142. foreach ($currencies as $currency) {
  143. $historyList[$currency['currency']] = $currency['rate'];
  144. }
  145. //Cache
  146. $this->_store($historyList, 'history');
  147. return $currencyList;
  148. }
  149. /**
  150. * CurrencyComponent::_retrieveCurrencies()
  151. *
  152. * @return array
  153. */
  154. protected function _retrieveCurrencies() {
  155. if ($currencyList = $this->_retrieve()) {
  156. return $currencyList;
  157. }
  158. // Retrieve rates as an XML object
  159. $CurrencyXml = Xml::build(self::URL);
  160. $currencies = Xml::toArray($CurrencyXml);
  161. //Filter down to just the rates
  162. $currencies = $currencies['Envelope']['Cube']['Cube']['Cube'];
  163. //Create an array to hold the rates
  164. $currencyList = array();
  165. //European Central bank gives us everything against Euro so add this manually
  166. $currencyList[$this->baseCurrency] = 1;
  167. //Now iterate through and add the rates provided
  168. foreach ($currencies as $currency) {
  169. $currencyList[$currency['@currency']] = $currency['@rate'];
  170. }
  171. if ($this->includeBitcoin && ($res = $this->_getBitcoin())) {
  172. $currencyList['BTC'] = $res;
  173. }
  174. //Cache
  175. $this->_store($currencyList);
  176. return $currencyList;
  177. }
  178. protected function _getBitcoin() {
  179. App::uses('CurrencyBitcoinLib', 'Tools.Lib');
  180. $Btc = new CurrencyBitcoinLib();
  181. return $Btc->rate(array('currency'=>$this->baseCurrency));
  182. }
  183. /**
  184. * @param string $name: "" (none), "history", "full" (both)
  185. * 2010-09-19 ms
  186. */
  187. protected function _store($currencyList, $name = '') {
  188. $this->cacheFileUsed = false;
  189. Cache::write('currencyList'.ucfirst($name), serialize($currencyList));
  190. }
  191. /**
  192. * @param string $name: "" (none), "history", "full" (both)
  193. * 2010-09-19 ms
  194. */
  195. protected function _retrieve($name = '') {
  196. $res = Cache::read('currencyList'.ucfirst($name));
  197. if ($res !== false) {
  198. $this->cacheFileUsed = true;
  199. return unserialize($res);
  200. }
  201. return false;
  202. }
  203. public $currencies = array(
  204. 'AFA' => 'Afghanistan Afghani',
  205. 'ALL' => 'Albanian Lek',
  206. 'DZD' => 'Algerian Dinar',
  207. 'ARS' => 'Argentine Peso',
  208. 'AWG' => 'Aruba Florin',
  209. 'AUD' => 'Australian Dollar',
  210. 'BSD' => 'Bahamian Dollar',
  211. 'BHD' => 'Bahraini Dinar',
  212. 'BDT' => 'Bangladesh Taka',
  213. 'BBD' => 'Barbados Dollar',
  214. 'BZD' => 'Belize Dollar',
  215. 'BMD' => 'Bermuda Dollar',
  216. 'BTN' => 'Bhutan Ngultrum',
  217. 'BOB' => 'Bolivian Boliviano',
  218. 'BWP' => 'Botswana Pula',
  219. 'BRL' => 'Brazilian Real',
  220. 'GBP' => 'British Pound',
  221. 'BND' => 'Brunei Dollar',
  222. 'BIF' => 'Burundi Franc',
  223. 'XOF' => 'CFA Franc (BCEAO)',
  224. 'XAF' => 'CFA Franc (BEAC)',
  225. 'KHR' => 'Cambodia Riel',
  226. 'CAD' => 'Canadian Dollar',
  227. 'CVE' => 'Cape Verde Escudo',
  228. 'KYD' => 'Cayman Islands Dollar',
  229. 'CLP' => 'Chilean Peso',
  230. 'CNY' => 'Chinese Yuan',
  231. 'COP' => 'Colombian Peso',
  232. 'KMF' => 'Comoros Franc',
  233. 'CRC' => 'Costa Rica Colon',
  234. 'HRK' => 'Croatian Kuna',
  235. 'CUP' => 'Cuban Peso',
  236. 'CYP' => 'Cyprus Pound',
  237. 'CZK' => 'Czech Koruna',
  238. 'DKK' => 'Danish Krone',
  239. 'DJF' => 'Dijibouti Franc',
  240. 'DOP' => 'Dominican Peso',
  241. 'XCD' => 'East Caribbean Dollar',
  242. 'EGP' => 'Egyptian Pound',
  243. 'SVC' => 'El Salvador Colon',
  244. 'EEK' => 'Estonian Kroon',
  245. 'ETB' => 'Ethiopian Birr',
  246. 'EUR' => 'Euro',
  247. 'FKP' => 'Falkland Islands Pound',
  248. 'GMD' => 'Gambian Dalasi',
  249. 'GHC' => 'Ghanian Cedi',
  250. 'GIP' => 'Gibraltar Pound',
  251. 'XAU' => 'Gold Ounces',
  252. 'GTQ' => 'Guatemala Quetzal',
  253. 'GNF' => 'Guinea Franc',
  254. 'GYD' => 'Guyana Dollar',
  255. 'HTG' => 'Haiti Gourde',
  256. 'HNL' => 'Honduras Lempira',
  257. 'HKD' => 'Hong Kong Dollar',
  258. 'HUF' => 'Hungarian Forint',
  259. 'ISK' => 'Iceland Krona',
  260. 'INR' => 'Indian Rupee',
  261. 'IDR' => 'Indonesian Rupiah',
  262. 'IQD' => 'Iraqi Dinar',
  263. 'ILS' => 'Israeli Shekel',
  264. 'JMD' => 'Jamaican Dollar',
  265. 'JPY' => 'Japanese Yen',
  266. 'JOD' => 'Jordanian Dinar',
  267. 'KZT' => 'Kazakhstan Tenge',
  268. 'KES' => 'Kenyan Shilling',
  269. 'KRW' => 'Korean Won',
  270. 'KWD' => 'Kuwaiti Dinar',
  271. 'LAK' => 'Lao Kip',
  272. 'LVL' => 'Latvian Lat',
  273. 'LBP' => 'Lebanese Pound',
  274. 'LSL' => 'Lesotho Loti',
  275. 'LRD' => 'Liberian Dollar',
  276. 'LYD' => 'Libyan Dinar',
  277. 'LTL' => 'Lithuanian Lita',
  278. 'MOP' => 'Macau Pataca',
  279. 'MKD' => 'Macedonian Denar',
  280. 'MGF' => 'Malagasy Franc',
  281. 'MWK' => 'Malawi Kwacha',
  282. 'MYR' => 'Malaysian Ringgit',
  283. 'MVR' => 'Maldives Rufiyaa',
  284. 'MTL' => 'Maltese Lira',
  285. 'MRO' => 'Mauritania Ougulya',
  286. 'MUR' => 'Mauritius Rupee',
  287. 'MXN' => 'Mexican Peso',
  288. 'MDL' => 'Moldovan Leu',
  289. 'MNT' => 'Mongolian Tugrik',
  290. 'MAD' => 'Moroccan Dirham',
  291. 'MZM' => 'Mozambique Metical',
  292. 'MMK' => 'Myanmar Kyat',
  293. 'NAD' => 'Namibian Dollar',
  294. 'NPR' => 'Nepalese Rupee',
  295. 'ANG' => 'Neth Antilles Guilder',
  296. 'NZD' => 'New Zealand Dollar',
  297. 'NIO' => 'Nicaragua Cordoba',
  298. 'NGN' => 'Nigerian Naira',
  299. 'KPW' => 'North Korean Won',
  300. 'NOK' => 'Norwegian Krone',
  301. 'OMR' => 'Omani Rial',
  302. 'XPF' => 'Pacific Franc',
  303. 'PKR' => 'Pakistani Rupee',
  304. 'XPD' => 'Palladium Ounces',
  305. 'PAB' => 'Panama Balboa',
  306. 'PGK' => 'Papua New Guinea Kina',
  307. 'PYG' => 'Paraguayan Guarani',
  308. 'PEN' => 'Peruvian Nuevo Sol',
  309. 'PHP' => 'Philippine Peso',
  310. 'XPT' => 'Platinum Ounces',
  311. 'PLN' => 'Polish Zloty',
  312. 'QAR' => 'Qatar Rial',
  313. 'ROL' => 'Romanian Leu',
  314. 'RUB' => 'Russian Rouble',
  315. 'WST' => 'Samoa Tala',
  316. 'STD' => 'Sao Tome Dobra',
  317. 'SAR' => 'Saudi Arabian Riyal',
  318. 'SCR' => 'Seychelles Rupee',
  319. 'SLL' => 'Sierra Leone Leone',
  320. 'XAG' => 'Silver Ounces',
  321. 'SGD' => 'Singapore Dollar',
  322. 'SKK' => 'Slovak Koruna',
  323. 'SIT' => 'Slovenian Tolar',
  324. 'SBD' => 'Solomon Islands Dollar',
  325. 'SOS' => 'Somali Shilling',
  326. 'ZAR' => 'South African Rand',
  327. 'LKR' => 'Sri Lanka Rupee',
  328. 'SHP' => 'St Helena Pound',
  329. 'SDD' => 'Sudanese Dinar',
  330. 'SRG' => 'Surinam Guilder',
  331. 'SZL' => 'Swaziland Lilageni',
  332. 'SEK' => 'Swedish Krona',
  333. 'TRY' => 'Turkey Lira',
  334. 'CHF' => 'Swiss Franc',
  335. 'SYP' => 'Syrian Pound',
  336. 'TWD' => 'Taiwan Dollar',
  337. 'TZS' => 'Tanzanian Shilling',
  338. 'THB' => 'Thai Baht',
  339. 'TOP' => 'Tonga Pa\'anga',
  340. 'TTD' => 'Trinidad & Tobago Dollar',
  341. 'TND' => 'Tunisian Dinar',
  342. 'TRL' => 'Turkish Lira',
  343. 'USD' => 'U.S. Dollar',
  344. 'AED' => 'UAE Dirham',
  345. 'UGX' => 'Ugandan Shilling',
  346. 'UAH' => 'Ukraine Hryvnia',
  347. 'UYU' => 'Uruguayan New Peso',
  348. 'VUV' => 'Vanuatu Vatu',
  349. 'VEB' => 'Venezuelan Bolivar',
  350. 'VND' => 'Vietnam Dong',
  351. 'YER' => 'Yemen Riyal',
  352. 'YUM' => 'Yugoslav Dinar',
  353. 'ZMK' => 'Zambian Kwacha',
  354. 'ZWD' => 'Zimbabwe Dollar',
  355. );
  356. }