Location: PHPKode > projects > Volunteer Management OpenSource Software > vmoss_alpha02/inst/setup.inc
<?php
/**
 * Sahana web setup. Initially launched to setup the database and sahana configuration
 *
 * PHP version 4 and 5
 *
 * LICENSE: This source file is subject to LGPL license
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/copyleft/lesser.html
 *
 * @package    Sahana - http://sahana.sourceforge.net
 * @author     http://www.linux.lk/~chamindra
 * @author     Pradeeper http://www.linux.lk/~pradeeper
 * @author     Ravindra http://r4vi.org
 * @copyright  Lanka Software Foundation - http://www.opensource.lk
 */

session_start();

if (!function_exists("gettext"))
{
	global $global;
	include_once ($global['approot'].'inc/lib_locale/lib_gettext.inc');
}
require_once ($global['approot'] . 'inc/lib_security/constants.inc');
require_once ($global['approot'] . 'inc/lib_security/lib_auth.inc');
require_once ($global['approot'].'inc/handler_html_head.inc');
require_once ($global['approot'].'inc/lib_modules.inc');
require_once ($global['approot'].'inc/lib_form.inc');
require_once ($global['approot'].'inc/lib_errors.inc');
require_once ($global['approot'].'3rd/adodb/adodb.inc.php');
require_once ($global['approot'].'inc/lib_uuid.inc');
require_once ($global['approot'].'inc/lib_validate.inc');
require_once ($global['approot'].'inc/lib_config.inc');
//require_once ($global['approot'].'inc/lib_locale/handler_locale.inc');

shn_setup_main();

// main setup switchboard
function shn_setup_main()
{
	$action = $_GET['act'];
	$modify = array();

	// display nice header
	shn_setup_header();
	switch ($action) {

		case 'dependancy': // first setup form
			if (shn_setup_check_dependancy()) { // check if all the dependencies are fullfill
				shn_setup_form1();
			} else {
				display_errors();
				shn_setup_form_dependancy();
			}

			break;

		case 'dbsetup': // second setup form
			if (shn_setup_database()) { // check if database writing is a success
				shn_setup_form2();
			} else {
				display_errors();
				shn_setup_form1();
			}
			break;

		case 'cfgsetup': // third setup form

			shn_email_validate();// try to catch the invalid emailaddresses of "second settup form"
			//shn_chk_root_pwd();// check root passwd validation

			if(!shn_setup_acl()){
				display_errors();
				shn_setup_form2();
				break;
			}
			if (shn_setup_config_update($_POST['conffile'])) {
				// check if writing the file was a success
				shn_setup_form_conffile();
			} else {
				display_errors();
				shn_setup_form2();
			}
			break;

		default:
			// first database setup form
			shn_setup_form_dependancy();

	}
	shn_setup_footer();
}

function shn_setup_check_dependancy()
{
	global $global;

	$continue = true;

	if (!version_compare(phpversion(), '4.1', '>')) $continue = false;
	if (!extension_loaded('gd')) $continue = false;
	if (!extension_loaded('mysql')) $continue = false;
	if (!extension_loaded('gettext')) $continue = false;
	if (!is_writable($global['approot'].'www/tmp')) $continue = false;

	return $continue;
}

function shn_email_validate()
{
	$email = $_POST['root_email'];
	if((eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))||($email=="")) {
		// if email is a valid one then do nothing ;-)
	}
	else {
		add_error("<b>$email</b> is an invalid email address! please check the 'Administrator Email' again.");
		display_errors();
		shn_setup_form2();
		break;
	}
}// end of shn_email_validate
/*
 function shn_pwd_validate()
 {
 $pwd=$_POST['root_pwd'];
 $re_pwd=$_POST['root_pwd_confirm'];
 if($pwd==""){ // if password slot is empty
 echo "<b><font color=red>Passwords</font> are empty!</b>";
 echo "";
 shn_setup_form2();
 break;
 } elseif (!($pwd==$re_pwd)) { // if password and retyped one are not matched
 echo "<b><font color=red>Passwords</font> are not matched!</b>";
 echo "";
 shn_setup_form2();
 break;
 }
 } // end of shn_root_pwd_validation
 */
