<?php
date_default_timezone_set("Europe/Athens");
if (file_exists("phpheaders.php"))
	{
	require_once("phpheaders.php");
	}
else if(file_exists("../../../phpheaders.php"))
	{
	require_once("../../../phpheaders.php");
	}
else
	{
require_once("../../phpheaders.php");
	}

function heder_js($title,$script,$css) {
echo<<<H
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="greenhouse" />
$css
<link rel="shortcut icon" type="image/x-icon" href="css/images/favicon.ico" />  
$script
H;
echo "<title>".$title."</title></head>" ;
}

function main_things()
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$o="έξοδος";
	$class="gr_buttona";
	$s=3;
	}
else
	{
	$o="sign out";
	$class="en_buttona";
	$s=4;
	}
echo<<<B
<body>
<div id = 'container'>
<div id='left'>
<img src='css/images/screw.png' alt='screw1' class='top'></img>
<div id="gr_en">
<input type='button' name='language_button' class="$class" onclick="logout($s);"/>
</div>
</div>
<div id='right'>
<div id="log_out">
<a id="href" onclick="logout(1);" >
<input type='button' name='log_out' class="top on_buttona" />
<a class="posti">$o</a></a>
</div>
<img src='css/images/screw.png' alt='screw4' class='bottom'></img>
</div>
B;
require("embedded/pages/menu.php");
echo<<<a
<div id="programm">
</div>
a;
require_once("embedded/functions/site_functions.php");
}

function main_things_admin()
{
echo<<<B
<body>

<div id = 'container'>
<div id='left'><img src='css/images/screw.png' alt='screw1' class='top'></img>
<img src='css/images/screw.png' alt='screw2' class='bottom'></img>
</div><div id='right'>
<div id="log_out">
<a id="href" onclick="logout(1);">
<input type='button' name='log_out' class="top on_buttona" />
<a class="posti">sign out</a></a>
</div>
<img src='css/images/screw.png' alt='screw4' class='bottom'></img></div>
B;
}

function footer()
{
echo"<div id ='footer'>";
require("embedded/pages/footer.php");
echo"</div></div></table></body></html>";
}

function days_in_month($month,$year) { 
if(checkdate($month, 31, $year)) return 31; 
if(checkdate($month, 30, $year)) return 30; 
if(checkdate($month, 29, $year)) return 29; 
if(checkdate($month, 28, $year)) return 28; 
return 0; // error 
}
//database function

function db_open() {
@ $db = mysql_connect('localhost', 'gnnpls', '49150zn@') or
die('Connection could not be established.');
@ mysql_select_db('SmartGreenhouse') or die('There is no valid database.');
}

function db_close() {
@ mysql_close($db);
}
/*
function db_open() {	
	$dtbhost=":/zstorage/home/ictest00120/mysql/run/mysql.sock";
	$dtbuser="root";
	$dtbpass="root";
	
	$dtbname="smartgreenhouse";
	@ $db = mysql_connect("$dtbhost", "$dtbuser", "$dtbpass") or die('00: No Connection');
	@ mysql_select_db("$dtbname") or die('01: No Database');
	mysql_query("SET CHARACTER SET 'utf8'"); 
	mysql_query("SET NAMES 'utf8'");
}

*/
function schedule_scenario($scenario_name,$device_id,$day,$start_time,$end_time,$option)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$pattern="/[^_A-Za-zάΆέΈήΉίΊόΌύΎώΏΖζΧχΨψωΩβΒνΝμΜΛλΚκΞξΗηΓγΦφΔδΣσΑαςΕεΡρΤτΥυΘθΙιΟοπΠ0-9\' ']/";
	$problem="Σφάλμα βάσης δεδομένων";
	}
else
	{
	$problem="Database troubleshoot";
	$pattern="/[^_A-Za-z0-9\' ']/";
	}
