<?php

/*
 * ***
 * You may not remove this header!
 *
 * phpUserLogin is made by Tanny 'Drakxter' Lund
 *
 * OxyScripts.com proudly presents phpUserLogin
 * Copyright (C) 2002 Drakxter
 *
 * This program 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. 
 * This program 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 this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/*
 * If you have problems then you can change these vars */
// On = TRUE / Off = FALSE
// Debug function: When on it prints useful info at the end of the login form that might help you find errors.
define ("PHPUSERLOGIN_SYSTEM_DEBUG", FALSE);
// Check Headers function: When on the script will check to see if the headers have already been sent before they should have been.
define ("PHPUSERLOGIN_SYSTEM_PATHMATCH", TRUE);
// Cookie Type: When on the script will use the cookie options when making the cookies. If turned off the cookies will not use the options (and will only work for the session), and should now work on almost all pcs.
define ("PHPUSERLOGIN_SYSTEM_COOKIES", TRUE);

/*
 * You DONT need to alter anything below this line
 * Its NOT inside this file you set the options for phpuserlogin
 * And just to make sure you understand this:
 * STAY AWAY
 * The last few people that edited stuff down here made the scirpt
 * always be in 'logged in mode' and make every one admins.*/

/*
 * Vars needed by script */
@define ("PHPUSERLOGIN_DOMAIN", $_SERVER['HTTP_HOST']); 
@define ("PHPUSERLOGIN_PAGE", 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
@define ("PHPUSERLOGIN_EMAIL", 'DONT-REPLY@'.PHPUSERLOGIN_DOMAIN);

/* Starting class */
class phpuserlogin {

	var $_systemDebug		= PHPUSERLOGIN_SYSTEM_DEBUG;
	var $_systemPathMatch	= PHPUSERLOGIN_SYSTEM_PATHMATCH;
	var $_systemCookiesAdv	= PHPUSERLOGIN_SYSTEM_COOKIES;

	var $loginstatus		= FALSE;
	var $adminstatus		= FALSE;
	var $userinfo			= array();

	var $_systemMySQL_Link	= NULL;
	var $_systemMySQL_Err	= NULL;
	var $_systemMySQL_QNum	= 0;
	var $_systemOutVar		= NULL;

	var $_systemRespons		= FALSE;
	var $_systemReOwner		= FALSE;
	var $_systemNewUser		= FALSE;

	var $_systemRunTime		= array('start' => 0, 'end' => 0);

	var $_systemVersion		= 'C1.4.0'; // Version number.
	var $_systemOptions		= array(
				/*
				 * Default _systemOptions
				 */
				'var_name'			=> 'phpuserlogin', // Is the word used a the name of the var's outside php (forms, urls) that have something to do with phpuserlogin2, must be changed for every new login object
				'page'				=> '', // Is the page where users may login, default is everywhere.
				'page_afterlogin'	=> '', // Is the url for the page the users should be sent to right after login (only after login), default is non = user is not sent to a new page.
				'hidden_key'		=> 0, // This is a hidden key, which is used in the cookies to make them secure, should be change every time you use the script.

				'mysql_table'		=> 'phpuserlogin_user', // Is the name of the table where users are stored.
				'mysql_serv'		=> 'localhost', // Is the address of the mysql server
				'mysql_user'		=> 'root', // Is the username on the mysql server
				'mysql_pass'		=> 'root.mysql.porta3', // Is the password for the mysql server
				'mysql_data'		=> 'phpuserlogin', // Is the name of the database on the mysql server.
				'mysql_pcon'		=> FALSE,
				'mysql_fields'		=> FALSE, // Special option, used to manage extra tables.
				'mysql_id'			=> 'id', // The name of the id field in the user table.

				'cookie_life'		=> '', // How long cookies will live on the client pc, in secs.
				'cookie_path'		=> '/', // The path on the server where the cookie will work, default is whole server.
				'cookie_domain'		=> PHPUSERLOGIN_DOMAIN, // The domain name of the server, default is the server running the script.

				'email_reply'		=> PHPUSERLOGIN_EMAIL, // The reply address used on mails sent by script, default is dontreply@SERVER_DOMAIN_NAME

				'admins'			=> '', // The usernames of the admins, split each name with a ,

				'lostpass'			=> TRUE, // Is the lost password feature on or off

				'register'			=> FALSE, // Is the register function on or off.
				'register_page'		=> '', // This is the page where the reg form is being printed!

				'temp_folder'		=> '', // The direct path to the folder where the templates files are.
				'temp_prefix'		=> 'phpuserlogin', // This is the prefix that is in front of the register templates.

				'anti_spam'			=> 6, // This is the number of times a user may use the forms (must have entered something in all fields), before being slowed down for 5 mins. Enter 0 and this function will be ignored.

				'logFile'			=> '', // This is the direct path (eg /home/path_to/logfile.log) to the file where log entrys will be written to, default is nothing, which means that the scritp will not log anything.

				'users_online'		=> FALSE // Should the script track user active or not. 
				);

	var $_systemText		= array(
				/*
				 * Default English
				 */
				'LOGIN_MISSING_USER'		=> 'You need to enter a username!',
				'LOGIN_MISSING_PASS'		=> 'You need to enter a password!',
				'LOGIN_TO_MANY_USERS'		=> 'To many users with the same username was found. - Contact the webmaster!',
				'LOGIN_WRONG_USER'			=> 'You have entered a wrong username!',
				'LOGIN_WRONG_PASS'			=> 'You have entered a wrong password!',
				'COOKIES_FAKE'				=> 'The cookies are not valid!',
				'COOKIES_NO_USER'			=> 'The user you have logged in with does not exist anymore!',
				'COOKIES_TO_MANY_USERS'		=> 'There is more then one user with the username you logged in with. - Contact the webmaster!',
				'COOKIES_LOGGED_IN'			=> 'You are logged in!',
				'LOST_MISSING_USER'			=> 'You need to enter a username!',
				'LOST_TO_MANY_USERS'		=> 'To many users with the same username was found. - Contact the webmaster!',
				'LOST_WRONG_USER'			=> 'No user with that username was found!',
				'LOST_TO_FAST'				=> 'This user have already requested a new password within the last day!',
				'LOST_NO_REQUEST'			=> 'This user have not requested a new password!',
				'LOST_WRONG_KEY'			=> 'The two keys did not match - No new password will be made!',
				'EMAIL_NONE'				=> 'No email address was found!',
				'EMAIL_NO_GO'				=> 'Could not send email. - Contact the webmaster!',
				'ERROR_MISSING_MSG'			=> 'Error - No script message found!',
				'MYSQL_NO_CON'				=> 'Could not connect to the MySQL server!',
				'MYSQL_NO_CON_P'			=> 'Could not connect (<i>Persistent</i>) to the MySQL server!',
				'MYSQL_NO_DATAB'			=> 'Could not select the database!',
				'MYSQL_QUERY_ERROR'			=> 'Error while running query on database!',
				'REG_MISSING_USER'			=> 'You need to enter an username!<br>Go back and try again.',
				'REG_MISSING_PASS'			=> 'You need to enter a password!<br>Go back and try again.',
				'REG_MISSING_EMAIL'			=> 'You need to enter an email!<br>Go back and try again.',
				'REG_WRONG_PASS'			=> 'The two passwords where not the same!<br>Go back and try again.',
				'REG_USER_E'				=> 'The username you have used is already in use!<br>Go back and try again with another username.',
				'REG_USER_MADE'				=> 'A user have been made.<br>You can now login!',
				'REG_USER_NOT_MADE'			=> 'Could not make user!<br>Please contact webmaster for help!',
				'REG_USER_MADE_ERROR'		=> 'A user have been made, but some of the info was lost while making the user.<br>Uusename, email and password was added into the database though, more data might also have been added but will not be listed here.<br>You can now login!',
				'SPAM'						=> 'You have used the forms to much within to little time<br>Please wait 5 min.!!<br>Why dont you go and grab yourself a drink while you wait.',
				'LOGOUT_FORCE'				=> 'You have been logged off!',
				'LOGOUT_USER'				=> 'You have logged off!',
				'LOGIN_USER'				=> 'You have logged in!',
				'EMAIL_SENT'				=> 'An email have been sent to you!',
				'DEACTIVATED'				=> 'This user have been deactivated!<br>Please contact webmaster for more info',
				'BEEN_DEACTIVATED'			=> 'This user have been deactivated',
				'regForm_1'					=> 'Enter an username:',
				'regForm_2'					=> 'Enter a password:',
				'regForm_3'					=> 'Retype the password:',
				'regForm_4'					=> 'Enter your e-mail:',
				'regForm_5'					=> 'Confirm',
				'regForm_6'					=> 'Please fill the form and press confirm',
				'regForm_7'					=> 'You may not make a new user while logged in!',
				'regForm_9'					=> 'Sorry, you may not register a new user at the moment<br>Please contact the webmaster for more help!',
				'regForm_10'				=> 'Reset',
				'Form_1'					=> 'Logout',
				'Form_2'					=> 'Your Username:',
				'Form_3'					=> '- Request -',
				'Form_4'					=> 'Back to login',
				'Form_5'					=> 'Username:',
				'Form_6'					=> 'Password:',
				'Form_7'					=> '- Login -',
				'Form_8'					=> 'Lost Password',
				'Form_9'					=> 'Login',
				'Form_10'					=> 'Admin',
				'After_login1'				=> 'If the page does not change, then click',
				'After_login2'				=> 'here!',
				'headers_sent'				=> 'phpUserLogin<br>Headers have already been sent: Stopping script.<br>This script must be run before any output have been sent to the browser.',
				'email_footer'				=> 'This mail was made and sent by phpUserLogin - http://phpuserlogin.oxyscripts.com/',
				'aC_1'						=> 'You may not use this page.<br>If the page does not change within 5 secs then please click',
				'aC_2'						=> 'here',
				'oul_1'						=> 'There have been',
				'oul_2'						=> 'user(s) online in the last 15 mins',
				'oul_3'						=> 'No users have been online the last 15 mins.',
				'oul_4'						=> 'Could not collect data about users from database'
				);

	var $_systemTemplates	= array(
				/*
				 * Default Templates
				 */
				'reg'		=> array(
								'top'				=> '<TABLE align="center">',
								'msg'				=> '<TR><TD align="center"><font size="2">{msg}</a></TD></TR><TR><TD align="center"><font size="2">--</a></TD></TR>',
								'form'				=> '<TR><TD align="center"><font size="2">{help}</a></TD></TR><TR><TD align="center"><table align="center"><form action="{form_page}" method="post"><tr><td align="right"><font size="2">{form_username}</font></td><td><input type="Text" name="{form_field_name_username}" size="10" MaxLength="20"></td></tr><tr><td align="right"><font size="2">{form_password}</font></td><td><input type="Password" name="{form_field_name_password}" size="10" MaxLength="20"></td></tr><tr><td align="right"><font size="2">{form_repassword}</font></td><td><input type="Password" name="{form_field_name_repassword}" size="10" MaxLength="20"></td></tr><tr><td align="right"><font size="2">{form_email}</font></td><td><input type="Text" name="{form_field_name_email}" size="10" MaxLength="100"></td></tr>{form_extra_fields}<tr><td align="center" colspan="2"><input type="hidden" name="{form_field_name_hidden}" value="1"><input type="submit" value="{form_submit}"> <input type="reset" value="{form_reset}"></td></tr></form></table></TD></TR>',
								'field_radio1'		=> '<tr><td align="Center" colspan="2"><font size="2">{field_text}</font><br><table>{field_more}</table></td></tr>',
								'field_radio2'		=> '<tr><td align="right"><font size="1">{field_text}</font></td><td><INPUT TYPE="radio" NAME="{field_name}" value="{field_value}" {field_checked}></td></tr>',
								'field_text'		=> '<tr><td align="right"><font size="2">{field_text}</font></td><td><input type="Text" name="{field_name}" size="10"></td></tr>',
								'field_textmax'		=> '<tr><td align="right"><font size="2">{field_text}</font></td><td><INPUT TYPE="text" NAME="{field_name}" size="10" MaxLength="{field_max}"></td></tr>',
								'field_textarea'	=> '<tr><td align="right"><font size="2">{field_text}</font></td><td><TEXTAREA NAME="{field_name}" ROWS="{field_rows}" COLS="{field_cols}"></TEXTAREA></td></tr>',
								'field_dropdown1'	=> '<tr><td align="right" colspan="2"><font size="2">{field_text}:</font><br><SELECT NAME="{field_name}">{field_more}</SELECT></td></tr>',
								'field_dropdown2'	=> '<OPTION value="{field_value}" {field_selected}>{field_text}</OPTION>',
								'field_pass'		=> '<tr><td align="right"><font size="2">{field_text}</font></td><td><INPUT TYPE="password" NAME="{field_name}" size="10" MaxLength="{field_max}"></td></tr>',
								'field_check'		=> '<tr><td align="right"><font size="2">{field_text}</font></td><td><INPUT TYPE="checkbox" NAME="{field_name}" value="{field_value}"></td></tr>',
								'bot'				=> '</TABLE>'
							),
				'login'		=> array(
								'top'				=> '<table align="center" cellspacing="0">',
								'msg'				=> '<tr><td align="center"><font size="1">{msg}</font></td></tr>',
								'logout'			=> '<tr><td align="center"><font size="2"><a href="{url}">{text}</a></font></td></tr>',
								'admin'				=> '<tr><td align="center"><font size="2"><a href="{url}" target="blank">{text}</a></font></td></tr>',
								'lost_pass'			=> '<tr><td align="center"><table cellspacing="0"><form action="{form_path}" method="post"><tr><td align="center"><font size="2">{form_text_username}</font></td></tr><tr><td align="center"><input type="Text" name="{form_name_username}" size="10" MaxLength="20"></td></tr><tr><td align="center"><input type="hidden" name="{form_name_hidden}" value="1"><input type="Submit" value="{form_value_submit}"></td></tr><tr><td align="center"><font size="2"><a href="{form_back_url}">{form_back_text}</a></font></td></tr></form></table></td></tr>',
								'login'				=> '<tr><td align="center"><table cellspacing="0"><form action="{form_path}" method="post"><tr><td align="right"><font size="2">{form_text_username}</font></td><td><input type="Text" name="{form_name_username}" size="10" MaxLength="20"></td></tr><tr><td align="right"><font size="2">{form_text_pass}</font></td><td><input type="Password" name="{form_name_pass}" size="10" MaxLength="20"></td></tr><tr><td align="center" colspan="2"><input type="hidden" name="{form_name_hidden}" value="1"><input type="Submit" value="{form_text_submit}"></td></tr>{lostpass_link}</form></table></td></tr>',
								'login_lost_link'	=> '<tr><td align="center" colspan="2"><font size="1"><a href="{url}">{text}</a></font></td></tr>',
								'login_link'		=> '<tr><td align="center"><font size="2"><a href="{url}">{text}</a></font></td></tr>',
								'bot'				=> '</table>'
							),
				'oul'		=> array(
								'top'				=> '<table align="center" cellspacing="0" width="100%">',								'msg'				=> '<tr><td align="center"><font size="1">{msg}</font></td></tr>',
								'list'				=> '<tr><td><font size="1"><i>{list}</i></font></td></tr>',
								'list_split'		=> ', ',
								'bot'				=> '</table>'
							)
				);

	var $_systemPowerBy		= ''; // This Text may not be removed or changed.

	/* Connect to MySQL database and puts a link in $_systemMySQL_Link */
	function connectMySQL() {

		if (!$this->_systemMySQL_Link) {
			if ($this->_systemOptions['mysql_pcon'] == FALSE) {
				if (!$link = @mysql_connect($this->_systemOptions['mysql_serv'], $this->_systemOptions['mysql_user'], $this->_systemOptions['mysql_pass'])) {
					$this->_systemRespons[$this->_systemReOwner]['mysql'] = 'phpUserLogin_MySQL_NO_CON';
					$this->_systemMySQL_Err[] = array('query'=>'','error'=>mysql_error(),'errno'=>mysql_errno());
					return FALSE;
				}
			} else { 
				if (!$link = @mysql_pconnect($this->_systemOptions['mysql_serv'], $this->_systemOptions['mysql_user'], 	$this->_systemOptions['mysql_pass'])) {
					$this->_systemRespons[$this->_systemReOwner]['mysql'] = 'phpUserLogin_MySQL_NO_CON_P';
					$this->_systemMySQL_Err[] = array('query'=>'','error'=>mysql_error(),'errno'=>mysql_errno());
					return FALSE;
				}
			}

			if (!@mysql_select_db($this->_systemOptions['mysql_data'], $link)) {
				$this->_systemRespons[$this->_systemReOwner]['mysql'] = 'phpUserLogin_MySQL_NO_DATAB';
				$this->_systemMySQL_Err[] = array('query'=>'','error'=>mysql_error(),'errno'=>mysql_errno());
				return FALSE;
			} else {
				$this->_systemMySQL_Link = $link;
				return TRUE;
			}
		} else {
			return TRUE;
		}

	}

	function runQuery($query) {

		if ($this->connectMySQL()) {
			$this->_systemMySQL_QNum++;
			if ($result = @mysql_query($query, $this->_systemMySQL_Link)) {
				if (ereg("^INSERT", $query)) {
					$id = @mysql_insert_id();
				} else {
					$id = -1;
				}

				if (ereg("^SELECT", $query)) {
					$num = @mysql_num_rows($result);
				} elseif (ereg("^(INSERT|UPDATE|DELETE)", $query)) {
					$num = @mysql_affected_rows();
				} else {
					$num = -1;
				}

				$data = @mysql_fetch_assoc($result);
				@mysql_data_seek($result, 0);
				return array('num'=>$num,'data'=>$data,'result'=>$result, 'id'=>$id);
			} else {
				$this->_systemRespons[$this->_systemReOwner]['mysql'] = 'phpUserLogin_MySQL_QUERY_ERROR';
				$this->_systemMySQL_Err[] = array('query'=>$query,'error'=>mysql_error(),'errno'=>mysql_errno());
				return FALSE;
			}
		} else {
			return FALSE;
		}

	}

	// Loggging function
	function runLog($log_entry) {

		if (!empty($log_entry) && !empty($this->_systemOptions['logFile'])) {

			// Opening Log File
			if (@$log_fp = fopen ($this->_systemOptions['logFile'], "a+b")) {

				// Writing to log file
				@fwrite($log_fp, gmdate("M-d-Y H:i:s").' | '.$_SERVER['REMOTE_ADDR'].' | '.$log_entry.'
');

				// Closing Log File
				@fclose($log_fp);

			}
			
		}

	}

	function findUser($user) {

		return $this->runQuery("SELECT * FROM ".$this->_systemOptions['mysql_table']." WHERE username = '".mysql_escape_string($user)."'");

	}

	function sendMail($email, $subject, $message) {

		if ($email == '' or $email == NULL) {
			$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_EMAIL_NONE';
			return FALSE;
		} else {
			if (mail($email, $subject, $message."\n\n".$this->_systemText['email_footer'], 'From: '.$this->_systemOptions['email_reply']."\r\n".'Reply-To: '.$this->_systemOptions['email_reply']."\r\n")) {
				return TRUE;
			} else {
				$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_EMAIL_NO_GO';
				return FALSE;
			}
		}

	}

	function stopCaching() {

		header("Expires: Sun 25 Jul 1997 05:00:00 GMT");				// Date in the past
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");	// always modified
		header("Cache-Control: no-cache, must-revalidate");				// HTTP/1.1
		header("Pragma: no-cache");										// HTTP/1.0

	}

	/* Set cookies and update time and date in table */
	function startSession($_username) {

		$username = $_username;
		$hash = md5($_username.$this->_systemOptions['hidden_key']);
		$status = 'ACTIVE';

		if ($this->_systemCookiesAdv == TRUE) {

			if (!empty($this->_systemOptions['cookie_life'])) {
				$lifetime = (time()+$this->_systemOptions['cookie_life']);
			} else {
				$lifetime = NULL;
			}

			@setcookie ($this->_systemOptions['var_name'].'[session][user]', $username, $lifetime, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain']);
			@setcookie ($this->_systemOptions['var_name'].'[session][hash]', $hash, $lifetime, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain']);
			@setcookie ($this->_systemOptions['var_name'].'[session][status]', $status, $lifetime, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain']);

		} else {

			@setcookie ($this->_systemOptions['var_name'].'[session][user]', $username);
			@setcookie ($this->_systemOptions['var_name'].'[session][hash]', $hash);
			@setcookie ($this->_systemOptions['var_name'].'[session][status]', $status);


		}

		if ($this->_systemOptions['users_online'] == TRUE) {

			$this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET last_active='".gmdate("YmdHis")."' WHERE username = '".$_username."' LIMIT 1");

		}

	}

	/* Delete cookies */
	function endSession() {

		if ($this->_systemCookiesAdv == TRUE) {
		
			@setcookie ($this->_systemOptions['var_name'].'[session][user]', '', 0, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain'] );
			@setcookie ($this->_systemOptions['var_name'].'[session][hash]', '', 0, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain'] );
			@setcookie ($this->_systemOptions['var_name'].'[session][status]', '', 0, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain'] );

		} else {

			@setcookie ($this->_systemOptions['var_name'].'[session][user]');
			@setcookie ($this->_systemOptions['var_name'].'[session][hash]');
			@setcookie ($this->_systemOptions['var_name'].'[session][status]');

		}
	
	}

	/* Spam stopper */
	function spamCount($check = FALSE) {

		if ($this->_systemCookiesAdv == TRUE AND $this->_systemDebug == FALSE AND $this->_systemOptions['anti_spam'] > 0) {

			if (!isset($this->_systemOutVar['spamCounter'])) {
				$this->_systemOutVar['spamCounter'] = 0;
			}

			if ($check == FALSE) {

				$lifetime = (mktime()+300);
				@setcookie ($this->_systemOptions['var_name'].'[spamCounter]', ($this->_systemOutVar['spamCounter']+1), $lifetime, $this->_systemOptions['cookie_path'], $this->_systemOptions['cookie_domain']);

			} else {

				if ($this->_systemOutVar['spamCounter'] < $this->_systemOptions['anti_spam']) {
					return TRUE;
				} else {
					$this->_systemRespons['spam'] = TRUE;
					return FALSE;
				}

			}

		} else {

			return TRUE;

		}

	}

	function phpuserlogin($new_systemOptions = FALSE) {

		/* Run time counter - Start */
		$this->_systemRunTime['start'] = microtime();

		/* If class is called with new options, then override the old ones */
		if ($new_systemOptions != FALSE && is_array($new_systemOptions)) { 
			foreach ($new_systemOptions as $key => $value) {
				if (isset($this->_systemOptions[$key])) { // Exclude non excisting Options
					$this->_systemOptions[$key] = $value;
				}
			}		
		}

		if (is_array($this->_systemOptions['mysql_fields'])) {
			$extra_tables = $this->_systemOptions['mysql_fields'];
			$extra_tables['_main']['table_name'] = $this->_systemOptions['mysql_table'];
			$main_table['_main'] = $extra_table['_main'];
			unset($extra_table['_main']);
			$this->_systemOptions['mysql_fields'] = array_merge($main_table,$extra_tables);
		} else {
			$this->_systemOptions['mysql_fields']['_main']['table_name'] = $this->_systemOptions['mysql_table'];
		}

		@$this->_systemOutVar = array_merge ($_COOKIE[$this->_systemOptions['var_name']], $_POST[$this->_systemOptions['var_name']], $_GET[$this->_systemOptions['var_name']]);

		/* If a user is already logged in */
		if (@$this->_systemOutVar['session']['status'] == 'ACTIVE') {

			$this->_systemReOwner = 'login';

			if (@md5($this->_systemOutVar['session']['user'].$this->_systemOptions['hidden_key']) == $this->_systemOutVar['session']['hash']) {

				if (@$result = $this->findUser($this->_systemOutVar['session']['user'])) {

					if ($result['num'] == 1) {
						// User did exist.

						// Checking user status
						if ($result['data']['user_status'] == 1) {
							if (isset($this->_systemOutVar['logout'])) {
								$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_USER';
								$this->endSession();
								$this->runLog('"'.$result['data']['username'].'" logs off.');
							} else {
								$this->stopCaching();
								$this->startSession($result['data']['username']);
								$this->userinfo = $result['data'];
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_COOKIES_LOGGED_IN';
								$this->loginstatus = TRUE;
								$this->runLog('"'.$result['data']['username'].'" passes check and remains logged in.');
							}
						} else {
							// This users have been deactivated.
							$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_USER_BEEN_DEACTIVATED';
							$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_FORCE';
							$this->endSession();
							$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is logged off by script. User have been deactivated!');
						}

					} elseif ($result['num'] > 1) {
						// To many users with same username
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_COOKIES_TO_MANY_USERS';
						$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_FORCE';
						$this->endSession();
						$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is logged off by script. To many users with the same username found!');
					} elseif ($result['num'] < 1) {
						// No users with that username
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_COOKIES_NO_USER';
						$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_FORCE';
						$this->endSession();
						$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is logged off by script. No users with that username found!');
					}

				} else {
					$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_FORCE';
					$this->endSession();
					$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is logged off by script. MySQL server problems!');
				}

			} else {
				$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_COOKIES_FAKE';
				$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGOUT_FORCE';
				$this->endSession();
				$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is logged off by script. Cookies where bad!');
			}

		/* If a user is not logged in, run all other code */
		} else {

			/* Check to see how many times the user have used a form, if to many times slow him/her down for 5 mins */
			if ($this->spamCount(TRUE)) {

				/* User tries to login */
				if (isset($this->_systemOutVar['L']['login']) && $this->matchPath('login')) {

					$this->_systemReOwner = 'login';

					/* Deletes old cookies, if any */
					$this->endSession();

					if ($this->_systemOutVar['L']['username'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOGIN_MISSING_USER';
					} elseif ($this->_systemOutVar['L']['password'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOGIN_MISSING_PASS';
					} else {

						// Anti Spam Counter
						$this->spamCount();

						if ($result = $this->findUser($this->_systemOutVar['L']['username'])) {
							if ($result['num'] == 1) {

								// User did exist.
								if ($result['data']['password'] == md5($this->_systemOutVar['L']['password'])) {
									// Checking user status
									if ($result['data']['user_status'] == 1) {
										$this->stopCaching();
										$this->startSession($result['data']['username']);
										if (!empty($this->_systemOptions['page_afterlogin'])) {
											// If there has been set a page to take the user to after login, then run this.
											$this->runLog('"'.$result['data']['username'].'" has logged in and is being sent to another page.');
											header('Refresh: 2; url='.$this->_systemOptions['page_afterlogin']);
											echo'<font size="+1"><b>'.$this->_systemText['LOGIN_USER'].'</b></font><p><font size="-2">'.$this->_systemText['After_login1'].' <a href="'.$this->_systemOptions['page_afterlogin'].'">'.$this->_systemText['After_login2'].'</a></font>';
											exit;
										} else {
											$this->runLog('"'.$result['data']['username'].'" has logged in.');
										}
										$this->userinfo = $result['data'];
										$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_LOGIN_USER';
										$this->loginstatus = TRUE;
									} else {
										// This user have been deactivated.
										$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_USER_DEACTIVATED';
										$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is stopped by script (Logging In). User have been deactivated!');
									}

								} else {
									// Wrong password for this username.
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOGIN_WRONG_PASS';
								}

							} elseif ($result['num'] > 1) {
								// To many users with same username
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOGIN_TO_MANY_USERS';
							} elseif ($result['num'] < 1) {
								// No users with that username
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOGIN_WRONG_USER';
							}
						}

					}

				/* User tries to make a new user, hmm, gah */
				} elseif (isset($this->_systemOutVar['REG']['register']) AND $this->_systemOptions['register'] == TRUE && $this->matchPath('reg')) {

					$this->_systemReOwner = 'register';

					if ($this->_systemOutVar['REG']['username'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_MISSING_USER';
					} elseif ($this->_systemOutVar['REG']['password'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_MISSING_PASS';
					} elseif ($this->_systemOutVar['REG']['email'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_MISSING_EMAIL';
					} else {

						if ($this->_systemOutVar['REG']['password'] == $this->_systemOutVar['REG']['password2']) {

							// Anti Spam Counter
							$this->spamCount();

							if ($result = $this->findUser($this->_systemOutVar['REG']['username'])) {

								if ($result['num'] < 1) {

									$error = 0;

									foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
										$query = "INSERT INTO ".$table_value['table_name']." SET";
										if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
											foreach($table_value['fields'] as $field_key => $field_value) {
												list($field_name,,$field_extra) = explode('||', $field_value);
												if (ereg('AUTO\[(.*)\]', $field_extra, $extra_data)) {
													$query .= " ".$field_name." = '".$extra_data[1]."',";
												} elseif (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
													if ($this->_systemOutVar['REG']['ADV'][$table_key][$field_name] != $extra_data[1] OR !isset($this->_systemOutVar['REG']['ADV'][$table_key][$field_name])) {
														$this->_systemOutVar['REG']['ADV'][$table_key][$field_name] = $extra_data[2];
													}
													$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['REG']['ADV'][$table_key][$field_name])."',";
												} else {
													$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['REG']['ADV'][$table_key][$field_name])."',";
												}
											}
										}

										if ($table_key == '_main') {
											$query .= " username = '".mysql_escape_string($this->_systemOutVar['REG']['username'])."', password = '".md5($this->_systemOutVar['REG']['password'])."', email = '".mysql_escape_string($this->_systemOutVar['REG']['email'])."'";
											if (!$result = $this->runQuery($query)) {
												$error = -1;
												break;
											}
										} else {
											$query .= " ".$table_value['id_field']." = '".$result['id']."'";
											if (!$this->runQuery($query)) {
												$error += 1;
											}

										}

									}

									if ($error == -1) {
										$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_USER_NOT_MADE';
									} elseif ($error == 0) {
										$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_REG_USER_MADE';
										$this->runLog('New user! "'.$this->_systemOutVar['REG']['username'].'" is added to database!');
										$this->_systemNewUser = TRUE;
									} else {
										$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_REG_USER_MADE_ERROR';
										$this->runLog('New user! "'.$this->_systemOutVar['REG']['username'].'" is added to database! Some or all "extra table" data was not added to database!');
										$this->_systemNewUser = TRUE;
									}

								} else {

									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_USER_E';

								} 

							}

						} else {

							$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_REG_WRONG_PASS';

						}

					}

				/* User wants to request a new password - Part 1 */
				} elseif (isset($this->_systemOutVar['LP']['run']) && $this->_systemOptions['lostpass'] == TRUE && $this->matchPath('login')) {

					$this->_systemReOwner = 'login';

					if ($this->_systemOutVar['LP']['username'] == '') {
						$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_MISSING_USER';
					} else {

						// Anti Spam Counter
						$this->spamCount();

						if ($result = $this->findUser($this->_systemOutVar['LP']['username'])) {

							if ($result['num'] == 1) {
								// Checking user status
								if ($result['data']['user_status'] == 1) {
								// User did exist.
									if ($result['data']['lost_date'] < gmdate("YmdHis")) {
										srand(microtime()*100000000);
										$random_key = md5(rand(1, 999).$this->_systemOptions['var_name'].rand(1, 999));
										if ($this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET lost_key='".$random_key."', lost_date='".date("YmdHis", mktime (gmdate("H"),gmdate("i"),gmdate("s"),gmdate("m"),gmdate("d")+1,gmdate("Y")))."' WHERE ".$this->_systemOptions['mysql_id']." = '".$result['data'][$this->_systemOptions['mysql_id']]."' LIMIT 1")) {
											// Made a new key and set a new date
											if ($this->sendMail($result['data']['email'], 'Request New Password: Step 1', 'A new password have been requested for the user, '.$result['data']['username'].'.

To make a new random password follow this link:
'.$this->pagePath('login',$this->_systemOptions['var_name'].'[LP][user]='.$result['data']['username'].'&'.$this->_systemOptions['var_name'].'[LP][key]='.$random_key).'

If you did not loose or request a new password, then someone else have entered you username, maybe by mistake.
If you keep getting this mail and you did not ask for it, please contact the webmaster of the website.
	
Thank you for your time!')) {
												$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_EMAIL_SENT';
												$this->runLog('"'.$result['data']['username'].'" has requested a new password - Part 1: First email.');
											}
										}
									} else {
										// This user have already had a request made within the last day
										$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_TO_FAST';
									}

								} else {
									// This users have been deactivated.
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_USER_DEACTIVATED';
									$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is stopped by script (Lost password: Part 1). User have been deactivated!');
								}

							} elseif ($result['num'] > 1) {
								// To many users with same username
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_TO_MANY_USERS';
							} elseif ($result['num'] < 1) {
								// No users with that username
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_WRONG_USER';
							}

						}

					}

				/* User wants to request a new password - Part 2 */
				} elseif (isset($this->_systemOutVar['LP']['user']) && isset($this->_systemOutVar['LP']['key']) && $this->_systemOptions['lostpass'] == TRUE && $this->matchPath('login')) {

					$this->_systemReOwner = 'login';

					if ($result = $this->findUser($this->_systemOutVar['LP']['user'])) {

						if ($result['num'] == 1) {
							// Checking user status
							if ($result['data']['user_status'] == 1) {
								// User did exist.
								if ($result['data']['lost_key'] != '0') {
									if ($result['data']['lost_key'] == $this->_systemOutVar['LP']['key']) {
										srand(microtime()*100000000);
										$random_pass = rand(1, 9).'a'.rand(1, 9).'b'.rand(1, 9).'c'.rand(1, 9);
										if ($this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET lost_key='0', password='".md5($random_pass)."' WHERE ".$this->_systemOptions['mysql_id']." = '".$result['data'][$this->_systemOptions['mysql_id']]."' LIMIT 1")) {
											if ($this->sendMail($result['data']['email'], 'Request New Password: Step 2', 'A new password have been made for the user, '.$result['data']['username'].'.

The new password is:
'.$random_pass.'


If you did not request this mail, the login system may have been hacked, contact the webmaster ASAP and tell him what has happend.
	
Thank you for your time!')) {
												$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_EMAIL_SENT';
												$this->runLog('"'.$result['data']['username'].'" has requested a new password - Part 2: Secound email with new password.');
											} else {
												$this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET password='".$result['data']['password']."' WHERE ".$this->_systemOptions['mysql_id']." = '".$result['data'][$this->_systemOptions['mysql_id']]."' LIMIT 1");
											}
										}
									} else {
										// The two keys where not the same
										$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_WRONG_KEY';
									}
								} else {
									// This user have not requested a new password
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_NO_REQUEST';
								}

							} else {
								// This users have been deactivated.
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_USER_DEACTIVATED';
								$this->runLog('"'.$this->_systemOutVar['session']['user'].'" is stopped by script (Lost password: Part 2). User have been deactivated!');
							}

						} elseif ($result['num'] > 1) {
							// To many users with same username
							$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_TO_MANY_USERS';
						} elseif ($result['num'] < 1) {
							// No users with that username
							$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_LOST_WRONG_USER';
						}

					}

				}

			}

		}

		/* Checking to see if user is an admin */
		if ($this->_systemOptions['admins'] != '' && $this->loginstatus == TRUE) {
			$admins = explode(',', $this->_systemOptions['admins']);
			if (in_array($this->userinfo['username'], $admins)) {
				$this->adminstatus = TRUE;
			}
		}

		/* ADMIN */
		if (isset($this->_systemOutVar['ADMIN']['RUN'])) {

			$this->_systemReOwner = 'admin';

?>

<html>
<head>
<title>phpUserLogin2 - Admin</title>

<style type="text/css">
<!--
h3 { 
 font-family: verdana, arial, "ms sans serif", sans-serif;
 font-size: 16px; 
 margin: 10px;
 line-height: 18px;
 padding-left: 5px;
 color: #000000;
 } 
a:link {
 color: #000000;
 font-weight: normal; 
 text-decoration: underline;
 }
a:visited {
 color: #000000;
 font-weight: normal; 
 text-decoration: underline;
 }
a:active {
 color: #000000;
 font-weight: normal; 
 text-decoration: ;
 }
a:hover {
 color:#000000;
 font-weight: normal; 
 text-decoration: none;
 }  
.content { 
 font-family: verdana, arial, "ms sans serif", sans-serif; 
 font-size: 12px; 
 margin: 2px;
 line-height: 14px;
 color: #000000;
 }
input, textarea, select {
 background-color: #CCCCCC;
 border-style: solid;
 border-width: 1px;
 font-family: verdana, arial, sans-serif;
 font-size: 10px;
 color: #333333;
 padding: 0px;
}
.smallheader
 { 
 font-family: verdana, arial, "ms sans serif", sans-serif; 
 font-size: 10px; 
 font-weight: normal;
 padding-left: 5px;
 padding-right: 5px;
 line-height: 14px;
 color: #e9f2fc;
 }
-->
</style>

</head>

<body bgcolor="#808080">

<br>

<center>

  <table border="0" cellpadding="1" cellspacing="0" bgcolor="#808080" width="80%">
    <tr> 
      <td colspan="2"> 
        <table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width="100%">
          <tr>
            <td> 
              <table border="0" cellpadding="0" cellspacing="0" bgcolor="#808080" width="100%">
                <tr> 
                  <td bgcolor="#354463" align="center"><img src="http://phpuserlogin.oxyscripts.com/img/phpuserlogin.gif" width="364" height="31"></td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
	<tr> 
      <td> 
        <table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width="100%">
          <tr>
            <td> 
              <table border="0" cellpadding="0" cellspacing="10" width="100%" bgcolor="#dcdcdc">
                <tr>
                  <td valign="top"> 
                    <table border="0" cellpadding="0" cellspacing="0" width="100%">
                      <tr> 
                        <td width="100%" class="content">

<center>- <a href="" onClick="self.close()">Close Window</a> -</center><br>
<?

			if ($this->adminstatus == TRUE) {

				if ($this->_systemOutVar['ADMIN']['RUN'] == 'START_WINDOW') {

?>
<center><nobr>[ <a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][SHOW]=ADD')?>">Add New User!</a> - <a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][SHOW]=USER_LIST')?>">Edit/Delete An User!</a> ]<br><br>
<a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][PROCESS][RUN]=DEACTIVATE')?>"><b>De-activate ALL users</b></a> - <a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][PROCESS][RUN]=REACTIVATE')?>"><b>Re-activate ALL users</b></a></nobr></center><br>
<HR width="70%">
<br>
<?

					if (isset($this->_systemOutVar['ADMIN']['PROCESS']['RUN'])) {
?>
<center><b>Processing....</b><br>
<?
						if ($this->_systemOutVar['ADMIN']['PROCESS']['RUN'] == 'ADD') {
?>
<b>Adding...</b>
<?
							$error = 0;
							if (empty($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['USERNAME'])) {
 								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_ADD_NO_USERNAME';
								$error += 1;
							} elseif (empty($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['PASSWORD'])) {
 								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_ADD_NO_PASSWORD';
								$error += 1;
							} elseif ($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['PASSWORD'] != $this->_systemOutVar['ADMIN']['PROCESS']['ADD']['PASSWORD2']) {
 								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_ADD_PASSWORD_WRONG';
								$error += 1;
							} else {
								foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
									$query = "INSERT INTO ".$table_value['table_name']." SET";
									if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
										foreach($table_value['fields'] as $field_key => $field_value) {
											list($field_name,,$field_extra) = explode('||', $field_value);
											if (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
												if ($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EXTRA'][$table_key][$field_name] != $extra_data[1] OR !isset($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EXTRA'][$table_key][$field_name])) {
													$this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EXTRA'][$table_key][$field_name] = $extra_data[2];
												}
												$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EXTRA'][$table_key][$field_name])."',";
											} else {
												$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EXTRA'][$table_key][$field_name])."',";
											}
										}
									}

									if ($table_key == '_main') {
										$query .= " username = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['USERNAME'])."', password = '".md5($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['PASSWORD'])."', email = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['ADD']['EMAIL'])."'";
										if (!$result = $this->runQuery($query)) {
											$error = -1;
											break;
										}
									} else {
										$query .= " ".$table_value['id_field']." = '".$result['id']."'";
										if (!$this->runQuery($query)) {
											$error += 1;
										}

									}

								}

								if ($error == -1) {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_ADD_USER_NOT_MADE';
								} elseif ($error == 0) {
									$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_ADD_USER_MADE';
								} else {
									$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_ADD_USER_MADE';
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_ADD_USER_MADE_ERROR';
								}
							}
						} elseif ($this->_systemOutVar['ADMIN']['PROCESS']['RUN'] == 'EDIT') {
?>
<b>Editing...</b>
<?
							if(!empty($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['PASSWORD']) AND $this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['PASSWORD'] != $this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['PASSWORD2']) {
 								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_EDIT_PASSWORD_WRONG';
								$error += 1;
							} else {
								if ($this->userinfo[$this->_systemOptions['mysql_id']] == $this->_systemOutVar['ADMIN']['EDIT_ID']) {
									$this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['USER_STATUS'] = 1;
								}
								foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
									if ($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA_TABLE_INFO'][$table_key] != 'TOMANY') {
										if ($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA_TABLE_INFO'][$table_key] == 'NODATA') {
											$query = "INSERT";
										} else {
											$query = "UPDATE";
										}
										$query .= " ".$table_value['table_name']." SET";
										if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
											foreach($table_value['fields'] as $field_key => $field_value) {
												list($field_name,,$field_extra) = explode('||', $field_value);
												if (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
													if ($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA'][$table_key][$field_name] != $extra_data[1] OR !isset($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA'][$table_key][$field_name])) {
														$this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA'][$table_key][$field_name] = $extra_data[2];
													}
													$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA'][$table_key][$field_name])."',";
												} else {
													$query .= " ".$field_name." = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA'][$table_key][$field_name])."',";
												}
											}
										}

										if ($table_key == '_main') {
											$query .= " password = ".((empty($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['PASSWORD'])) ? "password" : "'".md5($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['PASSWORD'])."'" ).", email = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EMAIL'])."', user_status = '".mysql_escape_string($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['USER_STATUS'])."' WHERE ".$this->_systemOptions['mysql_id']." = '".$this->_systemOutVar['ADMIN']['EDIT_ID']."'";
											if (!$result = $this->runQuery($query)) {
												$error = -1;
												break;
											}
										} else {
											$query .= " ".$table_value['id_field']." = '".$this->_systemOutVar['ADMIN']['EDIT_ID']."'";
											if ($this->_systemOutVar['ADMIN']['PROCESS']['EDIT']['EXTRA_TABLE_INFO'][$table_key] != 'NODATA') {
												$query .= " WHERE ".$table_value['id_field']." = '".$this->_systemOutVar['ADMIN']['EDIT_ID']."'";
											}
											if (!$this->runQuery($query)) {
												$error += 1;
											}

										}

									}
								}

								if ($error == -1) {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_EDIT_USER_FAIL';
								} elseif ($error == 0) {
									$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_EDIT_USER_DONE';
								} else {
									$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_EDIT_USER_DONE';
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_EDIT_USER_DONE_ERROR';
								}
							}
						} elseif ($this->_systemOutVar['ADMIN']['PROCESS']['RUN'] == 'DELETE') {
?>
<b>Deleting...</b>
<?
							$delete_count = count($this->_systemOutVar['ADMIN']['DELETE_ID']);
							foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
								$query = "DELETE FROM ".$table_value['table_name']." WHERE 1=0";
								if ($table_key == '_main') {
									for ($i = 0; $i < $delete_count; $i++) {
										if ($this->userinfo[$this->_systemOptions['mysql_id']] != $this->_systemOutVar['ADMIN']['DELETE_ID'][$i]) {
											$query .= " OR ".$this->_systemOptions['mysql_id']." = '".$this->_systemOutVar['ADMIN']['DELETE_ID'][$i]."'";
										}
									}

									if (!$result = $this->runQuery($query)) {
										$error = -1;
										break;
									}
								} else {
									for ($i = 0; $i < $delete_count; $i++) {
										if ($this->userinfo[$this->_systemOptions['mysql_id']] != $this->_systemOutVar['ADMIN']['DELETE_ID'][$i]) {
											$query .= " OR ".$table_value['id_field']." = '".$this->_systemOutVar['ADMIN']['DELETE_ID'][$i]."'";
										}
									}
									if (!$this->runQuery($query)) {
										$error += 1;
									}
								}

							}

							if ($error == -1) {
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_DELETE_FAIL';
							} elseif ($error == 0) {
								$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_DELETE_DONE';
							} else {
								$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_DELETE_DONE';
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_DELETE_DONE_ERROR';
							}

						} elseif ($this->_systemOutVar['ADMIN']['PROCESS']['RUN'] == 'DEACTIVATE') {
?>
<b>Starting Total Lockdown Sequence...</b>
<?
							if (!$result = $this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET user_status = '0' WHERE ".$this->_systemOptions['mysql_id']." != '".$this->userinfo[$this->_systemOptions['mysql_id']]."'")) {
								$error = +1;
							}

							if ($error == 0) {
								$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_DEACTIVATE_DONE';
							} else {
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_DEACTIVATE_ERROR';
							}
						} elseif ($this->_systemOutVar['ADMIN']['PROCESS']['RUN'] == 'REACTIVATE') {
?>
<b>Reactivating All Users...</b>
<?
							if (!$result = $this->runQuery("UPDATE ".$this->_systemOptions['mysql_table']." SET user_status = '1' WHERE ".$this->_systemOptions['mysql_id']." != '".$this->userinfo[$this->_systemOptions['mysql_id']]."'")) {
								$error = +1;
							}

							if ($error == 0) {
								$this->_systemRespons[$this->_systemReOwner]['action'] = 'phpUserLogin_ADMIN_REACTIVATE_DONE';
							} else {
								$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_REACTIVATE_ERROR';
							}
						}

						if ($error != 0) {
?>
<br><br>[- <a href="javascript:history.back()">Go Back</a> -]
<?
						}
?>
</center>
<?
					}

					if (isset($this->_systemOutVar['ADMIN']['SHOW'])) { // Show a form or admin function
						if ($this->_systemOutVar['ADMIN']['SHOW'] == 'ADD') { // Show Add form
?>
<h3>Add New User:.</h3><p>

Remember that you may only use a username ones in the database. So you cant have two users with the username.<br><br>

<table align="center" class="content"><form action="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][PROCESS][RUN]=ADD')?>" method="post">
<tr>
	<td align="right">Username</td>
	<td><input type="Text" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][USERNAME]'?>" size="10" MaxLength="20"></td>
</tr>
<tr>
	<td align="right">Password</td>
	<td><input type="Password" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][PASSWORD]'?>" size="10" MaxLength="20"></td>
</tr>
<tr>
	<td align="right">Retype Password</td>
	<td><input type="Password" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][PASSWORD2]'?>" size="10" MaxLength="20"></td>
</tr>
<tr>
	<td align="right">Email</td>
	<td><input type="Text" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EMAIL]'?>" size="10" MaxLength="100"></td>
</tr>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?
							if (is_array($this->_systemOptions['mysql_fields'])) {
								foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
									if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
										foreach($table_value['fields'] as $field_key => $field_value) {
											list($field_name,$field_text,$field_extra) = explode('||', $field_value);
											if (!empty($field_extra)) {
												if (ereg('MAX\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="text" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" MaxLength="<?=$extra_data[1]?>"></td>
</tr>
<?
												} elseif (ereg('DROP_DOWN\[(.*)\]', $field_extra, $extra_data)) {
													$options = explode(',', $extra_data[1]);
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><SELECT NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>">
<?
													foreach($options as $options_value) {
														$sub_options = explode('=', $options_value);
?>
<OPTION value="<?=$sub_options[1]?>" <?=((@$sub_options[2]=='s') ? 'selected' : '' )?>><?=$sub_options[0]?></OPTION>
<?
													}
?>
	</td>
</tr>
<?
												} elseif (ereg('AUTO\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="text" value="<?=$extra_data[1]?>" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10"></td>
</tr>
<?
												} elseif (ereg('PASS\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="password" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" MaxLength="<?=$extra_data[1]?>"></td>
</tr>
<?
												} elseif (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="checkbox" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" value="<?=$extra_data[1]?>"></td>
</tr>
<?
												} elseif (ereg('RADIO\[(.*)\]', $field_extra, $extra_data)) {
													$options = explode(',', $extra_data[1]);
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="Center" colspan="2"><table>
<?
													foreach($options as $options_value) {
														$sub_options = explode('=', $options_value);
?>
<tr><td align="right"><font size="1"><?=$sub_options[0]?></font></td><td><INPUT TYPE="radio" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" value="<?=$sub_options[1]?>" <?=((@$sub_options[2]=='s') ? 'checked' : '' )?>></td></tr>
<?
													}
?>
</table></td>
</tr>
<?
												} elseif (ereg('TEXT\[(.*),(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><TEXTAREA NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" ROWS="<?=$extra_data[2]?>" COLS="<?=$extra_data[1]?>"></TEXTAREA></td>
</tr>
<?
												}
											} else {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><input type="Text" name"<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][ADD][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10"></td>
</tr>
<?
											}
?>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?

										}
									}
								}
							}
?>
<tr>
	<td align="center" colspan="2"><input type="submit" value="Add User"> <input type="reset" value="Reset"></td>
</tr>
</form></table>

<?
						} elseif ($this->_systemOutVar['ADMIN']['SHOW'] == 'USER_LIST') { // Show Edit List form
?>
<h3>Edit/Delete - User List:.</h3><p>
<?
							if ($result = $this->runQuery("SELECT ".$this->_systemOptions['mysql_id'].",username,user_status FROM ".$this->_systemOptions['mysql_table']." ORDER BY username ASC")) {
								if ($result['num'] > 0) {
?>
To edit a user simply click on that users username.<br>
To delete one or more users check the checkbox next to there name and then click delete user(s).<br>
Deactivated users are shown in red.<br><br>

<table align="center" class="content" width="100%" cellspacing="4">
<FORM METHOD=POST ACTION="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][SHOW]=DELETE')?>">
<tr>
	<td colspan="3"><i>User(s) Found: <?=$result['num']?></i></td>
</tr>
<tr>
<?
									$cols = 0;
									while ($row = mysql_fetch_assoc($result['result'])) {
										$cols++;
?>
	<td><INPUT TYPE="checkbox" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][DELETE_ID][]'?>" VALUE="<?=$row['id']?>"> - <a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][EDIT_ID]='.$row['id'].'&'.$this->_systemOptions['var_name'].'[ADMIN][SHOW]=EDIT')?>"><font color="<? if ($row['user_status'] == 0) { echo'#FF0000'; } else { echo'#000000'; } ?>"><?=$row['username']?></font></a></td>
<?
										if ($cols >= 3) {
											$cols = 0;
?>
</tr>
<tr>
<?
										}
									}
?>
</tr>
<tr>
	<td colspan="3" align="center"><INPUT TYPE="submit" value="Delete User(s)"></td>
</tr>
</form>
</table>
<?
								} else {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_NO_USERS_LIST';
								}
							}
						} elseif ($this->_systemOutVar['ADMIN']['SHOW'] == 'EDIT') { // Show Edit User form
?>
<h3>Edit User:.</h3><p>
<?
							if ($result = $this->runQuery("SELECT * FROM ".$this->_systemOptions['mysql_table']." WHERE ".$this->_systemOptions['mysql_id']." = '".$this->_systemOutVar['ADMIN']['EDIT_ID']."'")) {
								if ($result['num'] == 1) {
?>
If you leave the password fields empty no new password will be made.<br>

<table align="center" class="content"><form action="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][PROCESS][RUN]=EDIT&'.$this->_systemOptions['var_name'].'[ADMIN][EDIT_ID]='.$this->_systemOutVar['ADMIN']['EDIT_ID'])?>" method="post">
<tr>
	<td align="right">Username</td>
	<td><?=$result['data']['username']?></td>
</tr>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<tr>
	<td align="center" rowspan="2">User Status</td>
	<td><INPUT TYPE="radio" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][USER_STATUS]'?>" value="1"<? if ($result['data']['user_status'] == 1) { echo'checked'; } ?>> Activated</td>
</tr>
<tr>
	<td><INPUT TYPE="radio" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][USER_STATUS]'?>" value="0"<? if ($result['data']['user_status'] == 0) { echo'checked'; } ?>> DeActivated</td>
</tr>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<tr>
	<td align="right">New Password</td>
	<td><input type="Password" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][PASSWORD]'?>" size="10" MaxLength="20"></td>
</tr>
<tr>
	<td align="right">Retype New Password</td>
	<td><input type="Password" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][PASSWORD2]'?>" size="10" MaxLength="20"></td>
