<?php

// install.php -- Web-based installation script
// ------------------------------------------------------------------------
// Copyright (c) 2001, 2002 The phpBugTracker Group
// Copyright (c) 2004, 2005 David Han Sze Chuen, Denis Guinnepain for Air Liquide Medical Systems (Taema)
// Copyright (c) 2005, 2006, 2015 Denis Guinnepain
 
// ------------------------------------------------------------------------
// This file is part of Diamentis

// Diamentis is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// Diamentis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with phpBugTracker; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ------------------------------------------------------------------------

$HTTP_POST_VARS = $_POST;
$HTTP_GET_VARS = $_GET;
$HTTP_SERVER_VARS = $_SERVER;
$HTTP_COOKIE_VARS = $_COOKIE;
$HTTP_ENV_VARS = $_ENV;
$HTTP_POST_FILES = $_FILES;

// Location of smarty templates class
define ('SMARTY_PATH','./inc/smarty/');

if (!@include(SMARTY_PATH . 'Smarty.class.php')) { // Template class
	include('templates/default/base/smartymissing.html');
	exit;
}
if (!@is_writeable('c_templates')) {
	include('templates/default/base/templatesperm.html');
	exit;
}

// Template class
class extSmarty extends Smarty {
	function fetch($_smarty_tpl_file, $_smarty_cache_id = null, $_smarty_compile_id = null, $_smarty_display = false) {
		error_reporting(E_ALL ^ E_NOTICE); // Clobber Smarty warnings
		return Smarty::fetch($_smarty_tpl_file, $_smarty_cache_id, $_smarty_compile_id, $_smarty_display);
	}
}

$t = new extSmarty;
$t->template_dir = 'templates/default';
$t->compile_dir = 'c_templates';
$t->config_dir = '.';
$t->register_function('build_select', 'build_select');

$db_types = array(
	'mysql' => 'MySQL'
	// 'oci8' => 'Oracle 8.1.x',
	// 'pgsql' => 'PostgreSQL'
);

ini_set("magic_quotes_runtime", 0); // runtime quotes will kill the included sql
ini_set("magic_quotes_sybase", 0);

if (!empty($_POST)) {
	$tables = array(
		'/^#.*/' => '', // if line starts with a comment
		'/^--.*/' => '', // if line starts with a comment
//		'/TBL_ACTIVE_SESSIONS/' => $_POST['tbl_prefix'].'active_sessions',
//		'/TBL_DB_SEQUENCE/' => $_POST['tbl_prefix'].'db_sequence',
		'/TBL_PREFIX/' => $_POST['tbl_prefix'],
		'/TBL_ATTACHMENT/' => $_POST['tbl_prefix'].'attachment',
		'/TBL_AUTH_GROUP/' => $_POST['tbl_prefix'].'auth_group',
		'/TBL_AUTH_PERM/' => $_POST['tbl_prefix'].'auth_perm',
		'/TBL_AUTH_USER/' => $_POST['tbl_prefix'].'auth_user',
		'/TBL_BUG_CC/' => $_POST['tbl_prefix'].'contacts',
		'/TBL_BUG_DEPENDENCY/' => $_POST['tbl_prefix'].'bug_dependency',
//		'/TBL_BUG_GROUP/' => $_POST['tbl_prefix'].'bug_group',
		'/TBL_FILE_HISTORY/' => $_POST['tbl_prefix'].'file_history',
		'/TBL_BUG_VOTE/' => $_POST['tbl_prefix'].'bug_vote',
//		'/TBL_BUG/' => $_POST['tbl_prefix'].'bug',
		'/TBL_COMMENT/' => $_POST['tbl_prefix'].'comment',
//		'/TBL_COMPONENT/' => $_POST['tbl_prefix'].'component',
		'/TBL_CONFIGURATION/' => $_POST['tbl_prefix'].'configuration',
		'/TBL_GROUP_PERM/' => $_POST['tbl_prefix'].'group_perm',
//		'/TBL_OS/' => $_POST['tbl_prefix'].'os',
		
		'/TBL_PROJECT_STATUS/' => $_POST['tbl_prefix'] . 'project_status',
		
		'/TBL_PROJECT_GROUP/' => $_POST['tbl_prefix'].'project_group',
		'/TBL_PROJECT_PERM/' => $_POST['tbl_prefix'].'project_perm',
		'/TBL_PROJECT/' => $_POST['tbl_prefix'].'project',
//		'/TBL_RESOLUTION/'  => $_POST['tbl_prefix'].'resolution',
		'/TBL_SAVED_QUERY/' => $_POST['tbl_prefix'].'saved_query',
//		'/TBL_SEVERITY/' => $_POST['tbl_prefix'].'severity',
//		'/TBL_STATUS/' => $_POST['tbl_prefix'].'status',
		'/TBL_USER_GROUP/' => $_POST['tbl_prefix'].'user_group',
//		'/TBL_USER_PERM/' => $_POST['tbl_prefix'].'user_perm',
		'/TBL_USER_PREF/' => $_POST['tbl_prefix'].'user_pref',
//		'/TBL_VERSION/' => $_POST['tbl_prefix'].'version',
//		'/TBL_DATABASE/' => $_POST['tbl_prefix'].'database_server',
//		'/TBL_SITE/' => $_POST['tbl_prefix'].'site',

		// new regexps for the new Memento Plus tables
		'/TBL_ASSIGNATION/' => $_POST['tbl_prefix'] . 'assignation',
		'/TBL_FILE_INDEX/' => $_POST['tbl_prefix'] . 'file_index',
		'/TBL_FIELD_CONF/' => $_POST['tbl_prefix'] . 'field_conf',
		'/TBL_FIELD_TYPE/' => $_POST['tbl_prefix'] . 'field_type',
		'/TBL_SELECTBOX_VALUE/' => $_POST['tbl_prefix'] . 'selectbox_value',
		'/TBL_SELECTBOX_OPTION/' => $_POST['tbl_prefix'] . 'selectbox_option',		
		'/TBL_FILE_STATUS/' => $_POST['tbl_prefix'] . 'file_status',
		
		'/OPTION_ADMIN_EMAIL/' => $_POST['admin_login'],
		'/OPTION_ADMIN_PASS/' => $_POST['encrypt_pass'] ? md5($_POST['admin_pass'])
			: $_POST['admin_pass'],
		'/OPTION_PHPBT_EMAIL/' => $_POST['phpbt_email'],
		'/OPTION_ENCRYPT_PASS/' => $_POST['encrypt_pass'],
		'/OPTION_INSTALL_URL/' => 'http://'.$HTTP_SERVER_VARS['SERVER_NAME'].
		dirname($_SERVER['SCRIPT_NAME'])
		);
}

