<?php

/*
** SellaNMS
** $Id: startup.php,v 1.12 2005/03/31 18:57:12 sella Exp $
** Copyright (c) 2001 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

function initSellaNMS() {
	/* Handles normal setup for all SellaNMS pages. */
	set_magic_quotes_runtime(0);
	startSession();
	disableCache();
	/* Load prefs into session variable. */
	registerUserPrefs();
}

function dbConnect() {
	global $config;

	if ($config['databasePersistent']) {
		$con = mysql_pconnect($config['databaseServer'], $config['databaseUsername'], $config['databasePassword']);
	} else {
		$con = mysql_connect($config['databaseServer'], $config['databaseUsername'], $config['databasePassword']);
	}

	if ($con == false) {
		die("Failed to connect to server " . $config['databaseServer'] . " with username " . $config['databaseUsername'] . ". Verify configuration.");
	}

	if (mysql_select_db($config['databaseName'], $con) == false) {
		die("Failed to select database " . $config['databaseName'] . " on server " . $config['databaseServer'] . ". Verify configuration.");
	}

	return $con;
}

function processConfig($data) {
	global $config;

	if ($config['warn']) {
		/* Enable error reporting (All but notice). */
		error_reporting(E_ALL ^ E_NOTICE);
	}

	if ($config['debug']) {
		/* Enable heavy error reporting. Developer only. */
		error_reporting(E_ALL);
		printf(">Debug: processConfig()<BR>\n");
	}

	/* Put the config into a known state. */
	normalizeConfig();

	/* Swap in requested config set if needed. */
	processConfigSet($data['config']);

	/* Load Language */
	$errors = loadLanguage();

	/* Verify config */
	if (!$errors)
		$errors = verifyConfig();

	/* Handle Errors */
	if ($errors) {
		printf("<B>%s %s</B><P>", $config['program'], $config['version']);
		printf("<B>Error: Configuration error(s) in config.php. Details below:<BR>\n<BR>\n");
		reset($errors);
		while (list(, $error) = each($errors)) {
			printf("&nbsp;&nbsp;%s<BR>\n", $error);
		}
		printf("</B><BR>\n");
		return false;
	}

	return true;
}

function startSession() {
//	session_cache_limiter('public'); /* Not sure this is needed. */
	/* Must be called prior to accessing superglobal _SESSION */
	session_start();
}

function disableCache() {
	/* Disable Caching (as best we can). This helps with proxies and some browsers. */
	header("Expires: Thu, 1 Jan 1970 01:01:01 GMT"); // Date in the past
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
	header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
	header("Cache-Control: post-check=0, pre-check=0", false);
//	header("Cache-control: private"); // Makes IE6 happy for downloads.
	header("Pragma: no-cache"); // HTTP/1.0
}

function registerUserPrefs($con = false) {
	global $config;

	/* Are prefs already loaded into the session variable? */
	if (isset($_SESSION['gui_user_prefs_init']) && $_SESSION['gui_user_prefs_init'] == true) {
		return;
	}

	if (!$con) {
		$disconnect = $config['databasePersistent'] ? true : false;
		$con = dbConnect();
	}

	$_SESSION['user'] = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : 'default';

	/* Handle user entry. */
	mysql_query('LOCK TABLE gui_user WRITE', $con);
	$sql = sprintf("SELECT gui_user.id AS id FROM gui_user WHERE name = '%s' LIMIT 1", $_SESSION['user']);
	$result = mysql_query($sql, $con);
	if (mysql_num_rows($result) < 1) {
		/* Insert an entry for this user. */
		$sql = sprintf("INSERT INTO gui_user (name) VALUES ('%s')", $_SESSION['user']);
		$result = mysql_query($sql, $con);
		$_SESSION['user_id'] = mysql_insert_id();
	} else {
		/* Set our user id. */
		list($_SESSION['user_id']) = mysql_fetch_row($result);
	}
	mysql_query('UNLOCK TABLE', $con);

	$sql = sprintf("SELECT var, val FROM gui_user_prefs WHERE user = %d", $_SESSION['user_id']);
	$result = mysql_query($sql, $con);
	if ($result != false  && mysql_num_rows($result) > 0) {
		/* Store prefs in session variable. */
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$_SESSION[$row['var']] = $row['val'];
		}
	}

	/* Close the temporary connection. */
	if ($disconnect) {
		mysql_close($con);
	}

	/* Set the initialization flag. */
	$_SESSION['gui_user_prefs_init'] = true;
}

function processConfigSet($set) {
	global $config, $confSet;
	$debug = $config['debug'];
	$installBase = $config['installBase'];
	$sep = $config['fileSeparator'];

	if (strlen($set) < 1) {
		if ($debug)
			printf("->Debug: processConfigSet() - Using default Config Set<BR>\n");
		return;
	} else if ($debug) {
		printf("->Debug: processConfigSet() - Requested Config Set: '%s'<BR>\n", $set);
	}

	if (isset($confSet[$set])) {
		$confFiles = array('config.php');
		while(list(, $file) = each($confFiles)) {
			$file = $installBase . $sep . $confSet[$set] . $sep . $file;
			if (is_file($file)) {
				include($file);
				normalizeConfig(); /* We may have altered things, so normalize again. */
			} else if ($debug) {
				printf("->Debug: processConfigSet() - File '%s' not found. <B>[Skip]</B><BR>\n", $file);
			}
		}
	} else if ($debug) {
		printf("->Debug: processConfigSet() - Config Set '%s' isn't setup. <B>[Skip]</B><BR>\n", $set);
	}
}