</tr>
<tr>
	<td align="right">Users Email</td>
	<td><input type="Text" name="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EMAIL]'?>" size="10" MaxLength="100" value="<?=$result['data']['email']?>"></td>
</tr>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?
									if (is_array($this->_systemOptions['mysql_fields'])) {
										foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
											if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
												if ($result_extra = $this->runQuery("SELECT * FROM ".$table_value['table_name']." WHERE ".$table_value['id_field']." = '".$this->_systemOutVar['ADMIN']['EDIT_ID']."'")) {
													if ($result_extra['num'] == 0) {
?>
<tr>
	<td colspan="2" align="center">No data found in table <?=$table_key?>. New data will be added to table ones you press "Edit User".</td>
</tr>
<INPUT TYPE="hidden" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA_TABLE_INFO]['.$table_key.']'?>" value="NODATA">
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?
													} elseif ($result_extra['num'] > 1) {
?>
<tr>
	<td colspan="2" align="center">To many entries with the same id was found in table <?=$table_key?>. No new data will be added or updated untill this problem is fixed.</td>
</tr>
<INPUT TYPE="hidden" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA_TABLE_INFO]['.$table_key.']'?>" value="TOMANY">
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?
													} else {
?>
<INPUT TYPE="hidden" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA_TABLE_INFO]['.$table_key.']'?>" value="">
<?
													}
												}
												foreach($table_value['fields'] as $field_key => $field_value) {
													list($field_name,$field_text,$field_extra) = explode('||', $field_value);
													if (!empty($field_extra)) {
														if (ereg('MAX\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="text" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" MaxLength="<?=$extra_data[1]?>" value="<?=$result_extra['data'][$field_name]?>"></td>
</tr>
<?
														} elseif (ereg('DROP_DOWN\[(.*)\]', $field_extra, $extra_data)) {
															$options = explode(',', $extra_data[1]);
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><SELECT NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>">
<?
															foreach($options as $options_value) {
																$sub_options = explode('=', $options_value);
?>
<OPTION value="<?=$sub_options[1]?>" <?=(($result_extra['data'][$field_name] == $sub_options[1]) ? 'selected' : '' )?>><?=$sub_options[0]?></OPTION>
<?
															}
?>
	</td>
</tr>
<?
														} elseif (ereg('AUTO\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="text" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" value="<?=$result_extra['data'][$field_name]?>"></td>
</tr>
<?
														} elseif (ereg('PASS\[(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="password" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" MaxLength="<?=$extra_data[1]?>" value="<?=$result_extra['data'][$field_name]?>"></td>
</tr>
<?
														} elseif (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><INPUT TYPE="checkbox" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" value="<?=$extra_data[1]?>"<?=(($result_extra['data'][$field_name] == $extra_data[1]) ? ' checked' : '' )?>></td>
</tr>
<?
														} elseif (ereg('RADIO\[(.*)\]', $field_extra, $extra_data)) {
															$options = explode(',', $extra_data[1]);
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="Center" colspan="2"><table>
<?
															foreach($options as $options_value) {
																$sub_options = explode('=', $options_value);
?>
<tr><td align="right"><font size="1"><?=$sub_options[0]?></font></td><td><INPUT TYPE="radio" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" value="<?=$sub_options[1]?>" <?=(($result_extra['data'][$field_name] == $sub_options[1]) ? 'checked' : '' )?>></td></tr>
<?
															}
?>
</table></td>
</tr>
<?
														} elseif (ereg('TEXT\[(.*),(.*)\]', $field_extra, $extra_data)) {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><TEXTAREA NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" ROWS="<?=$extra_data[2]?>" COLS="<?=$extra_data[1]?>"><?=$result_extra['data'][$field_name]?></TEXTAREA></td>
</tr>
<?
														}
													} else {
?>
<tr>
	<td align="center" colspan="2"><?='<b>'.$field_name.'</b> in <b>'.$table_value['table_name'].'</b><br>'.$field_text?></td>
</tr>
<tr>
	<td align="center" colspan="2"><input type="Text" name"<?=$this->_systemOptions['var_name'].'[ADMIN][PROCESS][EDIT][EXTRA]['.$table_key.']['.$field_name.']'?>" size="10" value="<?=$result_extra['data'][$field_name]?>"></td>
</tr>
<?
													}
?>
<tr>
	<td align="center" colspan="2"><HR width="80%"></td>
</tr>
<?
												}
											}
										}
									}
