<?php
/**
 *	Project:	Quicty: Quick application build environment depends on PEAR and Smarty
 *	File:		Utils.php
 *
 *	@copyright	Tomoyuki Negishi and ZubaPitaTech, Inc.
 *	@author		Tomoyuki Negishi <tomoyu-n@zubapita.jp>
 *	@license	http://www.opensource.org/licenses/bsd-license.php The BSD License
 *	@package	Quicty
 *	@version	$Id:$
 */

function redirect($url,$die=true) {
	if($_SERVER['SERVER_NAME']=='127.0.0.1' or $_SERVER['SERVER_NAME']=='localhost') {
		$SERVER_NAME = $_SERVER['SERVER_ADDR'];
	} else {
		$SERVER_NAME = $_SERVER['SERVER_NAME'];
	}
	//echo "url=$url<br>";
	switch($url) {
		case 'top':
			$goto_url = 'http://'.$SERVER_NAME.quicty_base_url().'/';
			break;
		default:
			if(substr($url,0,7)=='http://' or substr($url,0,8)=='https://') {
				$goto_url = $url;
			} else {
				$goto_url = 'http://'.$SERVER_NAME.quicty_base_url().$url;
			}
	}
	//die("goto_url=$goto_url\n");
	if (!headers_sent()) { 
		ob_end_clean(); 
		header("Location: ".$goto_url); 
		if($die)  die(); 
	} else {
		echo "can't redirect to $goto_url. because header was already sent<br>\n";
	}
}

function request_or_session($value_name) {
	@session_start();
	if($_GET[$value_name]) {
		$value = $_GET[$value_name];
		$_SESSION[$value_name] = $value;
	} elseif($_POST[$value_name]) {
		$value = $_POST[$value_name];
		$_SESSION[$value_name] = $value;
	} else {
		$value = $_SESSION[$value_name];
	}
	return $value;
}

function quicty_base_path() {
	$self = $_SERVER['PHP_SELF'];
	if(substr($self,-10)=='/index.php')
		$self = substr($self,0,-10);
	elseif($_SERVER['QtRootShift']=='Yes')
		$self = '/'.array_shift(explode('/',substr($self,1)));
	else
		$self = '';
	return $self;
}

// old function name of quicty_base_path
function quicty_base_url() {
	return quicty_base_path();
}


function get_argv() {
	$_ARGV = $_SERVER['argv'];
	$argv['script_name'] = array_shift($_ARGV);
	foreach($_ARGV as $param) {
		list($key,$value) = explode('=',$param);
		$argv[$key] = $value;
	}
	return $argv;
}

function unify_newline($line) {
	$line=str_replace("\r\n","\n",$line);//WindowsのCRLF改行をLF改行に変更
	$line=str_replace("\r","\n",$line);//MACのCR改行をLF改行に変更
	return $line;
}

function var_check(&$var,$var_name='') {
	echo '<div style="text-align:left;">'."\n";
	echo "<pre>\n";
	if($var_name) {
		echo "$var_name = ";
	}
	var_dump($var);
	echo "</pre>\n";
	echo "</div><br />\n";
}

function get_query_id() {
	return md5(serialize($_GET).serialize($_POST));
}

function get_uri_id() {
	return md5(serialize($_SERVER['REQUEST_URI']));
}

function file_write_contents($filename,$contents,$mode='w') {
	if(!$handle = fopen($filename,$mode)) {
		die("Quicty error: can't open file ($filename).");
	}
	if(fwrite($handle,$contents)===false) {
		die("Quicty error: can't write file ($filename).");
	}
	fclose($handle);
}

function make_dir($dir,$permit=0755) {
	if(!file_exists($dir)) {
		mkdir($dir,$permit);
	} elseif(!is_dir($dir)) {
		die("abort! $dir is already exists and not directory.\n");
	}
}

function list_dir($dir) {
	if (is_dir($dir)) {
		if($dh = opendir($dir)) {
			while (($file_name = readdir($dh)) !== false) {
				if($file_name=='.' or $file_name=='..' or $file_name=='.DS_Store' or $file_name=='.svn')
					continue;
				$files[] = $file_name;
			}
		}
		closedir($dh);
	}
	return $files;
}

