<?php

/*
 *	W-AGORA 4.2
 *	-----------
 *	$Id: setup.php,v 1.46 2005/12/21 11:13:48 mdruilhe Exp $
 *	Usage:		Main configuration
 *	Author:		Marc Druilhe <mdruilhe@w-agora.net>

	Description:
	This script create the main administration database:

	files:
	------
	conf/site_agora.php	Configuration file for the 'site' view
	forums/agora/*.php		layout/localization files

	tables/DBM files:
	-----------------
	agora				sites
	agora_users			admin users
	agora_userforum		user-site relations
 */


	require ("globals.inc");

	if (file_exists("$lang_dir/admin_$lang.inc") ) {
		include ("$lang_dir/admin_$lang.inc");
	} else {
		include ("$lang_dir/admin_${default_lang}.inc");
	}

	include "$inc_dir/misc_func.$ext";
	include "$inc_dir/config.$ext";

	if (!empty($_POST['mode'])) {
		$mode = $_POST['mode'];
	} elseif (!empty($_GET['mode'])) {
		$mode = $_GET['mode'];
	} else {
		$mode = 'basic';
	}

function create_dir($dir) {
	global $ext;

# Check if safe_mode is On
# ------------------------
	$sf = @get_cfg_var("safe_mode");

	if (is_dir ($dir)) {
		$ret = true;
		$dir_created = false;
	} else {
		$ret = mkdir ("$dir", _DIRMODE);
		$dir_created = true;
	}

	if ($ret) {

		// Directory have been created, make sure we can create a file in it
		$perm = false;
		$fd = fopen ("$dir/tmp.$ext", "w+");
		if (!$fd) {
			if ($dir_created) {
			    rmdir($dir);
			}
			msgForm (sprintf (ERROR_SF_CREATE_FILE, $dir), "setup.$ext", 'back');
			return false;
		}
		fputs ($fd, "<?php \$perm=true; ?" . '>');
		fclose ($fd);
		include "$dir/tmp.$ext";
		@unlink ("$dir/tmp.$ext");
		if ($perm) {
			return true;
		} else {
			if ($dir_created) {
			    rmdir($dir);
			}
			msgForm (sprintf (ERROR_SF_CREATE_FILE, $dir), "setup.$ext", 'back');
			return false;
		}

	} else {

		// Could not create dir, try to figure out why.
		if ($sf) {
			msgForm (str_replace("{DIRECTORY}", $dir, ERROR_SAFE_MODE), "setup.$ext", 'back');
		} else {
			msgForm (str_replace("{DIRECTORY}", $dir, ERROR_CREATE_DIR), "setup.$ext", 'back');
		}
		return false;
	}
}

function table_header ($title, $width="95%") {
	echo "<div style=\"text-align: center\"><table class=\"admintable\" width=\"$width\">\n";
	echo "<tr><td class=\"admintabletitle\">$title</td></tr><tr><td class=\"admintabledata\">\n";
}

function table_footer () {
	echo "</td></tr></table></div>\n";
}

	$languages = array(
		"fr" => "W-Agora en français",
		"en" => "W-Agora in english",
		"de" => "W-Agora in deutsch",
		"ja" => "W-Agora in Japanese",
		"da" => "W-Agora p&aring; dansk",
		"it" => "W-Agora in italiano",
		"pl" => "W-Agora in polish",
		"nl" => "W-Agora in dutch",
		"sv" => "W-Agora in swedish",
		"ru" => "W-Agora in russian",
		"ca" => "W-Agora in catalan",
		"es" => "W-Agora en español",
		"he" => "W-Agora in hebrew",
		"hu" => "W-Agora in hungarian"
	);

	foreach($languages as $lg=>$text) {
		$flags .= "<a href=\"setup.$ext?mode=$mode&amp;lang=$lg\" title=\"$text\" onMouseover=\"window.status='$text';return true\" onMouseout=\"window.status='';return true\" onClick=\"document.setupform.lang.value='$lg';document.setupform.mode.value='$mode';document.setupform.submit();return false;\"><img height=\"16\" width=\"30\" src=\"images/flag_$lg.png\" border=\"0\" align=\"middle\" alt=\"$text\"></a>&nbsp;\n";
	}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html lang="<?php echo $lang?>" dir="<?php echo $bn_html_dir?>">
<head>
 <link rel="stylesheet" href="style.css">
 <link rel="stylesheet" href="admin_style.css">
 <?php
	if (!empty($bn_charset)) {
		echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=$bn_charset\">\n";
	}