?>
<tr>
	<td align="center" colspan="2"><input type="submit" value="Edit User"> <input type="reset" value="Reset"></td>
</tr>
</form></table>

<?
								} elseif ($result['num'] > 1) {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_TOMANY_USERS_EDIT';
								} else {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_NO_USERS_EDIT';
								}
							}
						} elseif ($this->_systemOutVar['ADMIN']['SHOW'] == 'DELETE') { // Show Final Delete List form
?>
<h3>Delete User(s):.</h3><p>
<?
							$delete_count = count($this->_systemOutVar['ADMIN']['DELETE_ID']);
							$query = "SELECT ".$this->_systemOptions['mysql_id'].",username FROM ".$this->_systemOptions['mysql_table']." WHERE 0";
							for ($i = 0; $i < $delete_count; $i++) {
								$query .= " OR ".$this->_systemOptions['mysql_id']." = '".$this->_systemOutVar['ADMIN']['DELETE_ID'][$i]."'";
							}
							$query .= " ORDER BY username ASC";

							if ($result = $this->runQuery($query)) {
								if ($result['num'] > 0) {
?>
Are you sure you want to delete these users!!<br>
If you dont want to delete one or more of the selected users but still the rest of them, then you can de select them here.<br><br>

<table align="center" class="content" width="100%" cellspacing="4">
<FORM METHOD=POST ACTION="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW&'.$this->_systemOptions['var_name'].'[ADMIN][PROCESS][RUN]=DELETE')?>">
<tr>
	<td><i>User(s) Found: <?=$result['num']?></i></td>
</tr>
<tr>
	<td align="center">
		<table class="content">
<?
									while ($row = mysql_fetch_assoc($result['result'])) {
?>
		<tr>
			<td><INPUT TYPE="checkbox" NAME="<?=$this->_systemOptions['var_name'].'[ADMIN][DELETE_ID][]'?>" VALUE="<?=$row['id']?>" checked> - <?=$row['username']?></td>
		</tr>
<?
									}
?>
		</table>
	</td>
</tr>
<tr>
	<td align="center"><INPUT TYPE="submit" value="Delete User(s)"></td>
</tr>
</form>
</table>
<?
								} else {
									$this->_systemRespons[$this->_systemReOwner]['info'] = 'phpUserLogin_ADMIN_NO_USERS_DELETE';
								}
							}
						}
					}

					if ($msgs = $this->SystemMsg('admin')) {
						echo '<br><center>'.$msgs.'</center>';
					}

					if ($this->_systemMySQL_Err != NULL) {
						echo'<br><center><HR width="80%">MySQL Error(s):</font><br><div align="left"><table class="content">';
						foreach($this->_systemMySQL_Err as $mysql_error_num => $mysql_error) {
							echo'<tr><td align="right"><NOBR>Error Number:</NOBR></td><td>'.$mysql_error_num.'<td></tr><tr><td valign="top" align="right">Query:</td><td>'.$mysql_error['query'].'</td></tr><tr><td valign="top" align="right">Error:</td><td>'.$mysql_error['errno'].': '.$mysql_error['error'].'</td></tr>';
						}
						echo'</table></div></center>';
					}

				} else { // Show link to Admin Window.
?>
<center>
Welcome to the phpUserLogin2 Admin.<br>
<a href="<?=$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=START_WINDOW')?>">Start the Admin</a><br><br>
</center>
<?
				}

			} else {

?>
<center>You are either not logged in or not an admin so you may not use this feature.</center>
<?			

			}

