
	<?PHP

/**
 * Class:             yahoo.stocks.class.php
 * Require:           mySQL (if using cache functionality)
 * Optional:
 * Description:       A class to grab the latest stocks from Yahoo Finance, and to cache them optionally
 * Created on:        Thu, 31 Jul 2003 14:01:46 +0200
 * Last Change:       Wed, 31 Mar 2004 12:59:35 +0200
 * Author:            Marc Giombetti <marc@giombetti.com>
 * Website:              http://www.giombetti.com
 * Copyright:         GPL - General Public License
 * Version:           0.2
 * Bugfies:           Scott Bratcher (Problems with -6 timezones)
 *
 * -----------------------------------------------------------------------------
 * Configuration options
 *
 * $time                - Difference in time between you and the yahoo Server (GMT)
 * $refreshtime            - How often a value may (at most) be checked for on the yahoo website (in minutes)
 *                           (Minimal value is 0,25 because yahoo updates the stocks approx every 15sec)
 * The following values are only necessary if the cache functionality is used
 * $dbhost                - mySQL database host
 * $user                - mySQL username
 * $passwd                - mySQL password
 * $db                    - mySQL database
 * $stocks_table        - mySQL table
 *
 * -----------------------------------------------------------------------------
 * mySQL table structure (only needed if cache functionality is used and no active mySQL connection to $db is present)
 *
 * CREATE TABLE `stocks` (
 *     `ID` int(11) NOT NULL auto_increment,
 *     `stock` varchar(64) NOT NULL default '',
 *     `value` varchar(16) NOT NULL default '0',
 *     `changepoints` varchar(16) NOT NULL default '0',
 *     `open` varchar(16) NOT NULL default '',
 *     `intra_top` varchar(16) NOT NULL default '',
 *     `intra_down` varchar(16) NOT NULL default '',
 *     `date` varchar(10) NOT NULL default '',
 *     `time` varchar(6) NOT NULL default '',
 *     `unixtime` int(12) NOT NULL default '0',
 *     `reallocaltime` int(12) NOT NULL default '0',
 *     `md5` varchar(32) NOT NULL default '',
 *     PRIMARY KEY  (`ID`)
 * ) TYPE=MyISAM AUTO_INCREMENT=39 ;
 *
 * -----------------------------------------------------------------------------
 * How to use this class? - Examples:
 *
 * $stocks = new yahoo_stocks();
 * $stocks->my_connect();//if you have no open mySQL connection (yet)
 * $eurostoxx = $stocks->get_stocks("^STOXX50E", "y"); //Get data for Euro StoXX 50 and use cache (returns an array)
 * $dowjones = $stocks->get_stocks("^DJI", "n");//Dow Jones and no cacheing
 * echo var_dump($stocks->get_stocks("^DJI", "n"));//displays the kind of array this class returns
 * $stocks->my_close();
 *
 * -----------------------------------------------------------------------------
 * Some tock keywords:
 * ^DJI         - Dow Jones
 * ^IXIC         - Nasdaq
 * ^GSPC         - S&P 500
 * ^STOXX50E     - Euro STOXX50
 * For more stock keywords visit http://finance.yahoo.com
 * -----------------------------------------------------------------------------
 */


 $stocks = new yahoo_stocks();
 $stocks->my_connect();
   $bsesensex = $stocks->get_stocks("^BSESN", "y"); //Get data for Euro StoXX 50 and use cache (returns an array)


    //echo var_dump($stocks->get_stocks("^DJI", "y"));//displays the kind of array this class returns

    $google = $Stocks->get_quotes("GOOG"); //Get data form
	  $msft = $Stocks->get_quotes("MSFT");
	 $moto = $Stocks->get_quotes("MO");
	 $apple = $Stocks->get_quotes("AAPL");
	 $aig = $Stocks->get_quotes("AIG");
	 $bsc = $Stocks->get_quotes("BSC");
	 $amazon = $Stocks->get_quotes("AMZN");
	 $amd = $Stocks->get_quotes("AMD");
	 $att = $Stocks->get_quotes("T");
	 $adobe = $Stocks->get_quotes("ADBE");
	 $aberfitch = $Stocks->get_quotes("ANF");
	 $gs = $Stocks->get_quotes("GS");
	 $barcap = $Stocks->get_quotes("BARC.L");
	 $barnes = $Stocks->get_quotes("BKS");
	 $helwett = $Stocks->get_quotes("HPQ");
	 $merill = $Stocks->get_quotes("MER");
	 $lockheed = $Stocks->get_quotes("LMT");
	 $honeywell = $Stocks->get_quotes("HON");
	 $warner = $Stocks->get_quotes("TWX");
	 $goodyear = $Stocks->get_quotes("GT");
	 $nytimes = $Stocks->get_quotes("NYT");
	 $ti = $Stocks->get_quotes("TXN");
	 $natinstr = $Stocks->get_quotes("NATI");
	 $qualcomm = $Stocks->get_quotes("QCOM");
	 $avaya = $Stocks->get_quotes("AVR.F");
	 $lehmann = $Stocks->get_quotes("LEH");
	 $verizon = $Stocks->get_quotes("VZ");
	 $vodafone = $Stocks->get_quotes("VOD");
	 $sprint = $Stocks->get_quotes("S");
	 $ibm = $Stocks->get_quotes("IBM");
	 $yahoo = $Stocks->get_quotes("YHOO");
	 $disney = $Stocks->get_quotes("DIS");
	 $walmart = $Stocks->get_quotes("WMT");
	 $walgreen = $Stocks->get_quotes("WAG");
	 $siemens = $Stocks->get_quotes("SI");
	 $blackrock = $Stocks->get_quotes("BLK");
	 $xilinx = $Stocks->get_quotes("XLNX");
	 $analogdev = $Stocks->get_quotes("ADI");
	 $boa = $Stocks->get_quotes("BAC");
	 $intel = $Stocks->get_quotes("INTC");
	 $wachovia = $Stocks->get_quotes("WB");
	 $lenovo = $Stocks->get_quotes("LHL.F");
	 $toshiba = $Stocks->get_quotes("TOA.F");
	 $dell = $Stocks->get_quotes("DELL");
	 $tata = $Stocks->get_quotes("TTM");
	 $infy = $Stocks->get_quotes("INFY");
	 $tcs = $Stocks->get_quotes("TCS.NS");
	 $cognizant = $Stocks->get_quotes("CTSH");
	 $accenture = $Stocks->get_quotes("ACN");
	 $cisco = $Stocks->get_quotes("CSCO");
	 $delphi = $Stocks->get_quotes("DFG");
	 $jpmorgan = $Stocks->get_quotes("JPM");
	 $sony = $Stocks->get_quotes("SNE");
	 $phillips = $Stocks->get_quotes("PHG");
	 $jnj = $Stocks->get_quotes("JNJ");
	 $schlum = $Stocks->get_quotes("SLB");
	 $citi = $Stocks->get_quotes("C");
	 $deutsch = $Stocks->get_quotes("DB");
	 $bearstreans = $Stocks->get_quotes("BSC");
	 $dowjones = $Stocks->get_quotes("^DJI");//Dow Jones and no cacheing