?>
 <title><?php echo LABEL_SETUP_AGORA?></title>
 <script type="text/javascript">
 <!-- // Hide for old browsers
  var newWindow = null;
  function OpenWindow (Url,Title, Width, Height) {
    var win_opt= "toolbar=0,location=0,directories=0,status=0,menubar=0,";
    win_opt += "scrollbars=1,resizable=1,copyhistory=0,";
    win_opt += "width=" + Width + ",height=" + Height;
    newWindow = window.open('',Title,win_opt);
    if (newWindow != null) {
      if (newWindow.opener == null)
        newWindow.opener = self;
      newWindow.location.href = Url;
      if (newWindow.focus) newWindow.focus();
    }
  }
  // End of script -->
 </script>
</head>
<body>
<div align="center">
 <a href="http://www.w-agora.net/"><img src="images/logo1.jpg" align="bottom" border="0" alt="<?php echo LABEL_AGORA_WEBSITE?>"></a>
</div>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
 <tr><td align="center" valign="middle">&nbsp;<?php echo $flags; ?></td></tr>
</table>
<br />
<?php


# Define main site and configuration file
# ---------------------------------------
	$site = 'agora';
	$site_cfgfile = "${cfg_dir}/site_agora.$ext";

	if (empty ($bn_dir_forums)) {
		$bn_dir_forums = 'forums';
	}

# Check if the main site (agora) is already configured
# ----------------------------------------------------
	if (file_exists ("$site_cfgfile")) {
		$errmsg = sprintf (ERROR_SETUP_ALREADY_DONE, $site_cfgfile);
		msgForm ($errmsg, "create_site.$ext", '');
		echo "</body>\n</html>";
		exit;
	}

