<?php
    // $Id: ExchangeRates.php,v 1.8 2004/08/11 12:30:38 doug Exp $
    // Exchange Rates
    // Gets exchange rates from yahoo.com
    // Doug Rinckes

    class KCART_ExchangeRates {

        // retrieve exchange rate from $source to $dest
        // returns a float or 0 if unable to retrieve the exchange rate
        // submits to http://finance.yahoo.com/m5, a=1, s=<src>, t=<dest>
        function getExchangeRate($source,$dest) {

            // quick and easy check - if the currencies are the same, the
            // exchange rate is 1
            if ($source == $dest) {
                return(1);
            }

            // the URL where we will try to get the exchange rate data
            $link = "http://finance.yahoo.com/currency/convert?amt=1&from=$source&to=$dest&submit=Convert";
            // how many times we will retry the connection
            $retries = 5;

            // now try to open the link
            while ($retries > 0) {
                $file = @fopen($link,"r");
                $retries --;
                if ($file) break;
            }
            // if we couldn't open the link to the site
            if(!$file) {
                // display an error
                KCART_kCart::error("Failed repeatedly to get exchange rates.  One or more of your payment processors is using an old exchange rate.  You may try reloading this page.");
                // return 0
                $result = "0";
            } else {
                // read in the data from the link in chunks - newer versions of PHP don't 
                // seem to need this, older ones do.
                $data = "";
                while (true) {
                    $chunk = fread($file, 8192);
                    // if nothing to read, we must be done
                    if (strlen($chunk) == 0) {
                        break;
                    }
                    $data .= $chunk;
                }
                // process the data read back from the site
                eregi(">([0-9]+.[0-9]+|-)</td><td",$data,$rate);
                // if it looks like we got a rate, that's our result
                if ($rate[1] > 0) {
                    $result = $rate[1];
                } else {
                    // otherwise, 
                    $result = 0;
                    KCART_kCart::error("Could not find exchange rate data.<br>Most likely one of the currency codes is incorrect.  Check currency codes $source and $dest.");
                    KCART_kCart::error("Offending chunk is <pre>\n$data\n</pre>");
                    @fclose($file);
                }
            }
            // return the exchange rate
            return($result);
        }
    }
?>
