<?PHP
 
/**
 * Class:             yahoo.stocks.class.php
 * Created and modified by Shivangi C
 * -----------------------------------------------------------------------------
 * 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 
 * 
 * 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 '',
 *      PRIMARY KEY  (`ID`)
 * ) TYPE=MyISAM AUTO_INCREMENT=1 ;
 * 
 */

class yahoo_stocks {
    /**
     * Time difference Between Yahoo and your local time;
     */
    //var $time = "+6"; //ATTENTION: daylight saving isn't (yet) respected
    //var $refreshtime = "5"; // 0,25 because yahoo updates their values approx every 15sec!
    var $dbhost = "software-ece.rutgers.edu";
    var $user = "group804";
    var $passwd = "EE#rt18";
    var $db = "group804";
    var $stocks_table = "stocks";
    var $Day_Prices = "DayPrice";
    var $Month_Prices= "MonthPrice";


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

    /**
     * yahoo_stocks :: generate_stock_array() 
     * :: function will need an open mySQL connection to be present!
     * :: use my_connect() first
     * 
     * @return array ()
     */
    
  
    /**
     * yahoo_stocks::generate_stock_array() 
     * 
     * :: please don't use this function - Use generate_stock_array() instead
     * :: this function is for internal use in generate_stock_array()
     * 
     * @param  $stock 
     * @return 
     */
    function generate_stock_array($stock)
    {
		
        $open = fopen("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1d1t1c1ohgv&e=.csv", "r");
        //http://finance.yahoo.com/d/table.csv?s=GOOG&f=sl1d1t1c1ohgv&e=.csv
        $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['newDate'] = date("Y-m-d", $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");
        } 
		$sql1 = "SELECT * FROM `$this->stocks_table` WHERE `stock_name` = '${return['stock']}'";
		$d = mysql_query($sql1);

		if (mysql_num_rows($d) > 0){
	    $sql = "UPDATE `$this->stocks_table` SET `current_value` = '${return['value']}', `change_points` = '${return['changepoints']}', `opening_value` = '${return['open']}', ";
		$sql .=" `days_high` =  '${return['intra_top']}', `days_low` = '${return['intra_down']}', `date` = '${return['date']}', `time` = '${return['time']}' WHERE `stock_name` = '${return['stock']}'";
		}
		else
		{
		$sql = "INSERT INTO `$this->stocks_table` (`stock_name` , `current_value` , `change_points` , `opening_value` , `days_high` , `days_low` , `date` , `time` )";
        $sql .= " VALUES('${return['stock']}','${return['value']}','${return['changepoints']}','${return['open']}','${return['intra_top']}','${return['intra_down']}',";
        $sql .= "'${return['date']}','${return['time']}')";
		}
		
		
		$d = mysql_query($sql);

		$sql2 = "INSERT IGNORE INTO `$this->Day_Prices` (`Stock_Name` , `Date` ) ";
        $sql2 .= "VALUES('${return['stock']}','${return['date']}')";

		$d = mysql_query($sql2);
		$curtime = $return['unixtime'];

		
		
		if ( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(10,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(11,00))) ) )
		{
		$sql3 = "UPDATE `$this->Day_Prices` SET `10AM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		}
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(11,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(12,00))) ) )
		{
		$sql3 = "UPDATE `$this->Day_Prices` SET `11AM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		}
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(12,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(13,00))) ) )
		{
			$sql3 = "UPDATE `$this->Day_Prices` SET `12AM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		}
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(13,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(14,00))) ) )
		$sql3 = "UPDATE `$this->Day_Prices` SET `1PM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(14,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(15,00))) ) )
		$sql3 = "UPDATE `$this->Day_Prices` SET `2PM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(15,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(16,00))) ) )
		$sql3 = "UPDATE `$this->Day_Prices` SET `3PM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
		elseif( (strtotime(date("G:i", $curtime)) >= strtotime(date("G:i", mktime(16,00))))  && (strtotime(date("G:i", $curtime)) < strtotime(date("G:i", mktime(17,00))) ) )
		{
			
			print($return['newDate']);
			print("\n");
			$sql3 = "UPDATE `$this->Day_Prices` SET `4PM` = '${return['value']}', `Date` = '${return['date']}' WHERE `Stock_Name` = '${return['stock']}' ";
			$sql4 = "INSERT IGNORE INTO `$this->Month_Prices` VALUES('${return['stock']}', '${return['newDate']}', '${return['value']}', '${return['open']}', '${return['intra_top']}', '${return['intra_down']}' ) ";
			
			$d = mysql_query($sql4);

		}
		$d = mysql_query($sql3);

        return $d;
    } 


    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();
    } 
} 

//instantiate the class

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

?> 