// $ubs = $Stocks->get_quotes("UBS");

    $stocks->my_close();

class yahoo_stocks {

    /**
     * Time difference Between Yahoo and your local time;
     */
    var $time = "+6"; //ATTENTION: daylight saving isn't (yet) respected
    var $refreshtime = "1"; //minimal 0,25 because yahoo updates their values approx every 15sec!
    var $dbhost = "localhost";
    var $user = "group802";
    var $passwd = "Cor@538";
    var $db = "group802";
    var $stocks_table = "stocks";
   // var $stock = "^DJI";
    //var $cache = "y";

    /**
     * how long should quote values be stored in mysql (0 = unlimited / otherwise time in days)
     */
    var $keepfilesfor = 0;

    /**
     * yahoo_stocks :: get_stocks()
     * :: ATTENTION - IF THE CACHE IS USED  - calling this
     * :: function will need an open mySQL connection to be present!
     * :: use my_connect() first
     *
     * @param  $stock Stock shortcut
     * @param  $cache (y or n)
     * @return array ()
     */
    function get_stocks($stock, $cache)
    {

       if ($cache == "y") {
            if ($this->keepfilesfor != "0") {
                $deletefrom = time() - $this->keepfilesfor * 24 * 3600;
                $mystock = mysql_escape_string($stock);
                $q = "DELETE FROM `$this->stocks_table` WHERE stock='$mystock' AND reallocaltime<'$deletefrom'";
                mysql_query($q);
            }
            $timeout = time()-60 * $this->refreshtime;
            $mystock = mysql_escape_string($stock);
            $q = "SELECT * FROM `$this->stocks_table` WHERE stock='$mystock' AND reallocaltime>'$timeout' ";
            $q .= "ORDER BY `unixtime` DESC LIMIT 1";
            $d = mysql_query($q);
            if (!mysql_num_rows($d)) {
                $reallocaltime = time();
                $return = $this->generate_stock_array($stock);
                /**
                 * Check the mysql database to prevent double entries using the md5 hash
                 */
                $qquery = "SELECT * FROM `$this->stocks_table` WHERE md5='${return['md5']}'";
                $qcheck = mysql_query($qquery);
                if (mysql_num_rows($qcheck)) {
                    $x = mysql_fetch_array($qcheck);
                    return $x;
                } else {
                    $sql = "INSERT INTO `$this->stocks_table` (`stock` , `value` , `changepoints` , `open` , `intra_top` , `intra_down` , `date` , `time` , `unixtime` , `reallocaltime`, `md5` )";
                    $sql .= "VALUES('${return['stock']}','${return['value']}','${return['changepoints']}','${return['open']}','${return['intra_top']}','${return['intra_down']}',";
                    $sql .= "'${return['date']}','${return['time']}','${return['unixtime']}','$reallocaltime','${return['md5']}')";
                    mysql_query($sql);
                    return $return;
                }
            } else {
                $x = mysql_fetch_array($d);
                return $x;
            }
        } else {
            return $this->generate_stock_array($stock);
        }
    }