// 
function copy_files($source,$target_dir,$copy_dir=false,$permit=0644) {
	umask(0);
	if (is_dir($source)) {
		if($dh = opendir($source)) {
			while (($file_name = readdir($dh)) !== false) {
				if($file_name=='.' or $file_name=='..' or $file_name=='.DS_Store' or $file_name=='.svn')
					continue;
				if(filetype($source.'/'.$file_name)=='dir') {
					if(!$copy_dir) {
						continue;
					} else {
						$sub_dir = $file_name;
						make_dir($target_dir.'/'.$sub_dir,0777);
						copy_files($source.'/'.$sub_dir,$target_dir.'/'.$sub_dir,$copy_dir);
					}
				} elseif(filetype($source.'/'.$file_name)=='link') {
						$link_target = readlink($source.'/'.$file_name);
						_symlink($link_target,$target_dir.'/'.$file_name);
				} else {
					$file_body = file_get_contents($source.'/'.$file_name);
					file_write_contents($target_dir.'/'.$file_name,$file_body);
					chmod($target_dir.'/'.$file_name,$permit);
				}
			}
		}
		closedir($dh);
	} elseif(is_file($source)) {
		$file_body = file_get_contents($source);
		$path_info = pathinfo($source);
		$file_name = $path_info['basename'];
		file_write_contents($target_dir.'/'.$file_name,$file_body);
		chmod($target_dir.'/'.$file_name,$permit);
	}
}

function write_data_array($filename,$data_array) {
	foreach($data_array as $key=>$param_array) {
		foreach($param_array as $inter_key=>$inter_value) {
			if(is_array($inter_value)) {
				foreach($inter_value as $query=>$real_column) {
					$value_pairs[] = $query.'->'.$real_column;
				}
				$values = $inter_key.'::'.implode(',',$value_pairs);
			} else {
				$query = $inter_key;
				$real_column = $inter_value;
				$value_pairs[] = $query.'->'.$real_column;
			}
		}
		if(!$values) {
			$values = implode(',',$value_pairs);
			unset($value_pairs);
		}
		$tmp[] = $key.'=>'.$values;
		unset($values);
	}
	$source = implode('//',$tmp);
	file_put_contents($filename,$source);
	return $source;
}

function read_data_array($filename) {
	$source = file_get_contents($filename);
	foreach(explode('//',$source) as $line) {
		list($key,$values) = explode('=>',$line);
		$inter_key = strtok($values,'::');
		if($inter_value = strtok('::')) $values = $inter_value;
		foreach(explode(',',$values) as $value_pair) {
			list($query,$real_column) = explode('->',$value_pair);
			$param_array[$query] = $real_column;
		}
		if($inter_value) {
			$data_array[$key][$inter_key] = $param_array;
			unset($inter_key,$inter_value);
		} else {
			$data_array[$key] = $param_array;
		}
		unset($param_array);
	}
	return $data_array;
}


	function freadline($prompt,$readline=true) {
		if(function_exists(readline) and $readline) {
			$line = trim(readline($prompt));
		} else {
			echo $prompt;
			$line = trim(fgets(STDIN));
		}
		return $line;
	}


	function input_tty($prompt='Input :',$confirm='Are you sure?[y/n]:',$deny_null=true,$readline=true) {
		if($deny_null) {
			do {
				$text = freadline($prompt,$readline);
			} while($text==NULL);
			if($confirm) {
				do {
					$sure = freadline($confirm,$readline);
				} while(!preg_match('/^[YyNn]$/',$sure));
				if(preg_match('/^[Nn]$/',$sure)) $text = NULL;
			}
		} else {
			$text = freadline($prompt,$readline);
		}
		return $text;
	}
	
	function confirm_tty($prompt=NULL,$override=false) {
		if(!$override) {
			$sure_prompt = "Are you sure?[y/n] :";
		} else {
			$sure_prompt = $prompt;
		}
		do {
			if($prompt and !$override) echo $prompt;
			$sure = freadline($sure_prompt);
		} while(!preg_match('/^[YyNn]$/',$sure));
		if(preg_match('/^[Nn]$/',$sure)) return false;
		return true;
	}

	function file_write_contents_with_confirm($filename,$contents,$mode='w') {
		if(file_exists($filename) 
			and !confirm_tty("File '$filename' is already exists.\n"))
			return false;
		file_write_contents($filename,$contents,$mode);
		return true;
	}

	function trim_slash($name) {
		if(substr($name,0,1)=='/') $name = substr($name,1);
		if(substr($name,-1)=='/') $name = substr($name,0,-1);
		return $name;
	}

	function parse_datetime($datetime) {
		list($date,$time) = explode(' ',$datetime);
		list($d['Y'],$d['m'],$d['d']) = explode('-',$date);
		list($d['H'],$d['i'],$d['s']) = explode(':',$time);
		return $d;
	}

	function parse_csv($buffer) {
		if(!trim($buffer)) return false;
		$data = array();
		$word = '';
		$quote = false;
		$len = mb_strlen($buffer);
		for($i=0;$i<$len;$i++) {
			$char = mb_substr($buffer,$i,1);
			switch($char) {
				case ',':
					if($quote) {
						$word .= $char;
					} else {
						$data[] = $word;
						$word = '';
					}
					break;
				case '"':
					if($quote)
						$quote = false;
					else
						$quote = true;
					break;
				default:
					$word .= $char;
			}
		}
		$data[] = $word;
		return $data;
	}

	function _symlink($t /*target*/ ,$l /*link*/ ) {
		if ($_SERVER['windir']) {
			//$p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
			//exec("linkd ".$p.$l." ".$p.$t);
			exec("linkd ".$l." ".$t);
		} else {
			symlink($t,$l);
		}
	}
	function _unlink($l /*link*/ ) {
		if ($_SERVER['windir']) {
			//$p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
			//exec("linkd ".$p.$l." /d");
			exec("linkd ".$l." /D");
		} else {
			unlink($l);
		}
	}


	function apc_get($key) {
		//if(function_exists(apc_fetch)) {
		//	$data = unserialize(apc_fetch($key));
		//}
		return $data;
	}

	function apc_set($key,$data,$ttl=3600) {
		//if(function_exists(apc_store)) {
		//	$result = apc_store($key,serialize($data),$ttl);
		//}
		return $result;
	}

	function get_id_list($table,$id_key='id') {
		foreach($table as $row) {
			$ids[] = $row[$id_key]; 
		}
		$id_list = implode(',',$ids);
		return $id_list;
	}

	function strip_quote($value) {
		$value = trim($value,"'");
		return $value;
	}


