<?php

require_once dirname(__FILE__).'/lib/Config.php';

// Pre anything health check
$dirpaths = explode(Config::PathSeparator(), ini_get('include_path'));

$mdb = false;
foreach ($dirpaths as $path)
{
	if (file_exists("$path/MDB.php"))
	{
		$mdb = true;
	}
}

require_once dirname(__FILE__).'/include/i18n.php';

if (!$mdb)
{
?>
<html>
<head>
<title><?php __("Problem with IRM Installation") ?></title>
</head>
<body>
<h1><?php __("Error: MDB not installed or not in the include path") ?></h1>
<p>
<?php __("I failed to find the MDB package installed in any location in your
include path.  This may mean one of two things:") ?>

<ul>
<li><?php __("You haven't got MDB installed; or") ?>
<li><?php __("Your include path does not have the location of your MDB installation.") ?>
</ul>

<p>
<?php __("To remedy the former problem, please run the following command as an
administrator or root user:") ?>

<pre>
pear install -o MDB
</pre>

<p>
<?php __("(You may have to specify a path to the <tt>pear</tt> command).")?>
<?php __("If you do
not have a <tt>pear</tt> command, you should install the basic PEAR system
as packaged by your PHP or Linux distribution.  PEAR is the <b>PHP Extension
and Application Repository</b>, and provides a set of basic services for the
installation of PHP libraries such as MDB.") ?>

<p>
<?php __("If you are sure you have MDB installed, check your include path.
The include path I have is:"); ?>

<pre>
<?php echo ini_get('include_path'); ?>
</pre>

<p>
<?php __("Different paths will be separated with colons, or semicolons on windows).") ?>

<p>
<?php __("Please check that there is a file <tt>MDB.php</tt> in one of the
directories listed above.  If your <tt>MDB.php</tt> file is not in any of
the above locations, or <i>no</i> include path is shown above, you will need
to configure one in your system's <tt>php.ini</tt> file. Unfortunately, the
location for this file varies between Operating Systems and distributions,
so you may have to consult your system documentation or use a file searching
command to find it.") ?>

<p>
<?php __("Once you have found your <tt>php.ini</tt> file, you will need to edit it
using a text editor and modify the <tt>include_path</tt> parameter (search
for it in the <tt>php.ini</tt> file) to include the necessary paths.") ?>

<p>
<?php __("If you have verified that MDB.php exists in a directory specified in
your include_path but you are still seeing this error message, please send
an e-mail to <tt>irm-discuss@lists.sf.net</tt> with relevant information
such as OS and versions of relevant software, and we'll try to help you out.") ?>

</body>
</html>
<?php
}

require_once 'include/irm.inc';

error_reporting(E_ALL);
require_once 'lib/Config.php';
require_once 'lib/Databases.php';

function health_error($msg)
{
	return sprintf("<b>%s</b> %s<br>\n", _("ERROR:"), $msg);
}

if (@$_REQUEST['submit'] == _('Health Check'))
{
	$err = false;
	
	$RUNMSG = '';
	if (!function_exists('mysql_connect'))
	{
		$RUNMSG .= health_error(_("You do not appear to have the MySQL module installed."));
		$err = true;
	}
	
	if (@$tricksy_hiddens !== 'Precioussss')
	{
		$RUNMSG .= health_error(_("GPC variables not being registered globally."));
		$err = true;
	}

	if ((basename(@$_SERVER['SCRIPT_FILENAME']) != 'admin.php') && (basename(@$_SERVER['PATH_TRANSLATED']) != 'admin.php'))
	{
		$RUNMSG .= health_error(_("Your webserver isn't providing SCRIPT_FILENAME or PATH_TRANSLATED.  Please report a bug giving your OS and Webserver information."));
		$err = true;
	}

	if (!preg_match('/(\.[:;])|([:;]\.)/', ini_get('include_path')))
	{
		$RUNMSG .= health_error(_("The current directory ('.') does not appear to be in your include_path."));
		$err = true;
	}

	$verbits = explode('.', PHP_VERSION);
	if (($verbits[0] < 4) || ($verbits[0] == 4 && $verbits[1] < 1))
	{
		$RUNMSG .= health_error(_("IRM requires a minimum PHP version of 4.1.0."));
		$err = true;
	}
	
	if ($verbits[0] > 4)
	{
		$RUNMSG .= sprintf("<b>%s</b> %s<br>\n", _("WARNING"), _("IRM has not been properly tested with PHP 5.  Please report success and failure to irm-devel@lists.sf.net."));
		$err = true;
	}

	if (!file_exists(ini_get('session.save_path')))
	{
		$RUNMSG .= health_error(_("Your configured session save path is invalid!"));
		$err = true;
	}

	if ($err)
	{
		$RUNMSG .= _("There were problems detected.")."<br>\n";
	}
	else
	{
		$RUNMSG .= _("Your server appears healthy.  Enjoy IRM!")."<br>\n";
	}
}

if (@$_REQUEST['submit'] == 'Install')
{
	$cfg = Config::ReadConfig('database');
	$dbname = $cfg[$_REQUEST['init_db']]['name'];
	
	$DB = MDB::Connect($cfg[$_REQUEST['init_db']]['DSN']);
	if (MDB::isError($DB))
	{
		trigger_error($DB->getMessage()."\n".$DB->getUserInfo(), E_USER_ERROR);
	}
	$DB->setErrorHandling(PEAR_ERROR_RETURN);
	
	require_once 'database/install.php';
	
	foreach ($INSTALL as $q)
	{
		$err = $DB->query($q);
		if (MDB::isError($err))
		{
			trigger_error(_("Installation Query Failed: ") . $err->getMessage()."\n".$err->getUserInfo(), E_USER_ERROR);
		}
	}

	$DB->disconnect();
	unset($DB);

	$RUNMSG = sprintf("The database '%s' has been initialised.", $dbname);
}

if(@$_REQUEST['submit'] == "Upgrade")
{
	$cfg = Config::ReadConfig('database');
	$dbname = $cfg[$_REQUEST['upgrade_db']]['name'];
	
	$DB = MDB::Connect($cfg[$_REQUEST['upgrade_db']]['DSN']);
	if (MDB::isError($DB))
	{
		trigger_error(_("Database connection failed: ").$DB->getMessage()."\n".$DB->getUserInfo(), E_USER_ERROR);
	}

	require_once 'database/upgrades.php';

	$DB->setErrorHandling(PEAR_ERROR_RETURN);
	// 1.5.2+
	$curver = $DB->getOne("SELECT value FROM config WHERE variable='dbver'");
	if (MDB::isError($curver))
	{
		// Covers most versions
		$curver = $DB->getOne("SELECT version FROM config");
		if (MDB::isError($curver) && $curver->getCode() == MDB_ERROR_NOSUCHTABLE)
		{
			// Pre 1.3.1
			$curver = $DB->getOne("SELECT number FROM version");
		}
	}

	if (MDB::isError($curver))
	{
		echo $curver->getMessage()."\n".$curver->getUserInfo()."\n";
		die (_("Failed to obtain version number.  This may not be an IRM database, or your version of IRM may be very, very old.  Upgrades from versions of IRM prior to 1.3.0 are not supported.")."<br>\n");
	}
	
	$bits = explode('.', $curver);
	if ($bits[0] < 1 || ($bits[0] == 1 && $bits[1] < 3))
	{
		die(_("Sorry, your IRM database is pre-1.3.0.  Upgrades from versions of IRM prior to 1.3.0 are not supported, due to massive and catastrophic changes to the database format.")."<br>\n");
	}

	$upgrading = false;
	$RUNMSG = '';
	foreach ($UPGRADES as $ver => $queries)
	{
		if ($ver == $curver)
		{
			$upgrading = true;
		}
		
		if ($upgrading)
		{
			$RUNMSG .= sprintf(_("Running upgrade for %s"), $ver)."<br>\n";
			foreach ($queries as $q)
			{
				$err = $DB->query($q);
				if (MDB::isError($err))
				{
					trigger_error(sprintf(_("Upgrade query failed for %s: %s"), $ver, $err->getMessage() . "\n" . $err->getUserInfo()), E_USER_ERROR);
				}
			}
		}
	}
	

	$DB->disconnect();
	unset($DB);

	$RUNMSG .= sprintf(_("The database '%s' has been upgraded to the current system version."), $dbname);
}
	
?>
<HTML>
<HEAD>
<TITLE> <?php printf(_("Setup IRM version %s"), Config::Version()) ?></TITLE>
  <style type="text/css">
  //<!-- 
  body 
  {  
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
    background-color: white;
  }

  th   
  {  
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt; 
    font-weight: bold;
    background-color: #D3DCE3;
  }

  td
  {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
  }
 
  form
  {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
  }

  h1
  {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 16pt;
    font-weight: bold;
  }

  A:link
  {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
    text-decoration: none;
    color: blue;
  }
  A:visited
  {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
    text-decoration: none;
    color: blue;
  }
  A:hover
  {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10pt;
    text-decoration: underline;
    color: red;
  }

  A:link.nav
  {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    color: #000000;
  }

  A:visited.nav
  {
    font-family: Verdana, Arial, Helvetica, sans-serif;
     color: #000000;
  }

  A:hover.nav
  {
    font-family: Verdana, Arial, Helvetica, sans-serif;
     color: red;
  }

  .nav
  {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    color: #000000;
  }

  //-->
  </style>
</head>
<BODY>
  <img src=irm-jr1.jpg>
  <BR>
<?php
	if(@$RUNMSG)
	{
		print "<BR>
		$RUNMSG
		<BR>
		";
	}

?>

  <hr>
  <CENTER><h2><?php __("Health Check") ?></h2></CENTER>
  <p>
  <?php __("We provide a free \"health check\" for your web server to see if some common
  problems exist.  If there are errors, you may have problems running IRM.") ?>

  <form method="POST" ACTION="admin.php">
    <input type="submit" name="submit" value="<?php __("Health Check") ?>">
    <input type="hidden" name="tricksy_hiddens" value="Precioussss">
  </form>
  
<?php
	if (Config::onWindows())
	{
		echo "<p>";
		__("I have detected that you are running on some form of Windows system.");
	}
	else
	{
		echo "<p>";
		__("I have detected that you are running on a Unix-liks system (Linux, Mac OS X, etc).");
	}
?>
<p><?php __("If this autodetection is not correct, we have a serious problem.  Please report a bug."); ?>

<?php
	$dblist = Databases::Uninitialised();
	
	if ($dblist)
	{
	?>
		<hr>
		<CENTER><H2><?php __("New Install") ?></H2></CENTER>
		<form method="POST" action="admin.php">
		<p>
		<?php __("Select a database to initialise.") ?>
		<p>
		<b><?php __("Warning:")?></b> <?php __("The database you initialise will be totally destroyed.") ?>
		<select name="init_db">
		<?php
		
		$dblist = Databases::Uninitialised();

		foreach ($dblist as $f => $v)
		{
			echo "<option value=\"$f\">$v</option>\n";
		}
		?>
		</select>
		<input type="submit" name="submit" value="<?php __("Install") ?>">
		</form>
	<?php
	}
	?>
		<hr>
		<CENTER><H2><?php __("Upgrade") ?></H2></CENTER>
		<form method="POST" action="admin.php">
		<?php __("Please select a database to upgrade.  If the database
			 is up to date,	no changes will be applied.") ?>
		<SELECT NAME="upgrade_db">
		<?php
		
		$dblist = Databases::All();

		foreach ($dblist as $f => $v)
		{
			echo "<option value=\"$f\">$v</option>\n";
		}
		?>
		</SELECT>
		<input type="submit" name="submit" value="<?php __("Upgrade") ?>">
		</form>

<hr noshade>
<br>
</font>
<i>
	<?php printf(_("IRM Version %s"), '<b>'.Config::Version().'</b>') ?>
</i>
<a href="http://irm.schoenefeld.org/"><?php __("IRM Website") ?></a>
<br>IRM is protected by the 
		<a href="<?php echo Config::AbsLoc('docs/COPYING'); ?>">GNU GPL License</a>.
		&copy; 1999,2003 <a href="<?php echo Config::AbsLoc('docs/AUTHORS'); ?>">Yann Ramin, Keith Schoenefeld, and others</a>

<a href="mailto:atrus@atrustrivalie.org">atrus@atrustrivalie.org</a>.<br>
</body>
</html>