@include_once('config.php');
if (defined('DB_HOST')) { // Already configured
	header("Location: index.php");
}

function build_select($params) {
	global $db_types;

	extract($params);
	$text = '';
	foreach ($db_types as $val => $item) {
		if ($selected == $val and $selected != '') $sel = ' selected';
	else $sel = '';
	$text .= "<OPTION value=\"$val\"$sel>$item</OPTION>";
	}
	echo $text;
} // end of build_select($params)

///
/// Check the validity of an email address
/// (From zend.com user russIndr)
function bt_valid_email($email) {
  return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$', $email);
} // end of bt_valid_email($email)

function grab_config_file() {
	global $t;

	foreach ($_POST as $key => $val) {
		$patterns[] = '{'.$key.'}';
		$replacements[] = $val;
	}
	// Smarty
	$patterns[] = '{smarty_path}';
	$replacements[] = SMARTY_PATH;

	$contents = join('', file('config-dist.php'));
	return str_replace($patterns, $replacements, $contents);
} // end of grab_config_file()

function test_database(&$params, $testonly = false) {
	// PEAR::DB
	define('PEAR_PATH', 'lib/pear/'); // Set this to '' to use system-wide PEAR
	require_once(PEAR_PATH.'MDB2.php');
	$dsn = array(
		'phptype' => $params['db_type'],
		'hostspec' => $params['db_host'],
		'database'  => $params['db_database'],
		'username'  => $params['db_user'],
		'password'  => $params['db_pass']
		);
	$mdb2 = MDB2::Connect($dsn);
	if (PEAR::isError($mdb2)) {

		include('templates/default/install-dbfailure.html');
		die($db->message.'<br>'.$db->userinfo);
		exit;
	} else {
		if ($testonly) {
			include('templates/default/install-dbsuccess.html');
			exit;
		} else {
			return $mdb2;
		}
	}
} // end of test_database(&$params, $testonly = false)


function test_tables_present($db,&$params, $testonly = false) {
//	include_once('inc/func_html.inc.php');
	$tables=$db->queryAll(" SHOW TABLES ");
//printarray($tables);
	foreach ($tables as $k=>$table)
	{
		if (eregi($params['tbl_prefix'], $table['0'])) 
		{
			return true;
		}
	}
	return false;
} // end of test_tables_present