$q= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($scenario_name))));
	if ((preg_match($pattern, $q)) || !is_numeric($device_id) || !is_numeric($option) || (preg_match("/[^-0-9\' ']/", $day)) ||(preg_match("/[^:0-9\' ']/", $start_time)) || (preg_match("/[^:0-9\' ']/", $end_time)) )
		{
		die("$problem");
		}
	else
		{
		
		if ($scenario_name=='manual')
			{
			$table='new_scenarios';
			$sql="SELECT * FROM new_scenarios WHERE scenario_name='manual'";
			@ $r=mysql_query($sql);
			if ($r!=0)
				{
				$row=mysql_fetch_array($r);
				$fan=$row['fan'];
				$water=$row['watering'];
				$light=$row['lighting'];
				$sql1="UPDATE scenarios SET fan='$fan', watering='$water', lighting='$light' WHERE device_id='$device_id' AND scenario_id='1'";
				@ $rr=mysql_query($sql1);
				if ($rr!=0)	
					{
					$sql3 = "DELETE FROM new_scenarios WHERE device_id='$device_id'";
					@ $resulta=mysql_query($sql3);
					}
				}
			}
	
		$sql = "SELECT scenario_id FROM scenarios WHERE device_id='$device_id' AND scenario_name='$scenario_name'";
		@ $resulta = mysql_query($sql);
		$id=mysql_fetch_array($resulta);
		$scenario_id=$id["0"];
		if ($option==1)
			{
			$sql_insert="INSERT INTO schedule_scenarios (schedule_id,day,start_time,end_time,scenario_id,status,device_id) VALUES 
			(null,'$day','$start_time','$end_time','$scenario_id','1','$device_id')";
			@ $result_insert = mysql_query($sql_insert);
			if ($result_insert==1)
				{
				return 5;//shmainei oti den eixe provlima kai apla mpike
				}
			}
		
		}
}

function last_data($device_id) 
{
$language=$_SESSION['language'];
$exp="";
for ($as=0;$as<=23;$as++)
					{
					$tt=$as.':00:59';
					if ($exp=="")
						{
						$exp="'".$tt."'";
						}
					else
						{
						$exp=$exp.",'".$tt."'";
						}
					}
				$sql1="SELECT * FROM data WHERE device_id='$device_id' AND timer NOT IN($exp) AND timer!='23:00:58' AND timer!='23:00:57' ORDER BY data_id DESC LIMIT 1";
@ $resulta = mysql_query($sql1);
$id=mysql_fetch_array($resulta);
$id=$id["0"];
if (is_numeric($id))
	{
	$sql = "SELECT * FROM data WHERE data_id='$id'";
	@ $result = mysql_query($sql);
	if ($result>=0)
		{		
		while($row = mysql_fetch_array($result))
			{	
				$t= $row["temp"];
				$h= $row["hum"];
				$sm= $row["somo"];
				if ($sm==1)
					{
					if ($language==1)
						{
						$sm="υγρό";
						}
					else
						{
						$sm="wet";
						}
					}
				else if ($sm==0)
					{
					if ($language==1)
						{
						$sm="ξηρό";
						}
					else
						{
						$sm="dry";
						}
					}
				else
					{
					$sm="X";
					}
				$il= $row["inli"];
				$ti= $row["timer"];
				$da= $row["dater"];
			//outputs-actions
				$f=$row["fan"];
				$l=$row["lighting"];
				$v=$row["watering"];
				$id=$row["data_id"];
				//returns
				$data = array($t, $h, $sm, $il, $f, $l, $v, $da." ".$ti, $id);
				return $data;			
				
			}
		}
	else
		{
		die();
		}
	}
}
function update_device($device,$status,$scenario,$table,$device_id)
{

$sql="UPDATE $table SET $device='$status' WHERE device_id='$device_id' AND scenario_name='$scenario'";
@ $result=mysql_query($sql);
if ($result==0)
	{
	die("problem");
	}

}

function scenario_data($name,$device_id,$table)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$pattern="/[^_A-Za-zάΆέΈήΉίΊόΌύΎώΏΖζΧχΨψωΩβΒνΝμΜΛλΚκΞξΗηΓγΦφΔδΣσΑαςΕεΡρΤτΥυΘθΙιΟοπΠ0-9\' ']/";
	$problem="Σφάλμα βάσης δεδομένων";
	}
else
	{
	$problem="Database troubleshoot";
	$pattern="/[^_A-Za-z0-9\' ']/";
	}
$q= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($name))));
	if ((preg_match($pattern, $q)) || !is_numeric($device_id))
	{
	return "$problem";
	}
