<?php
class Utility
{
	function pdoConnect($dbname)
	{
		$servername = 'localhost';
		$username = 'cp162885_movie';
		$password = 'Theppitak1';
		try 
		{
		    $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
		    // set the PDO error mode to exception
		    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		    return $conn;
		}
		catch(PDOException $e)
		{
		    return $e->getMessage();
		}
	}		
	function MyQuery($sql, $conn, $params)
	{

		global $DEBUG,$SYNC,$_GLOBALS,$logTimeStart,$logTimeEnd,$cacheTime,$noconv;
		$noconv = "ok"; // only utf8	
		if (!isset($cacheTime)) $cacheTime=(15*60);//15 minute
		list($usec, $sec) = explode(" ", microtime());
		$before = ((float)$usec + (float)$sec);
		if($DEBUG) {
			echo $sql;
		}
		
	
		$file_name=sprintf('%s',md5(str_replace(' ','',$sql)));
		$folder = substr($file_name,0,2);
		if(!file_exists("cache/$folder")){
			mkdir("cache/$folder",777);
		}
		$cache_file = sprintf("cache/%s/%s.php",$folder,$file_name);

	
		if((!$SYNC) && (file_exists($cache_file))) {
			$fstat = stat($cache_file);
			$fdiff = mktime() - $fstat[9];
			if($fdiff > $cacheTime) { //CACHE_CLEAR 
				$sync = 1;
			}
			else{
				include($cache_file);
				$arr = $ARR;
			}
		}
		else {
			$sync = 1;
		}
		$ARR = array();
		if ($SYNC==3) {
			unset($SYNC);
			unset($sync);
			include($cache_file);
			$arr = $ARR;
		}	
		if ($SYNC || $sync) {
			$html = "<"."?\n";
			
			$sth = $conn->prepare($sql);
			$sth->execute($params);
			$res = $sth->fetchAll(PDO::FETCH_ASSOC);
			for($i=0; $i<count($res); $i++){
				foreach ($res[$i] as $column => $value){
				
					$ARR[$i][$column] = $value;
					if ($noconv!="ok") {
						$ARR[$i][$column] = iconv('tis-620','utf-8',$value); 
					}
					$html.= sprintf("\$ARR['%s']['%s'] = \"%s\";\n",$i,$column,trim(str_replace('"','\"',$ARR[$i][$column])));
				}
			}
		
			$html.= "?".">";
			$fw = fopen($cache_file,"w");
			if(flock($fw,LOCK_EX)){
				fwrite($fw,$html);
				flock($fw,LOCK_UN);
			}else{
				include($cache_file);
				$arr = $ARR;
			}
			fclose($fw);
			$arr = $ARR;
			unset($fw);
			unset($html);
			unset($cache_file);
			unset($ARR);
			unset($rowNum);
			unset($filedNum);
			unset($i);
			unset($sql);
			//mysql_free_result($res);
			if($DEBUG) echo " (REALTIME)";						
		} else{
			if($DEBUG) echo " (CACHE) $cacheTime ";
		}
		if(isset($arr)){
			return $arr;
		}
	}
	function MyExecute($sql, $conn, $params)
	{
		$sth = $conn->prepare($sql);
		$sth->execute($params);
		return $sth;
	}
}
?>