<?php
require_once 'includes/datasets_conf/_base.class.php';
class datasets_conf_write extends datasets_conf {

function write_conf($datasets_id,$all=false) {
	$this->init($datasets_id);

	if($_REQUEST['data_def']=='yes' or $all)
		$message .= $this->write_data_def();
	if($_REQUEST['data_view']=='yes' or $all)
		$message .= $this->write_data_view();
	if($_REQUEST['search_view']=='yes' or $all)
		$message .= $this->write_search_view();
	if($_REQUEST['search_form']=='yes' or $all)
		$message .= $this->write_search_form();
	if($_REQUEST['search_sys']=='yes' or $all)
		$message .= $this->write_search_system();
	//if($_REQUEST['sort_tab']=='yes' or $all)
	//	$message .= $this->write_sort_tab();
	if($_REQUEST['data_set']=='yes' or $all)
		$message .= $this->write_data_set();
	if($_REQUEST['sql']=='yes' or $all)
		$message .= $this->write_sql();
	if($_REQUEST['init']=='yes' or $all)
		$message .= $this->write_init();
	$result['message'] = $message;
	return $result;
}

// data_def

function write_data_def() {
	umask(0);
	$data_def_file_name = $this->application_path.'/etc/data_def/'.$this->dsn['dataname'].'.def';
	if(file_exists($data_def_file_name)) {
		$recent_files_dir = $this->application_path.'/etc/data_def/recent';
		if(!file_exists($recent_files_dir)) make_dir($recent_files_dir,0777);
		copy($data_def_file_name,$recent_files_dir.'/'.$this->dsn['dataname'].'.def');
		@chmod($recent_files_dir.'/'.$this->dsn['dataname'].'.def',0666);
		$old_files_dir = $this->application_path.'/etc/data_def/old';
		if(!file_exists($old_files_dir)) make_dir($old_files_dir,0777);
		$datetime = date("YmdHi");
		copy($data_def_file_name,$old_files_dir.'/'.$this->dsn['dataname'].'_'.$datetime.'.def');
		@chmod($old_files_dir.'/'.$this->dsn['dataname'].'_'.$datetime.'.def',0666);
	}
	$data_def = serialize(array('dsn'=>$this->dsn,'data_set'=>$this->data_sets));
	$data_def_file_name = $this->application_path.'/etc/data_def/'.$this->dsn['dataname'].'.def';
	file_write_contents($data_def_file_name,$data_def);
	@chmod($data_def_file_name,0666);
	return 'wrote '.$this->dsn['dataname'].'.def -> '.$data_def_file_name."\n";
}

// data_view

function set_attribute($tag,$attributes) {
	if(is_array($attributes) and count($attributes)>0) {
		$data_view = $tag."=start\n";
		foreach($attributes as $key=>$value) {
			$data_view .= "$key=$value\n";
		}
		$data_view .= "end_".$tag."=true\n";
	}
	return $data_view;
}

function get_data_view_of_column($column) {
	foreach($column as $property=>$attribute) {
		switch($property) {
			case 'name':
				$data_view .= '['.$attribute.']'."\n";
				break;
			case 'type':
				$type = $this->fields_reverse_map[$attribute]['type'];
				$data_view .= 'type'.'='.$type."\n";
				break;
			case 'label':
				$data_view .= $property.'='.$attribute."\n";
				break;
			case 'attr':
			case 'list':
			case 'opt':
			case 'rule':
			case 'values':
				$data_view .= $this->set_attribute($property,$attribute);
				break;
			case 'value':
				if(is_array($attribute)) {
					$data_view .= $this->set_attribute($property,$attribute);
				} else {
					$data_view .= $property.'='.$attribute."\n";
				}
				break;
			case 'default':
			case 'force_value':
				if(is_array($attribute)) {
					$data_view .= $this->set_attribute($property.'_list',$attribute);
				} else {
					$data_view .= $property.'='.$attribute."\n";
				}
				break;
			case 'virtual':
				$data_view .= $property.'='.$attribute."\n";
				break;
		}
	}
	//var_check($data_view);
	return $data_view;
}


function write_data_view() {
	foreach($this->data_sets as $column) {
		$data_view .= $this->get_data_view_of_column($column);
		$data_view .= "\n";
	}
	//echo "data_view=$data_view<br>";
	$data_view_file_name = $this->application_path.'/etc/data_view/'.$this->dsn['dataname'].'.view.conf';
	file_write_contents($data_view_file_name,$data_view);
	@chmod($data_view_file_name,0666);
	return 'wrote '.$this->dsn['dataname'].'.view.conf -> '.$data_view_file_name."\n";
}

// search_view

function write_search_view() {
	if(!is_array($this->search_columns) or count($this->search_columns)<1) {
		$result['message'] = "search_view : there are no column for search\n";
		return $result;
	}
	foreach($this->search_columns as $name=>$properties) {
		$label = $properties['label'];
		$type = $properties['type'];
		$data_type = $GLOBALS['quicksmart_datatype'][$type]['pgsql'];
		if($data_type=='text' and $label and $type!='advcheckbox') {
			$kinds[$name] = $name.'='.$label;
		} elseif($type=='date' and $label) {
			$column = $properties['properties'];
			$column['name'] = 'start_'.$name;
			$column['label'] = '開始';
			$each_conditions .= "\n".$this->get_data_view_of_column($column);
			
			$column['name'] = 'end_'.$name;
			$column['label'] = '終了';
			$each_conditions .= "\n".$this->get_data_view_of_column($column);
		} elseif($label) {
			$column = $properties['properties'];
			$each_conditions .= "\n".$this->get_data_view_of_column($column);
		}
	}
	
	if(is_array($kinds) and count($kinds)>0) {
		$keyword_kind = implode("\n",$kinds);
	}
	
	$search_view = <<<EOS
[keyword]
label=キーワード
type=text
attr=start
size=30
maxlength=50
end_attr=true

[kind]
label=種類
type=select
value=start
$keyword_kind
end_value=true
default_list=start
kind=1
end_default_list=true
EOS;

	umask(0);
	if($each_conditions) $search_view.= "\n".$each_conditions;
	$search_view_dir_name = $this->application_path.'/etc/search_view/';
	if(!file_exists($search_view_dir_name)) make_dir($search_view_dir_name,0777);
	$search_view_file_name = $search_view_dir_name.$this->dsn['dataname'].'_search.view.conf';
	file_write_contents($search_view_file_name,$search_view);
	@chmod($search_view_file_name,0666);
	$message = 'wrote '.$this->dsn['dataname'].'_search.view.conf -> '.$search_view_file_name."\n";
	return $message;
}

// search_form

function write_search_form() {
	if(!is_array($this->search_columns) or count($this->search_columns)<1) {
		$result['message'] = "search_form : there are no column for search\n";
		return $result;
	}
	foreach($this->search_columns as $name=>$properties) {
		$label = $properties['label'];
		$type = $properties['type'];
		$data_type = $GLOBALS['quicksmart_datatype'][$type]['pgsql'];
		$hqf_type = $GLOBALS['quicksmart_datatype'][$type]['hqf_type'];
		if($data_type=='text' and $label and $type!='advcheckbox') {
			$kinds[$name] = $name.'='.$label;
		} elseif($type=='date' and $label) {
			$each_forms[] = "<tr><th><label for=\"$name\">{\$search_form.start_$name.label}</label></th><td>{\$search_form.start_$name.html}</td></tr>";
			$each_forms[] = "<tr><th><label for=\"$name\">{\$search_form.end_$name.label}</label></th><td>{\$search_form.end_$name.html}</td></tr>";
		} elseif($label and $hqf_type!='hidden') {
			$each_forms[] = "<tr><th><label for=\"$name\">{\$search_form.$name.label}</label></th><td>{\$search_form.$name.html}</td></tr>";
		}
	}

	$search_form = 
		"<div class=\"search-form\">\n".
		"<form {\$search_form.attributes}>\n".
		"<table cellspacing=\"0\">\n".
		"<tr><th><label for=\"keyword\">キーワード</label></th>".
		"<td><input type=\"text\" id=\"keyword\" name=\"keyword\" value=\"{\$smarty.request.keyword}\" />\n".
		"{\$search_form.kind.html}\n".
		"<input type=\"submit\" value=\"検索\" id=\"submit[SEND]\" name=\"submit[SEND]\" />".
		"<span id=\"search-reset\">{if count(\$smarty.request)>0}<a href=\"./{if \$quicty.action != 'index'}{\$quicty.action}{/if}\">リセット</a>{else}リセット{/if}</span></td></tr>\n";

	if(is_array($each_forms) and count($each_forms)>0) {
		$each_form = implode("\n",$each_forms)."\n";
		$search_form .= $each_form;
	}
	
	$search_form .= 
		"</table>\n".
		"</form>\n".
		"</div>\n";

	$search_form_dir_name = $this->application_path.'/view/includes/'.$this->dsn['dataname']."/";
	if(!file_exists($search_form_dir_name)) mkdir($search_form_dir_name,0777);
	$search_form_file_name = $search_form_dir_name.'search_form.inc';
	file_write_contents($search_form_file_name,$search_form);
	@chmod($search_form_file_name,0666);
	$message .= 'wrote '.$this->dsn['dataname'].'/search_form.inc -> '.$search_form_file_name."\n";
	return $message;
}
// search_system
function write_search_system() {
	if(!is_array($this->search_columns) or count($this->search_columns)<1) {
		$result['message'] = "search_system : there are no column for search\n";
		return $result;
	}
	foreach($this->search_columns as $name=>$properties) {
		$label = $properties['label'];
		$type = $properties['type'];
		$data_type = $GLOBALS['quicksmart_datatype'][$type]['pgsql'];

		if($data_type=='text' and $label and $type!='advcheckbox') {
			$keyword[$name] = $this->dsn['dataname'].'.'.$name;
		} elseif($type=='date' and $label) {
			$start_name = 'start_'.$name;
			$end_name = 'end_'.$name;
			$period[$start_name] = array('column'=>$name,'end'=>$end_name);
		} elseif($label) {
			$condition[$name] = $this->dsn['dataname'].'.'.$name;
		}
	}
	if(is_array($keyword) and count($keyword)>0) $search_system['keyword'] = $keyword;
	if(is_array($condition) and count($condition)>0) $search_system['condition'] = $condition;
	if(is_array($period) and count($period)>0) $search_system['period'] = $period;

	//var_check($search_system);
	if(is_array($search_system) and count($search_system)>0) {
		$search_sys_file_name = $this->application_path.'/etc/search_view/'.$this->dsn['dataname'].'.sys';
		write_data_array($search_sys_file_name,$search_system);
		@chmod($search_sys_file_name,0666);
		$message = 'wrote '.$this->dsn['dataname'].'.sys -> '.$search_sys_file_name."\n";
	} else {
		$message = 'not wrote '.$this->dsn['dataname'].".sys. because search sys is empty.\n";
	}
	return $message;
}


// sort tab
/*
function write_sort_tab() {
	if(!is_array($this->sort_columns) or count($this->sort_columns)<1) {
		$result['message'] = "sort_tab : there are no column for sort\n";
		return $result;
	}
	foreach($this->sort_columns as $name=>$properties) {
		$label = $properties['label'];
		$type = $properties['type'];
		if($type=='id') {
			$reset_tab = "<td nowrap=\"nowrap\"><span style=\"font-size:small;\">{if count(\$smarty.request)>0}<a href=\"./{if \$quicty.action != 'index'}{\$quicty.action}{/if}\">リセット</a>{else}リセット{/if}</span></td>";
		} elseif($label) {
			$each_tabs[] = "<td nowrap=\"nowrap\">$label<span style=\"font-size:x-small;\">{if \$sort=='$name' and \$order==''}△{else}<a href=\"?{make_get_query sort=$name order=''}\">▲</a>{/if}{if \$sort=='$name' and \$order=='desc'}▽{else}<a href=\"?{make_get_query sort=$name order=desc}\">▼</a>{/if}&nbsp;|&nbsp;</span></td>";
		}
	}

	$sort_tab = <<<EOS
{assign var='sort' value=\$smarty.request.sort}{assign var='order' value=\$smarty.request.order}
<table cellspacing="0" cellpadding="0" valign="top" class="menu-tab" style="margin:5px 0;">
<tr valign="top"><td>並べ替え：</td>
EOS;
	if(is_array($each_tabs) and count($each_tabs)>0) {
		$each_tab = implode("\n",$each_tabs)."\n";
		$sort_tab .= $each_tab.$reset_tab;
	}
	$sort_tab .= <<<EOS
</tr>
</table>
EOS;

	$sort_tab_dir_name = $this->application_path.'/view/includes/'.$this->dsn['dataname']."/";
	if(!file_exists($sort_tab_dir_name)) mkdir($sort_tab_dir_name,0777);
	$sort_tab_file_name = $sort_tab_dir_name.'sort_tab.inc';
	file_write_contents($sort_tab_file_name,$sort_tab);
	@chmod($sort_tab_file_name,0666);
	$message .= 'wrote '.$this->dsn['dataname'].'/sort_tab -> '.$sort_tab_file_name."\n";
	return $message;
}
*/

// data_set
function write_data_set() {
	global $quicksmart_datatype;
	$data_set_dsn = "[dsn]\n";
	$data_set_dsn .= "system=".$this->dsn['system']."\n";
	$data_set_dsn .= "dbname=".$this->dsn['dbname']."\n";
	if(isset($this->dsn['path'])) $data_set_dsn .= "path=".$this->dsn['path']."\n";
	if(isset($this->dsn['host'])) $data_set_dsn .= "host=".$this->dsn['host']."\n";
	if(isset($this->dsn['port'])) $data_set_dsn .= "port=".$this->dsn['port']."\n";
	if(isset($this->dsn['user'])) $data_set_dsn .= "user=".$this->dsn['user']."\n";
	if(isset($this->dsn['password'])) $data_set_dsn .= "password=".$this->dsn['password']."\n";
	if(isset($this->dsn['persistent'])) $data_set_dsn .= "persistent=".$this->dsn['persistent']."\n";
	$data_set_dsn .= "\n";
	
	$data_set_bind = "[bind]\n";
	foreach($this->data_sets as $column) {
		if($column['type']=='id') continue;
		if($column['virtual']=='yes') continue;
		$type = $this->fields_reverse_map[$column['type']]['type'];
		$sql_type = $quicksmart_datatype[$type][$this->dsn['system']];
		$data_set_bind .= $column['name'].':'.$type.'='
			.$this->data_name.'.'.$column['name'].':'.$sql_type."\n";
	}
	$data_set_bind .= "\n";
	$data_set = $data_set_dsn.$data_set_bind;
	
	$data_set_file_name = $this->application_path.'/etc/data_set/'.$this->dsn['dataname'].'.set.conf';
	file_write_contents($data_set_file_name,$data_set);
	@chmod($data_set_file_name,0666);
	$return_mes = 'wrote '.$this->dsn['dataname'].'.set.conf -> '.$data_set_file_name."\n";
	
	$auth_set_name = $this->application_path.'/etc/data_set/auth.set.conf';
	if($this->dsn['dataname']=='userauth' AND file_exists($auth_set_name)) {
		$auth_set_source = file($this->application_path.'/etc/data_set/auth.set.conf');
		$auth_set = $data_set_dsn;
		foreach($auth_set_source as $line) {
			if(substr($line,0,9)=="[session]") {
				$skip = "off";
			}
			if($skip=="off") {
				$auth_set .= $line;
			}
		}
		//echo nl2br($auth_set);
		file_write_contents($auth_set_name,$auth_set);
		@chmod($auth_set_name,0666);
		$return_mes .= 'wrote auth.set.conf -> '.$auth_set_name."\n";
	}
	
	return $return_mes;
}


// sql
function write_sql() {
	global $quicksmart_datatype;
	
	if($this->system=='sqlite3') {
		$true_system_name = 'sqlite3';
		$this->system = 'sqlite';
	}
	
	// drop db
	if($this->system=='mysql') {
		$sql = "drop table if exists $this->data_name;\n";
	} else {
		$sql = "drop table $this->data_name;\n";
	}
	
	// set owner
	if($this->dsn['user']) {
		$user = $this->dsn['user'];
		if($this->system=='pgsql') {
			$sql.= "SET SESSION AUTHORIZATION '$user';\n";
		}
	}
	
	// create db
	$sql .= "create table $this->data_name(\n";

	foreach($this->data_sets as $column) {
		if($column['virtual']=='yes') continue;
		//$type = $this->fields_reverse_map[$column['type']]['type'];
		$type = $column['hqf_type'];
		if(!$sql_type = $quicksmart_datatype[$type][$this->system]) {
			$type = $this->fields_reverse_map[$column['type']]['type'];
			$sql_type = $quicksmart_datatype[$type][$this->system];
			$sql_type = str_replace(array('#','@'),array('(',')'),$sql_type);
		}
		if($sql_type=='null') continue;
		$sql_array[] = $column['name'].' '.$sql_type;
	}

	if($true_system_name=='sqlite3') {
		$this->system = 'sqlite3';
	}

	if(is_array($sql_array) and count($sql_array)>0) {
		if(!file_exists($this->application_path.'/etc/sql/'.$this->system))
			make_dir($this->application_path.'/etc/sql/'.$this->system,0777);
		$sql .= "\t".implode(",\n\t",$sql_array);
		$sql .= "\n);\n";
		$sql_file_name = $this->application_path.'/etc/sql/'.$this->system.'/'.$this->dsn['dataname'].'.sql';
		file_write_contents($sql_file_name,$sql);
		@chmod($sql_file_name,0666);
		$message = 'wrote '.$this->dsn['dataname'].'.sql -> '.$sql_file_name."\n";
	}
	
	if(is_array($sql_array) and count($sql_array)>0) {
		$recent_def_files = $this->application_path.'/etc/data_def/recent/'.$this->dsn['dataname'].'.def';
		if(file_exists($recent_def_files)) {
			$old_def = unserialize(file_get_contents($recent_def_files));
			$old_data_sets = $old_def['data_set'];
			foreach($old_data_sets as $column) {
				$old_sets[$column['name']] = $column;
			}
			$table = $this->dsn['dataname'];
			foreach($this->data_sets as $column) {
				if($column['virtual']=='yes') continue;
				$name = $column['name'];
				$my_type = $column['type'];
				if($my_type==$old_sets[$name]['type']) continue;
				$type = $this->fields_reverse_map[$my_type]['type'];
				$sql_type = $quicksmart_datatype[$type][$this->system];
				$alter_sql_array[] = "alter table $table add column $name $sql_type;";
			}
			if(count($alter_sql_array)>0) {
				$alter_sql = implode("\n",$alter_sql_array);
				$alter_sql_file_name = $this->application_path.'/etc/sql/'.$this->system.'/alter_'.$this->dsn['dataname'].'.sql';
				if(file_exists($alter_sql_file_name)) {
					$old_files_dir = $this->application_path.'/etc/sql/'.$this->system.'/old';
					if(!file_exists($old_files_dir)) make_dir($old_files_dir,0777);
					$datetime = date("YmdHi");
					copy($alter_sql_file_name,$old_files_dir.'/alter_'.$this->dsn['dataname'].'_'.$datetime.'.sql');
					@chmod($old_files_dir.'/alter_'.$this->dsn['dataname'].'_'.$datetime.'.sql',0666);
				}
				file_write_contents($alter_sql_file_name,$alter_sql);
				@chmod($alter_sql_file_name,0666);
				$message .= 'wrote '.$this->dsn['dataname'].'.sql -> '.$sql_file_name."\n";
			}
		}
	}
	return $message;
}

// all init.sh
function make_init_db_statements($dataset) {
	$db_system = $dataset['system'];
	$db_name = $dataset['dbname'];

	switch($db_system) {
		case 'sqlite':
		case 'sqlite3':
			break;
		case 'pgsql':
			$statements = "createdb $db_name\n";
			break;
		case 'mysql':
			$statements = "mysqladmin -u root create $db_name\n";
			break;
	}
	return $statements;
}

function make_init_table_statements($dataset) {
	$db_system = $dataset['system'];
	$db_name = $dataset['dbname'];
	$table = $dataset['name'];

	switch($db_system) {
		case 'sqlite':
		case 'sqlite3':
			$db_name = $dataset['path'].'/'.$db_name;
			if($_ENV['windir']) {
				$db_name = str_replace('/','\\',$db_name);
				$statements = "sqlite $db_name < .\\etc\\sql\\sqlite\\$table.sql\r\n";
			} else {
				$statements = "sqlite $db_name < etc/sql/sqlite/$table.sql\n";
				$statements .= "chmod o+w $db_name\n";
			}
			break;
		case 'pgsql':
			//$statements = "createdb $db_name\n";
			if($_ENV['windir']) {
				$statements = "psql $db_name < .\\etc\\sql\\pgsql\\$table.sql\r\n";
			} else {
				$statements = "psql $db_name < etc/sql/pgsql/$table.sql\n";
			}
			break;
		case 'mysql':
			//$statements = "mysqladmin -u root create $db_name\n";
			if($_ENV['windir']) {
				$statements = "mysql -u root -D $db_name < .\\etc\\sql\mysql\\$table.sql\r\n";
			} else {
				$statements = "mysql -u root -D $db_name < etc/sql/mysql/$table.sql\n";
			}
			break;
	}
	return $statements;
}


function write_all_init($datasets) {
	foreach($datasets as $dataset) {
		$dbs[$db_name] = $this->make_init_db_statements($dataset);
		$table_statements .= $this->make_init_table_statements($dataset);
	}
	$db_statements = implode("",$dbs);

	if($_ENV['windir']) {
		$init_file_name = $this->application_path.'/bin/init_all_datasets.bat';
		$init = "@echo off\n";
	} else {
		$init_file_name = $this->application_path.'/bin/init_all_datasets.sh';
		$init = "#!/bin/sh\n";
	}
	$init .= <<<EOS
echo "#----------------------------------------------#"
echo "# initialize all data sets"
echo "#----------------------------------------------#"
$db_statements
$table_statements
echo done.
EOS;
	file_write_contents($init_file_name,$init);
	if($_ENV['windir']) chmod($init_file_name,0744);
	return 'wrote init_all_datasets.sh'."\n";
}


// init.sh
function write_init() {
	switch($this->system) {
		case 'sqlite':
			if($_ENV['windir']) {
				$this->db_set = str_replace('/','\\',$this->db_set);
				$statements = "sqlite $this->db_set < .\\etc\\sql\\sqlite\\$this->data_name.sql\r\n";
			} else {
				$statements = "sqlite $this->db_set < etc/sql/sqlite/$this->data_name.sql\n";
				$statements .= "chmod o+w $this->db_set\n";
			}
			break;
		case 'pgsql':
			$statements = "createdb $this->db_name\n";
			if($_ENV['windir']) {
				$statements .= "psql $this->db_name < .\\etc\\sql\\pgsql\\$this->data_name.sql\r\n";
			} else {
				$statements .= "psql $this->db_name < etc/sql/pgsql/$this->data_name.sql\n";
			}
			break;
		case 'mysql':
			$statements = "mysqladmin -u root create $this->db_name\n";
			if($_ENV['windir']) {
				$statements .= "mysql -u root -D $this->db_name < .\\etc\\sql\mysql\\$this->data_name.sql\r\n";
			} else {
				$statements .= "mysql -u root -D $this->db_name < etc/sql/mysql/$this->data_name.sql\n";
			}
			break;
	}
	if($_ENV['windir']) {
		$init_file_name = $this->application_path.'/bin/init_'.$this->dsn['dataname'].'.bat';
		$init = "\n".<<<EOS
@echo off
echo "#----------------------------------------------#"
echo "# initialize $this->system $this->db_set  "
echo "#----------------------------------------------#"
$statements
echo done.
EOS;
	} else {
		$init_file_name = $this->application_path.'/bin/init_'.$this->dsn['dataname'].'.sh';
		$init = "\n".<<<EOS
#!/bin/sh
echo "#----------------------------------------------#"
echo "# initialize $this->system $this->db_set  "
echo "#----------------------------------------------#"
$statements
echo done.
EOS;
	}
	file_write_contents($init_file_name,$init);
	if($_ENV['windir']) chmod($init_file_name,0744);
	return 'wrote init_'.$this->dsn['dataname'].'.sh -> '.$init_file_name."\n";
}

} // end of class datasets_conf_write
?>