function get_mobile_carrier() {
	// ユーザエージェントの取得
	$agent = $_SERVER['HTTP_USER_AGENT'];

	if (preg_match('/^J-PHONE/', $agent) or
	    preg_match('/^Vodafone/', $agent) or
	    preg_match('/^SoftBank/', $agent) or
	    preg_match('/^MOT-/', $agent)) {
	    // J-PHONE, Vodafone, SoftBankの場合
	    $carrier = "softbank";
	} elseif (preg_match('/^DoCoMo/', $agent)) {
	    // DoCoMoの場合
	    $carrier = 'docomo';
	} elseif (preg_match('/UP.Browser/', $agent)) {
	    // auの場合
	    if(preg_match('/^KDDI/', $agent)) {
	        // au（HTML-OK）
	        $carrier = 'au';
	    } else {
	        // au（HDML-Only）
	        $carrier = 'au_hdml';
	    }
	} else {
	    // その他PC等
	    $carrier = '';
	}
	return $carrier;
}



$html_quickform_datatype = array(
	'advcheckbox'=>array('name'=>'string','label'=>'string','text'=>'string','attr'=>'property_array','values'=>'property_array'),
	'button'=>array('name'=>'string','value'=>'string','attr'=>'property_array'),
	'checkbox'=>array('name'=>'string','label'=>'string','text'=>'string','attr'=>'property_array'),
	'captcha'=>array('name'=>'string','label'=>'string','attr'=>'property_array','error_message'=>'string'),
	'captcha_image'=>array('name'=>'string','label'=>'string','opt'=>'property_array','error_message'=>'string'),
	'date'=>array('name'=>'string','label'=>'string','opt'=>'property_array','attr'=>'property_array'),
	'file'=>array('name'=>'string','label'=>'string','attr'=>'property_array'),
	'header'=>array('name'=>'string','label'=>'string'),
	'hidden'=>array('name'=>'string','value'=>'string','attr'=>'property_array'),
	'hireselect'=>array('name'=>'string','label'=>'string','attr'=>'property_array'),
	'html'=>array('html'=>'string'),
	'image'=>array('name'=>'string','src'=>'string','attr'=>'property_array'),
	'link'=>array('name'=>'string','label'=>'string','href'=>'string','value'=>'string','attr'=>'property_array'),
	'password'=>array('name'=>'string','label'=>'string','attr'=>'property_array'),
	'password_plain'=>array('name'=>'string','label'=>'string','attr'=>'property_array'),
	'radio'=>array('name'=>'string','label'=>'string','text'=>'string','value'=>'property_array','attr'=>'property_array','list'=>'property_array'),
	'reset'=>array('name'=>'string','value'=>'string','attr'=>'property_array'),
	'select'=>array('name'=>'string','label'=>'string','value'=>'property_array','attr'=>'property_array'),
	'static'=>array('name'=>'string','label'=>'string','text'=>'string'),
	'submit'=>array('name'=>'string','value'=>'string','attr'=>'property_array'),
	'text'=>array('name'=>'string','label'=>'string','attr'=>'property_array'),
	'textarea'=>array('name'=>'string','label'=>'string','attr'=>'property_array')
);

