<?php

/******************************************************************************
@owner: SVSi
@author: Arthur Johnson
@function: Various Server Commands
*******************************************************************************/
	
	//error_reporting(E_ALL); ini_set('display_errors', 1);
	ini_set('post_max_size', '256M');
	ini_set('max_input_time', '1000');
	ini_set('max_execution_time', '600');
	ini_set('memory_limit','1024M');

	$logfile = @fopen('log/phplog.txt', 'a+');
	
	if (isset($_POST['opts'])) $opts = json_decode($_POST['opts'], true);
	if (isset($_POST['data'])) $data = $_POST['data'];
	
	function delTree($dir){ 
		$files = array_diff(scandir($dir), array('.','..')); 
		foreach ($files as $file){ 
			(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
		} 
		return rmdir($dir);
	} 
	
	function folderSize($dir){
		$count_size = 0;
		$count = 0;
		$dir_array = @scandir($dir);
		foreach ($dir_array as $key=>$filename){
			if ($filename!=".." && $filename!="."){
				if (@is_dir($dir."/".$filename)){
					$new_foldersize = @foldersize($dir."/".$filename);
					$count_size = $count_size+ $new_foldersize;
				}
				else if(@is_file($dir."/".$filename)){
					$count_size = $count_size + filesize($dir."/".$filename);
					$count++;
				}
			}
		}
		return $count_size;
	}
	
	function clean($string) {
	   $string = str_replace(' ', '-', $string);
	   return preg_replace('/[^A-Za-z0-9\-\.]/', '', $string);
	}
	
	function recurse_copy($src, $dst) { 
		$dir = opendir($src); 
		@mkdir($dst); 
		while(false !== ( $file = readdir($dir)) ) { 
			if (( $file != '.' ) && ( $file != '..' )) { 
				if ( is_dir($src . '/' . $file) ) { 
					recurse_copy($src . '/' . $file,$dst . '/' . $file); 
				} 
				else { 
					copy($src . '/' . $file,$dst . '/' . $file); 
				} 
			} 
		} 
		closedir($dir); 
	} 
	
	function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)){ 
        
		$result=false; 
        
        if (is_file($source)) { 
            if ($dest[strlen($dest)-1]=='/') { 
                if (!file_exists($dest)) { 
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true); 
                } 
                $__dest=$dest."/".basename($source); 
            } else { 
                $__dest=$dest; 
            } 
            $result=copy($source, $__dest); 
            chmod($__dest,$options['filePermission']); 
            
        } elseif(is_dir($source)) { 
            if ($dest[strlen($dest)-1]=='/') { 
                if ($source[strlen($source)-1]=='/') { 
                    //Copy only contents 
                } else { 
                    //Change parent itself and its contents 
                    $dest=$dest.basename($source); 
                    @mkdir($dest); 
                    chmod($dest,$options['filePermission']); 
                } 
            } else { 
                if ($source[strlen($source)-1]=='/') { 
                    //Copy parent directory with new name and all its content 
                    @mkdir($dest,$options['folderPermission']); 
                    chmod($dest,$options['filePermission']); 
                } else { 
                    //Copy parent directory with new name and all its content 
                    @mkdir($dest,$options['folderPermission']); 
                    chmod($dest,$options['filePermission']); 
                } 
            } 

            $dirHandle=opendir($source); 
            while($file=readdir($dirHandle)){ 
                if($file!="." && $file!="..") 
                { 
                     if(!is_dir($source."/".$file)) { 
                        $__dest=$dest."/".$file; 
                    } else { 
                        $__dest=$dest."/".$file; 
                    } 
                    //echo "$source/$file ||| $__dest<br />"; 
                    $result=smartCopy($source."/".$file, $__dest, $options); 
                } 
            } 
            closedir($dirHandle); 
            
        } 
		else { 
            $result=false; 
        }
		
        return $result; 
		
    }
	
	function compareFiles($a, $b){
		return ($b->mtime > $a->mtime)?1:-1;
	}
	
	function getProjectNames(){
	
		$files = @scandir("projects");
		if (!$files) return array();
		
		$index = array_search('lost+found', $files);
		if ($index !== false){
			unset($files[$index]);
		}
	
		$output = array();
		foreach ($files as &$file){
			if ($file != '.' && $file != '..' && is_dir('projects/'.$file)){
				
				$projectfiles = scandir("projects/".$file);
				
				foreach ($projectfiles as &$projectfile){
					if ($projectfile == "name.txt"){
						
						$projectname = @file_get_contents("projects/".$file."/name.txt");
						$mtime = filemtime("projects/".$file."/name.txt");
						
						$obj = (object) array('name' => $projectname, 'puid' => $file, 'fromDB' => false, 'mtime' => $mtime);
						array_push($output, $obj);

					}
				}
				
			}
		}
		
		@usort($output, compareFiles);
		
		return $output;
		
	}
	
	if (isset($_GET['export'])){
		
		$puid = $_GET['export'];
		$pname = $_GET['name'].".zip";

		header("Content-Type: archive/zip");
		header("Content-Disposition: attachment; filename=$puid".".zip");

		$tmp_zip = tempnam("tmp", "tempname").".zip";

		chdir('projects/'.$puid);

		exec('zip -r '.$tmp_zip.' *');

		/*$filesize = filesize($tmp_zip);
		header("Content-Length: $filesize");

		$fp = fopen("$tmp_zip","r");
		echo fpassthru($fp);*/
		
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"".$pname."\"");
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($tmp_zip));
		ob_end_flush();
		@readfile($tmp_zip);
		
		unlink($tmp_zip);
		
		exit;
	}
	
	if ($opts['command'] == 'write_module'){
		
		$manufacturername = $opts['manufacturer'];
		
		@mkdir("js/modules/".$manufacturername, 0777);
		$tmp_name = $_FILES["module"]["tmp_name"];
		$name = $_FILES["module"]["name"];
		@chmod("js/modules/".$manufacturername."/".$name, 0777);
		move_uploaded_file($tmp_name, "js/modules/".$manufacturername."/".$name);
		@chmod("js/modules/".$manufacturername."/".$name, 0777);
		
		echo $tmp_name." ".$name;
		
		exit;
		
	}
	
	if ($opts['command'] == 'delete_module'){
		
		$name = $opts['filename'];
		
		unlink($name);

	}
	
	if ($opts['command'] == 'write_project'){
		
		$projectname = $opts['name'];
		
		if (!isset($opts['puid'])){
			$puid = mt_rand();
			$projects = getProjectNames();
			
			$match = true;
			while ($match){
				$match = false;
				for ($i=0; $i<count($projects); $i++){
					if ($projects[$i]->puid == $puid){
						$puid = mt_rand();
						$match = true;
					}
				}
			}
		}
		else $puid = $opts['puid'];
		
		@mkdir("projects/".$puid, 0777);
		@mkdir("projects/".$puid."/images", 0777);
		$projectfile = fopen("projects/".$puid."/project.svsi", "w");
		fwrite($projectfile, $data);
		fclose($projectfile);
		$namefile = fopen("projects/".$puid."/name.txt", "w");
		fwrite($namefile, $projectname);
		fclose($namefile);
		
		@touch("projects/".$puid."/name.txt", $opts['time']/1000);
		
		echo $puid;
		
		exit;
		
	}
	
	if ($opts['command'] == 'write_image'){
		
		if (!isset($opts['puid'])){
			$puid = mt_rand();
			$projects = getProjectNames();
			
			$match = true;
			while ($match){
				$match = false;
				for ($i=0; $i<count($projects); $i++){
					if ($projects[$i]->puid == $puid){
						$puid = mt_rand();
						$match = true;
					}
				}
			}
		}
		else $puid = $opts['puid'];
		
		@mkdir("projects/".$puid, 0777);
		@mkdir("projects/".$puid."/images", 0777);
		$images_dir = "projects/".$puid."/images";
		$tmp_name = $_FILES["image"]["tmp_name"];
		$name = $_FILES["image"]["name"];
		
		$name = clean($name);
		
		if (isset($opts['width']) && isset($opts['height'])){
			smart_resize_image($tmp_name, null, intval($opts['width']), intval($opts['height']),
				true, "projects/".$puid."/images/".$name, true, false, 100);
		}
		else {
			@move_uploaded_file($tmp_name, "projects/".$puid."/images/".$name);
		}
		
		echo "projects/".$puid."/images/".$name;
		
		exit;
		
	}
	
	if ($opts['command'] == 'start_unit_broadcast'){
		
		$makefile = fopen("../tmp/polldev", "w");
		
		exit;
		
	}
	
	if ($opts['command'] == 'stop_unit_broadcast'){
		
		unlink("../tmp/polldev");
		
		echo file_get_contents("../tmp/unitStatus.json");
		
		exit;
		
	}
	
	if ($opts['command'] == 'check_projectname'){
	
		$projectname = $opts['name'];	
		
		//if (is_dir("projects/".$projectname)) echo '1';
		//else echo '0';
		echo '0';
		exit;
		
	}
	
	if ($opts['command'] == 'delete_image'){
		
		$puid = $opts['puid'];
		$name = $opts['filename'];
		
		unlink($name);

	}
	
	if ($opts['command'] == 'read_image_filenames'){
		
		if (!isset($opts['puid'])){
			exit();
		}
		else $puid = $opts['puid'];
		
		$files = scandir("projects/".$puid."/images");
	
		$output = array();
		foreach ($files as &$file){
			if ($file != '.' && $file != '..' && is_file("projects/".$puid."/images/".$file)){
				array_push($output, $file);
			}
		}
		
		echo json_encode($output);
		
	}
	
	if ($opts['command'] == 'get_disk_filesize'){

		echo folderSize('projects');
		
	}
	
	if ($opts['command'] == 'read_project'){
	
		$puid = $opts['puid'];
		
		if (isset($opts['wallcon'])) $wallcon = true;
		else $wallcon = true;
		
		$dirsize = @folderSize("projects/".$puid);

		if ($wallcon){
			if ($dirsize >= 10 * 1024 * 1024){
				echo 'project_too_large_'.$dirsize;
				exit;
			}
		}
		
		$str = @file_get_contents("projects/".$puid."/project.svsi");
		
		if ($str === false){
			echo 'project_not_found';
			exit;
		}
		
		while (strpos($str, 'url(http://') !== false){
			$tstr = substr($str, strpos($str, 'url(http://')+4,
				((strpos($str, '/panels/')+8)-(strpos($str, 'url(http://')+4)));
			$str = str_replace($tstr, "", $str);
		}
		
		if (isset($opts['time'])) @touch("projects/".$puid."/name.txt", $opts['time']);
		
		echo $str;
		exit;
		
	}
	
	if ($opts['command'] == 'export_project'){
		
		$projectname = $opts['name'];
		$puid = $opts['puid'];

		$tmp_zip = tempnam("tmp", "tempname").".zip";
		chdir('projects/'.$puid);
		exec('zip '.$tmp_zip.' *');
		$filesize = filesize($tmp_zip);
		
		header('Content-Description: File Transfer');
		header('Content-Disposition: attachment; filename='.basename($tmp_zip));
		header('Content-Transfer-Encoding: binary');
		header('Expires: 0');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		header('Content-Length: '.filesize($tmp_zip));

		ob_clean();
		flush();
		ob_start();
		
		$fp = fopen("php://output", 'r+');
		
		fwrite($fp, file_get_contents($tmp_zip));
		fflush($fp);
		fclose($fp);
		
		/*
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"".basename($tmp_zip)."\"");
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($tmp_zip));
		ob_end_flush();
		@readfile($tmp_zip);
		*/
		
		unlink($tmp_zip);

		exit;
		
	}
	
	if ($opts['command'] == 'import_project'){
	
		$projectname = $opts['name'];
		$puid = mt_rand();
		$projects = getProjectNames();
		
		$match = true;
		while ($match){
			$match = false;
			for ($i=0; $i<count($projects); $i++){
				if ($projects[$i]->puid == $puid){
					$puid = mt_rand();
					$match = true;
				}
			}
		}
		
		@mkdir("projects/".$puid, 0777);
		$tmp_zip = $_FILES["zip"]["tmp_name"];
		chdir('projects/'.$puid);
		exec('unzip '.$tmp_zip);
		
		/*$terrible = file_get_contents("project.svsi");
		//var_dump($terrible);
		$alsoterrible = json_decode($terrible);
		$oldpuid = $alsoterrible->puid;
		
		chdir('../');
		$source = $puid;
		$dest= $oldpuid;

		//smartCopy($source, $dest);
		delTree($dest);
		rename($source, $dest);*/
		
		//$terrible = str_replace($alsoterrible->puid, (string)$puid, $terrible);
		//$terrible = str_replace("\\t", "", $terrible);
		//echo $terrible;
		//file_put_contents("project.svsi", json_encode($terrible));
		
		//$obj = (object) array('name' => $projectname, 'puid' => $puid);
		//echo $oldpuid;//json_encode($obj);
		echo $puid;//json_encode($obj);
		
		exit;
		
	}
	
	if ($opts['command'] == 'read_allmodules'){
		
		$files = scandir("js/modules");
		$dirs = array();
		foreach ($files as &$file){
			if ($file != '.' && $file != '..' && is_dir('js/modules/'.$file)){
				array_push($dirs, $file);
			}
		}
		
		$output = array();
		foreach ($dirs as &$dir){
			
			$files = scandir('js/modules/'.$dir);

			foreach ($files as &$file){
				if ($file != '.' && $file != '..' && is_file('js/modules/'.$dir.'/'.$file)){
					$module = (object) array(
						'manufacturer' => $dir,
						'make' => str_replace(".js", "", $file),
						'file' => 'js/modules/'.$dir.'/'.$file
					);
					array_push($output, $module);
				}
			}
			
		}
		echo json_encode($output);
		exit;
		
	}
	
	if ($opts['command'] == 'read_allmanufacturers'){
		
		$files = scandir("js/modules");
	
		$output = array();
		foreach ($files as &$file){
			if ($file != '.' && $file != '..' && is_dir('js/modules/'.$file)){
				array_push($output, $file);
			}
		}
		
		echo json_encode($output);
		exit;
		
	}
	
	if ($opts['command'] == 'read_unitlist_WC'){
		$rawulist = @file_get_contents("/var/www/htdocs/tmp/unitStatus.json");
		echo $rawulist;
	}
	
	if ($opts['command'] == 'delete_project'){
		
		$puid = $opts['puid'];
		
		deleteDir("projects/".$puid);
		
	}
	
	if ($opts['command'] == 'read_projectnames'){
	
		echo json_encode(getProjectNames());
		exit;
	
	}
	
	if ($opts['command'] == 'read_allprojects'){
		
		$files = scandir("projects");
		$dirs = array();
		foreach ($files as &$file){
			if ($file != '.' && $file != '..' && is_dir('projects/'.$file)){
				array_push($dirs, $file);
			}
		}
		$output = array();
		foreach ($dirs as &$dir){
		
			$str = file_get_contents("projects/".$dir."/project.svsi");
			$str = str_replace("<!!server!!>", $_SERVER['SERVER_ADDR'], $str);
			
			while (strpos($str, 'url(http://') !== FALSE && strpos($str, '/panels/') !== FALSE){
				$tstr = substr($str, strpos($str, 'url(http://')+4, ((strpos($str, '/panels/')+8)-(strpos($str, 'url(http://')+4)));
				$str = str_replace($tstr, "", $str);
			}
		
			array_push($output, $str);
		}
		echo json_encode($output);
		exit;
		
	}
	
	if ($opts['command'] == 'vars_up'){
	
		$puid = $opts['puid'];
		
		$str = file_get_contents("projects/".$puid."/vars.svsi");
		$toldobj = json_decode($str);
		
		$projectfile = fopen("projects/".$puid."/vars.svsi", "w+");
		
		$tobj = json_decode($data);
		$tobjvars = get_object_vars($tobj);
		
		foreach ($tobjvars as &$value){
			$toldobj[$value] = $tobjvars[$value];
		}
		
		$newdata = json_encode($toldobj);
		
		fwrite($projectfile, $newdata);
		fclose($projectfile);
		
	}
	
	if ($opts['command'] == 'vars_down'){
		
		$puid = $opts['puid'];
		
		echo file_get_contents("projects/".$puid."/vars.svsi");
		
	}
	
	if ($opts['command'] == 'read_file'){
	
		$file  = isset($_POST['filename']) ? $_POST['filename'] : null;

		if ($file != null) {
		
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			ob_clean();
			flush();
			readfile($file);
			exit;
			
		}
		
	}

	if ($opts['command'] == 'read_file_b'){
		
		$file = isset($_POST['filename']) ? $_POST['filename'] : null;
		$json = isset($_POST['json']) ? $_POST['json'] : null;
		
		if ($file != null && $json != null){
		
			header('Content-Description: File Transfer');
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate');
			header('Pragma: public');
			header('Content-Length: '.strlen($json));

			ob_clean();
			flush();
			ob_start();
			
			fwrite($logfile, "Begin: jsonlength-".strlen($json)."\n\n");
			
			$fp = fopen("php://output", 'r+');

			if ($bytesWritten = fwrite($fp, $json) ) {
				fwrite($logfile, "There were " . $bytesWritten . " bytes written to the text file.\n\n");
			}
				
			if (!fflush($fp)) {
				fwrite($logfile, "There was a problem outputting all the data to the text file.\n\n");
			}

			if (!fclose($fp)) { 
				fwrite($logfile, "There was a problem closing the text file.\n\n"); 
			}
			
		}
		
	}
	
	if ($opts['command'] == 'write_json'){
	
		$name = $_POST['name'];
		$json = $_POST['json'];

		if (json_decode($json) != null){
		
			$file = fopen($name, 'w+');
			fwrite($file, $json);
			fclose($file);
			
			$file = fopen('log/phplog.txt', 'a+');
			fwrite('log/phplog.txt', 'Wrote file: ' . $name . ' ' . $json . "\r\n");
			fclose('log/phplog.txt');
			
		} 
		else {
		
			$file = fopen('log/phplog.txt', 'a+');
			fwrite('log/phplog.txt', 'Error writing json file: ' . $name . ' ' . $json . "\r\n");
			fclose('log/phplog.txt');
			
		}
		
	}
	
	if ($opts['command'] == 'read_weather'){
	
		$zip = isset($_POST['zip']) ? $_POST['zip'] : '35806';
		
		function xmlObjToArr($obj){ 
		
			$namespace = $obj->getDocNamespaces(true); 
			$namespace[NULL] = NULL; 
			
			$children = array(); 
			$attributes = array(); 
			$name = strtolower((string)$obj->getName()); 
			
			$text = trim((string)$obj); 
			if (strlen($text) <= 0){ 
				$text = NULL; 
			} 

			if (is_object($obj)){ 
				foreach ( $namespace as $ns=>$nsUrl ){ 
				
					$objAttributes = $obj->attributes($ns, true);
					
					foreach( $objAttributes as $attributeName => $attributeValue ) { 
						$attribName = strtolower(trim((string)$attributeName)); 
						$attribVal = trim((string)$attributeValue); 
						if (!empty($ns)) { 
							$attribName = $ns . ':' . $attribName; 
						} 
						$attributes[$attribName] = $attribVal; 
					} 
					
					$objChildren = $obj->children($ns, true); 
					
					foreach( $objChildren as $childName=>$child ) { 
						$childName = strtolower((string)$childName); 
						if( !empty($ns) ) { 
							$childName = $ns.':'.$childName; 
						} 
						$children[$childName][] = xmlObjToArr($child); 
					} 
					
				} 
			} 
			
			return array( 
				'name'=>$name, 
				'text'=>$text, 
				'attributes'=>$attributes, 
				'children'=>$children 
			); 
		} 
		
		$mydata = simplexml_load_file("http://weather.yahooapis.com/forecastrss?p=$zip&u=f");
		
		$newdata = xmlObjToArr($mydata);
		
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:condition'][0]
					 ['attributes']['code'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['title'][0]['text'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:condition'][0]
					 ['attributes']['text'];
		echo "|, ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:condition'][0]
					 ['attributes']['temp'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['yweather:units'][0]
					 ['attributes']['temperature'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][0]
					 ['attributes']['day'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][0]
					 ['attributes']['date'];
		echo "|: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][0]
					 ['attributes']['text'];
		echo "|, low: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][0]
					 ['attributes']['low'];
		echo "|, high: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][0]
					 ['attributes']['high'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][1]
					 ['attributes']['day'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][1]
					 ['attributes']['date'];
		echo "|: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][1]
					 ['attributes']['text'];
		echo "|, low: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][1]
					 ['attributes']['low'];
		echo "|, high: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][1]
					 ['attributes']['high'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][2]
					 ['attributes']['day'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][2]
					 ['attributes']['date'];
		echo "|: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][2]
					 ['attributes']['text'];
		echo "|, low: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][2]
					 ['attributes']['low'];
		echo "|, high: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][2]
					 ['attributes']['high'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][3]
					 ['attributes']['day'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][3]
					 ['attributes']['date'];
		echo "|: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][3]
					 ['attributes']['text'];
		echo "|, low: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][3]
					 ['attributes']['low'];
		echo "|, high: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][3]
					 ['attributes']['high'];
		echo "|";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][4]
					 ['attributes']['day'];
		echo "| ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][4]
					 ['attributes']['date'];
		echo "|: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][4]
					 ['attributes']['text'];
		echo "|, low: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][4]
					 ['attributes']['low'];
		echo "|, high: ";
		echo $newdata['children']['channel'][0]
					 ['children']['item'][0]
					 ['children']['yweather:forecast'][4]
					 ['attributes']['high'];
					 
	}
	
	function deleteDir($dir){ 
		if (is_dir($dir)){ 
			$objects = scandir($dir); 
			foreach ($objects as $object){ 
				if ($object != "." && $object != ".."){ 
					if (filetype($dir."/".$object) == "dir") 
						deleteDir($dir."/".$object); 
					else unlink($dir."/".$object); 
				} 
			} 
			reset($objects); 
			rmdir($dir); 
		} 
	} 
	
	/**
	* easy image resize function
	* @param  $file - file name to resize
	* @param  $string - The image data, as a string
	* @param  $width - new image width
	* @param  $height - new image height
	* @param  $proportional - keep image proportional, default is no
	* @param  $output - name of the new file (include path if needed)
	* @param  $delete_original - if true the original image will be deleted
	* @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
	* @param  $quality - enter 1-100 (100 is best quality) default is 100
	* @return boolean|resource
	*/
	///*
	function smart_resize_image(
		$file,
		$string             = null,
		$width              = 0, 
		$height             = 0, 
		$proportional       = false, 
		$output             = 'file', 
		$delete_original    = true, 
		$use_linux_commands = false,
		$quality = 100
			){
	  
		if ( $height <= 0 && $width <= 0 ) return false;
		if ( $file === null && $string === null ) return false;

		# Setting defaults and meta
		$info                         = $file !== null ? getimagesize($file) : getimagesizefromstring($string);
		$image                        = '';
		$final_width                  = 0;
		$final_height                 = 0;
		list($width_old, $height_old) = $info;
		$cropHeight = $cropWidth = 0;

		# Calculating proportionality
		if ($proportional){
			if      ($width  == 0)  $factor = $height/$height_old;
			elseif  ($height == 0)  $factor = $width/$width_old;
			else                    $factor = min( $width / $width_old, $height / $height_old );

			$final_width  = round( $width_old * $factor );
			$final_height = round( $height_old * $factor );
		}
		else {
			$final_width = ( $width <= 0 ) ? $width_old : $width;
			$final_height = ( $height <= 0 ) ? $height_old : $height;
			$widthX = $width_old / $width;
			$heightX = $height_old / $height;
		  
			$x = min($widthX, $heightX);
			$cropWidth = ($width_old - $width * $x) / 2;
			$cropHeight = ($height_old - $height * $x) / 2;
		}

		# Loading image to memory according to type
		switch ($info[2]){
			case IMAGETYPE_JPEG:  $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string);  break;
			case IMAGETYPE_GIF:   $file !== null ? $image = imagecreatefromgif($file)  : $image = imagecreatefromstring($string);  break;
			case IMAGETYPE_PNG:   $file !== null ? $image = imagecreatefrompng($file)  : $image = imagecreatefromstring($string);  break;
			default: return false;
		}


		# This is the resizing/resampling/transparency-preserving magic
		$image_resized = imagecreatetruecolor($final_width, $final_height);
		if (($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG)){
			$transparency = imagecolortransparent($image);
			$palletsize = imagecolorstotal($image);

			if ($transparency >= 0 && $transparency < $palletsize) {
				$transparent_color  = imagecolorsforindex($image, $transparency);
				$transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
				imagefill($image_resized, 0, 0, $transparency);
				imagecolortransparent($image_resized, $transparency);
			}
			elseif ($info[2] == IMAGETYPE_PNG) {
				imagealphablending($image_resized, false);
				$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
				imagefill($image_resized, 0, 0, $color);
				imagesavealpha($image_resized, true);
			}
		}
		imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);

		# Taking care of original, if needed
		if ($delete_original){
			if ($use_linux_commands) exec('rm '.$file);
			else @unlink($file);
		}

		# Preparing a method of providing result
		switch (strtolower($output)){
			case 'browser':
				$mime = image_type_to_mime_type($info[2]);
				header("Content-type: $mime");
				$output = NULL;
			break;
			case 'file':
				$output = $file;
			break;
			case 'return':
				return $image_resized;
			break;
			default:
			break;
		}

		# Writing image according to type to the output destination and image quality
		switch ($info[2]){
			case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
			case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
			case IMAGETYPE_PNG:
				$quality = 9 - (int)((0.9*$quality)/10.0);
				imagepng($image_resized, $output, $quality);
			break;
			default: return false;
		}

		return true;
		
	}
	//*/
?>