else
	{
	
	$sql="SELECT * FROM $table WHERE device_id='$device_id' AND scenario_name='$q'";
	@ $result = mysql_query($sql);
	if ($result>=0)
		{	
		while($row = mysql_fetch_array($result))
			{
			$data= array($row["scenario_id"], $row["scenario_name"], $row["device_id"],$row["temp_status"],$row["temp_prior"],$row["temp1"],$row["temp2"],$row["temp_rule"],
			$row["hum_status"],$row["hum_prior"],$row["hum1"],$row["hum2"], $row["hum_rule"],$row["somo_status"],$row["somo_prior"],$row["somo_limit"],$row["somo_rule"],
			$row["inli_status"],$row["inli_prior"],$row["inli1"],$row["inli2"],$row["inli_rule"],$row["fan"],$row["lighting"],$row["watering"]);
			return $data;
			}
		}
	
	
	}
}

function enable_custom($device_id)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$problem="Σφάλμα βάσης δεδομένων";
	}
else
	{
	$problem="Database troubleshoot";
	}

$sql3 = "DELETE FROM new_scenarios WHERE device_id='$device_id'";
@ $resulta=mysql_query($sql3);
$sql1="INSERT INTO new_scenarios(scenario_id,scenario_name,device_id,temp_status,temp_prior,temp1,temp2,temp_rule,hum_status,hum_prior,hum1,hum2,hum_rule,somo_status,somo_prior,somo_limit,somo_rule,inli_status,inli_prior,inli1,inli2,inli_rule,fan,lighting,watering) 
VALUES(NULL,'manual','$device_id','0','0','0','0','0','0',0,'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0')";
@ $result=mysql_query($sql1);
if ($result==0)
	{
	
	die("$problem");
	}

}

function check_availability($name,$table,$device)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$problem="Σφάλμα βάσης δεδομένων";
	}
else
	{
	$problem="Database troubleshoot";
	}
$q= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($name))));
$d= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($table))));
	if ((preg_match("/[^_A-Za-zάΆέΈήΉίΊόΌύΎώΏΖζΧχΨψωΩβΒνΝμΜΛλΚκΞξΗηΓγΦφΔδΣσΑαςΕεΡρΤτΥυΘθΙιΟοπΠ0-9\' ']/", $q)) || (preg_match("/[^?;_A-Za-z0-9\' ']/", $table)  || !is_numeric($device)))
	{
	
	return "$problem";
	}
else
	{
	
	$sql="SELECT scenario_name FROM $table WHERE device_id='$device' AND scenario_name='$q'";
	@ $resulta = mysql_query($sql);
	$id=mysql_fetch_array($resulta);
	$id=$id["0"];
	if ($id=="")
		{
		$msg="1";
		}
	else
		{
		$msg="2";
		}
	return $msg;	
	
	}
}

function scenario_insert($scenario_name,$device_id,$temp_status,$temp_prior,$temp1,$temp2,$temp_rule,$hum_status,$hum_prior,$hum1,$hum2,$hum_rule,$inli_status,$inli_prior,$inli1,$inli2,$inli_rule,$somo_status,$somo_prior,$somo_limit,$somo_rule,$fan,$lighting,$watering)
{

$sql="SELECT scenario_id FROM new_scenarios WHERE device_id='$device_id' AND scenario_name='$scenario_name'";
@ $result = mysql_fetch_array(mysql_query($sql));
if ($result==0)
	{
	$sql1="INSERT INTO new_scenarios(scenario_id,scenario_name,device_id,temp_status,temp_prior,temp1,temp2,temp_rule,hum_status,hum_prior,hum1,hum2,hum_rule,somo_status,somo_prior,somo_limit,somo_rule,inli_status,inli_prior,inli1,inli2,inli_rule,fan,lighting,watering) 
	VALUES(NULL,'$scenario_name','$device_id','$temp_status','$temp_prior','$temp1','$temp2','$temp_rule','$hum_status',$hum_prior,'$hum1','$hum2','$hum_rule','$somo_status','$somo_prior','$somo_limit','$somo_rule','$inli_status','$inli_prior','$inli1','$inli2','$inli_rule','$fan','$lighting','$watering')";
	}
else
	{
	$scenario_id=$result[0];
	$sql1="UPDATE new_scenarios SET scenario_name='$scenario_name', temp_status='$temp_status', temp_prior='$temp_prior', temp1='$temp1', temp2='$temp2', temp_rule='$temp_rule', hum_status='$hum_status', hum_prior='$hum_prior', hum1='$hum1', hum2='$hum2', hum_rule='$hum_rule',   
	somo_status='$somo_status', somo_prior='$somo_prior', somo_limit='$somo_limit', somo_rule='$somo_rule', inli_status='$inli_status', inli_prior='$inli_prior', inli1='$inli1', inli2='$inli2', inli_rule='$inli_rule' WHERE device_id='$device_id' AND scenario_id='$scenario_id'";
	}
@ $resulta = mysql_query($sql1);
return $resulta;

}