$html_quickform_datatype_default = array(
	'advcheckbox'=>array('name'=>'advcheckbox','label'=>'チェック','text'=>'','attr'=>NULL,'values'=>array(0=>'off',1=>'on')),
	'button'=>array('name'=>'button','value'=>'OK','attr'=>NULL),
	'captcha'=>array('name'=>'captcha','label'=>'画像内の文字列','attr'=>array('size'=>10,'maxlength'=>30)),
	'captcha_image'=>array('name'=>'captcha_image','label'=>'認証画像','opt'=>NULL,'error_message'=>'画像内の文字列を入力してください'),
	'checkbox'=>array('name'=>'checkbox','label'=>NULL,'text'=>'有効','attr'=>NULL),
	'date'=>array('name'=>'date','label'=>'日付','opt'=>array('language'=>'ja','minYear'=>1945,'maxYear'=>206,'format'=>'Y年m月d日'),'attr'=>NULL),
	'file'=>array('name'=>'file','label'=>'ファイルアップロード','attr'=>NULL),
	'header'=>array('name'=>'header','label'=>'データの入力'),
	'hidden'=>array('name'=>'hidden','value'=>NULL,'attr'=>NULL),
	'hireselect'=>array('name'=>'hireselect','label'=>'選択','attr'=>NULL),
	'html'=>array('html'=>NULL),
	'image'=>array('name'=>'image','src'=>NULL,'attr'=>NULL),
	'link'=>array('name'=>'link','label'=>'URL','href'=>NULL,'value'=>NULL,'attr'=>NULL),
	'password'=>array('name'=>'password','label'=>'パスワード','attr'=>array('size'=>20,'maxlength'=>30)),
	'password_plain'=>array('name'=>'password','label'=>'パスワード','attr'=>array('size'=>20,'maxlength'=>30)),
	'radio'=>array('name'=>'radio','label'=>NULL,'text'=>'候補','value'=>NULL,'attr'=>NULL,'list'=>array(1=>'on',2=>'off')),
	'reset'=>array('name'=>'reset','value'=>'リセット','attr'=>NULL),
	//'select'=>array('name'=>'select','label'=>'選択','value'=>array(0=>NULL,1=>'候補1',2=>'候補2',3=>'候補3')),
	//'select_text'=>array('name'=>'select','label'=>'選択','value'=>array(0=>NULL,1=>'候補1',2=>'候補2',3=>'候補3')),
	//'select_from_table'=>array('name'=>'select','label'=>'選択','value'=>array(0=>NULL,1=>'候補1',2=>'候補2',3=>'候補3')),
	'select'=>array('name'=>'select','label'=>'選択','value'=>array()),
	'select_text'=>array('name'=>'select','label'=>'選択','value'=>array()),
	'select_from_table'=>array('name'=>'select','label'=>'選択','value'=>array()),
	'static'=>array('name'=>'static','label'=>'テキスト','text'=>''),
	'submit'=>array('name'=>'submit','value'=>'送信','attr'=>NULL),
	'text'=>array('name'=>'text','label'=>'テキスト','attr'=>array('size'=>20,'maxlength'=>30)),
	'textarea'=>array('name'=>'textarea','label'=>'フリー入力欄','attr'=>array('rows'=>4,'cols'=>20,))
);

