3 // note this no longer works -- we could try using their JSON feed?
6 require_once 'Pman.php';
8 class Pman_Core_UpdateCurrencyRate extends Pman
11 static $cli_desc = "Update Currency Exchange Rate";
13 static $cli_opts = array();
17 var $actionUrl = 'http://www.oanda.com/currency/historical-rates-classic';
25 $ff = HTML_FlexyFramework::get();
26 if (!empty($ff->cli)) {
34 function get($args, $opts=array())
37 //DB_DataObject::DebugLevel(1);
38 $d = DB_DataObject::Factory('core_curr_rate');
41 $hkd = $d->convert(1,'USD','HKD');
43 echo "1 USD is ~ $hkd HKD (should be about 7.75)\n ";
54 $response = $this->curl($this->actionUrl, array(), 'GET');
56 libxml_use_internal_errors (true);
58 $doc = new DOMDocument();
59 $doc->loadHTML($response);
61 libxml_use_internal_errors (false);
63 $xpath = new DOMXpath($doc);
65 $elements = $xpath->query("//select[@name='exch']/option");
67 foreach($elements as $el) {
68 $currency[] = $el->getAttribute('value');
72 die('no any currency');
75 $fromDate = date('m/d/y', strtotime("-6 MONTH"));
76 $toDate = date('m/d/y');
78 $total = count($currency);
80 foreach ($currency as $k => $c){
82 echo "\nProcessing Currency : $c ($k / $total) \n";
96 $response = $this->curl($this->actionUrl, $params, 'POST');
98 libxml_use_internal_errors (true);
100 $doc = new DOMDocument();
101 $doc->loadHTML($response);
103 libxml_use_internal_errors (false);
105 $xpath = new DOMXpath($doc);
107 $elements = $xpath->query("//td[@id='content_section']/table/tr[last()]/td/table/tr[1]/td[last()]");
109 $rate = empty($elements->item(0)->nodeValue) ? 0 : $elements->item(0)->nodeValue * 1;
111 $this->processCurrRate($c, $rate, $fromDate, $toDate);
113 if(array_key_exists($c, $this->mapping)){
114 $this->processCurrRate($this->mapping[$c], $rate, $fromDate, $toDate);
121 function processCurrRate($currency, $rate, $from, $to)
123 $curr = DB_DataObject::factory('core_curr_rate');
125 $curr->curr = $currency;
129 if($curr->find(true)){
133 $curr->setFrom(array(
135 'from_dt' => date('Y-m-d H:i:s', strtotime($from)),
136 'to_dt' => date('Y-m-d H:i:s', strtotime($to))
139 (empty($o)) ? $curr->insert() : $curr->update($o);
144 function curl($url, $request = array(), $method = 'GET')
147 if(is_array($request)){
148 $request = http_build_query($request);
151 $url = $url . ($method == 'GET' ? "?" . $request : '');
152 $ch = curl_init($url);
154 if ($method == 'POST') {
155 curl_setopt($ch, CURLOPT_POST, 1);
156 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
157 curl_setopt($ch, CURLOPT_HTTPHEADER,
158 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
161 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
163 curl_setopt($ch, CURLOPT_HEADER, false);
164 curl_setopt($ch, CURLOPT_VERBOSE, 1);
165 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
166 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
168 $response = curl_exec($ch);