function scenario_enabled_availability($device_id)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$problem="Σφάλμα βάσης δεδομένων";
	}
else
	{
	$problem="Database troubleshoot";
	}

if(!is_numeric($device_id))
	{
	return "$problem";
	}
else
	{
	
	$sql1 = "SELECT * FROM schedule_scenarios WHERE device_id='$device_id' AND status='1'";
	@ $result = mysql_query($sql1);
	$resulta= mysql_numrows($result);
	
	if ($resulta !=0)
		{
		
		if ($resulta ==1)
			{
			$row= mysql_fetch_array($result);
			$s=$row["scenario_name"];
			$a=array('1',$s);
			}
		else
			{
			$s="";
			while($row= mysql_fetch_array($result))
				{
				if($s=="")
					{
					$s=$row["scenario_name"];
					}
				else
					{
					$s=$s."/".$row["scenario_name"];
					}
					$a=array('2',$s);
				}
			}
		}
	else
		{
		$a=array('0','0');
		}
	return $a;
	
	}
}

function scenario_numbers($device_id,$date)
{

if(is_numeric($device_id) && !preg_match("/[^-0-9\' ']/", $date))
	{
	$i=0;
	
	$sql="SELECT * FROM schedule_scenarios WHERE device_id='$device_id' AND day='$date'";
	@ $result = mysql_query($sql);
	while ($row= mysql_fetch_array($result))
		{
		$scenario_id=$row["scenario_id"];
		$sql1="SELECT scenario_id FROM scenarios WHERE scenario_id='$scenario_id'";
		@ $resul = mysql_fetch_array(mysql_query($sql1));
		if ($resul!=0)
			{
			$i++;
			}
		}
	return $i;
	
	}
}

function scenario_id($scenario)
{

$sql1="SELECT scenario_id FROM new_scenarios WHERE scenario_name='$scenario'";
@ $resul = mysql_fetch_array(mysql_query($sql1));
if ($resul!=0)
	{
	return $resul[0];
	}
else
	{
	return 0;
	}

}

function return_rule($rule,$s)
{
$language=$_SESSION['language'];
if ($language==1)
	{
	$or="Ή";
	$and="Και";
	$wet="Υγρό";
	$dry="Ξηρό";
	}
else
	{
	$or="OR";
	$and="AND";
	$wet="Wet";
	$dry="Dry";
	}
if ((is_numeric($rule) && ($rule==1 || $rule==2 || $rule==0)) && (is_numeric($s) && ($s==1 || $s==2)))
	{
	if ($s==1)
		{
		if ($rule==1)
			{
			$rule="$or";
			}
		else if ($rule==2)
			{
			$rule="$and";
			}
		else
			{
			$rule="";
			}
		}
	else
		{
		if ($rule==1)
			{
			$rule="$wet";
			}
		else
			{
			$rule="$dry";
			}
		}
	}
	return $rule;
}