?>

						</td>
                      </tr>
					</table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <tr> 
      <td colspan="2"> 
        <table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width="100%">
          <tr>
            <td> 
              <table border="0" cellpadding="0" cellspacing="0" bgcolor="#808080" width="100%">
                <tr> 
                  <td bgcolor="#354463" align="center" class="smallheader"><?=$this->_systemPowerBy?><br>Using version: <?=$this->_systemVersion?></td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>

</center>

<br>

</body>
</html>

<?

			exit;

		}

		/* Run time counter - End */
		$this->_systemRunTime['end'] = microtime();
	
	}

	function loadMore($table_name, $id_field = 'id') {

		if ($this->loginstatus) {
			$query = "SELECT * FROM ".$table_name." WHERE ".$id_field." = '".$this->userinfo["id"]."'";
			$result = @mysql_query($query, $this->_systemMySQL_Link);
			$num = @mysql_num_rows($result);
			if ($num == 1) {
				$this->userinfo[$table_name] = mysql_fetch_assoc($result);
				return TRUE;
			} elseif ($num < 1) {
				return FALSE;
			} elseif ($num > 1) {
				return FALSE;
			}
		}
	}

	function accessControl($back_page, $check = FALSE, $table_name = NULL, $field_check = NULL, $ok_value = TRUE, $field_id = 'id') {

		$test_result = NULL;

		if ($this->loginstatus == TRUE) {
			if ($check == TRUE) {
				if (!isset($this->userinfo[$table_name][$field_check])) {
					if (!$this->loadMore($table_name, $field_id)) {
						$test_result = FALSE;
					}
				}

				if ($test_result == NULL) {
					$ok_value = explode(',', $ok_value);

					if (is_array($ok_value)) {
						for ($i = 0; $i < count($ok_value); $i++) {
							if ($this->userinfo[$table_name][$field_check] == $ok_value[$i]) {
								$test_result = TRUE;
								break;
							} elseif (($i+1) == count($ok_value)) {
								$test_result = FALSE;
								break;
							}
						}
					} else {
						if ($this->userinfo[$table_name][$field_check] == $ok_value) {
							$test_result = TRUE;
						} else {
							$test_result = FALSE;
						}
					}
				}
			} else {
				$test_result = TRUE;
			}

		} else {
			$test_result = FALSE;
		}


		if ($test_result == FALSE || $test_result == NULL) {

			header('Refresh: 5; url='.$back_page);
			echo'<center>'.$this->_systemText['aC_1'].' <a href="'.$back_page.'">'.$this->_systemText['aC_2'].'</a>.</center>';
			exit;
		}

	}

	function templates($template_name, $template_folder = FALSE, $template_prefix = FALSE) {

		if ($template_prefix == FALSE) {
			$template_prefix = $this->_systemOptions['temp_prefix'];
		}

		if ($template_folder == FALSE) {
			$template_folder = $this->_systemOptions['temp_folder'];
		}

		if ($template_folder != FALSE) { 
			foreach ($this->_systemTemplates[$template_name] as $key => $value) {
				$template_holder = '';
				if (@$fp = fopen($template_folder.'/'.$template_prefix.'_'.$template_name.'_'.$key.'.tpl','r')) {
					@$template_holder = fread ($fp, filesize ($template_folder.'/'.$template_prefix.'_'.$template_name.'_'.$key.'.tpl'));
					@fclose($fp);
				}
				if (!empty($template_holder)) {
					$templates[$key] = $template_holder;
				} else {
					$templates[$key] = $value;
				}
			}		
		} else {
			$templates = $this->_systemTemplates[$template_name];
		}

		return $templates;

	}

	function SystemMsg($ResponsOwner) {

		$text = '';
		$msg_check = 0;

		if (isset($this->_systemRespons['spam']) AND $this->adminstatus == FALSE) {

			return $this->_systemText['SPAM'];

		} elseif (isset($this->_systemRespons[$ResponsOwner])) {

			if (isset($this->_systemRespons[$ResponsOwner]['mysql'])) {

				$msg_check = 1;

				switch ($this->_systemRespons[$ResponsOwner]['mysql']) {
					case 'phpUserLogin_MySQL_NO_CON':
						$text .= $this->_systemText['MYSQL_NO_CON'];
						break;
					case 'phpUserLogin_MySQL_NO_CON_P':
						$text .= $this->_systemText['MYSQL_NO_CON_P'];
						break;
					case 'phpUserLogin_MySQL_NO_DATAB':
						$text .= $this->_systemText['MYSQL_NO_DATAB'].' '.$this->_systemOptions['mysql_data'];
						break;
					case 'phpUserLogin_MySQL_QUERY_ERROR':
						$text .= $this->_systemText['MYSQL_QUERY_ERROR'];
						break;
					default:
						$text .= $this->_systemText['ERROR_MISSING_MSG'].': '.$this->_systemRespons[$ResponsOwner]['mysql'];
						break;
				}

			}

			if (isset($this->_systemRespons[$ResponsOwner]['action'])) {

				if ($msg_check == 1) {
					$text .= '<br>';
				}

				$msg_check = 1;

				$text .= '<i>';
				switch ($this->_systemRespons[$ResponsOwner]['action']) {
					case 'phpUserLogin_REG_USER_MADE':
						$text .= $this->_systemText['REG_USER_MADE'];
						break;
					case 'phpUserLogin_REG_USER_MADE_ERROR':
						$text .= $this->_systemText['REG_USER_MADE_ERROR'];
						break;
					case 'phpUserLogin_LOGOUT_FORCE':
						$text .= $this->_systemText['LOGOUT_FORCE'];
						break;
					case 'phpUserLogin_LOGOUT_USER':
						$text .= $this->_systemText['LOGOUT_USER'];
						break;
					case 'phpUserLogin_LOGIN_USER':
						$text .= $this->_systemText['LOGIN_USER'];
						break;
					case 'phpUserLogin_EMAIL_SENT':
						$text .= $this->_systemText['EMAIL_SENT'];
						break;
					case 'phpUserLogin_ADMIN_ADD_USER_MADE':
						$text .= 'A new user has been added into the database.';
						break;
					case 'phpUserLogin_ADMIN_EDIT_USER_DONE':
						$text .= 'User updated.';
						break;
					case 'phpUserLogin_ADMIN_DELETE_DONE':
						$text .= 'Users deleted.';
						break;
					case 'phpUserLogin_ADMIN_DEACTIVATE_DONE':
						$text .= 'Total Lockdown Complete! All users have been deactivated.';
						break;
					case 'phpUserLogin_ADMIN_REACTIVATE_DONE':
						$text .= 'All users have been reactivated.';
						break;
					default:
						$text .= $this->_systemText['ERROR_MISSING_MSG'].': '.$this->_systemRespons[$ResponsOwner]['action'];
						break;
				}
				$text .= '</i>';
			}

			if (isset($this->_systemRespons[$ResponsOwner]['info'])) {

				if ($msg_check == 1) {
					$text .= '<br>';
				}
				
				switch ($this->_systemRespons[$ResponsOwner]['info']) {
					case 'phpUserLogin_REG_MISSING_USER':
						$text .= $this->_systemText['REG_MISSING_USER'];
						break;
					case 'phpUserLogin_REG_MISSING_PASS':
						$text .= $this->_systemText['REG_MISSING_PASS'];
						break;
					case 'phpUserLogin_REG_MISSING_EMAIL':
						$text .= $this->_systemText['REG_MISSING_EMAIL'];
						break;
					case 'phpUserLogin_REG_WRONG_PASS':
						$text .= $this->_systemText['REG_WRONG_PASS'];
						break;
					case 'phpUserLogin_REG_USER_E':
						$text .= $this->_systemText['REG_USER_E'];
						break;
					case 'phpUserLogin_REG_USER_NOT_MADE':
						$text .= $this->_systemText['REG_USER_NOT_MADE'];
						break;
					case 'phpUserLogin_LOGIN_MISSING_USER':
						$text .= $this->_systemText['LOGIN_MISSING_USER'];
						break;
					case 'phpUserLogin_LOGIN_MISSING_PASS':
						$text .= $this->_systemText['LOGIN_MISSING_PASS'];
						break;
					case 'phpUserLogin_LOGIN_TO_MANY_USERS':
						$text .= $this->_systemText['LOGIN_TO_MANY_USERS'];
						break;
					case 'phpUserLogin_LOGIN_WRONG_USER':
						$text .= $this->_systemText['LOGIN_WRONG_USER'];
						break;
					case 'phpUserLogin_LOGIN_WRONG_PASS':
						$text .= $this->_systemText['LOGIN_WRONG_PASS'];
						break;
					case 'phpUserLogin_COOKIES_FAKE':
						$text .= $this->_systemText['COOKIES_FAKE'];
						break;
					case 'phpUserLogin_COOKIES_NO_USER':
						$text .= $this->_systemText['COOKIES_NO_USER'];
						break;
					case 'phpUserLogin_COOKIES_TO_MANY_USERS':
						$text .= $this->_systemText['COOKIES_TO_MANY_USERS'];
						break;
					case 'phpUserLogin_COOKIES_LOGGED_IN':
						$text .= $this->_systemText['COOKIES_LOGGED_IN'];
						break;
					case 'phpUserLogin_LOST_MISSING_USER':
						$text .= $this->_systemText['LOST_MISSING_USER'];
						break;
					case 'phpUserLogin_LOST_TO_MANY_USERS':
						$text .= $this->_systemText['LOST_TO_MANY_USERS'];
						break;
					case 'phpUserLogin_LOST_WRONG_USER':
						$text .= $this->_systemText['LOST_WRONG_USER'];
						break;
					case 'phpUserLogin_LOST_TO_FAST':
						$text .= $this->_systemText['LOST_TO_FAST'];
						break;
					case 'phpUserLogin_LOST_NO_REQUEST':
						$text .= $this->_systemText['LOST_NO_REQUEST'];
						break;
					case 'phpUserLogin_LOST_WRONG_KEY':
						$text .= $this->_systemText['LOST_WRONG_KEY'];
						break;
					case 'phpUserLogin_EMAIL_NONE':
						$text .= $this->_systemText['EMAIL_NONE'];
						break;
					case 'phpUserLogin_EMAIL_NO_GO':
						$text .= $this->_systemText['EMAIL_NO_GO'];
						break;
					case 'phpUserLogin_USER_DEACTIVATED':
						$text .= $this->_systemText['DEACTIVATED'];
						break;
					case 'phpUserLogin_USER_BEEN_DEACTIVATED':
						$text .= $this->_systemText['BEEN_DEACTIVATED'];
						break;
					case 'phpUserLogin_ADMIN_ADD_USER_NOT_MADE':
						$text .= 'No new user made. Could not add data into the main table. Are you sure the username you used is not already in use.';
						break;
					case 'phpUserLogin_ADMIN_ADD_USER_MADE_ERROR':
						$text .= 'Some of the data for the "extra tables" could not be added.';
						break;
					case 'phpUserLogin_ADMIN_ADD_NO_USERNAME':
						$text .= 'You need to enter a username for the new user.';
						break;
					case 'phpUserLogin_ADMIN_ADD_NO_PASSWORD':
						$text .= 'You need to enter a password for the new user.';
						break;
					case 'phpUserLogin_ADMIN_ADD_PASSWORD_WRONG':
						$text .= 'The two passwords you typed in was not the same, go back and try again.';
						break;
					case 'phpUserLogin_ADMIN_EDIT_PASSWORD_WRONG':
						$text .= 'The two new passwords you typed in was not the same, go back and try again.';
						break;
					case 'phpUserLogin_ADMIN_EDIT_USER_FAIL':
						$text .= 'Could not edit this users data in the main table.';
						break;
					case 'phpUserLogin_ADMIN_EDIT_USER_DONE_ERROR':
						$text .= 'Some of the data for the "extra tables" could not be edited.';
						break;
					case 'phpUserLogin_ADMIN_DELETE_FAIL':
						$text .= 'Could not delete the user(s) from the main table.';
						break;
					case 'phpUserLogin_ADMIN_DELETE_DONE_ERROR':
						$text .= 'Could not delete some of the data from the "extra tables".';
						break;
					case 'phpUserLogin_ADMIN_NO_USER_LIST':
						$text .= 'Could not find any users in the database.';
						break;
					case 'phpUserLogin_ADMIN_TOMANY_USER_EDIT':
						$text .= 'To many users with the same ID found!!';
						break;
					case 'phpUserLogin_ADMIN_NO_USER_EDIT':
						$text .= 'No user found or no user was selected.';
						break;
					case 'phpUserLogin_ADMIN_NO_USER_DELETE':
						$text .= 'Either no user(s) where found in the database or no user(s) where selected!!!';
						break;
					case 'phpUserLogin_ADMIN_DEACTIVATE_ERROR':
						$text .= 'Total Lockdown Failed! Could not deactivate users.';
						break;
					case 'phpUserLogin_ADMIN_REACTIVATE_ERROR':
						$text .= 'Could not reactivate users.';
						break;

					default:
						$text .= $this->_systemText['ERROR_MISSING_MSG'].': '.$this->_systemRespons[$ResponsOwner]['info'];
						break;
				}
			}

			return $text;

		} else {

			return FALSE;

		}

	}

	function matchPath($type) {

		if ($this->_systemPathMatch == TRUE) {

			if ($type == 'login') {
				if (empty($this->_systemOptions['page'])) {
					return TRUE;
				} else {
					$path = $this->_systemOptions['page'];
				}
			} elseif ($type == 'reg') {
				if (empty($this->_systemOptions['register_page'])) {
					return TRUE;
				} else {
					$path = $this->_systemOptions['register_page'];
				}
			}

			$self = PHPUSERLOGIN_PAGE;
			
			$self = @parse_url($self);
			$path = @parse_url($path);

			if ($self['path'] == $path['path'])  {
				return TRUE;
			} else {
				return FALSE;
			}

		} else {
			return TRUE;
		}
	}

	function pagePath($type = '', $query = '')  {

		if ($type == 'login') {
			$path = $this->_systemOptions['page'];
		} elseif ($type == 'reg') {
			$path = $this->_systemOptions['register_page'];
		} else {
			$path = '';
		}

		if (empty($path)) {
			$path = PHPUSERLOGIN_PAGE;
		}

		if (!empty($query)) {
			$path_parse = @parse_url($path);
			if (!empty($path_parse['query'])) {
				$path .= '&';
			} else {
				$path .= '?';
			}
			$path .= $query;
		}

		return $path;

	}

	function printOnlineUsersList($template_folder = FALSE, $template_prefix = FALSE) {

		if ($this->_systemOptions['users_online'] == TRUE) {

			$templates = $this->templates('oul', $template_folder, $template_prefix);

			$output = '<!-- Powered by phpuserlogin2 -->';

			$output .= $templates['top'];

				if ($result = $this->runQuery("SELECT `username` FROM `".$this->_systemOptions['mysql_table']."` WHERE last_active > ".date("YmdHis", mktime (gmdate("H"),gmdate("i")-15,gmdate("s"),gmdate("m"),gmdate("d"),gmdate("Y")))." ORDER BY `username` ASC")) {

					if ($result['num'] > 0) {

						$msg = $templates['msg'];
						$msg  = str_replace ("{msg}", $this->_systemText['oul_1'].' <b>'.$result['num'].'</b> '.$this->_systemText['oul_2'], $msg);
						$output .= $msg;

						$list = $templates['list'];

						$username_list = '';
						$check_num = $result['num'];

						while($row = mysql_fetch_assoc($result['result'])) {

							$check_num--;

							$username_list .= $row['username'];

							if ($check_num > 0) {

								$username_list .= $templates['list_split'];

							}

						}

						$list  = str_replace ("{list}", $username_list, $list);
						$output .= $list;

					} else {

						$msg = $templates['msg'];
						$msg  = str_replace ("{msg}", $this->_systemText['oul_3'], $msg);
						$output .= $msg;

					}

				} else {

					$msg = $templates['msg'];
					$msg  = str_replace ("{msg}", $this->_systemText['oul_4'], $msg);
					$output .= $msg;

				}

			$output .= $templates['bot'];

			// Print the Online Users List.
			echo $output;

		}

	}

	function printRegForm($template_folder = FALSE, $template_prefix = FALSE) {

		$templates = $this->templates('reg', $template_folder, $template_prefix);

		$output = '<!-- Powered by phpuserlogin2 -->';

		$output .= $templates['top'];

		if ($this->_systemOptions['register'] == TRUE && $this->matchPath('reg')) {

			if ($this->loginstatus == FALSE) {

				if ($SysteMsg = $this->SystemMsg('register')) {
					$msg = $templates['msg'];
					$msg  = str_replace ("{msg}", $SysteMsg, $msg);
					$output .= $msg;
				}

				if ($this->_systemNewUser == FALSE) {

					$form = $templates['form'];
					$form = str_replace ("{help}", $this->_systemText['regForm_6'], $form);
					$form = str_replace ("{form_page}", $this->pagePath('reg'), $form);
					$form = str_replace ("{form_username}", $this->_systemText['regForm_1'], $form);
					$form = str_replace ("{form_password}", $this->_systemText['regForm_2'], $form);
					$form = str_replace ("{form_repassword}", $this->_systemText['regForm_3'], $form);
					$form = str_replace ("{form_email}", $this->_systemText['regForm_4'], $form);
					$form = str_replace ("{form_field_name_username}", $this->_systemOptions['var_name'].'[REG][username]', $form);
					$form = str_replace ("{form_field_name_password}", $this->_systemOptions['var_name'].'[REG][password]', $form);
					$form = str_replace ("{form_field_name_repassword}", $this->_systemOptions['var_name'].'[REG][password2]', $form);
					$form = str_replace ("{form_field_name_email}", $this->_systemOptions['var_name'].'[REG][email]', $form);

					if (is_array($this->_systemOptions['mysql_fields'])) {

						$form_extra = '';

						foreach($this->_systemOptions['mysql_fields'] as $table_key => $table_value) {
							if (isset($table_value['fields']) AND is_array($table_value['fields'])) {
								foreach($table_value['fields'] as $field_key => $field_value) {
									list($field_name,$field_text,$field_extra) = explode('||', $field_value);
									if (!empty($field_extra)) {
										if (ereg('MAX\[(.*)\]', $field_extra, $extra_data)) {
											$form_extra_field = $templates['field_textmax'];
											$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
											$form_extra_field = str_replace ("{field_max}", $extra_data[1], $form_extra_field);
											$form_extra .= $form_extra_field;
										} elseif (ereg('DROP_DOWN\[(.*)\]', $field_extra, $extra_data)) {
											$options = explode(',', $extra_data[1]);

											$form_extra_field = $templates['field_dropdown1'];
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
											$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);

											$form_extra_field_store = '';

											foreach($options as $options_value) {
												$sub_options = explode('=', $options_value);

												$form_extra_field_more = $templates['field_dropdown2'];
												$form_extra_field_more = str_replace ("{field_text}", $sub_options[0], $form_extra_field_more);
												$form_extra_field_more = str_replace ("{field_value}", $sub_options[1], $form_extra_field_more);
												$form_extra_field_more = str_replace ("{field_selected}", ((@$sub_options[2]=='s') ? 'selected' : '' ), $form_extra_field_more);
												$form_extra_field_store .= $form_extra_field_more;
											}

											$form_extra_field  = str_replace ("{field_more}", $form_extra_field_store, $form_extra_field);
											$form_extra .= $form_extra_field;
										} elseif (ereg('PASS\[(.*)\]', $field_extra, $extra_data)) {
											$form_extra_field = $templates['field_pass'];
											$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
											$form_extra_field = str_replace ("{field_max}", $extra_data[1], $form_extra_field);
											$form_extra .= $form_extra_field;
										} elseif (ereg('ON_OFF\[(.*),(.*)\]', $field_extra, $extra_data)) {
											$form_extra_field = $templates['field_check'];
											$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
											$form_extra_field = str_replace ("{field_value}", $extra_data[1], $form_extra_field);
											$form_extra .= $form_extra_field;
										} elseif (ereg('RADIO\[(.*)\]', $field_extra, $extra_data)) {
											$options = explode(',', $extra_data[1]);

											$form_extra_field = $templates['field_radio1'];
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);

											$form_extra_field_store = '';

											foreach($options as $options_value) {
												$sub_options = explode('=', $options_value);

												$form_extra_field_more = $templates['field_radio2'];
												$form_extra_field_more = str_replace ("{field_text}", $sub_options[0], $form_extra_field_more);
												$form_extra_field_more = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field_more);
												$form_extra_field_more = str_replace ("{field_value}", $sub_options[1], $form_extra_field_more);
												$form_extra_field_more = str_replace ("{field_checked}", ((@$sub_options[2]=='s') ? 'checked' : '' ), $form_extra_field_more);
												$form_extra_field_store .= $form_extra_field_more;
											}

											$form_extra_field  = str_replace ("{field_more}", $form_extra_field_store, $form_extra_field);
											$form_extra .= $form_extra_field;
										} elseif (ereg('TEXT\[(.*),(.*)\]', $field_extra, $extra_data)) {
											$form_extra_field = $templates['field_textarea'];
											$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);
											$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
											$form_extra_field = str_replace ("{field_cols}", $extra_data[1], $form_extra_field);
											$form_extra_field = str_replace ("{field_rows}", $extra_data[2], $form_extra_field);
											$form_extra .= $form_extra_field;
										}
									} else {
										$form_extra_field = $templates['field_text'];
										$form_extra_field = str_replace ("{field_name}", $this->_systemOptions['var_name'].'[REG][ADV]['.$table_key.']['.$field_name.']', $form_extra_field);
										$form_extra_field = str_replace ("{field_text}", $field_text, $form_extra_field);
										$form_extra .= $form_extra_field;
									}
								}
							}
						}
						$form  = str_replace ("{form_extra_fields}", $form_extra, $form);
					} else {
						$form  = str_replace ("{form_extra_fields}", '', $form);
					}

					$form = str_replace ("{form_field_name_hidden}", $this->_systemOptions['var_name'].'[REG][register]', $form);
					$form = str_replace ("{form_submit}", $this->_systemText['regForm_5'], $form);
					$form = str_replace ("{form_reset}", $this->_systemText['regForm_10'], $form);
					$output .= $form;

				}

			} else {
				$msg = $templates['msg'];
				$msg = str_replace ("{msg}", $this->_systemText['regForm_7'], $msg);
				$output .= $msg;
			}

		} else {
			$msg = $templates['msg'];
			$msg = str_replace ("{msg}", $this->_systemText['regForm_9'], $msg);
			$output .= $msg;
		}

		$output .= $templates['bot'];

		// Print form.
		echo $output;

	}

	function printForm($template_folder = FALSE, $template_prefix = FALSE) {

		$templates = $this->templates('login', $template_folder, $template_prefix);

		$output = '<!-- Powered by phpuserlogin2 -->';

		$output .= $templates['top'];

		/* Print System msgs */
		if ($SysteMsg = $this->SystemMsg('login')) {
			$msg = $templates['msg'];
			$msg  = str_replace ("{msg}", $SysteMsg, $msg);
			$output .= $msg;
		}

		/* If logged in */
		if ($this->loginstatus) {
			/* Print logout link */
			$logout = $templates['logout'];

			$logout_pat[1] = '{url}';
			$logout_rep[1] = $this->pagePath('login', $this->_systemOptions['var_name'].'[logout]=1');
			$logout_pat[2] = '{text}';
			$logout_rep[2] = $this->_systemText['Form_1'];

			$logout  = str_replace ($logout_pat, $logout_rep, $logout);
			$output .= $logout;

			/* Print admin link if admin */
  			if ($this->adminstatus == TRUE) {

				$output .= "<SCRIPT language=\"JavaScript\">
function openNewWindow(url,w,h) {
	var newWin = window.open(url, 'phpuserloginAdminWindow', 'width='+w+',height='+h+',scrollbars');
}
</SCRIPT>";
				
				$admin = $templates['admin'];

				$admin_pat[1] = '{url}';
				$admin_rep[1] = "javascript:openNewWindow('".$this->pagePath('',$this->_systemOptions['var_name'].'[ADMIN][RUN]=1')."',660,700);";
				$admin_pat[2] = '{text}';
				$admin_rep[2] = $this->_systemText['Form_10'];
				
				$admin  = str_replace ($admin_pat, $admin_rep, $admin);
				$output .= $admin;
			}

		/* If not logged in */	
		} else {

			if ($this->matchPath('login')) {

				// Lost password form
				if (isset($this->_systemOutVar['LP']['form']) && $this->_systemOptions['lostpass'] == TRUE) {

					$lost_pass = $templates['lost_pass'];

					$lost_pass_pat[1] = '{form_path}';
					$lost_pass_rep[1] = $this->pagePath('login', $this->_systemOptions['var_name'].'[LP][form]=1');
					$lost_pass_pat[2] = '{form_text_username}';
					$lost_pass_rep[2] = $this->_systemText['Form_2'];
					$lost_pass_pat[3] = '{form_name_username}';
					$lost_pass_rep[3] = $this->_systemOptions['var_name'].'[LP][username]';
					$lost_pass_pat[4] = '{form_value_submit}';
					$lost_pass_rep[4] = $this->_systemText['Form_3'];
					$lost_pass_pat[5] = '{form_name_hidden}';
					$lost_pass_rep[5] = $this->_systemOptions['var_name'].'[LP][run]';
					$lost_pass_pat[6] = '{form_back_url}';
					$lost_pass_rep[6] = $this->pagePath('login');
					$lost_pass_pat[7] = '{form_back_text}';
					$lost_pass_rep[7] = $this->_systemText['Form_4'];

					$lost_pass  = str_replace ($lost_pass_pat, $lost_pass_rep, $lost_pass);
					$output .= $lost_pass;
					
				// Login form
				} else {

					$login = $templates['login'];

					$login_pat[1] = '{form_path}';
					$login_rep[1] = $this->pagePath('login');
					$login_pat[2] = '{form_text_username}';
					$login_rep[2] = $this->_systemText['Form_5'];
					$login_pat[3] = '{form_name_username}';
					$login_rep[3] = $this->_systemOptions['var_name'].'[L][username]';
					$login_pat[4] = '{form_text_pass}';
					$login_rep[4] = $this->_systemText['Form_6'];
					$login_pat[5] = '{form_name_pass}';
					$login_rep[5] = $this->_systemOptions['var_name'].'[L][password]';
					$login_pat[6] = '{form_name_hidden}';
					$login_rep[6] = $this->_systemOptions['var_name'].'[L][login]';
					$login_pat[7] = '{form_text_submit}';
					$login_rep[7] = $this->_systemText['Form_7'];
					$login_pat[8] = '{lostpass_link}';
					if ($this->_systemOptions['lostpass'] == TRUE) {
						$lostpass_link = $templates['login_lost_link'];

						$lostpass_link_pat[1] = '{url}';
						$lostpass_link_rep[1] = $this->pagePath('login', $this->_systemOptions['var_name'].'[LP][form]=1');
						$lostpass_link_pat[2] = '{text}';
						$lostpass_link_rep[2] = $this->_systemText['Form_8'];

						$lostpass_link  = str_replace ($lostpass_link_pat, $lostpass_link_rep, $lostpass_link);
						$login_rep[8] = $lostpass_link;
					} else {
						$login_rep[8] == '';
					}

					$login  = str_replace ($login_pat, $login_rep, $login);
					$output .= $login;

				}

			} else {

				$login_link = $templates['login_link'];

				$login_link_pat[1] = '{url}';
				$login_link_rep[1] = $this->pagePath('login');
				$login_link_pat[2] = '{text}';
				$login_link_rep[2] = $this->_systemText['Form_9'];
				
				$login_link  = str_replace ($login_link_pat, $login_link_rep, $login_link);
				$output .= $login_link;
				
			}

		}

		$copy = $templates['msg'];
		$copy  = str_replace ("{msg}", $this->_systemPowerBy, $copy);
		$output .= $copy;

		$output .= $templates['bot'];

		// Print form.
		echo $output;

		// Debug info
		if ($this->_systemDebug == TRUE) {

			$temp_options = $this->_systemOptions;
			$temp_options['mysql_pass'] = $temp_options['hidden_key'] = '***';

			$start_time = explode(" ", $this->_systemRunTime['start']);
			$start_time = $start_time[1] + $start_time[0];
			$end_time = explode(" ", $this->_systemRunTime['end']);
			$end_time = $end_time[1] + $end_time[0];
			$total_time = round(($end_time - $start_time), 4);

?>
<div style="color: #000000; background-color: #CCCCCC; padding: 5px; margin: 10px" align="left" width="160">
<font size="1" >Debug Mode Activated:</font>

<hr align="center">

<font size="1">Script Version: <?=$this->_systemVersion?> </font>

<hr align="center">

<font size="1">Script Options:</font><br>
<pre><? print_r($temp_options) ?></pre>

<hr align="center">

<font size="1">MySQL queries run:</font><br>
<?=$this->_systemMySQL_QNum?>

<hr align="center">

<font size="1">MySQL Error(s):</font><br>
<pre><? if ($this->_systemMySQL_Err == NULL) { echo'No Errors'; } else { print_r($this->_systemMySQL_Err); } ?></pre>

<hr align="center">

<font size="1">Time used to run code in constructor:</font><br>
<?=$total_time?> Secounds.

<hr align="center">

<font size="1">Vars from outside php:</font><br>
<pre><? print_r($this->_systemOutVar) ?></pre>

<hr align="center">

<font size="1">Login status: <?=(($this->loginstatus == FALSE) ? 'Not logged in' : 'Logged in<br>Admin status: '.(($this->adminstatus == FALSE) ? 'Not an admin' : 'Is admin'))?></font>

<hr align="center">

<font size="1">Data stored in userinfo:</font><br>
<pre><? print_r($this->userinfo) ?></pre>

</div>
<?

		}

	}