# if setup from has been submitted
# --------------------------------
if (isSet($do_setup)) {

	unset ($do_setup);

#	check all required variables
#	---------------------------
	if (empty($admin_name)) {
		msgForm (ERROR_MISSING_ADMIN_NAME, "setup.$ext", 'back');
		echo "</body>\n</html>";
		exit;
	} elseif (!validate_email($admin_address, false)) {
		msgForm (ERROR_MISSING_ADMIN_EMAIL, "setup.$ext", 'back');
		echo "</body>\n</html>";
		exit;
	} elseif (empty($bn_access)){
		msgForm (ERROR_MISSING_DB_ACCESS, "setup.$ext", 'back');
		echo "</body>\n</html>";
		exit;
	} elseif (empty ($passwd1) || ($passwd1 != $passwd2)) {
		msgForm (ERROR_BAD_PASSWORD, "setup.$ext", 'back');
		echo "</body>\n</html>";
		exit;
	} elseif (empty($dbname)){
		msgForm (ERROR_MISSING_DB_NAME, "setup.$ext", 'back');
		echo "</body>\n</html>";
		exit;
	}

# ------------------
# Create directories
# ------------------

	/* Create site configuration's directory */
	$dir = "$cfg_dir";
	create_dir($dir) or die ('</body></html>');

	/* Create forum's directory */
	$dir = "$bn_dir_forums";
	create_dir($dir) or die ('</body></html>');

	/* Create forum's directory */
	$dir = "$bn_dir_forums/$site";
	create_dir($dir) or die ('</body></html>');

# ---------------------------------
# Create w-agora Configuration File
# ---------------------------------
	$bn_dir="$bn_dir_forums/$site";
	$bn_dir_notes="$bn_dir";
	$bn_dir_default="$bn_dir";
	$bn_db=$site;

	$bn_usersource = "agora_user";

	$bn_search=0;
	$bn_search_engine = "none";
	$bn_search_path="";

	$dbadmuser = (empty($dbadmuser) ) ? $dbuser : $dbadmuser;
	$dbadmpassword = (empty($dbadmpassword) && ($dbadmuser==$dbuser) ) ? $dbpassword : $dbadmpassword;

	include ("$tmpl_dir/admin/conf_agora.$ext");

	// Check permissions
	$perm = false;
	$fd = fopen ("$cfg_dir/tmp.$ext", "w+");
	if (!$fd) {
		msgForm (sprintf (ERROR_SF_CREATE_FILE, $cfg_dir), "setup.$ext", 'back'); /* access problem */
		die ("</body>\n</html>");
	}
	fputs ($fd, "<?php \$perm=true; ?" . '>');
	fclose ($fd);
	include "$cfg_dir/tmp.$ext";
	if ($perm) {
	    @unlink ("$cfg_dir/tmp.$ext");
	} else {
		msgForm (sprintf (ERROR_SF_CREATE_FILE, $cfg_dir), "setup.$ext", 'back'); /* access problem */
		die ("</body>\n</html>");
	}

# Copy all w-agora customization/layout files (sites listing)
# -----------------------------------------------------------
	$files = array ('bn_fields', 'bn_header', 'bn_list_vars', 'bn_msgs', 'bn_footer');

	reset ($files);
	while ( list(,$name) = each ($files) ) {
		$file = $$name;
		if (!empty ($file) ) {
			if (!copy ("$tmpl_dir/admin/$file", "$bn_dir/$file") ) {
				msgForm (sprintf(ERROR_COPY_FILE, "$bn_dir/$file"), $WA_SELF, 'back');
				exit;
			}
		}
	}

# Open database
# -------------
	include "$inc_dir/$bn_access.$ext";
	$db_class = "${bn_access}_access";
	$db = new $db_class;
	$db->setHaltOnError("report");
	$ret = $db->openDB($dbhost, $dbport, $dbadmuser, $dbadmpassword, $dbname, $site);
	if ($ret < 0) {
		msgForm (sprintf (ERROR_OPEN_DB, $dbname, $dbhost, $dbport, $dbadmuser), "setup.$ext", 'back');
		die ('</body></html>');
	}

	$db->setHaltOnError("yes");

# Create site forums table
# ------------------------
	$ret = $db->createSite ("$site", "$bn_dir/$bn_fields");
	if ($ret == -1) {
		msgForm (str_replace("{SITE}", $site, str_replace("{DATABASE}", $dbname, ERROR_DB_EXISTS)), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret == -3) {
		msgForm (str_replace("{DATABASE}", $dbname, ERROR_DB_ACCESS), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret < 0) {
		msgForm (str_replace("{SITE}", $site, ERROR_CREATE_SITE), "setup.$ext", 'back');
		die ('</body></html>');
	}

# Create site users table
# -----------------------
	if (!is_file ("$tmpl_dir/admin/user_fields.$ext")) {
		$db->deleteTable ("$site");
		msgForm ("error: could not include file: '$tmpl_dir/admin/user_fields.$ext'", "setup.$ext", 'back');
		die ('</body></html>');
	}

	include "$tmpl_dir/admin/user_fields.$ext";
	if (!is_array($user_var)) {
		$db->deleteTable ("$site");
		msgForm ("error: file '$tmpl_dir/admin/user_fields.$ext' could not be open or has an invalid format", "setup.$ext", 'back');
		die ('</body></html>');
	}

	$field_descr = array();
	foreach($user_var as $var) {
		$field_descr[$var] = $user_var_size[$var];
	}
	$ret = $db->createTable ("${site}_users", $field_descr, 'userid');
	if ($ret == -1) {
		$db->deleteTable ("$site");
		msgForm (str_replace("{TABLE}", "${site}_users", str_replace("{DATABASE}", $dbname, ERROR_TABLE_EXISTS)), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret == -3) {
		$db->deleteTable ("$site");
		msgForm (str_replace("{DATABASE}", $dbname, ERROR_DB_ACCESS), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret < 0) {
		$db->deleteTable ("$site");
		msgForm (str_replace("{SITE}", $site, ERROR_CREATE_SITE), "setup.$ext", 'back');
		die ('</body></html>');
	}

# Create user-forum table
# -----------------------
	if (!is_file ("$tmpl_dir/admin/userforum_fields.$ext")) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		msgForm ("error: could not include file: '$tmpl_dir/admin/userforum_fields.$ext'", "setup.$ext", 'back');
		die ('</body></html>');
	}

	include "$tmpl_dir/admin/userforum_fields.$ext";
	if (!is_array($bn_var)) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		msgForm ("error: file '$tmpl_dir/admin/userforum_fields.$ext' could not be open or has an invalid format", "setup.$ext", 'back');
		die ('</body></html>');
	}

	$field_descr = array();
	foreach($bn_var as $var) {
		$field_descr[$var] = $bn_var_size[$var];
	}

	$ret = $db->CreateTable ("${site}_userforum", $field_descr, 'userid,bn_name');
	if ($ret == -1) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		msgForm (str_replace("{TABLE}", "${site}_userforum", str_replace("{DATABASE}", $dbname, ERROR_TABLE_EXISTS)), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret == -3) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		msgForm (str_replace("{DATABASE}", $dbname, ERROR_DB_ACCESS), "setup.$ext", 'back');
		die ('</body></html>');
	} elseif ($ret < 0) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		msgForm (str_replace("{SITE}", $site, ERROR_CREATE_SITE), "setup.$ext", 'back');
		die ('</body></html>');
	}

	$now = time();

# insert admin user in users table
# --------------------------------
	$user = array();

	$user["unixdate"] = $now;
	$user["userid"] = "admin";
	$user["password"] = md5($passwd1);
	$user["username"] = $admin_name;
	$user["useraddress"] = $admin_address;
	$user["userpriv"] = "root";
	$user["state"] = "1";

	$ret = $db->insertUser ($site, $user);
	if ($ret < 0) {
		$db->deleteTable ("$site");
		$db->deleteTable ("${site}_users");
		$db->deleteTable ("${site}_userforum");
		msgForm (str_replace("{USER}", 'admin', str_replace("{TABLE}", "${site}_users", ERROR_CREATE_USER)), "setup.$ext", 'back');
		die ('</body></html>');
	}

	$conf = new Config;
	$ret=$conf->open("$site_cfgfile");
	if (!$ret) {
		msgForm (sprintf(ERROR_CREATE_CONFIG_FILE, $site_cfgfile), "setup.$ext", 'back');
		die ('</body></html>');
	}
	$conf->writeConfig();
	$conf->close ();

# Display success message, redirect to create_site.php
# -----------------------------------------------------
	unset ($_POST);
	if ($mode=="advanced") {
		msgForm (LABEL_SETUP_DONE, "create_site.$ext?loginform=1&loginuser=admin&loginpassword=$passwd1&mode=advanced", '', '', 'post');
	} else {
		msgForm (LABEL_SETUP_DONE, "create_site.$ext?loginform=1&loginuser=admin&loginpassword=$passwd1&mode=setup", '', '', 'post');
	}
	echo '</body></html>';
	exit;

} // End do_setup


	if ($mode=="advanced") {
		$newmode_url = "<a href=\"setup.$ext?mode=basic\" onClick=\"document.setupform.mode.value='basic';document.setupform.submit();return false;\">" . LABEL_BASIC ."</a> &nbsp; ".  LABEL_ADVANCED;
	} else {
		$newmode_url = LABEL_BASIC . " &nbsp; <a href=\"setup.$ext?mode=advanced\" onClick=\"document.setupform.mode.value='advanced';document.setupform.submit();return false;\">" . LABEL_ADVANCED ."</a>";
	}