function database_graph($date,$option,$device_id)
{
$language=$_SESSION['language'];

$device_id= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($device_id))));
$date= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($date))));
$option= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($option))));
	if (!preg_match("/[^-0-9\' ']/", $date) && is_numeric($option) && is_numeric($device_id))
		{
		$data=array();//24 sthles sto option 1
		$msg="";
		
		
		if($option==1)//mera:59
			{
			$sql="SELECT * FROM data WHERE dater='$date' AND device_id='$device_id'";
			$result=mysql_numrows(mysql_query($sql));
			if ($result!=0)
				{
				$i=0;
				for ($i=0;$i<=23;$i++)
					{
					$time=$i.":00:59";
					$sql1="SELECT * FROM data WHERE timer='$time' AND device_id='$device_id' AND dater='$date'";
					@ $res=mysql_query($sql1);
					$resulto=mysql_numrows($res);
					if ($resulto!=0)
						{
						$msg="";
						$row=mysql_fetch_array($res);
						$data[1][$i]=$row["temp"];
						$data[2][$i]=$row["hum"];
						$data[4][$i]=$row["inli"];
						$data[3][$i]=$row["somo"];
						$data[5][$i]=$row["fan"];
						$data[6][$i]=$row["watering"];
						$data[7][$i]=$row["lighting"];
						$data[8][$i]=date("H:00",strtotime($time));
						}
					else
						{
						if ($language!=1)
							{
							$msg=$msg." No data in database for ".$date."!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για ".$date."!";
							}
						break;
						}
					}
				}
			else
				{
				if ($language!=1)
							{
							$msg=$msg." No data in database for ".$date."!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για ".$date."!";
							}
				}
			if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			}
		else if ($option==2)//vdomada:58
			{
			$a=explode("-",$date);
			$year=$a[0];
			$month=$a[1];
			$week=$a[2];
			$k=days_in_month($month,$year);
			$start=($week*7 +1) -7;
			$end=$week*7;
			if ($k<=$end)
				{
				$end=$k;
				}
				$i=0;
			for ($d=$start;$d<=$end;$d++)
				{
				$dater=$year.'-'.$month.'-'.$d;
				$time="23:00:58";
				$sql="SELECT * FROM data WHERE dater='$dater' AND timer='$time' AND device_id='$device_id'";
				$res=mysql_query($sql);
				$result=mysql_numrows($res);
				if ($result!=0)
					{
						$row=mysql_fetch_array($res);
						$msg="";
						$data[1][$i]=$row["temp"];
						$data[2][$i]=$row["hum"];
						$data[4][$i]=$row["inli"];
						$data[3][$i]=$row["somo"];
						$data[5][$i]=$row["fan"];
						$data[6][$i]=$row["watering"];
						$data[7][$i]=$row["lighting"];
						$data[8][$i]=date("D",strtotime($dater))."-".$d;
						}
					else
						{
						if($language!=1)
							{
							$msg=$msg." No data in database for Week:$week of Month:$month!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για την Εβδομάδα:$week του Μήνα:$month!";
							}
						break;
						}
				$i++;
				}
			if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			if ($i<8)
				{
				for ($d=0;$d<=8;$d++)
					{
					for ($j=0;$j<=7;$j++)
						{
						if (empty($data[$i][$j]))
							{
							$data[$i][$j]="0";
							}
						
						}
					}
				}
			}
		else if ($option==22)//vdomada:58
			{
			$a=explode("-",$date);
			$year=$a[0];
			$month=$a[1];
			$week=$a[2];
			$k=days_in_month($month,$year);
			$start=($week*7 +1) -7;
			$end=$week*7;
			$i=0;
			for ($d=$start;$d<=$end;$d++)
				{
				if ($d>$k)
					{
					$data[5][$i]=0;
					$data[6][$i]=0;
					$data[7][$i]=0;
					$data[8][$i]="-";
					}
				else
				{	
				$dater=$year.'-'.$month.'-'.$d;
				$time="23:00:58";
				$sql="SELECT * FROM data WHERE dater='$dater' AND timer='$time' AND device_id='$device_id'";
				$res=mysql_query($sql);
				$result=mysql_numrows($res);
				if ($result!=0)
					{
						$row=mysql_fetch_array($res);
						$msg="";
						$data[5][$i]=$row["fan"];
						$data[6][$i]=$row["watering"];
						$data[7][$i]=$row["lighting"];
						$data[8][$i]=date("D",strtotime($dater))."-".$d;
						}
					else
						{
						if($language!=1)
							{
							$msg=$msg." No data in database for Week:$week of Month:$month!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για την Εβδομάδα:$week του Μήνα:$month!";
							}
						break;
						}
				}		
				$i++;
				}
			if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			if ($i<8)
				{
				for ($d=0;$d<=8;$d++)
					{
					for ($j=0;$j<=7;$j++)
						{
						if (empty($data[$i][$j]))
							{
							$data[$i][$j]="0";
							}
						
						}
					}
				}
			}	
		else if ($option==3)//mhnas
			{
			$a=explode("-",$date);
			$year=$a[0];
			$month=$a[1];
			$k=days_in_month($month,$year);
			$i=0;
			for ($d=1;$d<=$k;$d++)
				{
				$dater=$year.'-'.$month.'-'.$d;
				$time="23:00:58";
				$sql="SELECT * FROM data WHERE dater='$dater' AND timer='$time' AND device_id='$device_id'";
				$res=mysql_query($sql);
				$result=mysql_numrows($res);
				if ($result!=0)
					{
						$row=mysql_fetch_array($res);
						$msg="";
						$data[1][$i]=$row["temp"];
						$data[2][$i]=$row["hum"];
						$data[4][$i]=$row["inli"];
						$data[3][$i]=$row["somo"];
						$data[5][$i]=$row["fan"];
						$data[6][$i]=$row["watering"];
						$data[7][$i]=$row["lighting"];
						$data[8][$i]=date("D",strtotime($dater))."-".$d;
						}
					else
						{
						if($language!=1)
							{
							$msg=$msg." No data in database for Month:$month!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για τον Μήνα:$month!";
							}
						break;
						}
				$i++;
				}
			if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			if ($i<$k)
				{
				for ($d=0;$d<=8;$d++)
					{
					for ($j=0;$j<=7;$j++)
						{
						if (empty($data[$i][$j]))
							{
							$data[$i][$j]="0";
							}
						
						}
					}
				}		
			}
	else if ($option==32)//mhnas
			{
			$a=explode("-",$date);
			$year=$a[0];
			$month=$a[1];
			$k=days_in_month($month,$year);
			$i=0;
			for ($d=1;$d<=$k;$d++)
				{
				$dater=$year.'-'.$month.'-'.$d;
				$time="23:00:58";
				$sql="SELECT * FROM data WHERE dater='$dater' AND timer='$time' AND device_id='$device_id'";
				$res=mysql_query($sql);
				$result=mysql_numrows($res);
				if ($result!=0)
					{
						$row=mysql_fetch_array($res);
						$msg="";
						$data[5][$i]=$row["fan"];
						$data[6][$i]=$row["watering"];
						$data[7][$i]=$row["lighting"];
						$data[8][$i]=date("D",strtotime($dater))."-".$d."\n(%.1f%%)";
						}
					else
						{
						if($language!=1)
							{
							$msg=$msg." No data in database for Month:$month!";
							}
						else
							{
							$msg=$msg." Δεν υπάρχουν δεδομένα για τον Μήνα:$month!";
							}
						break;
						}
				$i++;
				}
			if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			if ($i<$k)
				{
				for ($d=0;$d<=8;$d++)
					{
					for ($j=0;$j<=7;$j++)
						{
						if (empty($data[$i][$j]))
							{
							$data[$i][$j]="0";
							}
						
						}
					}
				}		
			}		
	else if ($option==4)//xronos
			{
			$year=$date;
			for($i=1;$i<=12;$i++)
				{
				$a=$i-1;
				$l_d=days_in_month($i,$year);
				$dater=$year.'-'.$i.'-'.$l_d;
				$timer='23:00:57';
				$sql="SELECT * FROM data WHERE dater='$dater' AND timer='$timer' AND device_id='$device_id'";
				$res=mysql_query($sql);
				$result=mysql_numrows($res);
				if ($result!=0)
					{
						$row=mysql_fetch_array($res);
						$msg="";
						$data[1][$a]=$row["temp"];
						$data[2][$a]=$row["hum"];
						$data[4][$a]=$row["inli"];
						$data[3][$a]=$row["somo"];
						$data[5][$a]=$row["fan"];
						$data[6][$a]=$row["watering"];
						$data[7][$a]=$row["lighting"];
						$data[8][$i]=date("M",strtotime($dater));
						}
					else
						{
						if($language!=1)
								{
								$msg=$msg." No data in database for month:$i - year:$year";
								}
							else
								{
								$msg=$msg." Δεν υπάρχουν δεδομένα για τον Μήνα:$i - Έτος:$year!";
								}
						
						break;
						}
				}
				if ($msg!="")
				{
				$data[0][0]=$msg;
				}
			
			}
		else
			{
			die();
			}
		
		return $data;
		}