$quicksmart_datatype = array(
	'advcheckbox'=>array('hqf_type'=>'advcheckbox','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#2@','sqlite'=>'text'),
	'button'=>array('hqf_type'=>'button','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'captcha'=>array('hqf_type'=>'captcha','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'captcha_image'=>array('hqf_type'=>'captcha_image','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'checkbox'=>array('hqf_type'=>'checkbox','consist'=>'element','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'confirm'=>array('hqf_type'=>'submit','consist'=>'group','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'date'=>array('hqf_type'=>'date','consist'=>'element','pgsql'=>'timestamp','mysql'=>'datetime','sqlite'=>'text'),
	'file'=>array('hqf_type'=>'file','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'float'=>array('hqf_type'=>'text','consist'=>'element','pgsql'=>'float','mysql'=>'float','sqlite'=>'float'),
	'header'=>array('hqf_type'=>'header','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'hidden'=>array('hqf_type'=>'hidden','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'hidden_int'=>array('hqf_type'=>'hidden','consist'=>'element','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'hireselect'=>array('hqf_type'=>'hireselect','consist'=>'hireselect','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'id'=>array('hqf_type'=>'hidden','consist'=>'element','pgsql'=>'serial PRIMARY KEY','mysql'=>'int auto_increment NOT NULL PRIMARY KEY','sqlite'=>'INTEGER PRIMARY KEY'),
	'image_path'=>array('hqf_type'=>'image','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'image_file'=>array('hqf_type'=>'file','consist'=>'image_file','pgsql'=>array('file_path'=>'text','file_type'=>'text','width'=>'int','height'=>'int'),'mysql'=>array('file_path'=>'varchar#254@','file_type'=>'varchar#10@','width'=>'int','height'=>'int'),'sqlite'=>array('file_path'=>'text','file_type'=>'text','width'=>'int','height'=>'int')),
	'int'=>array('hqf_type'=>'text','consist'=>'element','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'link'=>array('hqf_type'=>'link','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'multiselect'=>array('hqf_type'=>'checkbox','consist'=>'group','pgsql'=>'int[]','mysql'=>'varchar#254@','sqlite'=>'text'),
	'password'=>array('hqf_type'=>'password','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'password_plain'=>array('hqf_type'=>'password_plain','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'radio'=>array('hqf_type'=>'radio','consist'=>'group','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'reset'=>array('hqf_type'=>'reset','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'select'=>array('hqf_type'=>'select','consist'=>'element','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'select_text'=>array('hqf_type'=>'select','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'select_from_table'=>array('hqf_type'=>'select','consist'=>'element','pgsql'=>'int','mysql'=>'int','sqlite'=>'int'),
	'static'=>array('hqf_type'=>'static','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'submit'=>array('hqf_type'=>'submit','consist'=>'element','pgsql'=>'null','mysql'=>'null','sqlite'=>'null'),
	'text'=>array('hqf_type'=>'text','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text'),
	'textarea'=>array('hqf_type'=>'textarea','consist'=>'element','pgsql'=>'text','mysql'=>'text','sqlite'=>'text'),
	'url'=>array('hqf_type'=>'text','consist'=>'element','pgsql'=>'text','mysql'=>'varchar#254@','sqlite'=>'text')
);

$validiate_rule = array(
	'required'=>'null',
	'maxlength'=>'int',
	'minlength'=>'int',
	'rangelength'=>array('int','int'),
	'regex'=>'text',
	'email'=>'null',
	'lettersonly'=>'null',
	'alphanumeric'=>'null',
	'numeric'=>'null',
	'nonzero'=>'null',
	'uploadedfile'=>'null',
	'maxfilesize'=>'int',
	'mimetype'=>'text',
	'filename'=>'text',
	'compare'=>'text'
);

$quicty_data_column_type= array(
	'serial'=>'numeric',
	'INTEGER PRIMARY KEY'=>'numeric',
	'int'=>'numeric',
	'integer'=>'numeric',
	'smallint'=>'numeric',
	'bigint'=>'numeric',
	'decimal'=>'numeric',
	'float'=>'numeric',
	'real'=>'numeric',
	'double'=>'numeric',
	'numeric'=>'numeric',
	'text'=>'text',
	'char'=>'text',
	'varchar'=>'text',
	'timestamp'=>'text',
	'date'=>'text',
	'time'=>'text',
	'interval'=>'text',
	'datetime'=>'text',
	'url'=>'text'
);

?>