# Initialize defaults then display form
# -------------------------------------
	if (!isset($bn_access))	$bn_access="mysql";
	if (!isset($dbname))	$dbname="agora";
	if (!isset($dbhost))	$dbhost="";
	if (!isset($dbport))	$dbport="";
	if (!isset($dbuser))	$dbuser="";
	if (!isset($dbadmuser))	$dbadmuser="";
	if (!isset($bn_search_engine)) $bn_search_engine="none";
	if (!isset ($admin_name))	$admin_name = "System Administrator";
	if (!isset ($admin_address)) {
		$admin_address = isset($SERVER_ADMIN) ? $SERVER_ADMIN : "";
	}
?>

<form id="setupform" action="<?php echo "setup.$ext"?>" method="post">
 <input type="hidden" name="mode" value="<?php echo $mode?>">
 <input type="hidden" name="lang" value="<?php echo $lang?>">
 <center>
 <br /><br />
<?php
	$help_url = (file_exists("doc/INSTALL_$lang.txt")) ? "doc/INSTALL_$lang.txt" : "doc/INSTALL.txt";
	table_header('<big>'. LABEL_SETUP_AGORA . ' v' . wa_version(1). "</big>  <a href=\"$help_url\" target=\"_blank\" onClick=\"OpenWindow('$help_url','help',720,560); return false;\"><img src=\"images/icons/help.gif\" alt=\"help\" width=\"22\" height=\"22\" border=\"0\" align=\"middle\"></a>", '600');
?>