else
	{
	die();
	}
}

function estimate_sum($div,$temp_sum,$hum_sum,$inli_sum,$somo_sum,$fan_sum,$watering_sum,$lighting_sum)
{
if (is_numeric($div))
{
$data=array();
$divv=$div/2;
	$data[0]=$temp_sum/$div;
	$data[1]=$hum_sum/$div;
	$data[2]=$inli_sum/$div;
	$somo_check=$somo_sum/$divv;
	$fan_check=$fan_sum/$divv;
	$watering_check=$watering_sum/$divv;
	$lighting_check=$lighting_sum/$divv;
	if ($somo_check>1)
	{
		$somo_sum=1;
	}
	else
	{
		$somo_sum=0;
	}
	$data[3]=$somo_sum;
	if ($fan_check>1)
	{
		$fan_sum=1;
	}
	else
	{
		$fan_sum=0;
	}
	$data[4]=$fan_sum;
	if ($watering_check>1)
	{
		$watering_sum=1;
	}
	else
	{
		$watering_sum=0;
	}	
	$data[5]=$watering_sum;
	if ($lighting_check>1)
	{
		$lighting_sum=1;
	}
	else
	{
		$lighting_sum=0;
	}
	$data[6]=$lighting_sum;
	return $data;
	}
}

//functions for user