function loadLanguage() {
	global $config, $lang;
	$debug = $config['debug'];
	$langInclude = $config['installBase'] . $config['fileSeparator'] . 'libs' . $config['fileSeparator'] . 'language' . $config['fileSeparator'] . $config['language'] . '.php';

	if ($debug)
		printf('->Debug: loadLanguage() - Checking language pack \'%s\' stored in \'%s\'. ', $config['language'], $langInclude);

	/* Verify we can read the language pack. */
	if (is_readable($langInclude)) {
		if ($debug)
			printf(" <B>[Readable]</B><BR>\n");
		include($langInclude);
		if ($lang['charset']) { //This will fail when debug is enabled, since we have already written to stdout.
			@header('Content-Type: text/html; charset=' . $lang['charset']);
		}
	} else {
		if ($debug)
			printf(" <B>[Not Readable]</B><BR>\n");
		$error = array(sprintf("Unable to access language '%s' (%s).", $config['language'], $langInclude));
		if (function_exists('getcwd')) {
			if (strcmp(getcwd(), $config['installBase'])) {
				$error[] = sprintf('Your $config[\'installBase\'] may be incorrect. It looks like it should be \'%s\'.', getcwd());
			}
		}
		return $error;
	}

	return false;
}

function normalizeConfig() {
	global $config;

	if ($config["debug"])
		printf("->Debug: normalizeConfig()<BR>\n");

	/* Change values as needed according to our rules. */
	$config['language'] = strtolower(trim($config['language']));
	$config['warn'] = ($config['debug']) ? true : $config['warn'];
	$config['verifyConfig'] = ($config['debug']) ? true : $config['verifyConfig'];

	/* Clean up trailing slashed. */
	$config['installBase'] = ereg_replace('(^.*)[/\\]$', '\\1', $config['installBase']);

	return true;
}

function verifyConfig() {
	global $config;

	$installBase = $config['installBase'];
	$verify = $config['verifyConfig'];

	if ($config['debug'])
		printf("->Debug: verifyConfig()<BR>\n");

	/* These checks are optional. */
	if ($verify) {
		$error = verifyPHPVersion(4,1,0);
		if (is_string($error))
			$errors[] = $error;
		if (!is_array($config['modules']))
			$errors[] = '$config[\'modules\'] is not set to an array type.';
		if (!is_string($installBase))
			$errors[] = '$config[\'installBase\'] is not set to a string type.';
		else if (!is_dir($installBase) || (is_link($installBase) && !is_dir(readlink($installBase))))
			$errors[] = '$config[\'installBase\'] is not set to a valid directory.';
	}

	/* Load and Verify modules is required. */
	$error = verifyModules($config['modules']);
	if (is_string($error))
		$errors[] = $error;

	if (!isset($errors))
		return false;
	return $errors;
}

function verifyModules($modules) {
	global $config;

	$installBase = $config['installBase'];
	$debug = $config['debug'];

	if ($config['debug'])
		printf("-->Debug: verifyModules()<BR>\n");

	reset($modules);
	while (list($x, $module) = each($modules)) {
		$modInclude = $installBase . $config['fileSeparator'] . 'modules' . $config['fileSeparator'] . $module . $config['fileSeparator'] . $module . '.php';
		/* Verify function isn't already available. */
		if (!class_exists($module)) {
			if ($debug)
				printf('-->Debug: verifyModules() - Checking module \'%s\' stored in \'%s\'. ', $module, $modInclude);
			/* Verify we can read the module. */
			if (is_readable($modInclude)) {
				if ($debug)
					printf(" <B>[Readable]</B><BR>\n");
				include($modInclude);
			} else {
				if ($debug)
					printf(" <B>[Not Readable]</B><BR>\n");
				return sprintf("Unable to access %s module '%s' (%s).<BR>\n", $modType, $module, $modInclude);
			}
			/* Verify that the module contains a function of the same name. */
			$mod = new $module();
			if (!method_exists($mod, 'doit')) {
				unset($mod);
				return sprintf("Module '%s' (%s) is not usable.<BR>\nThis module must contain the method 'doit'.<BR>\n", $module, $modInclude);
			} else {
				unset($mod);
				$loadedModules[$module] = true;
			}
		} else if ($loadedModules[$module] != true) {
			return sprintf("Error: The class '%s' was available before loading module '%s'.<BR>\n'%s' may be a built in PHP function or another module may have the same name. If this is the case, you will need to rename the module.<BR>\n", $module, $modInclude, $module);
		}
	}

	return true;
}

function getSpecificFormData() {
	/* The content of this function is specific to SellaNMS. */
	global $debug, $option;

	$data['debug'] = $debug;
	$data['option'] = $option;

	return $data;
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim600: fdm=marker
** vim: noet ts=3 sw=3
*/

?>
