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)
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 aobut 7.8)\n ";
58 $response = $this->curl($this->actionUrl, array(), 'GET');
60 libxml_use_internal_errors (true);
62 $doc = new DOMDocument();
63 $doc->loadHTML($response);
65 libxml_use_internal_errors (false);
67 $xpath = new DOMXpath($doc);
69 $elements = $xpath->query("//select[@name='exch']/option");
71 foreach($elements as $el) {
72 $currency[] = $el->getAttribute('value');
76 die('no any currency');
79 $fromDate = date('m/d/y', strtotime("-6 MONTH"));
80 $toDate = date('m/d/y');
82 $total = count($currency);
84 foreach ($currency as $k => $c){
86 echo "\nProcessing Currency : $c ($k / $total) \n";
100 $response = $this->curl($this->actionUrl, $params, 'POST');
102 libxml_use_internal_errors (true);
104 $doc = new DOMDocument();
105 $doc->loadHTML($response);
107 libxml_use_internal_errors (false);
109 $xpath = new DOMXpath($doc);
111 $elements = $xpath->query("//td[@id='content_section']/table/tr[last()]/td/table/tr[1]/td[last()]");
113 $rate = empty($elements->item(0)->nodeValue) ? 0 : $elements->item(0)->nodeValue * 1;
115 $this->processCurrRate($c, $rate, $fromDate, $toDate);
117 if(array_key_exists($c, $this->mapping)){
118 $this->processCurrRate($this->mapping[$c], $rate, $fromDate, $toDate);
125 function processCurrRate($currency, $rate, $from, $to)
127 $curr = DB_DataObject::factory('core_curr_rate');
129 $curr->curr = $currency;
133 if($curr->find(true)){
137 $curr->setFrom(array(
139 'from_dt' => date('Y-m-d H:i:s', strtotime($from)),
140 'to_dt' => date('Y-m-d H:i:s', strtotime($to))
143 (empty($o)) ? $curr->insert() : $curr->update($o);
148 function curl($url, $request = array(), $method = 'GET')
151 if(is_array($request)){
152 $request = http_build_query($request);
155 $url = $url . ($method == 'GET' ? "?" . $request : '');
156 $ch = curl_init($url);
158 if ($method == 'POST') {
159 curl_setopt($ch, CURLOPT_POST, 1);
160 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
161 curl_setopt($ch, CURLOPT_HTTPHEADER,
162 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
165 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
167 curl_setopt($ch, CURLOPT_HEADER, false);
168 curl_setopt($ch, CURLOPT_VERBOSE, 1);
169 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
170 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
172 $response = curl_exec($ch);