function password($option,$userlevel,$email,$password,$device_id,$live_login)
{
if(is_numeric($option) && ($option<=4))
	{
	$password= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($password))));
	$userlevel= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($userlevel))));
	$email= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($email))));
	$device_id= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($device_id))));
	$live_login= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($live_login))));
	$final="";
	if (preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email) && ($userlevel==0 || $userlevel==1) && is_numeric($device_id) && is_numeric($live_login))
	{
	if ($option==1)//to live login paizei to rolo tou private_id
		{
		$sql_insert="INSERT INTO users (user_id,device_id,email,password,userlevel,last_login,messages,live_login,troubleshoot,changes,device_overview,sensor_overview,lost,visits,active,private_id,language)
		VALUES(null,'$device_id','$email','','$userlevel','','','','','','','','','','0','$live_login','1')";
		@ $res=mysql_query($sql_insert);
		if ($res!=0)
			{
			$a=user_find($email);
			$id=$a[0];
			$aa=drogos($password,$id);
			$password=$aa;
			$sql="UPDATE users SET password='$password' WHERE email='$email' AND user_id='$id' AND device_id='$device_id'";
			@ $result= mysql_query($sql);
			if ($result!=0)
				{
				$final=1;
				}
			}
		}
	else if ($option==2)
		{
		$a=user_find($email);
		$userlevel=$a[3];
		$id=$a[0];
		$aa=drogos($password,$id);
		$password=$aa;
		$sql="SELECT * FROM users WHERE email='$email' AND password='$password' AND live_login<'$live_login' AND active='1'";
		@ $resulta= mysql_query($sql);
		@ $result=mysql_numrows($resulta);
		if ($result !=0)
			{
			$live_login=strtotime("+ 5 minutes", $live_login);
			$sql1="UPDATE users SET live_login='$live_login',visits=visits+1 WHERE email='$email' AND password='$password' AND active='1'";
			@ $resulto=mysql_query($sql1);
			if ($resulto!=0)
				{
				if ($userlevel==1)
					{
					$final=1;
					}
				else
					{
					$final=11;
					}
				}
			}
		}
	else if($option==3)
		{
		$a=user_find($email);
		$userlevel=$a[3];
		$id=$a[0];
		$aa=drogos($password,$id);
		$password=$aa;
		$sql="SELECT * FROM users WHERE email='$email' AND password='$password' AND device_id='$device_id' AND userlevel='$userlevel' AND active='1'";
		@ $resulta= mysql_query($sql);
		$r=mysql_numrows($resulta);
		if ($r==1)
			{
			$final=1;
			}
		}
	else if($option==4)
		{
		$sql="SELECT * FROM users WHERE email='$email' AND password='$password' AND device_id='$device_id' AND userlevel='$userlevel' AND active='1'";
		@ $resulta= mysql_query($sql);
		$r=mysql_numrows($resulta);
		if ($r==1)
			{
			$live_login=strtotime("+ 5 minutes", $live_login);
			$sql1="UPDATE users SET live_login='$live_login' WHERE email='$email' AND password='$password'";
			@ $resulto=mysql_query($sql1);
			if ($resulto!=0)
				{
				$final=1;
				}
			}
		}
	else
		{
		die();
		}
	
	if ($final!=1 && $final!=11)
		{
		$final=2;
		}
	return $final;
	}
}
}


