<?php

    ///include("access.php");
	//session_start(); //We need to have static variables
    ///$Esp8266SensorURL = $esp8266_9702_GetSensors_URL;


	//---------------------------------------------------------------------
	//Functions
	//---------------------------------------------------------------------
	//
	//---------------------------------------------------------------------
	//Name: get_fcontent( $url,  $javascript_loop = 0, $timeout = 5 )
	//Function: CURL that gets URL contents
    //Parameter 1: $url													-	URL to retrieve
    //Parameter 2: $javascript_loop - IDK, this function pulled from internet
    //Parameter 3: $timeout					 			-	IDK, this function pulled from internet
	//---------------------------------------------------------------------
	function get_fcontent_was( $url,  $javascript_loop = 0, $timeout = 15 ) {

	    echo "get_fcontent entry...<br>"; //die();

		$url = str_replace( "&amp;", "&", urldecode(trim($url)) );

		$cookie = tempnam ("/tmp", "CURLCOOKIE");
		$ch = curl_init();
		//curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
		curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
		curl_setopt( $ch, CURLOPT_ENCODING, "" );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    //# required for https urls
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
		curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
		curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
	    echo "ready to curl...<br>"; //die();
		$content = curl_exec( $ch );
	    echo "curl executed...<br>"; //die();
		$response = curl_getinfo( $ch );
		curl_close ( $ch );
	    echo "curl finished...<br>"; //die();

		if ($response['http_code'] == 301 || $response['http_code'] == 302) {
			ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

			if ( $headers = get_headers($response['url']) ) {
				foreach( $headers as $value ) {
					if ( substr( strtolower($value), 0, 9 ) == "location:" )
						return get_url( trim( substr( $value, 9, strlen($value) ) ) );
				}
			}
		}

		if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
						return get_url( $value[1], $javascript_loop+1 );
		} else {
						return array( $content, $response );
		}
	}

	//---------------------------------------------------------------------
	// curl_get_contents() - Returns contents of requested URL
	//---------------------------------------------------------------------
	function get_fcontent( $url) {
		$cookie = tempnam ("/tmp", "CURLCOOKIE");
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		/*
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		*/
        curl_setopt($ch, CURLOPT_PROXY, "209.18.47.61"); // $proxy is ip of proxy server
		/*
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		*/
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
//		
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		                                            'Content-Type: application/text',
		                                            'Connection: Keep-Alive',
		                                            'Upgrade-Insecure-Requests: 1',
		                                            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.200 Safari/537.36',
		                                            'Accept: application/text,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
		                                            'Accept-Encoding: gzip, deflate, sdch',
		                                            'Accept-Language: en-US,en;q=0.8',
		                                            ));
//
		$data = curl_exec($ch);
		$response = curl_error($ch);
	    //echo "Data::".$data." ".$response; die();
		curl_close($ch);
		return $data;
	}
	function get_fcontentCCC( $url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		//curl_setopt($ch, CURLOPT_GET, 1);
		//curl_setopt($ch, CURLOPT_NOBODY, 1);
		//curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		                                            'Content-Type: application/xml',
		                                            'Connection: Keep-Alive',
		                                            'Upgrade-Insecure-Requests: 1',
		                                            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
		                                            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
		                                            'Accept-Encoding: gzip, deflate, sdch',
		                                            'Accept-Language: en-US,en;q=0.8',
		                                            ));

		$data = curl_exec($ch);
	    echo "Data:".$data; die();
		curl_close($ch);
		return $data;
	}



	//---------------------------------------------------------------------
	//Name: getEsp8266Sensor($getUrl,$update,$k)
 	//Function: Gets value from ESP8266 (Return last value if 0)
    //Parameter 1: $getUrl -	ESP8266 URL that returned JSON with sensor values
    //Parameter 2: $update - if "Y", get JSON from ESP8200, else use last JSON
    //Parameter 3: $k	   -	key to retrieve value of (key:value)
	//---------------------------------------------------------------------
	function getEsp8266Sensor($getUrl,$update,$k) {
		if($update=="Y") {
            if(strstr($k,"field1")) {
			    ob_start();
                $status=get_fcontent($getUrl);
 				ob_flush();
				sleep(5);
               return $status;
            }
			$_SESSION['fetches']=0;
			$status="";
			ob_start();
			//echo get_fcontent($getUrl); die();
			//echo "Got to this point...while"; die();

			while((substr($status,0,1)!='{')&&($_SESSION['fetches']<20)) {
				$status=get_fcontent($getUrl);
				$_SESSION['fetches']=$_SESSION['fetches']+1;
				ob_flush();
				sleep(5);
			}
			$_SESSION['jsonstr'] = $status;
		}
	    //echo "Got to this point...123"." Rtn:".$status; die();
		
		if($_SESSION['fetches']<20) {
			$status_array = json_decode($_SESSION['jsonstr']); //Decode json

			foreach($status_array as $key => $value) {
				if(strstr($key,$k)) {
					$val = $value;
				}
			}
		}
		else {
			$val=0;
		}
		//return last value if current value is 0
		if($val!=0) {
			return $val;
		}
		else {
			if(strstr($k,"DS_TempInside")) return $last_in;
			if(strstr($k,"DS_TempOutside")) return $last_ou;
			if(strstr($k,"DS_TempAttic")) return $last_at;
			if(strstr($k,"DH_Humidity")) return $last_hu;
			if(strstr($k,"field1")) return "0";
			return $val;
		}
	}
	//Lost function...searching (this is a placeholder)
	function getMpkBaroPres() {
		$contents = file_get_contents("http://www.wunderground.com/weather-forecast/US/CA/Moorpark.html?&MR=1");
		$searchfor='@data-station="MD0915" data-variable="pressure">(.*)wx-unit@s';
		preg_match($searchfor,$contents,$matches); /* /i single line /s multi-line */
		preg_match('/<span class="wx-value">(.*)<\/span>/i',$matches[1],$bar);
		$barmpk = $bar[1]/33.86375258;
		$barmpk = substr($barmpk,0,5);
        return $barmpk;
	}

?>