function shn_setup_form_dependancy()
{
	global $global;
	$isOK = true;
	$tick_img = '<img align="top" src="theme/default/img/tic.png" alt="tick"/>';
	$cross_img = '<img align="top" src="theme/default/img/cross.png" alt="cross"/>';
	$oops_img = '<img align="bottom" src="theme/default/img/oops.png" alt="oops"/>';
	?>
<h1><?=_('Installation Step 1 - Check Dependencies')?></h1>

<p><?=_('Welcome to VMOSS. Please follow the following steps to setup VMOSS')?></p>

<p><?=_('First we need to check if all the relevant dependencies for VMOSS to be install are available on your system')?></p>
	<?php

	shn_form_fopen(_('dependancy'));

	shn_form_fsopen(_('PHP libraries'));
	?>
<p><?=_('The following checks if all the relevant VMOSS libraries are installed')?></p>
	<?php

	$value = (version_compare(phpversion(), '4.1', '>'));
	$isOK &= $value;

	//if ($isOK) echo "is OK";
	if ($value) {
		shn_form_label(_('PHP Version'), $tick_img.phpversion()." is installed");
	} else {
		shn_form_label(_('PHP Version'), $cross_img.phpversion()." is installed");
		echo "<p><br/>$oops_img VMOSS needs PHP version 4.1 or higher. Please upgrate your version of PHP</p>";
	}

	// Check if php-gd is loaded
	$value = (extension_loaded('gd'));
	$isOK &= $value;

	if ($value) {
		shn_form_label(_('PHP-GD Library'), $tick_img."installed");
	} else {
		shn_form_label(_('PHP-GD Library'), $cross_img."is not installed");
		echo "<p><br/>$oops_img VMOSS needs PHP-GD for image manipulations. Please install PHP-GD and restart the webserver. To find out how to do this for your operating system see <a href=\"http://www.sahana.lk/wiki/doku.php?id=manual:install\">Sahana WIKI</a></p>";
	}

	// Check if php-gettext is loaded
	$value = (extension_loaded('gettext'));
	$isOK &= $value;

	if ($value) {
		shn_form_label(_('PHP-gettext Library'), $tick_img."installed");
	} else {
		shn_form_label(_('PHP-gettext Library'), $cross_img."is not installed");
		echo "<p><br/>$oops_img VMOSS needs PHP-gettext for to support local languages. Please install PHP-GD and restart the webserver. To find out how to do this for your operating system see <a href=\"http://www.sahana.lk/wiki/doku.php?id=manual:install\">Sahana WIKI</a></p>";
	}

	$value = (extension_loaded('mysql'));
	$isOK &= $value;

	if ($value) {
		shn_form_label(_('MySQL library'), $tick_img."installed");
	} else {
		shn_form_label(_('MySQL library'), $cross_img."is not installed");
		echo "<p><br/>$oops_img VMOSS needs PHP-MySQL library and MySQL for database operation. Please install PHP-MySQL library and MySQL and restart the webserver. To find out how to do this for your operating system see <a href=\"http://www.sahana.lk/wiki/doku.php?id=manual:install\">Sahana WIKI</a></p>";
	}

	shn_form_fsclose();
	shn_form_fsopen(_('File and Directory Permissions'));
	?>
<p><?=_('The following checks if certain files and sub-directories have write permissions for VMOSS to function,')?></p>
	<?php
	$tmpWritable = is_writable($global['approot'].'www/tmp');
	$isOK &= $tmpWritable;


	if ($tmpWritable) {
		//shn_form_label(_('Sahana www/tmp/ is writable?'),"The Sahana sub-directory writable");
		shn_form_label(_('<i>/www/tmp/</i>'),"is <strong><font color=green>writable</font></strong>!<br>");
	} else {
		//shn_form_label(_('Sahana www/tmp/ is writable?'),"The Sahana sub-directory not writable");
		shn_form_label(_('<i>/www/tmp/</i>'),"is <strong><font color=red>not writable</font></strong>!<br>");
		//echo "<p><br/>$oops_img The directory ".$global['approot']."www/tmp needs to be writable by the web server at least. Please change the permissions of this directory and try again.</p>";
	}

	/* if ($value) {
	 shn_form_label(_('Sahana www/tmp/ is writable?'), $tick_img."The Sahana sub-directory writable");
	 } else {
	 shn_form_label(_('Sahana www/tmp/ is writable?'), $cross_img."The Sahana sub-directory not writable");
	 echo "<p><br/>$oops_img The directory ".$global['approot']."www/tmp needs to be writable by the web server at least. Please change the permissions of this directory and try again.</p>";
	 }

	 /*   $value = (is_writable($global['approot'].'res/locale'))? 'checked':'';

	 shn_form_checkbox('Sahana res/locale is writable?','write_locale',$value.'
	 disabled="true"',array('value'=>'y','help'=>'hello'));
	 */
	$confWritable = is_writable($global['approot'].'conf');

	if ($confWritable) {
		//shn_form_label(_('Sahana www/conf/ is writable?'), $tick_img."The Sahana sub-directory writable");
		shn_form_label(_('<i>/conf/</i>'),"is <strong><font color=green>writable</font></strong>!<br>");
	} else {
		//shn_form_label(_('Sahana www/conf/ is writable?'), "The Sahana sub-directory not writable");
		shn_form_label(_('<i>/conf/</i>'),"is <strong><font color=red>not writable</font></strong>!<br>");
	}

	if (!$tmpWritable || !$confWritable) {
		$both = (!$tmpWritable && !$confWritable);

		echo "<p>Note: <font color=gray>" . (($both ? "both " : "")) . ((!$confWritable) ? "<strong>/conf/</strong>" : "") . (($both) ? " and " : " ") . ((!$tmpWritable) ? "<strong>/www/tmp/</strong>" : "") . " need" . ((!$both) ? "s" : "") . " to be writable by the web server at least. Please change the permissions of " . ((!$both) ? "this directory" : "these directories") . " and try again.</font></p>";
	}

	shn_form_fsclose();

	if ($isOK) {
		echo _('<p>All the dependencies are OK and you may move to
                the next step</p>')."\n";
		shn_form_submit(_('Next >>'));
	} else {
		echo _('<p>Please correct the required dependencies above and</p>')."\n";
		shn_form_submit(_('Try Again'));
	}
	shn_form_fclose();
}

// the database setup form
function shn_setup_form1()
{
	?>
<h2><?=_('Installation Step 2 - Database Setup')?></h2>
<script type="text/javascript">
var keep_db_admin = true;
</script>
	<?php

	shn_form_fopen('dbsetup');

	shn_form_fsopen(_('Database Management System (DBMS)'));
	shn_form_select(
	//VMOSS: only support MySQL 5.0 or higher
	array( 'mysql' => 'MySQL 5.0 or above'), 'DBMS Type', 'dbtype', '', array('help' => 'This is the type of Database Management System that will be used. Currently only MySQL 5.0 or higher is supported.'));
	$engines['MyISAM']='MyISAM';
	//VMOSS: only MyISAM is supported currently
	//$engines['InnoDB']='InnoDB';
	shn_form_text(_('DBMS Host:Port'),'dbhost','size="30"', array('value'=>'localhost','req'=>true, 'help' => 'This is the address of the Database Management System. If no port is specified, the default port of 3306 is used.'));
	shn_form_text(_('Database Name'),'dbname','size="30"', array('value'=>'vmoss', 'req'=>true, 'help' => 'This is the name of the database to create on the Database Management System\'s server.'));
	shn_form_select($engines, _("Engine Type"), 'engine_type', '', array('help' => 'This is the database engine that will be used on the database just specified. Currently only MyISAM is supported.'));
	shn_form_fsclose();

	shn_form_fsopen('MySQL Administrator');
	echo '<label>What is this?</label>';
	shn_form_extra_opts(array('help' => 'These credentials are used to log into the Database Management System with the address specified above in order to install the VMOSS database. <br /><br />For this reason, it would be wise for these to be the credentials of the MySQL administrator, or a MySQL user who has privileges to create databases, insert, update, create users, and grant privileges to users.'));
	shn_form_text(_('Username'),'dbuser','size="30"', array('value'=>'root', 'req'=>true, 'help' => 'This should be a user who can log into the Database Management System and has appropriate permissions to create databases, create users, and grant privileges to users..'));
	shn_form_password(_('Password'),'dbpass','size="30"', array('req'=>true, 'help' => 'This is the password for this database administrator. If the user has no password, then leave blank.'));
	shn_form_fsclose();

	//VMOSS: redid notion of sahana db user
	shn_form_fsopen('VMOSS Database User');
	echo '<label>What is this?</label>';
	shn_form_extra_opts(array('help' => 'These credentials are stored in plain text and used within VMOSS to connect to the database.'));
	shn_form_checkbox('Use above MySQL credentials?', 'keep_db_admin', ($_POST['keep_db_admin'] == 'Y')?'checked':'',
		array('value' => 'Y',
				'help' => 'If you check this box, VMOSS will store the MySQL adiministrator\'s credentials provided above in plain text in the /conf/sysconf.inc file and use them each time it establishes a connection with the database. <br /><br /> ' .
						'For security reasons, you may want a MySQL user will less privileges to be used for this purpose. <br /><br />' .
						'If this is desired, uncheck this box and specify a username and password below. If this user already exists and the credentials are valid, all privileges to the created database will be given to this user. If the user does not exist, VMOSS will create this user and grant all privileges only to the VMOSS database.'));
	shn_form_text(_('Username'),'shndbuser','size="30"',array('req'=>true, 'help' => 'If this user already exists and the credentials are valid, all privileges to the created VMOSS database will be given to this user. If the user does not exist, VMOSS will create this user and grant all privileges only to the VMOSS database.'));
	shn_form_password(_('Password'),'shndbpass','size="30"',array('req'=>true, 'help' => 'This is the password for this database user. If the user has no password, then leave blank.'));
	shn_form_fsclose();


	//VMOSS: install defaul categories all the time
	shn_form_hidden(array('dbsample' => 'y'));
	//shn_form_fsopen(_('Schemas to Install'));
	// please add somedescription,
	/*
	?> <p><?=_('Check this to create the default categories for aid goods,units.')?></p> <?
	*/
	//shn_form_checkbox(_('Default Item Categories'),'dbsample','checked',
	//array('value'=>'y'));
	// this 'help' is to be removed :
	//, 'help'=>'Check this to
	//create the default categories for aid goods, units'));
	//shn_form_fsclose();

	shn_form_submit(_('Setup VMOSS Database >>'));

	shn_form_fclose();
}

/**
 * Last changed: 28-May-2007 - hide@address.com
 * Added the admin and normal user account fields
 **/
function shn_setup_form2()
{
	?>
<h1>Installation Step 3 - Configuration
</h2>
<p>Please follow the following steps to setup the VMOSS configuration</p>

	<?php
	echo PWDPOLICY."<br />";
	global $global;

	shn_form_fopen('cfgsetup');

	// pass the previous post varibles into hidden for the configuration file
	shn_form_hidden( array(
        'dbhost' => $_POST['dbhost'] ,
        'dbname' => $_POST['dbname'] ,
        'keep_db_admin' => $_POST['keep_db_admin'],
        'dbuser' => $_POST['dbuser'],
        'dbpass' => $_POST['dbpass'],
        'shndbuser' => ($_POST['keep_db_admin'] == 'Y')?$_POST['dbuser']:$_POST['shndbuser'] ,
        'shndbpass' => ($_POST['keep_db_admin'] == 'Y')?$_POST['dbpass']:$_POST['shndbpass'] ,
	'engine_type' => $_POST['engine_type']));

	shn_form_fsopen(_('Installation Details'));

	echo '<p>The following details are needed to uniquely identify your VMOSS installation</p>'; // some spellings corrected by chamath 2007-03-15 09:50

	$help_txt = "The following field is randomly generated to help uniquely identify \
                 this VMOSS installation. Please use this unless you have a \
                 convention defined";
	shn_form_text(_('Unique Installation ID'),'base_uuid','size="4" maxlength="4"',
	array('value'=> shn_generate_uuid(4),'req'=>true , 'help' => $help_txt));
	shn_form_text(_('Administrator Name'),'root_name','size="40"' );
	shn_form_text(_('Administrator Email'),'root_email','size="40"' );
	shn_form_text(_('Administrator Telephone'),'root_tel','size="30"' );

	shn_form_fsclose();


	shn_form_hidden(array(
		'acl' => 'enable',
		'theme' => 'default'
	));

	/*
	//VMOSS: need ACL enabled, and only show default theme to simplify
	shn_form_fsopen(_('Settings'));

	shn_form_select(
	array( 'disable' => _('Disable'),'enable' =>_('Enable')),
	_('Access Control'),'acl');
	shn_form_select(
	array( 'default' => _('Default Theme'),

	), ('Theme'), 'theme');
	shn_form_fsclose();
	*/

	shn_form_fsopen(_('Administrator Account'));
	echo '<label>What is this?</label>';
	shn_form_extra_opts(array('help'=>'These credentials will be used to log into VMOSS with the greatest privileges.'));
	shn_form_text(_('Admin User Name'),'admin_name','size="40"', array('req'=>true, 'value'=>'admin') );
	shn_form_password(_('Password'),'root_pwd','size="30"',
	array('req'=>true));
	shn_form_password(_('Confirm Password'),'root_pwd_confirm','size="30"',array('req'=>true));
	shn_form_fsclose();

	/*
	//VMOSS: no need for a normal user account
	shn_form_fsopen(_('Create Normal User Account'));
	shn_form_text(_('Normal User Name'),'user_name','size="40"', array('req'=>true,'value'=>'sahana', 'help'=>'Please login as this user for non-admin work') );
	shn_form_password(_('Password'),'user_pwd','size="30"',array('req'=>true));
	shn_form_password(_('Confirm Password'),'user_pwd_confirm','size="30"',array('req'=>true));
	shn_form_fsclose();
	*/

	shn_form_fsopen(_('Configuration File'));

	if (is_writeable($global['approot'].'conf')) {

		echo '<p>The next step is to write the configuration file sysconf.inc in the VMOSS /conf directory.</p>';

		shn_form_hidden(array('conffile' =>
		$global['approot'].'conf/sysconf.inc'));

	} else {

		echo '<p>The PHP/Web Server should normally not have access to write
    or modify the configuration file located in application <b>/conf</b>
    directory, as this is a security risk. Please specify where to write the temporary file (e.g. /tmp). Subsequently you need to move this file to
    the <b>/conf</b> directory.</p>';

		$tmp_filename = tempnam('/tmp','sysconf.inc');
		// Need the temporary directory rather than the filename
		$tmp_filename = preg_replace('/sysconf.inc.*$/','sysconf.inc',
		$tmp_filename);

		shn_form_text(_('Location To Write Config File (sysconf.inc)'),
                'conffile','size="50"', array('value'=>"$tmp_filename",
                'req'=>true ));

	}
	shn_form_fsclose();

	shn_form_submit(_('Write Configuration File >>'));

	shn_form_fclose();
}
/*
 function shn_chk_root_pwd()
 {
 clean_errors();
 // check whether the password is empty or not
 if ($_POST['acl']=='enable'){

 if ($_POST['root_pwd']==null) {
 add_error("Root password can not be empty!");
 display_errors();
 shn_setup_form2();
 break;
 // if it's not empty then check whether those are matching
 } elseif (!($_POST['root_pwd']==$_POST['root_pwd_confirm'])) {
 add_error("Root passwords do not match! Please re-type the root password and try again.");
 display_errors();
 shn_setup_form2();
 break;
 }
 }
 } // end of shn_chk_root_pwd
 */
function shn_setup_form_conffile()
{
	//shn_chk_root_pwd();


	?>
<h1><?=_('Installation Step 3 - Configurations')?></h1>
<p><?=_('Configuration file ')?><?=$_POST['conffile']?> <?=_(' has been successfully written.')?></p>

	<?php
	global $global;
	$oops_img = '<img align="bottom" src="theme/default/img/oops.png"/>';

	shn_form_fopen('default','admin',array('req_message' => false));
	shn_form_fsopen(_('Starting VMOSS'));

	shn_form_hidden( array(
        'conffile' => $_POST['conffile'] ));
	$sahana_url = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/index.php\?.*$/','',$_SERVER['REQUEST_URI']);

	if (is_writeable($global['approot'].'conf')) {
		?>
<p><b><u><?php echo $oops_img._('WARNING: Security')?></u></b></p>
<p><?php echo _('To secure the configuration you have to remove write
             permissions from the configuration file sysconf.inc located in
             the directory conf/')?></p>

<p><?=_('Click the button below to begin using VMOSS')?> <?php
} else {
	?>


<p><?=_('To finish the configuration follow the steps below')?></p>
<p><b>1.</b><?=_(' Copy the temporary config file created from: ')?><br />
<u><?=$_POST['conffile']?></u> to: <br />
<u><?=$global['approot']."conf/sysconf.inc"?></u></p>
<p><b>2.</b><?=_(' For security reasons delete the temporary configuration file at ')?><u><?=$_POST['conffile']?></u></p>
<p><b>3.</b><?=_(' Once done click the button below to start VMOSS or access it anytime using the url: ')?><a
	href="<?=$sahana_url?>"><?=$sahana_url?></a></p>

	<?php

}
shn_form_fsclose();
?>
<input type="button" value="Begin Using VMOSS" onClick="window.location='index.php';" />
<input type="button" value="How to Use VMOSS" onClick="window.location='index.php?mod=vm&amp;act=volunteer&amp;vm_action=help';" />
<?php
shn_form_fclose();
$_SESSION['first_time_run']=true;
}

// connect to the database and run the scripts specified by the user
function shn_setup_database()
{
	global $global;
	global $conf;
	$db = &NewADOConnection('mysql');

	if($_POST['dbtype']=='mysql'){
		// check host name
		if(isset($_POST['dbhost']) && $_POST['dbhost']!=''){
			// check for patterns.
			if(stripos($_POST['dbhost'],':')>0){
				// contains port
				$vals = explode(':',$_POST['dbhost']);
				if(preg_match('/^\d+$/',$vals[1])==false){
					add_error(_("The port number is invalid."));
					return false;
				}
			}
		}else{
			add_error(_("The database host:port cannot be empty."));
			return false;
		}

		// check sahana dbname.
		if(isset($_POST['dbname'])==false || $_POST['dbname']==''){
			add_error(_("The database name cannot be empty."));
			return false;
		}else{
			if(preg_match('/[!@#$%\^&\\*\/\?`~+=|:;\(\)-]/',$_POST['dbname'])){
				add_error(_("The database name cannot contain special characters."));
				return false;
			}
		}

		//if we keep the administrator credentials, then we don't need to connect to the mysql database within the MySQL DBMS
		if($_POST['keep_db_admin'] == 'Y') {
			$db->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass']);
			if(!($db->IsConnected())){
				add_error(_("Could not connect to DBMS with the given database administrator credentials. Please check to make sure that the credentials are valid."));
				return false;
			}
		} else {
			$db->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass'],'mysql');
			if(!($db->IsConnected())){
				add_error(_("Could not connect to the DBMS with the given database administrator credentials. Please check to make sure that the credentials are valid and that the database administrator has access to the 'mysql' database within the MySQL DBMS."));
				return false;
			}

			$res=$db->Execute("SELECT * FROM `user` WHERE `User`='".$_POST['shndbuser']."'");
			if($res->EOF){
				//app dbuser does not exist, create it
				if(strlen($_POST['shndbuser'])>=16){
					add_error(_("The application database username is too long. Maximum length is 15."));
					return false;
				} else if(trim($_POST['shndbuser']) == '') {
					add_error("Please specify an application database username.");
					return false;
				}
				$res = $db->Execute("CREATE USER '".$_POST['shndbuser']."'@'%' IDENTIFIED BY '".$_POST['shndbpass']."'");
				if($res === false) {
					add_error("The database administrator given does not have privileges to create a new user. Please specify another database administrator or contact your MySQL administrator to receive these permissions.");
					return false;
				}
			} else {
				//app dbuser exists, but verify credentials
				$ndb = &NewADOConnection('mysql');
				$ndb->NConnect($_POST['dbhost'],$_POST['shndbuser'],$_POST['shndbpass']);
				if(!($ndb->IsConnected())) {
					add_error("You have specified an application database user who exists, but whose password is incorrect.");
					return false;
				}
			}
			$res = $db->Execute("GRANT ALL ON ".$_POST['dbname'].".* TO '".$_POST['shndbuser']."'@'%'");
			if($res === false) {
				add_error("The database administrator given does not have privileges to grant privileges to other users. Please specify another database administrator or contact your MySQL administrator to receive these permissions.");
				return false;
			}
			$db->Close();
		}
	}else if($_POST['dbtype']=='pgsql'){
		// check whether user exists,
		//$tdb->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass'],'pgsql');
		//$res=$tdb->Execute("SELECT * FROM `user` WHERE `User`='".$_POST['shndbuser']."'");
		//if(!($res->EOF)){
		//	add_error(_("System database username already exists. Use a different system database username."));
		//	return false;

		// create system user and privileges
		//$db->Execute("CREATE USER ".$_POST['shndbuser']." WITH PASSWORD '".$_POST['shndbpass']."'");
		//$db->Execute("GRANT ALL PRIVILEGES ON ".$_POST['dbname']." TO ".$_POST['shndbuser']."@".$_POST['dbhost']);
	}else {
		add_error(_('Unsupported database. Please select a valid database type.'));
		return false;
	}

	if (! $db->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass']) ) {
		add_error(_('Could not connect to MySQL. Please check the database administrator credentials and try again'));
		return false;
	}

	$engine_type=$_POST['engine_type'];
	// create the main database
	$res = $db->Execute("CREATE DATABASE IF NOT EXISTS ".$_POST['dbname']);
	if($res === false) {
		add_error("The database administrator user that you provided does not have permissions to create databases. Please specify a new database administrator username and password or contact your MySQL administrator to receive these privileges.");
	}
	$db->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass'],$_POST['dbname']);
	$global['db'] = $db;
	$conf['db_engine']=$_POST['dbtype'];

	if($conf['db_engine'] == 'mysql')
	{
		$db->Execute("set storage_engine ='{$engine_type}'");
	}
	$conf['storage_engine']=$engine_type;
	//VMOSS: removed some module script runs
	shn_setup_run_sqlscript($db,'inst/mysql-dbcreate.sql');
	shn_setup_run_sqlscript($db,'inst/mysql-config.sql');
	//shn_setup_run_sqlscript($db,'mod/cs/inst/dbcreate.sql');
	//shn_setup_run_sqlscript($db,'mod/rms/inst/dbcreate.sql');
	//shn_setup_run_sqlscript($db,'mod/gis/dbcreate.sql');
	shn_setup_run_sqlscript($db,'mod/vm/inst/dbcreate.sql'); // for Volunteer management
	//shn_setup_run_sqlscript($db,'mod/ims/inst/dbcreate.sql');
	//shn_setup_run_sqlscript($db,'mod/msg/inst/dbcreate.sql'); // patched by SriGaneshan 2007-03-11 23:42
	//shn_setup_run_sqlscript($db,'mod/rs/inst/dbcreate.sql');
	//shn_setup_run_sqlscript($db,'mod/hr/inst/dbcreate.sql');//hr

	if ($_POST['dbsample']=='y') {
		include_once($global['approot'].'inc/lib_uuid.inc');
		shn_setup_run_sqlscript($db,'inst/mysql-sampledata.sql');
		include($global['approot'].'inst/cs_setup.inc');
		shn_cs_datacreate();
	}

	//modified by dinusha
	/*
	$db->Execute("insert into incident(incident_id,name) values(1,'default')");
	$db->Execute("insert into user_preference values(0,'ims','incident_id',1)");
	$db->Execute("insert into user_preference values(2,'ims','incident_id',1)");
	*/

	//make special VMOSS-specific modifications to the database
	$db->execute("INSERT INTO config (module_id, confkey, value) VALUES ('admin', 'loc_range_start', 1)");
	$db->execute("INSERT INTO config (module_id, confkey, value) VALUES ('admin', 'loc_range_end', 3)");

	//disregard sahana's acl in the vm
	$db->execute("INSERT INTO config (module_id, confkey, value) VALUES ('vm', 'use_sahana_acl', 0)");

	//make the admin a vm admin
	include $global['approot']."mod/vm/lib/Constants.php";
	$db->execute("INSERT INTO vm_user_role (fk_user, fk_role) VALUES (1, ".VM_ROLE_VM_ADMIN.")");
	//end
	return true;
}

// runs the script file relative to the approot
function shn_setup_run_sqlscript($db, $relative_script_path)
{
	global $global;

	$script = $global['approot'].$relative_script_path;

	if ($fh = fopen($script,'r')) {
		$sql=''; // clear the bucket

		while (! feof($fh) ) { // a fix as Execute gets confused over carriage returns
			$buffer = fgets($fh,1024); // read the script and fill the buffer
			$sql=$sql.$buffer; // fill the buffer until ';' appear
			if(preg_match('/;/',$buffer)) { // look after ';'
				$db->Execute($sql);
				$sql=''; // clear the bucket again
			}
		}
		//$sql = fread($fh,filesize($script));
		fclose($fh);
	}
	// @todo error handler if file does not exist
}


function shn_setup_config_update($tmp_configfile)
{
	global $global;
	$modify = array(
        '/\'theme\'/' => '$conf[\'theme\'] = \''.$_POST['theme'].'\';' ,
        '/\'db_host\'/' => '$conf[\'db_host\'] = \''.$_POST['dbhost'].'\';' ,
        '/\'db_name\'/' => '$conf[\'db_name\'] = \''.$_POST['dbname'].'\';' ,
        '/\'base_uuid\'/' => '$conf[\'base_uuid\'] = \''.$_POST['base_uuid'].'\';' ,
        '/\'root_name\'/' => '$conf[\'root_name\'] = \''.$_POST['root_name'].'\';' ,
        '/\'root_tel\'/' => '$conf[\'root_tel\'] = \''.$_POST['root_tel'].'\';' ,
        '/\'root_email\'/' => '$conf[\'root_email\'] = \''.$_POST['root_email'].'\';' ,
        '/\'db_user\'/' => '$conf[\'db_user\'] = \''.$_POST['shndbuser'].'\';' ,
        '/\'db_pass\'/' => '$conf[\'db_pass\'] = \''.$_POST['shndbpass'].'\';' ,
	'/\'storage_engine\'/' => '$conf[\'storage_engine\'] = \''.$_POST['engine_type'].'\';');

	echo "<pre>";

	echo "</pre>";
	if ( @shn_config_file_update( $modify, $global['approot'].'conf/sysconf.inc.tpl',
	$tmp_configfile) ) {
		return true;
	} else {
		add_error(_('Could not write to file $tmp_configfile. Try another location'));
		return false;
	}
}

function shn_setup_header()
{
	?>
<body>
<div id="container"><?php
shn_include_page_section('header',$module);
?>
<div id="wrapper" class="clearfix">
<div id="content" class="clearfix"><?php
}

function shn_setup_footer()
{
	?></div>
<!-- /content --> <?php
shn_include_page_section('footer',$module);
?></div>
<!-- /wrapper --></div>
<!-- /container -->
</body>
</html>
<?php
}

// install the ACL base
function shn_setup_acl(){
	global $global;
	$db = &NewADOConnection('mysql');
	$db->Connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpass'],$_POST['dbname']);
	$global['db'] = $db;



	$error=false;
	if ((null==$_POST["admin_name"])or(is_null($_POST["admin_name"]))){
		$error=true;
		add_error(_("Admin user name cannot be empty"));
	}
	if ((null==$_POST["root_pwd"])or(is_null($_POST["root_pwd"]))){
		$error=true;
		add_error(_("Root password cannot be empty"));
	}else {
		$re_password=trim($_POST{"root_pwd_confirm"});
	}
	if ((null==$_POST["root_pwd_confirm"])or(is_null($_POST["root_pwd_confirm"]))){
		$error=true;
		add_error(_("Root Confirm password cannot be empty"));
	}else {
		$re_password=trim($_POST{"root_pwd_confirm"});
	}
	if (!($_POST{"root_pwd"}==$re_password)){
		$error=true;
		add_error("Root password and confirm password should match");
	}

	/*
	//VMOSS does not need normal user account
	if ((null==$_POST["user_name"])or(is_null($_POST["user_name"]))){
		$error=true;
		add_error(_("Normal user name cannot be empty"));
	}
	if ((null==$_POST["user_pwd"])or(is_null($_POST["user_pwd"]))){
		$error=true;
		add_error(_("User password cannot be empty"));
	}else {
		$password=trim($_POST{"user_pwd"});
	}
	if ((null==$_POST["user_pwd_confirm"])or(is_null($_POST["user_pwd_confirm"]))){
		$error=true;
		add_error(_("User Confirm password cannot be empty"));
	}else {
		$re_password=trim($_POST{"user_pwd_confirm"});
	}
	if (!($_POST{"user_pwd"}==$re_password)){
		$error=true;
		add_error("User password and confirm password should match");
	}
	*/

	if($error){
		return false;
	}

	if (shn_validate_password($_POST["admin_name"],$_POST["root_pwd"])==false){
		$error=true;
		return false;
	}
	/*
	//VMOSS does not need normal user account
	if (shn_validate_password($_POST["user_name"],$_POST["user_pwd"])==false){
		$error=true;
		return false;
	}
	*/
	global $global;
	include_once $global['approot']. 'inc/lib_security/lib_acl.inc';
	return (shn_acl_install($_POST['admin_name'],$_POST['root_pwd'],$_POST['user_name'],$_POST['user_pwd'],$_POST['acl']=='enable'));

}

?>
Return current item: Volunteer Management OpenSource Software