function drogos($password,$id)
{
$password= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($password))));
$id= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($id))));
$password=strrev($password);
$l=strlen($password);
$key='p'.$id.'a'.$l.'s'.$l.'t'.$id.'@'.$l.'n'.$id.'*'.$l.'k'.$password[0].'a';
$m=(($l*$id) % 69);
if ($id<$l)
	{
	$m=$m + ($l % $id);
	}
else
	{
	$m=$m + ($id % $l);
	}
$hash=sha1(md5($key.$password));
for ($i=1;$i<=$m;$i++)
	{
	$hash=sha1($hash);
	}
return $hash;
}

function user_find($email)
{
$email= strip_tags(htmlspecialchars(mysql_real_escape_string(trim($email))));
$data=array();

$sql1="SELECT * FROM users WHERE email='$email'";
@ $resu=mysql_query($sql1);
@ $result=mysql_numrows($resu);
			if ($result!=0)
				{
				$row=mysql_fetch_array($resu);
				$data[0]=$row["user_id"];
				$data[1]=$row["device_id"];
				$data[2]=$row["email"];
				$data[3]=$row["userlevel"];
				$data[4]=$row["last_login"];
				$data[5]=$row["messages"];
				$data[6]=$row["live_login"];
				$data[7]=$row["troubleshoot"];
				$data[8]=$row["changes"];
				$data[9]=$row["device_overview"];
				$data[10]=$row["sensor_overview"];
				$data[11]=$row["lost"];	
				$data[12]=$row["password"];	
				$data[16]=$row["language"];	
				}

return $data;
}


function number_of_visitors()
{
$filename="../../admin/counter.txt";
if ( file_exists("../../admin/counter.txt"))
	{
	$filename="../../admin/counter.txt";
	}
else
	{
	$filename="embedded/admin/counter.txt";
	}
if(file_exists($filename))
	{
	$file_contents=file($filename);
	$number=$file_contents[0]; 
	}
else 
	{ 
	$number=0;
	}

$fl=fopen($filename, "w") or die("Error R");
flock( $fl, LOCK_EX ) or die ( "Cannot lock file" );
$number=rtrim( $number, "\n" );

if ( is_numeric($number) )
{
$number++;
}
else
{
$number=1;
}
rewind ( $fl );
fputs( $fl, $number );
fclose($fl);
return $number;
}

function device_password($device_id)
{
$device_idd=$device_id;
$date=strtotime(date("Yfdhms"));
$date=strrev($date);
$l=strlen($device_id);
$l=$device_id*$l;
$date=$l*$date;
$a=strlen($date);
$x="";
for($i=0;$i<$a;$i++)
	{
	$x=$x+$date[$i];	
	}
$hash=sha1(md5($device_id.$date));
for($a=0;$a<=$x[5];$a++)
	{
	$hash=sha1($hash);
	}

$sql="INSERT INTO devices (device_id,password) VALUES ('$device_idd','$hash')";
@ $result=mysql_query($sql);
return $result;

}

function check_device($device_id,$password)
{
$msg=0;

$sql="SELECT * FROM devices WHERE device_id='$device_id' AND password='$password'";
@ $result=mysql_query($sql);
if ($result!=0)
	{
	$msg=1;
	}
else
	{
	$msg=0;
	}

return $msg;
}


function mail_with_attachments($to,$subject,$message,$headers,$files)
{
// boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
// headers for attachment 
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
 
// multipart boundary 
$message = $message. "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";
 
// preparing attachments
for($x=0;$x<count($files);$x++){
	$file = fopen($files[$x],"rb");
	$data = fread($file,filesize($files[$x]));
	fclose($file);
	$data = chunk_split(base64_encode($data));
	$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
	"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
	"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
	$message .= "--{$mime_boundary}\n";
}
 
//
 
// send
$ok = mail($to, $subject, $message, $headers); 
if ($ok) { 
	return 1;
} else { 
	return 0;
}
}
?>