/* End of Class */
}

/*
 * Extra Data
// Special Option

	'mysql_fields'	=> array(
									'_main'	=> array( // This is for extra fields in the main table.
										'fields'		=> array(
															1	=> 'extra_test||This is a extra field',
															2	=> 'extra_2||This is another extra fields, very fun, dont you think'
															3	=> 'extra_3||Make your chose|DROP_DOWN[test1=1,test2=2,test3=3]'
															4	=> 'extra_4||User level|AUTO[1]'
															5	=> 'extra_5||Do you want others to see your email|ON_OFF[1,0]'
															6	=> 'extra_6||What do you like:|RADIO[Men=1,Females=2,Ice=3]'  
														)
										),
									2	=> array(
										'table_name'	=> 'extra_table',
										'id_field'		=> 'id',
										'fields'		=> array(
															1	=> 'extra_test||This is a extra field with a limit||MAX[10]',
															2	=> 'extra_2||This is another extra fields, very fun, dont you think'
															3	=> 'extra_3||Make your chose||DROP_DOWN[test1=1=s,test2=2,test3=3]'
															4	=> 'extra_4||User level||AUTO[1]'
															5	=> 'extra_7||Hidden thing||PASS[100]'
															6	=> 'extra_5||Do you want others to see your email||ON_OFF[1,0]'
															7	=> 'extra_6||What do you like:||RADIO[Men=1=s,Females=2,Ice=3]'  
														),

										)
								),

*/

?>