    /**
     * yahoo_stocks::generate_stock_array()
     *
     * :: please don't use this function - Use get_stocks() instead
     * :: this function is for internal use in get_stocks()
     *
     * @param  $stock
     * @return
     */
    function generate_stock_array($stock)
    {

        $open = fopen("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1d1t1c1ohgv&e=.csv", "r");
        $read = str_replace("","", trim(fread($open, 2000)));

        $data = explode(",", $read);
        fclose($open);

        /**
         * Converting yahoo's date to local date
         */
        $strtotime_date = strtotime(str_replace('"', '', "$data[2] $data[3]"));
        if (eregi("^-.*", $this->time)) {
            $this->time = str_replace("-", "", $this->time);
            $return['unixtime'] = $strtotime_date - $this->time * 3600;
        } else {
            $this->time = str_replace("+", "", $this->time);
            $return['unixtime'] = $strtotime_date + $this->time * 3600;
        }
        $return['stock'] = $data[0];
        $return['value'] = $data[1];
        $return['date'] = date("j.n.Y", $return['unixtime']);
        $return['time'] = date("G:i", $return['unixtime']);
        $return['changepoints'] = $data[4];
        $return['open'] = $data[5];
        $return['intra_top'] = $data[6];
        $return['intra_down'] = $data[7];
        $return['md5'] = md5($read);
        if ($return['value'] == "0.00" && $return['date'] == "1.1.1970") {
            die("ERROR: yahoo.stocks.class.php - <b>$stock</b> is no valid stock");
        }
        return $return;
    }

    /**
     * yahoo_stocks :: get_stock_bundle() :: uses an array ($symbols) to gather several stock quotes at once
     *
     * @param  $symbols ;
     * @return ;)
     */

    function get_stock_bundle($syms)
    {
        foreach ($syms as $s) {
            $bundle[$s] = $this->generate_stock_array($s);
        }

        return $bundle;
    }

    /** * yahoo_stocks :: my_connect() :: Connect to the mySQL server * *
    @return mysql _connection */ function my_connect() { $this->conn =
    @mysql_connect($this->dbhost, $this->user, $this->passwd) or die("Can't
    connect to mysqln"); return mysql_select_db($this->db, $this->conn); }

    /**
     * yahoo_stocks :: my_close() :: Disconnect from the mySQL server
     *
     * @return TRUE ;)
     */
    function my_close()
    {
        return @mysql_close();
    }
}


?>