<br />
  <fieldset><legend><b><?php echo CAPTION_DB_PARAMETERS ?></b></legend><br />
   <table border="0" cellspacing="2" cellpadding="2" width="90%">
    <tr>
     <td valign="middle" class="label"><strong><?php echo LABEL_DB_TYPE ?> (*)</strong> </td>
     <td><?php listBox("bn_access", $databases, $bn_access);?></td>
	</tr>

    <tr>
     <td valign="middle" class="label"><?php echo LABEL_DB_SERVER_NAME?></td>
     <td><input type="text" name="dbhost" value="<?php echo $dbhost?>" size="30"></td>
	</tr>

<?php if ($mode=='advanced') { ?>
	<tr>
     <td class="label"><?php echo LABEL_DB_SERVER_PORT ?></td>
     <td><input type="text" name="dbport" value="<?php echo $dbport?>" size="30"></td>
    </tr>
<?php  } ?>

	<tr>
     <td class="label"><strong><?php echo LABEL_DB_NAME ?> (*)</strong> </td>
     <td><input type="text" name="dbname" size="30" value="<?php echo $dbname?>"></td>
    </tr>

    <tr>
     <td valign="middle" class="label"><strong><?php echo LABEL_DB_USER ?> (*)</strong></td>
     <td><input type="text" name="dbuser" value="<?php echo $dbuser?>" size="30"></td>
	</tr>

	<tr>
     <td class="label"><?php echo LABEL_DB_PASSWORD ?></td>
     <td><input type="password" name="dbpassword" size="30"></td>
    </tr>

<?php if ($mode=='advanced') { ?>
    <tr>
     <td valign="middle" class="label"><?php echo LABEL_DB_ADMIN_USER ?></td>
     <td><input type="text" name="dbadmuser" value="<?php echo $dbadmuser?>" size="30"></td>
	</tr>

	<tr>
     <td valign="middle" class="label"><?php echo LABEL_DB_ADMIN_PASSWORD ?></td>
     <td><input type="password" name="dbadmpassword" size="30"></td>
    </TR>
<?php  } ?>

   </table>
	</fieldset>
<p>
<?php if ($mode=='advanced') { ?>
     <br /><FIELDSET><LEGEND><B><?php echo CAPTION_DEFAULT_PARAMETERS ?></B></LEGEND>
  <table border="0" cellpadding="2" width="100%">
    <tr>
     <td width="50%" align="right" class="label"><?php echo LABEL_FORUM_DIRECTORY?></td>
     <td><input type="text" name="bn_dir_forums" size="30" value="<?php echo $bn_dir_forums?>"></td>
    </tr>

    <tr>
     <td width="50%" align="right" class="label"><?php echo LABEL_SEARCH_ENGINE?></td>
     <td>
      <?php listBox ("bn_search_engine", $search_engines, $bn_search_engine);?>
     </td>
    </tr>

   </table>
	</fieldset>

<?php  } ?>
    <p><fieldset><legend><b><?php echo CAPTION_ADMIN_INFO ?></b></legend>
   <table border="0" cellspacing="5" cellpadding="2" width="100%">
    <tr>
     <td class="label"><?php echo LABEL_USERNAME?></td>
     <td><b>admin</b></td>
    </tr>
    <tr>
     <td class="label"><strong><?php echo LABEL_ADMIN_NAME?> (*)</strong></td>
     <td><input type="text" name="admin_name" size="30" value="<?php echo $admin_name?>"></td>
    </tr>
    <tr>
     <td class="label"><strong><?php echo LABEL_ADMIN_ADDRESS?> (*)</strong></td>
     <td><input type="text" name="admin_address" value="<?php echo $admin_address ?>" size="30"></td>
    </tr>
    <tr>
     <td class="label"><strong><?php echo LABEL_ADMIN_PASSWORD1?> (*)</strong></td>
     <td><input type="password" name="passwd1" size="30" maxlength="32"></td>
    </tr>
    <tr>
     <td class="label"><strong><?php echo LABEL_ADMIN_PASSWORD2?> (*)</strong></td>
     <td><input type="password" name="passwd2" size="30" maxlength="32"></td>
    </tr>
   </table>
	</fieldset>
   <table width="100%">
    <tr><td width="70%"> (*) <strong><?php echo LABEL_REQUIRED_FIELD?></strong> </td><td align=right width="70%"><?php submitButton('do_setup', BUTTON_INSTALL.' &raquo; ') ?></td></tr>
    <tr><td colspan="2"><span style="font-size: x-small"><?php echo LABEL_SITECONF . " : $newmode_url"; ?></span></td></tr>
   </table>
<?php
	table_footer();
	br();
?>
</center>

</form>
</body>
</html>