function create_tables() {
	global $tables;

	$db = test_database($_POST);
	$db->setOption('optimize', 'portability');
	if (test_tables_present($db,$_POST))
	{
		return;
	}
	for ($i=1;$i<=3;$i+=1)
	{
		if ($i==1)
		{
	        $q_temp_ary = file('schemas/'.$_POST['db_type'].'.in');
		}
		else if ($i==2)
		{
			$filename = 'schemas/config_proprietary.in';
			if (file_exists($filename))
			{
				$q_temp_ary = file($filename);
			}
			else
			{
				continue;
			}
		}
		else if ($i==3)
		{
			$filename = 'schemas/config.in';
			if (file_exists($filename))
			{
				$q_temp_ary = file($filename);
			}
			else
			{
				continue;
			}
		}
		else 
		{
			break;
		}

	
		$queries = preg_replace(array_keys($tables), array_values($tables),
			$q_temp_ary);
		$do_query = '';
		foreach ($queries as $query) {
		// First, collect multi-line queries into one line, then run the query
			$do_query .= chop($query);
			if (empty($do_query) or substr($do_query, -1) != ';') continue;
			if ($_POST['db_type'] == 'oci8' ) {
				$do_query = substr($do_query, 0, -1);
			} elseif ($_POST['db_type'] == 'mysql' ) {		
				$do_query = str_replace('\\\'', '\'\'', $do_query);
			}		
			
			$res = $db->query(stripslashes($do_query));		
			if(PEAR::isError($res)){
				if ($_POST['db_type'] == 'mysql' ) {
					$do_query = str_replace('TYPE', 'ENGINE', $do_query);
				}
				$res = $db->query(stripslashes($do_query));
				if(PEAR::isError($res)){
						
				echo ("<br>Error : " . $res->getMessage() . "<br>");
				print($do_query . "<br>");
				//die();
				}
			}
		// echo "query = ".stripslashes($do_query)."<br><br>";		
			$do_query = '';
		}
	}
	 // die();
} // end of create_tables()

function check_vars() {
	
	$error = '';
	if (!$_POST['db_host'] = trim($_POST['db_host'])) {
		$error = 'Please enter the host name for your database server';
	} elseif (!$_POST['db_database'] = trim($_POST['db_database'])) {
		$error = 'Please enter the name of the database you will be using';
	} elseif (!$_POST['db_user'] = trim($_POST['db_user'])) {
		$error = 'Please enter the user name for connecting to the database';
	} elseif (!$_POST['phpbt_email'] = trim($_POST['phpbt_email'])) {
		$error = 'Please enter the Diamentis application email address';
	} elseif (!$_POST['admin_login'] = trim($_POST['admin_login'])) {
		$error = 'Please enter the admin login';
	} elseif (!bt_valid_email($_POST['admin_login'])) {
		$error = 'Please use a valid email address for the admin login';
	} elseif (!$_POST['admin_pass'] = trim($_POST['admin_pass'])) {
		$error = 'Please enter the admin password';
	} elseif (!$_POST['admin_pass2'] = trim($_POST['admin_pass2'])) {
		$error = 'Please confirm the admin password';
	} elseif ($_POST['admin_pass'] != $_POST['admin_pass2']) {
		$error = 'The admin passwords don\'t match';
	}

	if (!empty($error)) {
		show_front($error);
		return false;
	} else {
		return true;
	}
} // end of check_vars()

function dump_config_file() {
	if (!check_vars()) {
		return;
	}
	create_tables();
 	header('Content-Type: text/x-delimtext; name="config.php"');
 	header('Content-disposition: attachment; filename=config.php');
 	echo grab_config_file();
} // end of dump_config_file()

function save_config_file() {
	if (!check_vars()) {
		return;
	}
	create_tables();
	if (!$fp = @fopen('config.php', 'w')) {
		show_front('Error writing to config.php');
	} else {
		fwrite($fp, grab_config_file());
		fclose($fp);
	}
	show_finished();
} // end of save_config_file()

function show_finished() {
	global $t;

	$t->assign('login', $_POST['admin_login']);
	$t->display('install-complete.html');
} // end of show_finished()

function show_front($error = '') {
	global $t, $select;

	$t->assign($_POST);
	$t->assign('error', $error);
	$t->assign('default_email', 'diamentis-application-software@'.$_SERVER['SERVER_NAME']);
	$t->display('install.html');
} // end of show_front($error = '')

if (isset($_POST['op'])) {
	switch ($_POST['op']) {
		case 'save_config_file' : save_config_file(); break;
		case 'dump_config_file' : dump_config_file(); break;
	}
} elseif (isset($_GET['op'])) {
	switch ($_GET['op']) {
		case 'dbtest' : test_database($_GET, true); break;
	}
} else {
	show_front();
}
// Any whitespace below the end tag will disrupt config.php
?>